code stringlengths 2 1.05M | repo_name stringlengths 5 114 | path stringlengths 4 991 | language stringclasses 1 value | license stringclasses 15 values | size int32 2 1.05M |
|---|---|---|---|---|---|
/*jslint browser: true, plusplus: true, vars: true, indent: 2 */
window.loadIndieConfig = (function () {
'use strict';
// Indie-Config Loading script
// by Pelle Wessman, voxpelli.com
// MIT-licensed
// http://indiewebcamp.com/indie-config
var config, configFrame, configTimeout,
callbacks = [],
handleConfig, parseConfig;
// When the configuration has been loaded – deregister all loading mechanics and call all callbacks
handleConfig = function () {
config = config || {};
configFrame.parentNode.removeChild(configFrame);
configFrame = undefined;
window.removeEventListener('message', parseConfig);
clearTimeout(configTimeout);
while (callbacks[0]) {
callbacks.shift()(config);
}
};
// When we receive a message, check if the source is right and try to parse it
parseConfig = function (message) {
var correctSource = (configFrame && message.source === configFrame.contentWindow);
if (correctSource && config === undefined) {
try {
config = JSON.parse(message.data);
} catch (ignore) {}
handleConfig();
}
};
return function (callback) {
// If the config is already loaded, call callback right away
if (config) {
callback(config);
return;
}
// Otherwise add the callback to the queue
callbacks.push(callback);
// Are we already trying to load the Indie-Config, then wait
if (configFrame) {
return;
}
// Create the iframe that will load the Indie-Config
configFrame = document.createElement('iframe');
configFrame.src = 'web+action:load';
document.getElementsByTagName('body')[0].appendChild(configFrame);
configFrame.style.display = 'none';
// Listen for messages so we will catch the Indie-Config message
window.addEventListener('message', parseConfig);
// And if no such Indie-Config message has been loaded in a while, abort the loading
configTimeout = setTimeout(handleConfig, 3000);
};
}());
| Lancey6/woodwind | woodwind/static/indieconfig.js | JavaScript | bsd-2-clause | 2,009 |
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails oncall+jsinfra
*/
'use strict';
jest.mock('vm');
const path = require('path');
const os = require('os');
const FILE_PATH_TO_INSTRUMENT = path.resolve(
__dirname,
'./module_dir/to-be-instrumented.js',
);
it('instruments files', () => {
const vm = require('vm');
const transform = require('../transform');
const config = {
cacheDirectory: os.tmpdir(),
cache: false,
collectCoverage: true,
rootDir: '/',
};
const instrumented = transform(FILE_PATH_TO_INSTRUMENT, config);
expect(instrumented instanceof vm.Script).toBe(true);
// We can't really snapshot the resulting coverage, because it depends on
// absolute path of the file, which will be different on different
// machines
expect(vm.Script.mock.calls[0][0]).toMatch(`gcv = '__coverage__'`);
});
| Daniel15/jest | packages/jest-runtime/src/__tests__/instrumentation-test.js | JavaScript | bsd-3-clause | 1,109 |
cdb.geo.ui.Annotation = cdb.core.View.extend({
className: "cartodb-overlay overlay-annotation",
defaults: {
minZoom: 0,
maxZoom: 40,
style: {
textAlign: "left",
zIndex: 5,
color: "#ffffff",
fontSize: "13",
fontFamilyName: "Helvetica",
boxColor: "#333333",
boxOpacity: 0.7,
boxPadding: 10,
lineWidth: 50,
lineColor: "#333333"
}
},
template: cdb.core.Template.compile(
'<div class="content">\
<div class="text widget_text">{{{ text }}}</div>\
<div class="stick"><div class="ball"></div></div>\
</div>',
'mustache'
),
events: {
"click": "stopPropagation"
},
stopPropagation: function(e) {
e.stopPropagation();
},
initialize: function() {
this.template = this.options.template || this.template;
this.mapView = this.options.mapView;
this.mobileEnabled = /Android|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
this._cleanStyleProperties(this.options.style);
_.defaults(this.options.style, this.defaults.style);
this._setupModels();
this._bindMap();
},
_setupModels: function() {
this.model = new cdb.core.Model({
display: true,
hidden: false,
text: this.options.text,
latlng: this.options.latlng,
minZoom: this.options.minZoom || this.defaults.minZoom,
maxZoom: this.options.maxZoom || this.defaults.maxZoom
});
this.model.on("change:display", this._onChangeDisplay, this);
this.model.on("change:text", this._onChangeText, this);
this.model.on('change:latlng', this._place, this);
this.model.on('change:minZoom', this._applyZoomLevelStyle, this);
this.model.on('change:maxZoom', this._applyZoomLevelStyle, this);
this.style = new cdb.core.Model(this.options.style);
this.style.on("change", this._applyStyle, this);
this.add_related_model(this.style);
},
_bindMap: function() {
this.mapView.map.bind('change', this._place, this);
this.mapView.map.bind('change:zoom', this._applyZoomLevelStyle, this);
this.mapView.bind('zoomstart', this.hide, this);
this.mapView.bind('zoomend', this.show, this);
},
_unbindMap: function() {
this.mapView.map.unbind('change', this._place, this);
this.mapView.map.unbind('change:zoom', this._applyZoomLevelStyle, this);
this.mapView.unbind('zoomstart', this.hide, this);
this.mapView.unbind('zoomend', this.show, this);
},
_onChangeDisplay: function() {
if (this.model.get("display")) this.show();
else this.hide();
},
_onChangeText: function() {
this.$el.find(".text").html(this._sanitizedText());
},
_sanitizedText: function() {
return cdb.core.sanitize.html(this.model.get("text"), this.model.get('sanitizeText'));
},
_getStandardPropertyName: function(name) {
if (!name) {
return;
}
var parts = name.split("-");
if (parts.length === 1) {
return name;
} else {
return parts[0] + _.map(parts.slice(1), function(l) {
return l.slice(0,1).toUpperCase() + l.slice(1);
}).join("");
}
},
_cleanStyleProperties: function(hash) {
var standardProperties = {};
_.each(hash, function(value, key) {
standardProperties[this._getStandardPropertyName(key)] = value;
}, this);
this.options.style = standardProperties;
},
_belongsToCanvas: function() {
var mobile = (this.options.device === "mobile") ? true : false;
return mobile === this.mobileEnabled;
},
show: function(callback) {
if (this.model.get("hidden") || !this._belongsToCanvas()) return;
var self = this;
this.$el.css({ opacity: 0, display: "inline-table" }); // makes the element to behave fine in the borders of the screen
this.$el.stop().animate({ opacity: 1 }, { duration: 150, complete: function() {
callback && callback();
}});
},
hide: function(callback) {
this.$el.stop().fadeOut(150, function() {
callback && callback();
});
},
_place: function() {
var latlng = this.model.get("latlng");
var lineWidth = this.style.get("lineWidth");
var textAlign = this.style.get("textAlign");
var pos = this.mapView.latLonToPixel(latlng);
if (pos) {
var top = pos.y - this.$el.height()/2;
var left = pos.x + lineWidth;
if (textAlign === "right") {
left = pos.x - this.$el.width() - lineWidth - this.$el.find(".ball").width();
}
this.$el.css({ top: top, left: left });
}
},
setMinZoom: function(zoom) {
this.model.set("minZoom", zoom);
},
setMaxZoom: function(zoom) {
this.model.set("maxZoom", zoom);
},
setPosition: function(latlng) {
this.model.set("latlng", latlng);
},
setText: function(text) {
this.model.set("text", text);
},
setStyle: function(property, value) {
var standardProperty = this._getStandardPropertyName(property);
if (standardProperty) {
this.style.set(standardProperty, value);
}
},
_applyStyle: function() {
var textColor = this.style.get("color");
var textAlign = this.style.get("textAlign");
var boxColor = this.style.get("boxColor");
var boxOpacity = this.style.get("boxOpacity");
var boxPadding = this.style.get("boxPadding");
var lineWidth = this.style.get("lineWidth");
var lineColor = this.style.get("lineColor");
var fontFamily = this.style.get("fontFamilyName");
this.$text = this.$el.find(".text");
this.$text.css({ color: textColor, textAlign: textAlign });
this.$el.find(".content").css("padding", boxPadding);
this.$text.css("font-size", this.style.get("fontSize") + "px");
this.$el.css("z-index", this.style.get("zIndex"));
this.$el.find(".stick").css({ width: lineWidth, left: -lineWidth });
var fontFamilyClass = "";
if (fontFamily == "Droid Sans") fontFamilyClass = "droid";
else if (fontFamily == "Vollkorn") fontFamilyClass = "vollkorn";
else if (fontFamily == "Open Sans") fontFamilyClass = "open_sans";
else if (fontFamily == "Roboto") fontFamilyClass = "roboto";
else if (fontFamily == "Lato") fontFamilyClass = "lato";
else if (fontFamily == "Graduate") fontFamilyClass = "graduate";
else if (fontFamily == "Gravitas One") fontFamilyClass = "gravitas_one";
else if (fontFamily == "Old Standard TT") fontFamilyClass = "old_standard_tt";
this.$el
.removeClass("droid")
.removeClass("vollkorn")
.removeClass("roboto")
.removeClass("open_sans")
.removeClass("lato")
.removeClass("graduate")
.removeClass("gravitas_one")
.removeClass("old_standard_tt");
this.$el.addClass(fontFamilyClass);
if (textAlign === "right") {
this.$el.addClass("align-right");
this.$el.find(".stick").css({ left: "auto", right: -lineWidth });
} else {
this.$el.removeClass("align-right");
}
this._place();
this._applyZoomLevelStyle();
},
_getRGBA: function(color, opacity) {
return 'rgba(' + parseInt(color.slice(-6,-4),16)
+ ',' + parseInt(color.slice(-4,-2),16)
+ ',' + parseInt(color.slice(-2),16)
+ ',' + opacity + ' )';
},
_applyZoomLevelStyle: function() {
var boxColor = this.style.get("boxColor");
var boxOpacity = this.style.get("boxOpacity");
var lineColor = this.style.get("lineColor");
var minZoom = this.model.get("minZoom");
var maxZoom = this.model.get("maxZoom");
var currentZoom = this.mapView.map.get("zoom");
if (currentZoom >= minZoom && currentZoom <= maxZoom) {
var rgbaLineCol = this._getRGBA(lineColor, 1);
var rgbaBoxCol = this._getRGBA(boxColor, boxOpacity);
this.$el.find(".text").animate({ opacity: 1 }, 150);
this.$el.css("background-color", rgbaBoxCol);
this.$el.find(".stick").css("background-color", rgbaLineCol);
this.$el.find(".ball").css("background-color", rgbaLineCol);
this.model.set("hidden", false);
this.model.set("display", true);
} else {
this.model.set("hidden", true);
this.model.set("display", false);
}
},
clean: function() {
this._unbindMap();
cdb.core.View.prototype.clean.call(this);
},
_fixLinks: function() {
this.$el.find("a").each(function(i, link) {
$(this).attr("target", "_top");
});
},
render: function() {
var d = _.clone(this.model.attributes);
d.text = this._sanitizedText();
this.$el.html(this.template(d));
this._fixLinks();
var self = this;
setTimeout(function() {
self._applyStyle();
self._applyZoomLevelStyle();
self.show();
}, 500);
return this;
}
});
| CartoDB/cartodb.js | src/geo/ui/annotation.js | JavaScript | bsd-3-clause | 8,814 |
// Generated by CoffeeScript 1.4.0
(function() {
"use strict";
var CTCPHandler, exports, _ref,
__slice = [].slice;
var exports = (_ref = window.irc) != null ? _ref : window.irc = {};
/*
* Handles CTCP requests such as VERSION, PING, etc.
*/
CTCPHandler = (function() {
CTCPHandler.DELIMITER = '\u0001';
function CTCPHandler() {
/*
* TODO: Respond with this message when an unknown query is seen.
*/
this._error = "" + CTCPHandler.DELIMITER + "ERRMSG" + CTCPHandler.DELIMITER;
}
CTCPHandler.prototype.isCTCPRequest = function(msg) {
if (!/\u0001[\w\s]*\u0001/.test(msg)) {
return false;
}
return this.getResponses(msg).length > 0;
};
CTCPHandler.prototype.getReadableName = function(msg) {
var args, type, _ref1;
_ref1 = this._parseMessage(msg), type = _ref1[0], args = _ref1[1];
return type;
};
CTCPHandler.prototype.getResponses = function(msg) {
var args, response, responses, type, _i, _len, _ref1, _results;
_ref1 = this._parseMessage(msg), type = _ref1[0], args = _ref1[1];
responses = this._getResponseText(type, args);
_results = [];
for (_i = 0, _len = responses.length; _i < _len; _i++) {
response = responses[_i];
_results.push(this._createCTCPResponse(type, response));
}
return _results;
};
/*
* Parses the type and arguments from a CTCP request.
* @param {string} msg CTCP message in the format: '\0001TYPE ARG1 ARG2\0001'.
* Note: \0001 is a single character.
* @return {string, Array.<string>} Returns the type and the args.
*/
CTCPHandler.prototype._parseMessage = function(msg) {
var args, type, _ref1;
msg = msg.slice(1, +(msg.length - 2) + 1 || 9e9);
_ref1 = msg.split(' '), type = _ref1[0], args = 2 <= _ref1.length ? __slice.call(_ref1, 1) : [];
return [type, args];
};
/*
* @return {Array.<string>} Returns the unformatted responses to a CTCP
* request.
*/
CTCPHandler.prototype._getResponseText = function(type, args) {
/*
* TODO support the o ther types found here:
* http://www.irchelp.org/irchelp/rfc/ctcpspec.html
*/
var environment, name;
switch (type) {
case 'VERSION':
name = 'CIRC';
environment = 'Chrome';
return [' ' + [name, globals.VERSION, environment].join(' ')];
case 'SOURCE':
return [' https://github.com/flackr/circ/'];
case 'PING':
return [' ' + args[0]];
case 'TIME':
var d = new Date();
return [' ' + d.toUTCString()];
default:
return [];
}
};
/*
* @return {string} Returns a correctly formatted response to a CTCP request.
*/
CTCPHandler.prototype._createCTCPResponse = function(type, response) {
return "" + CTCPHandler.DELIMITER + type + response + CTCPHandler.DELIMITER;
};
return CTCPHandler;
})();
exports.CTCPHandler = CTCPHandler;
}).call(this);
| diddledan/circ | package/bin/irc/ctcp_handler.js | JavaScript | bsd-3-clause | 3,122 |
webshims.register('form-native-extend', function($, webshims, window, doc, undefined, options){
"use strict";
var Modernizr = window.Modernizr;
var modernizrInputTypes = Modernizr.inputtypes;
if(!Modernizr.formvalidation || webshims.bugs.bustedValidity){return;}
var typeModels = webshims.inputTypes;
var runTest = false;
var validityRules = {};
var updateValidity = (function(){
var timer;
var getValidity = function(){
$(this).prop('validity');
};
var update = function(){
$('input').each(getValidity);
};
return function(){
clearTimeout(timer);
timer = setTimeout(update, 9);
};
})();
webshims.addInputType = function(type, obj){
typeModels[type] = obj;
runTest = true;
//update validity of all implemented input types
if($.isDOMReady && Modernizr.formvalidation && !webshims.bugs.bustedValidity){
updateValidity();
}
};
webshims.addValidityRule = function(type, fn){
validityRules[type] = fn;
};
$.each({typeMismatch: 'mismatch', badInput: 'bad'}, function(name, fn){
webshims.addValidityRule(name, function (input, val, cache, validityState){
if(val === ''){return false;}
var ret = validityState[name];
if(!('type' in cache)){
cache.type = (input[0].getAttribute('type') || '').toLowerCase();
}
if(typeModels[cache.type] && typeModels[cache.type][fn]){
ret = typeModels[cache.type][fn](val, input);
}
return ret || false;
});
});
var formsExtModule = webshims.modules['form-number-date-api'];
var overrideValidity = formsExtModule.loaded && !formsExtModule.test();
var validityProps = ['customError', 'badInput','typeMismatch','rangeUnderflow','rangeOverflow','stepMismatch','tooLong', 'tooShort','patternMismatch','valueMissing','valid'];
var validityChanger = ['value'];
var validityElements = [];
var testValidity = function(elem, init){
if(!elem && !runTest){return;}
var type = (elem.getAttribute && elem.getAttribute('type') || elem.type || '').toLowerCase();
if(typeModels[type]){
$.prop(elem, 'validity');
}
};
var oldSetCustomValidity = {};
['input', 'textarea', 'select'].forEach(function(name){
var desc = webshims.defineNodeNameProperty(name, 'setCustomValidity', {
prop: {
value: function(error){
error = error+'';
var elem = (name == 'input') ? $(this).getNativeElement()[0] : this;
desc.prop._supvalue.call(elem, error);
if(overrideValidity){
webshims.data(elem, 'hasCustomError', !!(error));
testValidity(elem);
}
}
}
});
oldSetCustomValidity[name] = desc.prop._supvalue;
});
if(overrideValidity){
validityChanger.push('min');
validityChanger.push('max');
validityChanger.push('step');
validityElements.push('input');
}
if(overrideValidity){
var stopValidity;
validityElements.forEach(function(nodeName){
var oldDesc = webshims.defineNodeNameProperty(nodeName, 'validity', {
prop: {
get: function(){
if(stopValidity){return;}
var elem = (nodeName == 'input') ? $(this).getNativeElement()[0] : this;
var validity = oldDesc.prop._supget.call(elem);
if(!validity){
return validity;
}
var validityState = {};
validityProps.forEach(function(prop){
validityState[prop] = validity[prop] || false;
});
if( !$.prop(elem, 'willValidate') ){
return validityState;
}
stopValidity = true;
var jElm = $(elem),
cache = {type: (elem.getAttribute && elem.getAttribute('type') || elem.type || '').toLowerCase(), nodeName: (elem.nodeName || '').toLowerCase()},
val = jElm.val(),
customError = !!(webshims.data(elem, 'hasCustomError')),
setCustomMessage
;
stopValidity = false;
validityState.customError = customError;
if( validityState.valid && validityState.customError ){
validityState.valid = false;
} else if(!validityState.valid) {
var allFalse = true;
$.each(validityState, function(name, prop){
if(prop){
allFalse = false;
return false;
}
});
if(allFalse){
validityState.valid = true;
}
}
$.each(validityRules, function(rule, fn){
validityState[rule] = fn(jElm, val, cache, validityState);
if( validityState[rule] && (validityState.valid || !setCustomMessage) && ((typeModels[cache.type])) ) {
oldSetCustomValidity[nodeName].call(elem, webshims.createValidationMessage(elem, rule));
validityState.valid = false;
setCustomMessage = true;
}
});
if(validityState.valid){
oldSetCustomValidity[nodeName].call(elem, '');
webshims.data(elem, 'hasCustomError', false);
}
return validityState;
},
writeable: false
}
});
});
validityChanger.forEach(function(prop){
webshims.onNodeNamesPropertyModify(validityElements, prop, function(s){
testValidity(this);
});
});
if(doc.addEventListener){
var inputThrottle;
var testPassValidity = function(e){
if(!('form' in e.target)){return;}
clearTimeout(inputThrottle);
testValidity(e.target);
};
doc.addEventListener('change', testPassValidity, true);
doc.addEventListener('input', function(e){
clearTimeout(inputThrottle);
inputThrottle = setTimeout(function(){
testValidity(e.target);
}, 290);
}, true);
}
var validityElementsSel = validityElements.join(',');
webshims.addReady(function(context, elem){
if(runTest){
$(validityElementsSel, context).add(elem.filter(validityElementsSel)).each(function(){
testValidity(this);
});
}
});
} //end: overrideValidity
webshims.defineNodeNameProperty('input', 'type', {
prop: {
get: function(){
var elem = this;
var type = (elem.getAttribute && elem.getAttribute('type') || '').toLowerCase();
return (webshims.inputTypes[type]) ? type : elem.type;
}
}
});
});;webshims.register('form-number-date-api', function($, webshims, window, document, undefined, options){
"use strict";
if(!webshims.addInputType){
webshims.error("you can not call forms-ext feature after calling forms feature. call both at once instead: $.webshims.polyfill('forms forms-ext')");
}
if(!webshims.getStep){
webshims.getStep = function(elem, type){
var step = $.attr(elem, 'step');
if(step === 'any'){
return step;
}
type = type || getType(elem);
if(!typeModels[type] || !typeModels[type].step){
return step;
}
step = typeProtos.number.asNumber(step);
return ((!isNaN(step) && step > 0) ? step : typeModels[type].step) * (typeModels[type].stepScaleFactor || 1);
};
}
if(!webshims.addMinMaxNumberToCache){
webshims.addMinMaxNumberToCache = function(attr, elem, cache){
if (!(attr+'AsNumber' in cache)) {
cache[attr+'AsNumber'] = typeModels[cache.type].asNumber(elem.attr(attr));
if(isNaN(cache[attr+'AsNumber']) && (attr+'Default' in typeModels[cache.type])){
cache[attr+'AsNumber'] = typeModels[cache.type][attr+'Default'];
}
}
};
}
var nan = parseInt('NaN', 10),
doc = document,
typeModels = webshims.inputTypes,
isNumber = function(string){
return (typeof string == 'number' || (string && string == string * 1));
},
supportsType = function(type){
return ($('<input type="'+type+'" />').prop('type') === type);
},
getType = function(elem){
return (elem.getAttribute('type') || '').toLowerCase();
},
isDateTimePart = function(string){
return (string && !(isNaN(string * 1)));
},
addMinMaxNumberToCache = webshims.addMinMaxNumberToCache,
addleadingZero = function(val, len){
val = ''+val;
len = len - val.length;
for(var i = 0; i < len; i++){
val = '0'+val;
}
return val;
},
EPS = 1e-7,
typeBugs = webshims.bugs.bustedValidity
;
webshims.addValidityRule('stepMismatch', function(input, val, cache, validityState){
if(val === ''){return false;}
if(!('type' in cache)){
cache.type = getType(input[0]);
}
if(cache.type == 'week'){return false;}
var base, attrVal;
var ret = (validityState || {}).stepMismatch || false;
if(typeModels[cache.type] && typeModels[cache.type].step){
if( !('step' in cache) ){
cache.step = webshims.getStep(input[0], cache.type);
}
if(cache.step == 'any'){return false;}
if(!('valueAsNumber' in cache)){
cache.valueAsNumber = typeModels[cache.type].asNumber( val );
}
if(isNaN(cache.valueAsNumber)){return false;}
addMinMaxNumberToCache('min', input, cache);
base = cache.minAsNumber;
if(isNaN(base) && (attrVal = input.prop('defaultValue'))){
base = typeModels[cache.type].asNumber( attrVal );
}
if(isNaN(base)){
base = typeModels[cache.type].stepBase || 0;
}
ret = Math.abs((cache.valueAsNumber - base) % cache.step);
ret = !( ret <= EPS || Math.abs(ret - cache.step) <= EPS );
}
return ret;
});
[{name: 'rangeOverflow', attr: 'max', factor: 1}, {name: 'rangeUnderflow', attr: 'min', factor: -1}].forEach(function(data, i){
webshims.addValidityRule(data.name, function(input, val, cache, validityState) {
var ret = (validityState || {})[data.name] || false;
if(val === ''){return ret;}
if (!('type' in cache)) {
cache.type = getType(input[0]);
}
if (typeModels[cache.type] && typeModels[cache.type].asNumber) {
if(!('valueAsNumber' in cache)){
cache.valueAsNumber = typeModels[cache.type].asNumber( val );
}
if(isNaN(cache.valueAsNumber)){
return false;
}
addMinMaxNumberToCache(data.attr, input, cache);
if(isNaN(cache[data.attr+'AsNumber'])){
return ret;
}
ret = ( cache[data.attr+'AsNumber'] * data.factor < cache.valueAsNumber * data.factor - EPS );
}
return ret;
});
});
webshims.reflectProperties(['input'], ['max', 'min', 'step']);
//IDLs and methods, that aren't part of constrain validation, but strongly tight to it
var valueAsNumberDescriptor = webshims.defineNodeNameProperty('input', 'valueAsNumber', {
prop: {
get: function(){
var elem = this;
var type = getType(elem);
var ret = (typeModels[type] && typeModels[type].asNumber) ?
typeModels[type].asNumber($.prop(elem, 'value')) :
(valueAsNumberDescriptor.prop._supget && valueAsNumberDescriptor.prop._supget.apply(elem, arguments));
if(ret == null){
ret = nan;
}
return ret;
},
set: function(val){
var elem = this;
var type = getType(elem);
if(typeModels[type] && typeModels[type].numberToString){
//is NaN a number?
if(isNaN(val)){
$.prop(elem, 'value', '');
return;
}
var set = typeModels[type].numberToString(val);
if(set !== false){
$.prop(elem, 'value', set);
} else {
webshims.error('INVALID_STATE_ERR: DOM Exception 11');
}
} else if(valueAsNumberDescriptor.prop._supset) {
valueAsNumberDescriptor.prop._supset.apply(elem, arguments);
}
}
}
});
var valueAsDateDescriptor = webshims.defineNodeNameProperty('input', 'valueAsDate', {
prop: {
get: function(){
var elem = this;
var type = getType(elem);
return (typeModels[type] && typeModels[type].asDate && !typeModels[type].noAsDate) ?
typeModels[type].asDate($.prop(elem, 'value')) :
valueAsDateDescriptor.prop._supget && valueAsDateDescriptor.prop._supget.call(elem) || null;
},
set: function(value){
var elem = this;
var type = getType(elem);
if(typeModels[type] && typeModels[type].dateToString && !typeModels[type].noAsDate){
if(value === null){
$.prop(elem, 'value', '');
return '';
}
var set = typeModels[type].dateToString(value);
if(set !== false){
$.prop(elem, 'value', set);
return set;
} else {
webshims.error('INVALID_STATE_ERR: DOM Exception 11');
}
} else {
return valueAsDateDescriptor.prop._supset && valueAsDateDescriptor.prop._supset.apply(elem, arguments) || null;
}
}
}
});
$.each({stepUp: 1, stepDown: -1}, function(name, stepFactor){
var stepDescriptor = webshims.defineNodeNameProperty('input', name, {
prop: {
value: function(factor){
var step, val, valModStep, alignValue, cache, base, attrVal;
var type = getType(this);
if(typeModels[type] && typeModels[type].asNumber){
cache = {type: type};
if(!factor){
factor = 1;
webshims.warn("you should always use a factor for stepUp/stepDown");
}
factor *= stepFactor;
step = webshims.getStep(this, type);
if(step == 'any'){
webshims.info("step is 'any' can't apply stepUp/stepDown");
throw('invalid state error');
}
webshims.addMinMaxNumberToCache('min', $(this), cache);
webshims.addMinMaxNumberToCache('max', $(this), cache);
val = $.prop(this, 'valueAsNumber');
if(factor > 0 && !isNaN(cache.minAsNumber) && (isNaN(val) || cache.minAsNumber > val)){
$.prop(this, 'valueAsNumber', cache.minAsNumber);
return;
} else if(factor < 0 && !isNaN(cache.maxAsNumber) && (isNaN(val) || cache.maxAsNumber < val)){
$.prop(this, 'valueAsNumber', cache.maxAsNumber);
return;
}
if(isNaN(val)){
val = 0;
}
base = cache.minAsNumber;
if(isNaN(base) && (attrVal = $.prop(this, 'defaultValue'))){
base = typeModels[type].asNumber( attrVal );
}
if(!base){
base = 0;
}
step *= factor;
val = (val + step).toFixed(5) * 1;
valModStep = (val - base) % step;
if ( valModStep && (Math.abs(valModStep) > EPS) ) {
alignValue = val - valModStep;
alignValue += ( valModStep > 0 ) ? step : ( -step );
val = alignValue.toFixed(5) * 1;
}
if( (!isNaN(cache.maxAsNumber) && val > cache.maxAsNumber) || (!isNaN(cache.minAsNumber) && val < cache.minAsNumber) ){
webshims.info("max/min overflow can't apply stepUp/stepDown");
return;
}
$.prop(this, 'valueAsNumber', val);
} else if(stepDescriptor.prop && stepDescriptor.prop._supvalue){
return stepDescriptor.prop._supvalue.apply(this, arguments);
} else {
webshims.info("no step method for type: "+ type);
throw('invalid state error');
}
}
}
});
});
/*
* ToDO: WEEK
*/
// var getWeek = function(date){
// var time;
// var checkDate = new Date(date.getTime());
//
// checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7));
//
// time = checkDate.getTime();
// checkDate.setMonth(0);
// checkDate.setDate(1);
// return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
// };
//
// var setWeek = function(year, week){
// var date = new Date(year, 0, 1);
//
// week = (week - 1) * 86400000 * 7;
// date = new Date(date.getTime() + week);
// date.setDate(date.getDate() + 1 - (date.getDay() || 7));
// return date;
// };
var typeProtos = {
number: {
bad: function(val){
return !(isNumber(val));
},
step: 1,
//stepBase: 0, 0 = default
stepScaleFactor: 1,
asNumber: function(str){
return (isNumber(str)) ? str * 1 : nan;
},
numberToString: function(num){
return (isNumber(num)) ? num : false;
}
},
range: {
minDefault: 0,
maxDefault: 100
},
color: {
bad: (function(){
var cReg = /^\u0023[a-f0-9]{6}$/;
return function(val){
return (!val || val.length != 7 || !(cReg.test(val)));
};
})()
},
date: {
bad: function(val){
if(!val || !val.split || !(/\d$/.test(val))){return true;}
var i;
var valA = val.split(/\u002D/);
if(valA.length !== 3){return true;}
var ret = false;
if(valA[0].length < 4 || valA[1].length != 2 || valA[1] > 12 || valA[2].length != 2 || valA[2] > 33){
ret = true;
} else {
for(i = 0; i < 3; i++){
if(!isDateTimePart(valA[i])){
ret = true;
break;
}
}
}
return ret || (val !== this.dateToString( this.asDate(val, true) ) );
},
step: 1,
//stepBase: 0, 0 = default
stepScaleFactor: 86400000,
asDate: function(val, _noMismatch){
if(!_noMismatch && this.bad(val)){
return null;
}
return new Date(this.asNumber(val, true));
},
asNumber: function(str, _noMismatch){
var ret = nan;
if(_noMismatch || !this.bad(str)){
str = str.split(/\u002D/);
ret = Date.UTC(str[0], str[1] - 1, str[2]);
}
return ret;
},
numberToString: function(num){
return (isNumber(num)) ? this.dateToString(new Date( num * 1)) : false;
},
dateToString: function(date){
return (date && date.getFullYear) ? addleadingZero(date.getUTCFullYear(), 4) +'-'+ addleadingZero(date.getUTCMonth()+1, 2) +'-'+ addleadingZero(date.getUTCDate(), 2) : false;
}
},
/*
* ToDO: WEEK
*/
// week: {
// bad: function(val){
// if(!val || !val.split){return true;}
// var valA = val.split('-W');
// var ret = true;
// if(valA.length == 2 && valA[0].length > 3 && valA.length == 2){
// ret = this.dateToString(setWeek(valA[0], valA[1])) != val;
// }
// return ret;
// },
// step: 1,
// stepScaleFactor: 604800000,
// stepBase: -259200000,
// asDate: function(str, _noMismatch){
// var ret = null;
// if(_noMismatch || !this.bad(str)){
// ret = str.split('-W');
// ret = setWeek(ret[0], ret[1]);
// }
// return ret;
// },
// asNumber: function(str, _noMismatch){
// var ret = nan;
// var date = this.asDate(str, _noMismatch);
// if(date && date.getUTCFullYear){
// ret = date.getTime();
// }
// return ret;
// },
// dateToString: function(date){
// var week, checkDate;
// var ret = false;
// if(date && date.getFullYear){
// week = getWeek(date);
// if(week == 1){
// checkDate = new Date(date.getTime());
// checkDate.setDate(checkDate.getDate() + 7);
// date.setUTCFullYear(checkDate.getUTCFullYear());
// }
// ret = addleadingZero(date.getUTCFullYear(), 4) +'-W'+addleadingZero(week, 2);
// }
// return ret;
// },
// numberToString: function(num){
// return (isNumber(num)) ? this.dateToString(new Date( num * 1)) : false;
// }
// },
time: {
bad: function(val, _getParsed){
if(!val || !val.split || !(/\d$/.test(val))){return true;}
val = val.split(/\u003A/);
if(val.length < 2 || val.length > 3){return true;}
var ret = false,
sFraction;
if(val[2]){
val[2] = val[2].split(/\u002E/);
sFraction = parseInt(val[2][1], 10);
val[2] = val[2][0];
}
$.each(val, function(i, part){
if(!isDateTimePart(part) || part.length !== 2){
ret = true;
return false;
}
});
if(ret){return true;}
if(val[0] > 23 || val[0] < 0 || val[1] > 59 || val[1] < 0){
return true;
}
if(val[2] && (val[2] > 59 || val[2] < 0 )){
return true;
}
if(sFraction && isNaN(sFraction)){
return true;
}
if(sFraction){
if(sFraction < 100){
sFraction *= 100;
} else if(sFraction < 10){
sFraction *= 10;
}
}
return (_getParsed === true) ? [val, sFraction] : false;
},
step: 60,
stepBase: 0,
stepScaleFactor: 1000,
asDate: function(val){
val = new Date(this.asNumber(val));
return (isNaN(val)) ? null : val;
},
asNumber: function(val){
var ret = nan;
val = this.bad(val, true);
if(val !== true){
ret = Date.UTC('1970', 0, 1, val[0][0], val[0][1], val[0][2] || 0);
if(val[1]){
ret += val[1];
}
}
return ret;
},
dateToString: function(date){
if(date && date.getUTCHours){
var str = addleadingZero(date.getUTCHours(), 2) +':'+ addleadingZero(date.getUTCMinutes(), 2),
tmp = date.getSeconds()
;
if(tmp != "0"){
str += ':'+ addleadingZero(tmp, 2);
}
tmp = date.getUTCMilliseconds();
if(tmp != "0"){
str += '.'+ addleadingZero(tmp, 3);
}
return str;
} else {
return false;
}
}
},
month: {
bad: function(val){
return typeProtos.date.bad(val+'-01');
},
step: 1,
stepScaleFactor: false,
//stepBase: 0, 0 = default
asDate: function(val){
return new Date(typeProtos.date.asNumber(val+'-01'));
},
asNumber: function(val){
//1970-01
var ret = nan;
if(val && !this.bad(val)){
val = val.split(/\u002D/);
val[0] = (val[0] * 1) - 1970;
val[1] = (val[1] * 1) - 1;
ret = (val[0] * 12) + val[1];
}
return ret;
},
numberToString: function(num){
var mod;
var ret = false;
if(isNumber(num)){
mod = (num % 12);
num = ((num - mod) / 12) + 1970;
mod += 1;
if(mod < 1){
num -= 1;
mod += 12;
}
ret = addleadingZero(num, 4)+'-'+addleadingZero(mod, 2);
}
return ret;
},
dateToString: function(date){
if(date && date.getUTCHours){
var str = typeProtos.date.dateToString(date);
return (str.split && (str = str.split(/\u002D/))) ? str[0]+'-'+str[1] : false;
} else {
return false;
}
}
}
,'datetime-local': {
bad: function(val, _getParsed){
if(!val || !val.split || (val+'special').split(/\u0054/).length !== 2){return true;}
val = val.split(/\u0054/);
return ( typeProtos.date.bad(val[0]) || typeProtos.time.bad(val[1], _getParsed) );
},
noAsDate: true,
asDate: function(val){
val = new Date(this.asNumber(val));
return (isNaN(val)) ? null : val;
},
asNumber: function(val){
var ret = nan;
var time = this.bad(val, true);
if(time !== true){
val = val.split(/\u0054/)[0].split(/\u002D/);
ret = Date.UTC(val[0], val[1] - 1, val[2], time[0][0], time[0][1], time[0][2] || 0);
if(time[1]){
ret += time[1];
}
}
return ret;
},
dateToString: function(date, _getParsed){
return typeProtos.date.dateToString(date) +'T'+ typeProtos.time.dateToString(date, _getParsed);
}
}
};
if(typeBugs || !supportsType('range') || !supportsType('time') || !supportsType('month') || !supportsType('datetime-local')){
typeProtos.range = $.extend({}, typeProtos.number, typeProtos.range);
typeProtos.time = $.extend({}, typeProtos.date, typeProtos.time);
typeProtos.month = $.extend({}, typeProtos.date, typeProtos.month);
typeProtos['datetime-local'] = $.extend({}, typeProtos.date, typeProtos.time, typeProtos['datetime-local']);
}
//
['number', 'month', 'range', 'date', 'time', 'color', 'datetime-local'].forEach(function(type){
if(typeBugs || !supportsType(type)){
webshims.addInputType(type, typeProtos[type]);
}
});
if($('<input />').prop('labels') == null){
webshims.defineNodeNamesProperty('button, input, keygen, meter, output, progress, select, textarea', 'labels', {
prop: {
get: function(){
if(this.type == 'hidden'){return null;}
var id = this.id;
var labels = $(this)
.closest('label')
.filter(function(){
var hFor = (this.attributes['for'] || {});
return (!hFor.specified || hFor.value == id);
})
;
if(id) {
labels = labels.add('label[for="'+ id +'"]');
}
return labels.get();
},
writeable: false
}
});
}
});
| GuanyemBarcelona/apoyos | js/vendor/js-webshim/dev/shims/combos/29.js | JavaScript | agpl-3.0 | 23,472 |
window.onload = function() {
/*
* Network
* Demonstration of using the Moebio Framework and its random network generator
* to create a random network and display it on the canvas. Uses the
*
*/
var network;
var N_NODES = 2000; // Number of nodes to put in visualization
var P_RELATION = 0.0006; //probablity that any two nodes are connected
new mo.Graphics({
container: "#maindiv",
/*
* init
* All Moebio Framework visualizations use init to setup variables.
* These variables are used in the cycle function.
*/
init: function(){
// create a sample network using NetworkGenerators
network = mo.NetworkGenerators.createRandomNetwork(N_NODES, P_RELATION, 1);
this.forces = new mo.Forces({
dEqSprings:30,
dEqRepulsors:120,
k:0.001,
friction:0.9
});
// apply the forces to the network
this.forces.forcesForNetwork(network, 400, new mo.Point(0, 0), 1, true);
},
/*
* The cycle function is called repeatedly to display the visualization.
* Here we render the network for each iteration.
*/
cycle: function(){
var i;
var node;
var relation;
var isOverCircle;
var iOver = null;
// update the forces applied to this network
this.forces.calculate();
this.forces.applyForces();
// set the drawing stroke to be black and thin
this.setStroke('black', 0.2);
// for each edge in the network, create a line connecting them
for(i=0; network.relationList[i] != null; i++){
relation = network.relationList[i];
// cX, cY are the coordinates of the center of the canvas
this.line(relation.node0.x + this.cX, relation.node0.y + this.cY,
relation.node1.x + this.cX, relation.node1.y+ this.cY
);
}
this.setFill('black');
// for each node in the network, draw it
for(i=0; network.nodeList[i] != null; i++){
node = network.nodeList[i];
// draws a node with radius = (2x number of node connections + 2) px, and detects wether the cursor is hovering
isOverCircle = this.fCircleM(node.x + this.cX, node.y + this.cY, 2*node.nodeList.length+2);
if(isOverCircle) {
iOver = i;
}
}
// for the circle that is being hovered over,
// if it exists, make a outlined circle
if(iOver != null){
this.setStroke('black', 4);
node = network.nodeList[iOver];
this.sCircle(node.x + this.cX, node.y + this.cY, 2*node.nodeList.length + 10);
this.setCursor('pointer');
}
}
});
};
| micahstubbs/moebio_framework | examples/network/network.js | JavaScript | mit | 2,659 |
module.exports = (function(Nodal) {
'use strict';
const async = require('async');
let expect = require('chai').expect;
describe('Nodal.API', function() {
let schemaPost = {
table: 'posts',
columns: [
{name: 'id', type: 'serial'},
{name: 'title', type: 'string'},
{name: 'body', type: 'string'},
{name: 'created_at', type: 'datetime'},
{name: 'updated_at', type: 'datetime'}
]
};
class Post extends Nodal.Model {}
Post.setSchema(schemaPost);
it('should output one post properly', () => {
let post = new Post({title: 'Howdy', body: 'hello world'});
let output = Nodal.API.format(post);
expect(output).to.have.ownProperty('meta');
expect(output).to.have.ownProperty('data');
expect(output.data.length).to.equal(1);
expect(output.data[0].title).to.equal('Howdy');
expect(output.meta.count).to.equal(1);
expect(output.meta.total).to.equal(1);
expect(output.meta.offset).to.equal(0);
});
it('should output posts properly', () => {
let posts = Nodal.ModelArray.from([
new Post({title: 'What', body: 'Test post A'}),
new Post({title: 'Who', body: 'Test post B'}),
new Post({title: 'When', body: 'Test post C'}),
new Post({title: 'Where', body: 'Test post D'}),
]);
posts.setMeta({offset: 1, total: 10});
let output = Nodal.API.format(posts);
expect(output).to.have.ownProperty('meta');
expect(output).to.have.ownProperty('data');
expect(output.data.length).to.equal(4);
expect(output.data[0].title).to.equal('What');
expect(output.data[3].title).to.equal('Where');
expect(output.meta.count).to.equal(4);
expect(output.meta.total).to.equal(10);
expect(output.meta.offset).to.equal(1);
});
it('should format ItemArrays properly', () => {
let groups = Nodal.ItemArray.from([
{count: 5, color: 'red'},
{count: 6, color: 'green'},
{count: 7, color: 'blue'}
]);
groups.setMeta({offset: 1, total: 10});
let output = Nodal.API.format(groups);
expect(output).to.have.ownProperty('meta');
expect(output).to.have.ownProperty('data');
expect(output.data.length).to.equal(3);
expect(output.data[0].color).to.equal('red');
expect(output.data[2].color).to.equal('blue');
expect(output.meta.count).to.equal(3);
expect(output.meta.total).to.equal(10);
expect(output.meta.offset).to.equal(1);
});
it('should format ItemArrays properly with include', () => {
let groups = Nodal.ItemArray.from([
{count: 5, color: 'red'},
{count: 6, color: 'green'},
{count: 7, color: 'blue'}
]);
groups.setMeta({offset: 1, total: 10});
let output = Nodal.API.format(groups, ['color']);
expect(output).to.have.ownProperty('meta');
expect(output).to.have.ownProperty('data');
expect(output.data.length).to.equal(3);
expect(output.data[0]).to.haveOwnProperty('color');
expect(output.data[0]).to.not.haveOwnProperty('count');
});
});
});
| nsipplswezey/nodal | test/tests/api.js | JavaScript | mit | 3,168 |
/**
* Copyright 2015 Telerik AD
*
* 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(f, define){
define([], f);
})(function(){
(function( window, undefined ) {
var kendo = window.kendo || (window.kendo = { cultures: {} });
kendo.cultures["es-GT"] = {
name: "es-GT",
numberFormat: {
pattern: ["-n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
percent: {
pattern: ["-n%","n%"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
symbol: "%"
},
currency: {
pattern: ["-$n","$n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
symbol: "Q"
}
},
calendars: {
standard: {
days: {
names: ["domingo","lunes","martes","miércoles","jueves","viernes","sábado"],
namesAbbr: ["dom.","lun.","mar.","mié.","jue.","vie.","sáb."],
namesShort: ["do.","lu.","ma.","mi.","ju.","vi.","sá."]
},
months: {
names: ["enero","febrero","marzo","abril","mayo","junio","julio","agosto","septiembre","octubre","noviembre","diciembre"],
namesAbbr: ["ene.","feb.","mar.","abr.","may.","jun.","jul.","ago.","sep.","oct.","nov.","dic."]
},
AM: ["a. m.","a. m.","A. M."],
PM: ["p. m.","p. m.","P. M."],
patterns: {
d: "dd/MM/yyyy",
D: "dddd, dd' de 'MMMM' de 'yyyy",
F: "dddd, dd' de 'MMMM' de 'yyyy h:mm:ss tt",
g: "dd/MM/yyyy h:mm tt",
G: "dd/MM/yyyy h:mm:ss tt",
m: "d' de 'MMMM",
M: "d' de 'MMMM",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "h:mm tt",
T: "h:mm:ss tt",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "MMMM' de 'yyyy",
Y: "MMMM' de 'yyyy"
},
"/": "/",
":": ":",
firstDay: 1
}
}
}
})(this);
return window.kendo;
}, typeof define == 'function' && define.amd ? define : function(_, f){ f(); }); | burkeholland/itunes-artist-search | app/components/kendo-ui-core/src/js/cultures/kendo.culture.es-GT.js | JavaScript | mit | 3,015 |
import _ from 'lodash'
import cx from 'classnames'
import React, { PropTypes } from 'react'
import {
customPropTypes,
getElementType,
getUnhandledProps,
META,
} from '../../lib'
/**
* A card can contain a description with one or more paragraphs
*/
function CardDescription(props) {
const { children, className, content } = props
const classes = cx(className, 'description')
const rest = getUnhandledProps(CardDescription, props)
const ElementType = getElementType(CardDescription, props)
return <ElementType {...rest} className={classes}>{_.isNil(children) ? content : children}</ElementType>
}
CardDescription._meta = {
name: 'CardDescription',
parent: 'Card',
type: META.TYPES.VIEW,
}
CardDescription.propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** Primary content. */
children: PropTypes.node,
/** Additional classes. */
className: PropTypes.string,
/** Shorthand for primary content. */
content: customPropTypes.contentShorthand,
}
export default CardDescription
| vageeshb/Semantic-UI-React | src/views/Card/CardDescription.js | JavaScript | mit | 1,070 |
'use strict';
const common = require('../common');
if (!common.hasCrypto)
common.skip('missing crypto');
const http2 = require('http2');
let client;
let req;
const server = http2.createServer();
server.on('stream', common.mustCall((stream) => {
stream.on('error', common.mustCall(() => {
client.close();
stream.on('close', common.mustCall(() => {
server.close();
}));
}));
req.close(2);
}));
server.listen(0, common.mustCall(() => {
client = http2.connect(`http://localhost:${server.address().port}`);
req = client.request();
req.resume();
req.on('error', common.mustCall(() => {
req.on('close', common.mustCall());
}));
}));
| enclose-io/compiler | lts/test/parallel/test-http2-stream-destroy-event-order.js | JavaScript | mit | 669 |
/*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v1.1.0
*/
(function( window, angular, undefined ){
"use strict";
/**
* @ngdoc module
* @name material.components.datepicker
* @description Module for the datepicker component.
*/
angular.module('material.components.datepicker', [
'material.core',
'material.components.icon',
'material.components.virtualRepeat'
]);
(function() {
'use strict';
/**
* @ngdoc directive
* @name mdCalendar
* @module material.components.datepicker
*
* @param {Date} ng-model The component's model. Should be a Date object.
* @param {Date=} md-min-date Expression representing the minimum date.
* @param {Date=} md-max-date Expression representing the maximum date.
* @param {(function(Date): boolean)=} md-date-filter Function expecting a date and returning a boolean whether it can be selected or not.
*
* @description
* `<md-calendar>` is a component that renders a calendar that can be used to select a date.
* It is a part of the `<md-datepicker` pane, however it can also be used on it's own.
*
* @usage
*
* <hljs lang="html">
* <md-calendar ng-model="birthday"></md-calendar>
* </hljs>
*/
angular.module('material.components.datepicker')
.directive('mdCalendar', calendarDirective);
// POST RELEASE
// TODO(jelbourn): Mac Cmd + left / right == Home / End
// TODO(jelbourn): Refactor month element creation to use cloneNode (performance).
// TODO(jelbourn): Define virtual scrolling constants (compactness) users can override.
// TODO(jelbourn): Animated month transition on ng-model change (virtual-repeat)
// TODO(jelbourn): Scroll snapping (virtual repeat)
// TODO(jelbourn): Remove superfluous row from short months (virtual-repeat)
// TODO(jelbourn): Month headers stick to top when scrolling.
// TODO(jelbourn): Previous month opacity is lowered when partially scrolled out of view.
// TODO(jelbourn): Support md-calendar standalone on a page (as a tabstop w/ aria-live
// announcement and key handling).
// Read-only calendar (not just date-picker).
function calendarDirective() {
return {
template: function(tElement, tAttr) {
// TODO(crisbeto): This is a workaround that allows the calendar to work, without
// a datepicker, until issue #8585 gets resolved. It can safely be removed
// afterwards. This ensures that the virtual repeater scrolls to the proper place on load by
// deferring the execution until the next digest. It's necessary only if the calendar is used
// without a datepicker, otherwise it's already wrapped in an ngIf.
var extraAttrs = tAttr.hasOwnProperty('ngIf') ? '' : 'ng-if="calendarCtrl.isInitialized"';
var template = '' +
'<div ng-switch="calendarCtrl.currentView" ' + extraAttrs + '>' +
'<md-calendar-year ng-switch-when="year"></md-calendar-year>' +
'<md-calendar-month ng-switch-default></md-calendar-month>' +
'</div>';
return template;
},
scope: {
minDate: '=mdMinDate',
maxDate: '=mdMaxDate',
dateFilter: '=mdDateFilter',
_currentView: '@mdCurrentView'
},
require: ['ngModel', 'mdCalendar'],
controller: CalendarCtrl,
controllerAs: 'calendarCtrl',
bindToController: true,
link: function(scope, element, attrs, controllers) {
var ngModelCtrl = controllers[0];
var mdCalendarCtrl = controllers[1];
mdCalendarCtrl.configureNgModel(ngModelCtrl);
}
};
}
/**
* Occasionally the hideVerticalScrollbar method might read an element's
* width as 0, because it hasn't been laid out yet. This value will be used
* as a fallback, in order to prevent scenarios where the element's width
* would otherwise have been set to 0. This value is the "usual" width of a
* calendar within a floating calendar pane.
*/
var FALLBACK_WIDTH = 340;
/** Next identifier for calendar instance. */
var nextUniqueId = 0;
/**
* Controller for the mdCalendar component.
* ngInject @constructor
*/
function CalendarCtrl($element, $scope, $$mdDateUtil, $mdUtil,
$mdConstant, $mdTheming, $$rAF, $attrs) {
$mdTheming($element);
/** @final {!angular.JQLite} */
this.$element = $element;
/** @final {!angular.Scope} */
this.$scope = $scope;
/** @final */
this.dateUtil = $$mdDateUtil;
/** @final */
this.$mdUtil = $mdUtil;
/** @final */
this.keyCode = $mdConstant.KEY_CODE;
/** @final */
this.$$rAF = $$rAF;
/** @final {Date} */
this.today = this.dateUtil.createDateAtMidnight();
/** @type {!angular.NgModelController} */
this.ngModelCtrl = null;
/**
* The currently visible calendar view. Note the prefix on the scope value,
* which is necessary, because the datepicker seems to reset the real one value if the
* calendar is open, but the value on the datepicker's scope is empty.
* @type {String}
*/
this.currentView = this._currentView || 'month';
/** @type {String} Class applied to the selected date cell. */
this.SELECTED_DATE_CLASS = 'md-calendar-selected-date';
/** @type {String} Class applied to the cell for today. */
this.TODAY_CLASS = 'md-calendar-date-today';
/** @type {String} Class applied to the focused cell. */
this.FOCUSED_DATE_CLASS = 'md-focus';
/** @final {number} Unique ID for this calendar instance. */
this.id = nextUniqueId++;
/**
* The date that is currently focused or showing in the calendar. This will initially be set
* to the ng-model value if set, otherwise to today. It will be updated as the user navigates
* to other months. The cell corresponding to the displayDate does not necesarily always have
* focus in the document (such as for cases when the user is scrolling the calendar).
* @type {Date}
*/
this.displayDate = null;
/**
* The selected date. Keep track of this separately from the ng-model value so that we
* can know, when the ng-model value changes, what the previous value was before it's updated
* in the component's UI.
*
* @type {Date}
*/
this.selectedDate = null;
/**
* Used to toggle initialize the root element in the next digest.
* @type {Boolean}
*/
this.isInitialized = false;
/**
* Cache for the width of the element without a scrollbar. Used to hide the scrollbar later on
* and to avoid extra reflows when switching between views.
* @type {Number}
*/
this.width = 0;
/**
* Caches the width of the scrollbar in order to be used when hiding it and to avoid extra reflows.
* @type {Number}
*/
this.scrollbarWidth = 0;
// Unless the user specifies so, the calendar should not be a tab stop.
// This is necessary because ngAria might add a tabindex to anything with an ng-model
// (based on whether or not the user has turned that particular feature on/off).
if (!$attrs.tabindex) {
$element.attr('tabindex', '-1');
}
$element.on('keydown', angular.bind(this, this.handleKeyEvent));
}
CalendarCtrl.$inject = ["$element", "$scope", "$$mdDateUtil", "$mdUtil", "$mdConstant", "$mdTheming", "$$rAF", "$attrs"];
/**
* Sets up the controller's reference to ngModelController.
* @param {!angular.NgModelController} ngModelCtrl
*/
CalendarCtrl.prototype.configureNgModel = function(ngModelCtrl) {
var self = this;
self.ngModelCtrl = ngModelCtrl;
self.$mdUtil.nextTick(function() {
self.isInitialized = true;
});
ngModelCtrl.$render = function() {
var value = this.$viewValue;
// Notify the child scopes of any changes.
self.$scope.$broadcast('md-calendar-parent-changed', value);
// Set up the selectedDate if it hasn't been already.
if (!self.selectedDate) {
self.selectedDate = value;
}
// Also set up the displayDate.
if (!self.displayDate) {
self.displayDate = self.selectedDate || self.today;
}
};
};
/**
* Sets the ng-model value for the calendar and emits a change event.
* @param {Date} date
*/
CalendarCtrl.prototype.setNgModelValue = function(date) {
var value = this.dateUtil.createDateAtMidnight(date);
this.focus(value);
this.$scope.$emit('md-calendar-change', value);
this.ngModelCtrl.$setViewValue(value);
this.ngModelCtrl.$render();
return value;
};
/**
* Sets the current view that should be visible in the calendar
* @param {string} newView View name to be set.
* @param {number|Date} time Date object or a timestamp for the new display date.
*/
CalendarCtrl.prototype.setCurrentView = function(newView, time) {
var self = this;
self.$mdUtil.nextTick(function() {
self.currentView = newView;
if (time) {
self.displayDate = angular.isDate(time) ? time : new Date(time);
}
});
};
/**
* Focus the cell corresponding to the given date.
* @param {Date} date The date to be focused.
*/
CalendarCtrl.prototype.focus = function(date) {
if (this.dateUtil.isValidDate(date)) {
var previousFocus = this.$element[0].querySelector('.md-focus');
if (previousFocus) {
previousFocus.classList.remove(this.FOCUSED_DATE_CLASS);
}
var cellId = this.getDateId(date, this.currentView);
var cell = document.getElementById(cellId);
if (cell) {
cell.classList.add(this.FOCUSED_DATE_CLASS);
cell.focus();
this.displayDate = date;
}
} else {
var rootElement = this.$element[0].querySelector('[ng-switch]');
if (rootElement) {
rootElement.focus();
}
}
};
/**
* Normalizes the key event into an action name. The action will be broadcast
* to the child controllers.
* @param {KeyboardEvent} event
* @returns {String} The action that should be taken, or null if the key
* does not match a calendar shortcut.
*/
CalendarCtrl.prototype.getActionFromKeyEvent = function(event) {
var keyCode = this.keyCode;
switch (event.which) {
case keyCode.ENTER: return 'select';
case keyCode.RIGHT_ARROW: return 'move-right';
case keyCode.LEFT_ARROW: return 'move-left';
// TODO(crisbeto): Might want to reconsider using metaKey, because it maps
// to the "Windows" key on PC, which opens the start menu or resizes the browser.
case keyCode.DOWN_ARROW: return event.metaKey ? 'move-page-down' : 'move-row-down';
case keyCode.UP_ARROW: return event.metaKey ? 'move-page-up' : 'move-row-up';
case keyCode.PAGE_DOWN: return 'move-page-down';
case keyCode.PAGE_UP: return 'move-page-up';
case keyCode.HOME: return 'start';
case keyCode.END: return 'end';
default: return null;
}
};
/**
* Handles a key event in the calendar with the appropriate action. The action will either
* be to select the focused date or to navigate to focus a new date.
* @param {KeyboardEvent} event
*/
CalendarCtrl.prototype.handleKeyEvent = function(event) {
var self = this;
this.$scope.$apply(function() {
// Capture escape and emit back up so that a wrapping component
// (such as a date-picker) can decide to close.
if (event.which == self.keyCode.ESCAPE || event.which == self.keyCode.TAB) {
self.$scope.$emit('md-calendar-close');
if (event.which == self.keyCode.TAB) {
event.preventDefault();
}
return;
}
// Broadcast the action that any child controllers should take.
var action = self.getActionFromKeyEvent(event);
if (action) {
event.preventDefault();
event.stopPropagation();
self.$scope.$broadcast('md-calendar-parent-action', action);
}
});
};
/**
* Hides the vertical scrollbar on the calendar scroller of a child controller by
* setting the width on the calendar scroller and the `overflow: hidden` wrapper
* around the scroller, and then setting a padding-right on the scroller equal
* to the width of the browser's scrollbar.
*
* This will cause a reflow.
*
* @param {object} childCtrl The child controller whose scrollbar should be hidden.
*/
CalendarCtrl.prototype.hideVerticalScrollbar = function(childCtrl) {
var self = this;
var element = childCtrl.$element[0];
var scrollMask = element.querySelector('.md-calendar-scroll-mask');
if (self.width > 0) {
setWidth();
} else {
self.$$rAF(function() {
var scroller = childCtrl.calendarScroller;
self.scrollbarWidth = scroller.offsetWidth - scroller.clientWidth;
self.width = element.querySelector('table').offsetWidth;
setWidth();
});
}
function setWidth() {
var width = self.width || FALLBACK_WIDTH;
var scrollbarWidth = self.scrollbarWidth;
var scroller = childCtrl.calendarScroller;
scrollMask.style.width = width + 'px';
scroller.style.width = (width + scrollbarWidth) + 'px';
scroller.style.paddingRight = scrollbarWidth + 'px';
}
};
/**
* Gets an identifier for a date unique to the calendar instance for internal
* purposes. Not to be displayed.
* @param {Date} date The date for which the id is being generated
* @param {string} namespace Namespace for the id. (month, year etc.)
* @returns {string}
*/
CalendarCtrl.prototype.getDateId = function(date, namespace) {
if (!namespace) {
throw new Error('A namespace for the date id has to be specified.');
}
return [
'md',
this.id,
namespace,
date.getFullYear(),
date.getMonth(),
date.getDate()
].join('-');
};
/**
* Util to trigger an extra digest on a parent scope, in order to to ensure that
* any child virtual repeaters have updated. This is necessary, because the virtual
* repeater doesn't update the $index the first time around since the content isn't
* in place yet. The case, in which this is an issue, is when the repeater has less
* than a page of content (e.g. a month or year view has a min or max date).
*/
CalendarCtrl.prototype.updateVirtualRepeat = function() {
var scope = this.$scope;
var virtualRepeatResizeListener = scope.$on('$md-resize-enable', function() {
if (!scope.$$phase) {
scope.$apply();
}
virtualRepeatResizeListener();
});
};
})();
(function() {
'use strict';
angular.module('material.components.datepicker')
.directive('mdCalendarMonth', calendarDirective);
/**
* Height of one calendar month tbody. This must be made known to the virtual-repeat and is
* subsequently used for scrolling to specific months.
*/
var TBODY_HEIGHT = 265;
/**
* Height of a calendar month with a single row. This is needed to calculate the offset for
* rendering an extra month in virtual-repeat that only contains one row.
*/
var TBODY_SINGLE_ROW_HEIGHT = 45;
/** Private directive that represents a list of months inside the calendar. */
function calendarDirective() {
return {
template:
'<table aria-hidden="true" class="md-calendar-day-header"><thead></thead></table>' +
'<div class="md-calendar-scroll-mask">' +
'<md-virtual-repeat-container class="md-calendar-scroll-container" ' +
'md-offset-size="' + (TBODY_SINGLE_ROW_HEIGHT - TBODY_HEIGHT) + '">' +
'<table role="grid" tabindex="0" class="md-calendar" aria-readonly="true">' +
'<tbody ' +
'md-calendar-month-body ' +
'role="rowgroup" ' +
'md-virtual-repeat="i in monthCtrl.items" ' +
'md-month-offset="$index" ' +
'class="md-calendar-month" ' +
'md-start-index="monthCtrl.getSelectedMonthIndex()" ' +
'md-item-size="' + TBODY_HEIGHT + '"></tbody>' +
'</table>' +
'</md-virtual-repeat-container>' +
'</div>',
require: ['^^mdCalendar', 'mdCalendarMonth'],
controller: CalendarMonthCtrl,
controllerAs: 'monthCtrl',
bindToController: true,
link: function(scope, element, attrs, controllers) {
var calendarCtrl = controllers[0];
var monthCtrl = controllers[1];
monthCtrl.initialize(calendarCtrl);
}
};
}
/**
* Controller for the calendar month component.
* ngInject @constructor
*/
function CalendarMonthCtrl($element, $scope, $animate, $q,
$$mdDateUtil, $mdDateLocale) {
/** @final {!angular.JQLite} */
this.$element = $element;
/** @final {!angular.Scope} */
this.$scope = $scope;
/** @final {!angular.$animate} */
this.$animate = $animate;
/** @final {!angular.$q} */
this.$q = $q;
/** @final */
this.dateUtil = $$mdDateUtil;
/** @final */
this.dateLocale = $mdDateLocale;
/** @final {HTMLElement} */
this.calendarScroller = $element[0].querySelector('.md-virtual-repeat-scroller');
/** @type {Date} */
this.firstRenderableDate = null;
/** @type {boolean} */
this.isInitialized = false;
/** @type {boolean} */
this.isMonthTransitionInProgress = false;
var self = this;
/**
* Handles a click event on a date cell.
* Created here so that every cell can use the same function instance.
* @this {HTMLTableCellElement} The cell that was clicked.
*/
this.cellClickHandler = function() {
var timestamp = $$mdDateUtil.getTimestampFromNode(this);
self.$scope.$apply(function() {
self.calendarCtrl.setNgModelValue(timestamp);
});
};
/**
* Handles click events on the month headers. Switches
* the calendar to the year view.
* @this {HTMLTableCellElement} The cell that was clicked.
*/
this.headerClickHandler = function() {
self.calendarCtrl.setCurrentView('year', $$mdDateUtil.getTimestampFromNode(this));
};
}
CalendarMonthCtrl.$inject = ["$element", "$scope", "$animate", "$q", "$$mdDateUtil", "$mdDateLocale"];
/*** Initialization ***/
/**
* Initialize the controller by saving a reference to the calendar and
* setting up the object that will be iterated by the virtual repeater.
*/
CalendarMonthCtrl.prototype.initialize = function(calendarCtrl) {
var minDate = calendarCtrl.minDate;
var maxDate = calendarCtrl.maxDate;
this.calendarCtrl = calendarCtrl;
/**
* Dummy array-like object for virtual-repeat to iterate over. The length is the total
* number of months that can be viewed. This is shorter than ideal because of (potential)
* Firefox bug https://bugzilla.mozilla.org/show_bug.cgi?id=1181658.
*/
this.items = { length: 2000 };
if (maxDate && minDate) {
// Limit the number of months if min and max dates are set.
var numMonths = this.dateUtil.getMonthDistance(minDate, maxDate) + 1;
numMonths = Math.max(numMonths, 1);
// Add an additional month as the final dummy month for rendering purposes.
numMonths += 1;
this.items.length = numMonths;
}
this.firstRenderableDate = this.dateUtil.incrementMonths(calendarCtrl.today, -this.items.length / 2);
if (minDate && minDate > this.firstRenderableDate) {
this.firstRenderableDate = minDate;
} else if (maxDate) {
// Calculate the difference between the start date and max date.
// Subtract 1 because it's an inclusive difference and 1 for the final dummy month.
var monthDifference = this.items.length - 2;
this.firstRenderableDate = this.dateUtil.incrementMonths(maxDate, -(this.items.length - 2));
}
this.attachScopeListeners();
calendarCtrl.updateVirtualRepeat();
// Fire the initial render, since we might have missed it the first time it fired.
calendarCtrl.ngModelCtrl && calendarCtrl.ngModelCtrl.$render();
};
/**
* Gets the "index" of the currently selected date as it would be in the virtual-repeat.
* @returns {number}
*/
CalendarMonthCtrl.prototype.getSelectedMonthIndex = function() {
var calendarCtrl = this.calendarCtrl;
return this.dateUtil.getMonthDistance(this.firstRenderableDate,
calendarCtrl.displayDate || calendarCtrl.selectedDate || calendarCtrl.today);
};
/**
* Change the selected date in the calendar (ngModel value has already been changed).
* @param {Date} date
*/
CalendarMonthCtrl.prototype.changeSelectedDate = function(date) {
var self = this;
var calendarCtrl = self.calendarCtrl;
var previousSelectedDate = calendarCtrl.selectedDate;
calendarCtrl.selectedDate = date;
this.changeDisplayDate(date).then(function() {
var selectedDateClass = calendarCtrl.SELECTED_DATE_CLASS;
var namespace = 'month';
// Remove the selected class from the previously selected date, if any.
if (previousSelectedDate) {
var prevDateCell = document.getElementById(calendarCtrl.getDateId(previousSelectedDate, namespace));
if (prevDateCell) {
prevDateCell.classList.remove(selectedDateClass);
prevDateCell.setAttribute('aria-selected', 'false');
}
}
// Apply the select class to the new selected date if it is set.
if (date) {
var dateCell = document.getElementById(calendarCtrl.getDateId(date, namespace));
if (dateCell) {
dateCell.classList.add(selectedDateClass);
dateCell.setAttribute('aria-selected', 'true');
}
}
});
};
/**
* Change the date that is being shown in the calendar. If the given date is in a different
* month, the displayed month will be transitioned.
* @param {Date} date
*/
CalendarMonthCtrl.prototype.changeDisplayDate = function(date) {
// Initialization is deferred until this function is called because we want to reflect
// the starting value of ngModel.
if (!this.isInitialized) {
this.buildWeekHeader();
this.calendarCtrl.hideVerticalScrollbar(this);
this.isInitialized = true;
return this.$q.when();
}
// If trying to show an invalid date or a transition is in progress, do nothing.
if (!this.dateUtil.isValidDate(date) || this.isMonthTransitionInProgress) {
return this.$q.when();
}
this.isMonthTransitionInProgress = true;
var animationPromise = this.animateDateChange(date);
this.calendarCtrl.displayDate = date;
var self = this;
animationPromise.then(function() {
self.isMonthTransitionInProgress = false;
});
return animationPromise;
};
/**
* Animates the transition from the calendar's current month to the given month.
* @param {Date} date
* @returns {angular.$q.Promise} The animation promise.
*/
CalendarMonthCtrl.prototype.animateDateChange = function(date) {
if (this.dateUtil.isValidDate(date)) {
var monthDistance = this.dateUtil.getMonthDistance(this.firstRenderableDate, date);
this.calendarScroller.scrollTop = monthDistance * TBODY_HEIGHT;
}
return this.$q.when();
};
/**
* Builds and appends a day-of-the-week header to the calendar.
* This should only need to be called once during initialization.
*/
CalendarMonthCtrl.prototype.buildWeekHeader = function() {
var firstDayOfWeek = this.dateLocale.firstDayOfWeek;
var shortDays = this.dateLocale.shortDays;
var row = document.createElement('tr');
for (var i = 0; i < 7; i++) {
var th = document.createElement('th');
th.textContent = shortDays[(i + firstDayOfWeek) % 7];
row.appendChild(th);
}
this.$element.find('thead').append(row);
};
/**
* Attaches listeners for the scope events that are broadcast by the calendar.
*/
CalendarMonthCtrl.prototype.attachScopeListeners = function() {
var self = this;
self.$scope.$on('md-calendar-parent-changed', function(event, value) {
self.changeSelectedDate(value);
});
self.$scope.$on('md-calendar-parent-action', angular.bind(this, this.handleKeyEvent));
};
/**
* Handles the month-specific keyboard interactions.
* @param {Object} event Scope event object passed by the calendar.
* @param {String} action Action, corresponding to the key that was pressed.
*/
CalendarMonthCtrl.prototype.handleKeyEvent = function(event, action) {
var calendarCtrl = this.calendarCtrl;
var displayDate = calendarCtrl.displayDate;
if (action === 'select') {
calendarCtrl.setNgModelValue(displayDate);
} else {
var date = null;
var dateUtil = this.dateUtil;
switch (action) {
case 'move-right': date = dateUtil.incrementDays(displayDate, 1); break;
case 'move-left': date = dateUtil.incrementDays(displayDate, -1); break;
case 'move-page-down': date = dateUtil.incrementMonths(displayDate, 1); break;
case 'move-page-up': date = dateUtil.incrementMonths(displayDate, -1); break;
case 'move-row-down': date = dateUtil.incrementDays(displayDate, 7); break;
case 'move-row-up': date = dateUtil.incrementDays(displayDate, -7); break;
case 'start': date = dateUtil.getFirstDateOfMonth(displayDate); break;
case 'end': date = dateUtil.getLastDateOfMonth(displayDate); break;
}
if (date) {
date = this.dateUtil.clampDate(date, calendarCtrl.minDate, calendarCtrl.maxDate);
this.changeDisplayDate(date).then(function() {
calendarCtrl.focus(date);
});
}
}
};
})();
(function() {
'use strict';
angular.module('material.components.datepicker')
.directive('mdCalendarMonthBody', mdCalendarMonthBodyDirective);
/**
* Private directive consumed by md-calendar-month. Having this directive lets the calender use
* md-virtual-repeat and also cleanly separates the month DOM construction functions from
* the rest of the calendar controller logic.
* ngInject
*/
function mdCalendarMonthBodyDirective($compile, $$mdSvgRegistry) {
var ARROW_ICON = $compile('<md-icon md-svg-src="' +
$$mdSvgRegistry.mdTabsArrow + '"></md-icon>')({})[0];
return {
require: ['^^mdCalendar', '^^mdCalendarMonth', 'mdCalendarMonthBody'],
scope: { offset: '=mdMonthOffset' },
controller: CalendarMonthBodyCtrl,
controllerAs: 'mdMonthBodyCtrl',
bindToController: true,
link: function(scope, element, attrs, controllers) {
var calendarCtrl = controllers[0];
var monthCtrl = controllers[1];
var monthBodyCtrl = controllers[2];
monthBodyCtrl.calendarCtrl = calendarCtrl;
monthBodyCtrl.monthCtrl = monthCtrl;
monthBodyCtrl.arrowIcon = ARROW_ICON.cloneNode(true);
monthBodyCtrl.generateContent();
// The virtual-repeat re-uses the same DOM elements, so there are only a limited number
// of repeated items that are linked, and then those elements have their bindings updated.
// Since the months are not generated by bindings, we simply regenerate the entire thing
// when the binding (offset) changes.
scope.$watch(function() { return monthBodyCtrl.offset; }, function(offset, oldOffset) {
if (offset !== oldOffset) {
monthBodyCtrl.generateContent();
}
});
}
};
}
mdCalendarMonthBodyDirective.$inject = ["$compile", "$$mdSvgRegistry"];
/**
* Controller for a single calendar month.
* ngInject @constructor
*/
function CalendarMonthBodyCtrl($element, $$mdDateUtil, $mdDateLocale) {
/** @final {!angular.JQLite} */
this.$element = $element;
/** @final */
this.dateUtil = $$mdDateUtil;
/** @final */
this.dateLocale = $mdDateLocale;
/** @type {Object} Reference to the month view. */
this.monthCtrl = null;
/** @type {Object} Reference to the calendar. */
this.calendarCtrl = null;
/**
* Number of months from the start of the month "items" that the currently rendered month
* occurs. Set via angular data binding.
* @type {number}
*/
this.offset = null;
/**
* Date cell to focus after appending the month to the document.
* @type {HTMLElement}
*/
this.focusAfterAppend = null;
}
CalendarMonthBodyCtrl.$inject = ["$element", "$$mdDateUtil", "$mdDateLocale"];
/** Generate and append the content for this month to the directive element. */
CalendarMonthBodyCtrl.prototype.generateContent = function() {
var date = this.dateUtil.incrementMonths(this.monthCtrl.firstRenderableDate, this.offset);
this.$element.empty();
this.$element.append(this.buildCalendarForMonth(date));
if (this.focusAfterAppend) {
this.focusAfterAppend.classList.add(this.calendarCtrl.FOCUSED_DATE_CLASS);
this.focusAfterAppend.focus();
this.focusAfterAppend = null;
}
};
/**
* Creates a single cell to contain a date in the calendar with all appropriate
* attributes and classes added. If a date is given, the cell content will be set
* based on the date.
* @param {Date=} opt_date
* @returns {HTMLElement}
*/
CalendarMonthBodyCtrl.prototype.buildDateCell = function(opt_date) {
var monthCtrl = this.monthCtrl;
var calendarCtrl = this.calendarCtrl;
// TODO(jelbourn): cloneNode is likely a faster way of doing this.
var cell = document.createElement('td');
cell.tabIndex = -1;
cell.classList.add('md-calendar-date');
cell.setAttribute('role', 'gridcell');
if (opt_date) {
cell.setAttribute('tabindex', '-1');
cell.setAttribute('aria-label', this.dateLocale.longDateFormatter(opt_date));
cell.id = calendarCtrl.getDateId(opt_date, 'month');
// Use `data-timestamp` attribute because IE10 does not support the `dataset` property.
cell.setAttribute('data-timestamp', opt_date.getTime());
// TODO(jelourn): Doing these comparisons for class addition during generation might be slow.
// It may be better to finish the construction and then query the node and add the class.
if (this.dateUtil.isSameDay(opt_date, calendarCtrl.today)) {
cell.classList.add(calendarCtrl.TODAY_CLASS);
}
if (this.dateUtil.isValidDate(calendarCtrl.selectedDate) &&
this.dateUtil.isSameDay(opt_date, calendarCtrl.selectedDate)) {
cell.classList.add(calendarCtrl.SELECTED_DATE_CLASS);
cell.setAttribute('aria-selected', 'true');
}
var cellText = this.dateLocale.dates[opt_date.getDate()];
if (this.isDateEnabled(opt_date)) {
// Add a indicator for select, hover, and focus states.
var selectionIndicator = document.createElement('span');
selectionIndicator.classList.add('md-calendar-date-selection-indicator');
selectionIndicator.textContent = cellText;
cell.appendChild(selectionIndicator);
cell.addEventListener('click', monthCtrl.cellClickHandler);
if (calendarCtrl.displayDate && this.dateUtil.isSameDay(opt_date, calendarCtrl.displayDate)) {
this.focusAfterAppend = cell;
}
} else {
cell.classList.add('md-calendar-date-disabled');
cell.textContent = cellText;
}
}
return cell;
};
/**
* Check whether date is in range and enabled
* @param {Date=} opt_date
* @return {boolean} Whether the date is enabled.
*/
CalendarMonthBodyCtrl.prototype.isDateEnabled = function(opt_date) {
return this.dateUtil.isDateWithinRange(opt_date,
this.calendarCtrl.minDate, this.calendarCtrl.maxDate) &&
(!angular.isFunction(this.calendarCtrl.dateFilter)
|| this.calendarCtrl.dateFilter(opt_date));
};
/**
* Builds a `tr` element for the calendar grid.
* @param rowNumber The week number within the month.
* @returns {HTMLElement}
*/
CalendarMonthBodyCtrl.prototype.buildDateRow = function(rowNumber) {
var row = document.createElement('tr');
row.setAttribute('role', 'row');
// Because of an NVDA bug (with Firefox), the row needs an aria-label in order
// to prevent the entire row being read aloud when the user moves between rows.
// See http://community.nvda-project.org/ticket/4643.
row.setAttribute('aria-label', this.dateLocale.weekNumberFormatter(rowNumber));
return row;
};
/**
* Builds the <tbody> content for the given date's month.
* @param {Date=} opt_dateInMonth
* @returns {DocumentFragment} A document fragment containing the <tr> elements.
*/
CalendarMonthBodyCtrl.prototype.buildCalendarForMonth = function(opt_dateInMonth) {
var date = this.dateUtil.isValidDate(opt_dateInMonth) ? opt_dateInMonth : new Date();
var firstDayOfMonth = this.dateUtil.getFirstDateOfMonth(date);
var firstDayOfTheWeek = this.getLocaleDay_(firstDayOfMonth);
var numberOfDaysInMonth = this.dateUtil.getNumberOfDaysInMonth(date);
// Store rows for the month in a document fragment so that we can append them all at once.
var monthBody = document.createDocumentFragment();
var rowNumber = 1;
var row = this.buildDateRow(rowNumber);
monthBody.appendChild(row);
// If this is the final month in the list of items, only the first week should render,
// so we should return immediately after the first row is complete and has been
// attached to the body.
var isFinalMonth = this.offset === this.monthCtrl.items.length - 1;
// Add a label for the month. If the month starts on a Sun/Mon/Tues, the month label
// goes on a row above the first of the month. Otherwise, the month label takes up the first
// two cells of the first row.
var blankCellOffset = 0;
var monthLabelCell = document.createElement('td');
var monthLabelCellContent = document.createElement('span');
monthLabelCellContent.textContent = this.dateLocale.monthHeaderFormatter(date);
monthLabelCell.appendChild(monthLabelCellContent);
monthLabelCell.classList.add('md-calendar-month-label');
// If the entire month is after the max date, render the label as a disabled state.
if (this.calendarCtrl.maxDate && firstDayOfMonth > this.calendarCtrl.maxDate) {
monthLabelCell.classList.add('md-calendar-month-label-disabled');
} else {
monthLabelCell.addEventListener('click', this.monthCtrl.headerClickHandler);
monthLabelCell.setAttribute('data-timestamp', firstDayOfMonth.getTime());
monthLabelCell.setAttribute('aria-label', this.dateLocale.monthFormatter(date));
monthLabelCell.appendChild(this.arrowIcon.cloneNode(true));
}
if (firstDayOfTheWeek <= 2) {
monthLabelCell.setAttribute('colspan', '7');
var monthLabelRow = this.buildDateRow();
monthLabelRow.appendChild(monthLabelCell);
monthBody.insertBefore(monthLabelRow, row);
if (isFinalMonth) {
return monthBody;
}
} else {
blankCellOffset = 3;
monthLabelCell.setAttribute('colspan', '3');
row.appendChild(monthLabelCell);
}
// Add a blank cell for each day of the week that occurs before the first of the month.
// For example, if the first day of the month is a Tuesday, add blank cells for Sun and Mon.
// The blankCellOffset is needed in cases where the first N cells are used by the month label.
for (var i = blankCellOffset; i < firstDayOfTheWeek; i++) {
row.appendChild(this.buildDateCell());
}
// Add a cell for each day of the month, keeping track of the day of the week so that
// we know when to start a new row.
var dayOfWeek = firstDayOfTheWeek;
var iterationDate = firstDayOfMonth;
for (var d = 1; d <= numberOfDaysInMonth; d++) {
// If we've reached the end of the week, start a new row.
if (dayOfWeek === 7) {
// We've finished the first row, so we're done if this is the final month.
if (isFinalMonth) {
return monthBody;
}
dayOfWeek = 0;
rowNumber++;
row = this.buildDateRow(rowNumber);
monthBody.appendChild(row);
}
iterationDate.setDate(d);
var cell = this.buildDateCell(iterationDate);
row.appendChild(cell);
dayOfWeek++;
}
// Ensure that the last row of the month has 7 cells.
while (row.childNodes.length < 7) {
row.appendChild(this.buildDateCell());
}
// Ensure that all months have 6 rows. This is necessary for now because the virtual-repeat
// requires that all items have exactly the same height.
while (monthBody.childNodes.length < 6) {
var whitespaceRow = this.buildDateRow();
for (var j = 0; j < 7; j++) {
whitespaceRow.appendChild(this.buildDateCell());
}
monthBody.appendChild(whitespaceRow);
}
return monthBody;
};
/**
* Gets the day-of-the-week index for a date for the current locale.
* @private
* @param {Date} date
* @returns {number} The column index of the date in the calendar.
*/
CalendarMonthBodyCtrl.prototype.getLocaleDay_ = function(date) {
return (date.getDay() + (7 - this.dateLocale.firstDayOfWeek)) % 7;
};
})();
(function() {
'use strict';
angular.module('material.components.datepicker')
.directive('mdCalendarYear', calendarDirective);
/**
* Height of one calendar year tbody. This must be made known to the virtual-repeat and is
* subsequently used for scrolling to specific years.
*/
var TBODY_HEIGHT = 88;
/** Private component, representing a list of years in the calendar. */
function calendarDirective() {
return {
template:
'<div class="md-calendar-scroll-mask">' +
'<md-virtual-repeat-container class="md-calendar-scroll-container">' +
'<table role="grid" tabindex="0" class="md-calendar" aria-readonly="true">' +
'<tbody ' +
'md-calendar-year-body ' +
'role="rowgroup" ' +
'md-virtual-repeat="i in yearCtrl.items" ' +
'md-year-offset="$index" class="md-calendar-year" ' +
'md-start-index="yearCtrl.getFocusedYearIndex()" ' +
'md-item-size="' + TBODY_HEIGHT + '"></tbody>' +
'</table>' +
'</md-virtual-repeat-container>' +
'</div>',
require: ['^^mdCalendar', 'mdCalendarYear'],
controller: CalendarYearCtrl,
controllerAs: 'yearCtrl',
bindToController: true,
link: function(scope, element, attrs, controllers) {
var calendarCtrl = controllers[0];
var yearCtrl = controllers[1];
yearCtrl.initialize(calendarCtrl);
}
};
}
/**
* Controller for the mdCalendar component.
* ngInject @constructor
*/
function CalendarYearCtrl($element, $scope, $animate, $q, $$mdDateUtil) {
/** @final {!angular.JQLite} */
this.$element = $element;
/** @final {!angular.Scope} */
this.$scope = $scope;
/** @final {!angular.$animate} */
this.$animate = $animate;
/** @final {!angular.$q} */
this.$q = $q;
/** @final */
this.dateUtil = $$mdDateUtil;
/** @final {HTMLElement} */
this.calendarScroller = $element[0].querySelector('.md-virtual-repeat-scroller');
/** @type {Date} */
this.firstRenderableDate = null;
/** @type {boolean} */
this.isInitialized = false;
/** @type {boolean} */
this.isMonthTransitionInProgress = false;
var self = this;
/**
* Handles a click event on a date cell.
* Created here so that every cell can use the same function instance.
* @this {HTMLTableCellElement} The cell that was clicked.
*/
this.cellClickHandler = function() {
self.calendarCtrl.setCurrentView('month', $$mdDateUtil.getTimestampFromNode(this));
};
}
CalendarYearCtrl.$inject = ["$element", "$scope", "$animate", "$q", "$$mdDateUtil"];
/**
* Initialize the controller by saving a reference to the calendar and
* setting up the object that will be iterated by the virtual repeater.
*/
CalendarYearCtrl.prototype.initialize = function(calendarCtrl) {
var minDate = calendarCtrl.minDate;
var maxDate = calendarCtrl.maxDate;
this.calendarCtrl = calendarCtrl;
/**
* Dummy array-like object for virtual-repeat to iterate over. The length is the total
* number of months that can be viewed. This is shorter than ideal because of (potential)
* Firefox bug https://bugzilla.mozilla.org/show_bug.cgi?id=1181658.
*/
this.items = { length: 400 };
this.firstRenderableDate = this.dateUtil.incrementYears(calendarCtrl.today, - (this.items.length / 2));
if (minDate && minDate > this.firstRenderableDate) {
this.firstRenderableDate = minDate;
} else if (maxDate) {
// Calculate the year difference between the start date and max date.
// Subtract 1 because it's an inclusive difference.
this.firstRenderableDate = this.dateUtil.incrementMonths(maxDate, - (this.items.length - 1));
}
if (maxDate && minDate) {
// Limit the number of years if min and max dates are set.
var numYears = this.dateUtil.getYearDistance(this.firstRenderableDate, maxDate) + 1;
this.items.length = Math.max(numYears, 1);
}
this.attachScopeListeners();
calendarCtrl.updateVirtualRepeat();
// Fire the initial render, since we might have missed it the first time it fired.
calendarCtrl.ngModelCtrl && calendarCtrl.ngModelCtrl.$render();
};
/**
* Gets the "index" of the currently selected date as it would be in the virtual-repeat.
* @returns {number}
*/
CalendarYearCtrl.prototype.getFocusedYearIndex = function() {
var calendarCtrl = this.calendarCtrl;
return this.dateUtil.getYearDistance(this.firstRenderableDate,
calendarCtrl.displayDate || calendarCtrl.selectedDate || calendarCtrl.today);
};
/**
* Change the date that is highlighted in the calendar.
* @param {Date} date
*/
CalendarYearCtrl.prototype.changeDate = function(date) {
// Initialization is deferred until this function is called because we want to reflect
// the starting value of ngModel.
if (!this.isInitialized) {
this.calendarCtrl.hideVerticalScrollbar(this);
this.isInitialized = true;
return this.$q.when();
} else if (this.dateUtil.isValidDate(date) && !this.isMonthTransitionInProgress) {
var self = this;
var animationPromise = this.animateDateChange(date);
self.isMonthTransitionInProgress = true;
self.calendarCtrl.displayDate = date;
return animationPromise.then(function() {
self.isMonthTransitionInProgress = false;
});
}
};
/**
* Animates the transition from the calendar's current month to the given month.
* @param {Date} date
* @returns {angular.$q.Promise} The animation promise.
*/
CalendarYearCtrl.prototype.animateDateChange = function(date) {
if (this.dateUtil.isValidDate(date)) {
var monthDistance = this.dateUtil.getYearDistance(this.firstRenderableDate, date);
this.calendarScroller.scrollTop = monthDistance * TBODY_HEIGHT;
}
return this.$q.when();
};
/**
* Handles the year-view-specific keyboard interactions.
* @param {Object} event Scope event object passed by the calendar.
* @param {String} action Action, corresponding to the key that was pressed.
*/
CalendarYearCtrl.prototype.handleKeyEvent = function(event, action) {
var calendarCtrl = this.calendarCtrl;
var displayDate = calendarCtrl.displayDate;
if (action === 'select') {
this.changeDate(displayDate).then(function() {
calendarCtrl.setCurrentView('month', displayDate);
calendarCtrl.focus(displayDate);
});
} else {
var date = null;
var dateUtil = this.dateUtil;
switch (action) {
case 'move-right': date = dateUtil.incrementMonths(displayDate, 1); break;
case 'move-left': date = dateUtil.incrementMonths(displayDate, -1); break;
case 'move-row-down': date = dateUtil.incrementMonths(displayDate, 6); break;
case 'move-row-up': date = dateUtil.incrementMonths(displayDate, -6); break;
}
if (date) {
var min = calendarCtrl.minDate ? dateUtil.incrementMonths(dateUtil.getFirstDateOfMonth(calendarCtrl.minDate), 1) : null;
var max = calendarCtrl.maxDate ? dateUtil.getFirstDateOfMonth(calendarCtrl.maxDate) : null;
date = dateUtil.getFirstDateOfMonth(this.dateUtil.clampDate(date, min, max));
this.changeDate(date).then(function() {
calendarCtrl.focus(date);
});
}
}
};
/**
* Attaches listeners for the scope events that are broadcast by the calendar.
*/
CalendarYearCtrl.prototype.attachScopeListeners = function() {
var self = this;
self.$scope.$on('md-calendar-parent-changed', function(event, value) {
self.changeDate(value);
});
self.$scope.$on('md-calendar-parent-action', angular.bind(self, self.handleKeyEvent));
};
})();
(function() {
'use strict';
angular.module('material.components.datepicker')
.directive('mdCalendarYearBody', mdCalendarYearDirective);
/**
* Private component, consumed by the md-calendar-year, which separates the DOM construction logic
* and allows for the year view to use md-virtual-repeat.
*/
function mdCalendarYearDirective() {
return {
require: ['^^mdCalendar', '^^mdCalendarYear', 'mdCalendarYearBody'],
scope: { offset: '=mdYearOffset' },
controller: CalendarYearBodyCtrl,
controllerAs: 'mdYearBodyCtrl',
bindToController: true,
link: function(scope, element, attrs, controllers) {
var calendarCtrl = controllers[0];
var yearCtrl = controllers[1];
var yearBodyCtrl = controllers[2];
yearBodyCtrl.calendarCtrl = calendarCtrl;
yearBodyCtrl.yearCtrl = yearCtrl;
yearBodyCtrl.generateContent();
scope.$watch(function() { return yearBodyCtrl.offset; }, function(offset, oldOffset) {
if (offset != oldOffset) {
yearBodyCtrl.generateContent();
}
});
}
};
}
/**
* Controller for a single year.
* ngInject @constructor
*/
function CalendarYearBodyCtrl($element, $$mdDateUtil, $mdDateLocale) {
/** @final {!angular.JQLite} */
this.$element = $element;
/** @final */
this.dateUtil = $$mdDateUtil;
/** @final */
this.dateLocale = $mdDateLocale;
/** @type {Object} Reference to the calendar. */
this.calendarCtrl = null;
/** @type {Object} Reference to the year view. */
this.yearCtrl = null;
/**
* Number of months from the start of the month "items" that the currently rendered month
* occurs. Set via angular data binding.
* @type {number}
*/
this.offset = null;
/**
* Date cell to focus after appending the month to the document.
* @type {HTMLElement}
*/
this.focusAfterAppend = null;
}
CalendarYearBodyCtrl.$inject = ["$element", "$$mdDateUtil", "$mdDateLocale"];
/** Generate and append the content for this year to the directive element. */
CalendarYearBodyCtrl.prototype.generateContent = function() {
var date = this.dateUtil.incrementYears(this.yearCtrl.firstRenderableDate, this.offset);
this.$element.empty();
this.$element.append(this.buildCalendarForYear(date));
if (this.focusAfterAppend) {
this.focusAfterAppend.classList.add(this.calendarCtrl.FOCUSED_DATE_CLASS);
this.focusAfterAppend.focus();
this.focusAfterAppend = null;
}
};
/**
* Creates a single cell to contain a year in the calendar.
* @param {number} opt_year Four-digit year.
* @param {number} opt_month Zero-indexed month.
* @returns {HTMLElement}
*/
CalendarYearBodyCtrl.prototype.buildMonthCell = function(year, month) {
var calendarCtrl = this.calendarCtrl;
var yearCtrl = this.yearCtrl;
var cell = this.buildBlankCell();
// Represent this month/year as a date.
var firstOfMonth = new Date(year, month, 1);
cell.setAttribute('aria-label', this.dateLocale.monthFormatter(firstOfMonth));
cell.id = calendarCtrl.getDateId(firstOfMonth, 'year');
// Use `data-timestamp` attribute because IE10 does not support the `dataset` property.
cell.setAttribute('data-timestamp', firstOfMonth.getTime());
if (this.dateUtil.isSameMonthAndYear(firstOfMonth, calendarCtrl.today)) {
cell.classList.add(calendarCtrl.TODAY_CLASS);
}
if (this.dateUtil.isValidDate(calendarCtrl.selectedDate) &&
this.dateUtil.isSameMonthAndYear(firstOfMonth, calendarCtrl.selectedDate)) {
cell.classList.add(calendarCtrl.SELECTED_DATE_CLASS);
cell.setAttribute('aria-selected', 'true');
}
var cellText = this.dateLocale.shortMonths[month];
if (this.dateUtil.isMonthWithinRange(firstOfMonth,
calendarCtrl.minDate, calendarCtrl.maxDate)) {
var selectionIndicator = document.createElement('span');
selectionIndicator.classList.add('md-calendar-date-selection-indicator');
selectionIndicator.textContent = cellText;
cell.appendChild(selectionIndicator);
cell.addEventListener('click', yearCtrl.cellClickHandler);
if (calendarCtrl.displayDate && this.dateUtil.isSameMonthAndYear(firstOfMonth, calendarCtrl.displayDate)) {
this.focusAfterAppend = cell;
}
} else {
cell.classList.add('md-calendar-date-disabled');
cell.textContent = cellText;
}
return cell;
};
/**
* Builds a blank cell.
* @return {HTMLTableCellElement}
*/
CalendarYearBodyCtrl.prototype.buildBlankCell = function() {
var cell = document.createElement('td');
cell.tabIndex = -1;
cell.classList.add('md-calendar-date');
cell.setAttribute('role', 'gridcell');
cell.setAttribute('tabindex', '-1');
return cell;
};
/**
* Builds the <tbody> content for the given year.
* @param {Date} date Date for which the content should be built.
* @returns {DocumentFragment} A document fragment containing the months within the year.
*/
CalendarYearBodyCtrl.prototype.buildCalendarForYear = function(date) {
// Store rows for the month in a document fragment so that we can append them all at once.
var year = date.getFullYear();
var yearBody = document.createDocumentFragment();
var monthCell, i;
// First row contains label and Jan-Jun.
var firstRow = document.createElement('tr');
var labelCell = document.createElement('td');
labelCell.className = 'md-calendar-month-label';
labelCell.textContent = year;
firstRow.appendChild(labelCell);
for (i = 0; i < 6; i++) {
firstRow.appendChild(this.buildMonthCell(year, i));
}
yearBody.appendChild(firstRow);
// Second row contains a blank cell and Jul-Dec.
var secondRow = document.createElement('tr');
secondRow.appendChild(this.buildBlankCell());
for (i = 6; i < 12; i++) {
secondRow.appendChild(this.buildMonthCell(year, i));
}
yearBody.appendChild(secondRow);
return yearBody;
};
})();
(function() {
'use strict';
/**
* @ngdoc service
* @name $mdDateLocaleProvider
* @module material.components.datepicker
*
* @description
* The `$mdDateLocaleProvider` is the provider that creates the `$mdDateLocale` service.
* This provider that allows the user to specify messages, formatters, and parsers for date
* internationalization. The `$mdDateLocale` service itself is consumed by Angular Material
* components that deal with dates.
*
* @property {(Array<string>)=} months Array of month names (in order).
* @property {(Array<string>)=} shortMonths Array of abbreviated month names.
* @property {(Array<string>)=} days Array of the days of the week (in order).
* @property {(Array<string>)=} shortDays Array of abbreviated dayes of the week.
* @property {(Array<string>)=} dates Array of dates of the month. Only necessary for locales
* using a numeral system other than [1, 2, 3...].
* @property {(Array<string>)=} firstDayOfWeek The first day of the week. Sunday = 0, Monday = 1,
* etc.
* @property {(function(string): Date)=} parseDate Function to parse a date object from a string.
* @property {(function(Date): string)=} formatDate Function to format a date object to a string.
* @property {(function(Date): string)=} monthHeaderFormatter Function that returns the label for
* a month given a date.
* @property {(function(Date): string)=} monthFormatter Function that returns the full name of a month
* for a giben date.
* @property {(function(number): string)=} weekNumberFormatter Function that returns a label for
* a week given the week number.
* @property {(string)=} msgCalendar Translation of the label "Calendar" for the current locale.
* @property {(string)=} msgOpenCalendar Translation of the button label "Open calendar" for the
* current locale.
*
* @usage
* <hljs lang="js">
* myAppModule.config(function($mdDateLocaleProvider) {
*
* // Example of a French localization.
* $mdDateLocaleProvider.months = ['janvier', 'février', 'mars', ...];
* $mdDateLocaleProvider.shortMonths = ['janv', 'févr', 'mars', ...];
* $mdDateLocaleProvider.days = ['dimanche', 'lundi', 'mardi', ...];
* $mdDateLocaleProvider.shortDays = ['Di', 'Lu', 'Ma', ...];
*
* // Can change week display to start on Monday.
* $mdDateLocaleProvider.firstDayOfWeek = 1;
*
* // Optional.
* $mdDateLocaleProvider.dates = [1, 2, 3, 4, 5, 6, ...];
*
* // Example uses moment.js to parse and format dates.
* $mdDateLocaleProvider.parseDate = function(dateString) {
* var m = moment(dateString, 'L', true);
* return m.isValid() ? m.toDate() : new Date(NaN);
* };
*
* $mdDateLocaleProvider.formatDate = function(date) {
* var m = moment(date);
* return m.isValid() ? m.format('L') : '';
* };
*
* $mdDateLocaleProvider.monthHeaderFormatter = function(date) {
* return myShortMonths[date.getMonth()] + ' ' + date.getFullYear();
* };
*
* // In addition to date display, date components also need localized messages
* // for aria-labels for screen-reader users.
*
* $mdDateLocaleProvider.weekNumberFormatter = function(weekNumber) {
* return 'Semaine ' + weekNumber;
* };
*
* $mdDateLocaleProvider.msgCalendar = 'Calendrier';
* $mdDateLocaleProvider.msgOpenCalendar = 'Ouvrir le calendrier';
*
* });
* </hljs>
*
*/
angular.module('material.components.datepicker').config(["$provide", function($provide) {
// TODO(jelbourn): Assert provided values are correctly formatted. Need assertions.
/** @constructor */
function DateLocaleProvider() {
/** Array of full month names. E.g., ['January', 'Febuary', ...] */
this.months = null;
/** Array of abbreviated month names. E.g., ['Jan', 'Feb', ...] */
this.shortMonths = null;
/** Array of full day of the week names. E.g., ['Monday', 'Tuesday', ...] */
this.days = null;
/** Array of abbreviated dat of the week names. E.g., ['M', 'T', ...] */
this.shortDays = null;
/** Array of dates of a month (1 - 31). Characters might be different in some locales. */
this.dates = null;
/** Index of the first day of the week. 0 = Sunday, 1 = Monday, etc. */
this.firstDayOfWeek = 0;
/**
* Function that converts the date portion of a Date to a string.
* @type {(function(Date): string)}
*/
this.formatDate = null;
/**
* Function that converts a date string to a Date object (the date portion)
* @type {function(string): Date}
*/
this.parseDate = null;
/**
* Function that formats a Date into a month header string.
* @type {function(Date): string}
*/
this.monthHeaderFormatter = null;
/**
* Function that formats a week number into a label for the week.
* @type {function(number): string}
*/
this.weekNumberFormatter = null;
/**
* Function that formats a date into a long aria-label that is read
* when the focused date changes.
* @type {function(Date): string}
*/
this.longDateFormatter = null;
/**
* ARIA label for the calendar "dialog" used in the datepicker.
* @type {string}
*/
this.msgCalendar = '';
/**
* ARIA label for the datepicker's "Open calendar" buttons.
* @type {string}
*/
this.msgOpenCalendar = '';
}
/**
* Factory function that returns an instance of the dateLocale service.
* ngInject
* @param $locale
* @returns {DateLocale}
*/
DateLocaleProvider.prototype.$get = function($locale, $filter) {
/**
* Default date-to-string formatting function.
* @param {!Date} date
* @returns {string}
*/
function defaultFormatDate(date) {
if (!date) {
return '';
}
// All of the dates created through ng-material *should* be set to midnight.
// If we encounter a date where the localeTime shows at 11pm instead of midnight,
// we have run into an issue with DST where we need to increment the hour by one:
// var d = new Date(1992, 9, 8, 0, 0, 0);
// d.toLocaleString(); // == "10/7/1992, 11:00:00 PM"
var localeTime = date.toLocaleTimeString();
var formatDate = date;
if (date.getHours() == 0 &&
(localeTime.indexOf('11:') !== -1 || localeTime.indexOf('23:') !== -1)) {
formatDate = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 1, 0, 0);
}
return $filter('date')(formatDate, 'M/d/yyyy');
}
/**
* Default string-to-date parsing function.
* @param {string} dateString
* @returns {!Date}
*/
function defaultParseDate(dateString) {
return new Date(dateString);
}
/**
* Default function to determine whether a string makes sense to be
* parsed to a Date object.
*
* This is very permissive and is just a basic sanity check to ensure that
* things like single integers aren't able to be parsed into dates.
* @param {string} dateString
* @returns {boolean}
*/
function defaultIsDateComplete(dateString) {
dateString = dateString.trim();
// Looks for three chunks of content (either numbers or text) separated
// by delimiters.
var re = /^(([a-zA-Z]{3,}|[0-9]{1,4})([ \.,]+|[\/\-])){2}([a-zA-Z]{3,}|[0-9]{1,4})$/;
return re.test(dateString);
}
/**
* Default date-to-string formatter to get a month header.
* @param {!Date} date
* @returns {string}
*/
function defaultMonthHeaderFormatter(date) {
return service.shortMonths[date.getMonth()] + ' ' + date.getFullYear();
}
/**
* Default formatter for a month.
* @param {!Date} date
* @returns {string}
*/
function defaultMonthFormatter(date) {
return service.months[date.getMonth()] + ' ' + date.getFullYear();
}
/**
* Default week number formatter.
* @param number
* @returns {string}
*/
function defaultWeekNumberFormatter(number) {
return 'Week ' + number;
}
/**
* Default formatter for date cell aria-labels.
* @param {!Date} date
* @returns {string}
*/
function defaultLongDateFormatter(date) {
// Example: 'Thursday June 18 2015'
return [
service.days[date.getDay()],
service.months[date.getMonth()],
service.dates[date.getDate()],
date.getFullYear()
].join(' ');
}
// The default "short" day strings are the first character of each day,
// e.g., "Monday" => "M".
var defaultShortDays = $locale.DATETIME_FORMATS.SHORTDAY.map(function(day) {
return day.substring(0, 1);
});
// The default dates are simply the numbers 1 through 31.
var defaultDates = Array(32);
for (var i = 1; i <= 31; i++) {
defaultDates[i] = i;
}
// Default ARIA messages are in English (US).
var defaultMsgCalendar = 'Calendar';
var defaultMsgOpenCalendar = 'Open calendar';
var service = {
months: this.months || $locale.DATETIME_FORMATS.MONTH,
shortMonths: this.shortMonths || $locale.DATETIME_FORMATS.SHORTMONTH,
days: this.days || $locale.DATETIME_FORMATS.DAY,
shortDays: this.shortDays || defaultShortDays,
dates: this.dates || defaultDates,
firstDayOfWeek: this.firstDayOfWeek || 0,
formatDate: this.formatDate || defaultFormatDate,
parseDate: this.parseDate || defaultParseDate,
isDateComplete: this.isDateComplete || defaultIsDateComplete,
monthHeaderFormatter: this.monthHeaderFormatter || defaultMonthHeaderFormatter,
monthFormatter: this.monthFormatter || defaultMonthFormatter,
weekNumberFormatter: this.weekNumberFormatter || defaultWeekNumberFormatter,
longDateFormatter: this.longDateFormatter || defaultLongDateFormatter,
msgCalendar: this.msgCalendar || defaultMsgCalendar,
msgOpenCalendar: this.msgOpenCalendar || defaultMsgOpenCalendar
};
return service;
};
DateLocaleProvider.prototype.$get.$inject = ["$locale", "$filter"];
$provide.provider('$mdDateLocale', new DateLocaleProvider());
}]);
})();
(function() {
'use strict';
/**
* Utility for performing date calculations to facilitate operation of the calendar and
* datepicker.
*/
angular.module('material.components.datepicker').factory('$$mdDateUtil', function() {
return {
getFirstDateOfMonth: getFirstDateOfMonth,
getNumberOfDaysInMonth: getNumberOfDaysInMonth,
getDateInNextMonth: getDateInNextMonth,
getDateInPreviousMonth: getDateInPreviousMonth,
isInNextMonth: isInNextMonth,
isInPreviousMonth: isInPreviousMonth,
getDateMidpoint: getDateMidpoint,
isSameMonthAndYear: isSameMonthAndYear,
getWeekOfMonth: getWeekOfMonth,
incrementDays: incrementDays,
incrementMonths: incrementMonths,
getLastDateOfMonth: getLastDateOfMonth,
isSameDay: isSameDay,
getMonthDistance: getMonthDistance,
isValidDate: isValidDate,
setDateTimeToMidnight: setDateTimeToMidnight,
createDateAtMidnight: createDateAtMidnight,
isDateWithinRange: isDateWithinRange,
incrementYears: incrementYears,
getYearDistance: getYearDistance,
clampDate: clampDate,
getTimestampFromNode: getTimestampFromNode,
isMonthWithinRange: isMonthWithinRange
};
/**
* Gets the first day of the month for the given date's month.
* @param {Date} date
* @returns {Date}
*/
function getFirstDateOfMonth(date) {
return new Date(date.getFullYear(), date.getMonth(), 1);
}
/**
* Gets the number of days in the month for the given date's month.
* @param date
* @returns {number}
*/
function getNumberOfDaysInMonth(date) {
return new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
}
/**
* Get an arbitrary date in the month after the given date's month.
* @param date
* @returns {Date}
*/
function getDateInNextMonth(date) {
return new Date(date.getFullYear(), date.getMonth() + 1, 1);
}
/**
* Get an arbitrary date in the month before the given date's month.
* @param date
* @returns {Date}
*/
function getDateInPreviousMonth(date) {
return new Date(date.getFullYear(), date.getMonth() - 1, 1);
}
/**
* Gets whether two dates have the same month and year.
* @param {Date} d1
* @param {Date} d2
* @returns {boolean}
*/
function isSameMonthAndYear(d1, d2) {
return d1.getFullYear() === d2.getFullYear() && d1.getMonth() === d2.getMonth();
}
/**
* Gets whether two dates are the same day (not not necesarily the same time).
* @param {Date} d1
* @param {Date} d2
* @returns {boolean}
*/
function isSameDay(d1, d2) {
return d1.getDate() == d2.getDate() && isSameMonthAndYear(d1, d2);
}
/**
* Gets whether a date is in the month immediately after some date.
* @param {Date} startDate The date from which to compare.
* @param {Date} endDate The date to check.
* @returns {boolean}
*/
function isInNextMonth(startDate, endDate) {
var nextMonth = getDateInNextMonth(startDate);
return isSameMonthAndYear(nextMonth, endDate);
}
/**
* Gets whether a date is in the month immediately before some date.
* @param {Date} startDate The date from which to compare.
* @param {Date} endDate The date to check.
* @returns {boolean}
*/
function isInPreviousMonth(startDate, endDate) {
var previousMonth = getDateInPreviousMonth(startDate);
return isSameMonthAndYear(endDate, previousMonth);
}
/**
* Gets the midpoint between two dates.
* @param {Date} d1
* @param {Date} d2
* @returns {Date}
*/
function getDateMidpoint(d1, d2) {
return createDateAtMidnight((d1.getTime() + d2.getTime()) / 2);
}
/**
* Gets the week of the month that a given date occurs in.
* @param {Date} date
* @returns {number} Index of the week of the month (zero-based).
*/
function getWeekOfMonth(date) {
var firstDayOfMonth = getFirstDateOfMonth(date);
return Math.floor((firstDayOfMonth.getDay() + date.getDate() - 1) / 7);
}
/**
* Gets a new date incremented by the given number of days. Number of days can be negative.
* @param {Date} date
* @param {number} numberOfDays
* @returns {Date}
*/
function incrementDays(date, numberOfDays) {
return new Date(date.getFullYear(), date.getMonth(), date.getDate() + numberOfDays);
}
/**
* Gets a new date incremented by the given number of months. Number of months can be negative.
* If the date of the given month does not match the target month, the date will be set to the
* last day of the month.
* @param {Date} date
* @param {number} numberOfMonths
* @returns {Date}
*/
function incrementMonths(date, numberOfMonths) {
// If the same date in the target month does not actually exist, the Date object will
// automatically advance *another* month by the number of missing days.
// For example, if you try to go from Jan. 30 to Feb. 30, you'll end up on March 2.
// So, we check if the month overflowed and go to the last day of the target month instead.
var dateInTargetMonth = new Date(date.getFullYear(), date.getMonth() + numberOfMonths, 1);
var numberOfDaysInMonth = getNumberOfDaysInMonth(dateInTargetMonth);
if (numberOfDaysInMonth < date.getDate()) {
dateInTargetMonth.setDate(numberOfDaysInMonth);
} else {
dateInTargetMonth.setDate(date.getDate());
}
return dateInTargetMonth;
}
/**
* Get the integer distance between two months. This *only* considers the month and year
* portion of the Date instances.
*
* @param {Date} start
* @param {Date} end
* @returns {number} Number of months between `start` and `end`. If `end` is before `start`
* chronologically, this number will be negative.
*/
function getMonthDistance(start, end) {
return (12 * (end.getFullYear() - start.getFullYear())) + (end.getMonth() - start.getMonth());
}
/**
* Gets the last day of the month for the given date.
* @param {Date} date
* @returns {Date}
*/
function getLastDateOfMonth(date) {
return new Date(date.getFullYear(), date.getMonth(), getNumberOfDaysInMonth(date));
}
/**
* Checks whether a date is valid.
* @param {Date} date
* @return {boolean} Whether the date is a valid Date.
*/
function isValidDate(date) {
return date != null && date.getTime && !isNaN(date.getTime());
}
/**
* Sets a date's time to midnight.
* @param {Date} date
*/
function setDateTimeToMidnight(date) {
if (isValidDate(date)) {
date.setHours(0, 0, 0, 0);
}
}
/**
* Creates a date with the time set to midnight.
* Drop-in replacement for two forms of the Date constructor:
* 1. No argument for Date representing now.
* 2. Single-argument value representing number of seconds since Unix Epoch
* or a Date object.
* @param {number|Date=} opt_value
* @return {Date} New date with time set to midnight.
*/
function createDateAtMidnight(opt_value) {
var date;
if (angular.isUndefined(opt_value)) {
date = new Date();
} else {
date = new Date(opt_value);
}
setDateTimeToMidnight(date);
return date;
}
/**
* Checks if a date is within a min and max range, ignoring the time component.
* If minDate or maxDate are not dates, they are ignored.
* @param {Date} date
* @param {Date} minDate
* @param {Date} maxDate
*/
function isDateWithinRange(date, minDate, maxDate) {
var dateAtMidnight = createDateAtMidnight(date);
var minDateAtMidnight = isValidDate(minDate) ? createDateAtMidnight(minDate) : null;
var maxDateAtMidnight = isValidDate(maxDate) ? createDateAtMidnight(maxDate) : null;
return (!minDateAtMidnight || minDateAtMidnight <= dateAtMidnight) &&
(!maxDateAtMidnight || maxDateAtMidnight >= dateAtMidnight);
}
/**
* Gets a new date incremented by the given number of years. Number of years can be negative.
* See `incrementMonths` for notes on overflow for specific dates.
* @param {Date} date
* @param {number} numberOfYears
* @returns {Date}
*/
function incrementYears(date, numberOfYears) {
return incrementMonths(date, numberOfYears * 12);
}
/**
* Get the integer distance between two years. This *only* considers the year portion of the
* Date instances.
*
* @param {Date} start
* @param {Date} end
* @returns {number} Number of months between `start` and `end`. If `end` is before `start`
* chronologically, this number will be negative.
*/
function getYearDistance(start, end) {
return end.getFullYear() - start.getFullYear();
}
/**
* Clamps a date between a minimum and a maximum date.
* @param {Date} date Date to be clamped
* @param {Date=} minDate Minimum date
* @param {Date=} maxDate Maximum date
* @return {Date}
*/
function clampDate(date, minDate, maxDate) {
var boundDate = date;
if (minDate && date < minDate) {
boundDate = new Date(minDate.getTime());
}
if (maxDate && date > maxDate) {
boundDate = new Date(maxDate.getTime());
}
return boundDate;
}
/**
* Extracts and parses the timestamp from a DOM node.
* @param {HTMLElement} node Node from which the timestamp will be extracted.
* @return {number} Time since epoch.
*/
function getTimestampFromNode(node) {
if (node && node.hasAttribute('data-timestamp')) {
return Number(node.getAttribute('data-timestamp'));
}
}
/**
* Checks if a month is within a min and max range, ignoring the date and time components.
* If minDate or maxDate are not dates, they are ignored.
* @param {Date} date
* @param {Date} minDate
* @param {Date} maxDate
*/
function isMonthWithinRange(date, minDate, maxDate) {
var month = date.getMonth();
var year = date.getFullYear();
return (!minDate || minDate.getFullYear() < year || minDate.getMonth() <= month) &&
(!maxDate || maxDate.getFullYear() > year || maxDate.getMonth() >= month);
}
});
})();
(function() {
'use strict';
// POST RELEASE
// TODO(jelbourn): Demo that uses moment.js
// TODO(jelbourn): make sure this plays well with validation and ngMessages.
// TODO(jelbourn): calendar pane doesn't open up outside of visible viewport.
// TODO(jelbourn): forward more attributes to the internal input (required, autofocus, etc.)
// TODO(jelbourn): something better for mobile (calendar panel takes up entire screen?)
// TODO(jelbourn): input behavior (masking? auto-complete?)
// TODO(jelbourn): UTC mode
angular.module('material.components.datepicker')
.directive('mdDatepicker', datePickerDirective);
/**
* @ngdoc directive
* @name mdDatepicker
* @module material.components.datepicker
*
* @param {Date} ng-model The component's model. Expects a JavaScript Date object.
* @param {expression=} ng-change Expression evaluated when the model value changes.
* @param {expression=} ng-focus Expression evaluated when the input is focused or the calendar is opened.
* @param {expression=} ng-blur Expression evaluated when focus is removed from the input or the calendar is closed.
* @param {Date=} md-min-date Expression representing a min date (inclusive).
* @param {Date=} md-max-date Expression representing a max date (inclusive).
* @param {(function(Date): boolean)=} md-date-filter Function expecting a date and returning a boolean whether it can be selected or not.
* @param {String=} md-placeholder The date input placeholder value.
* @param {String=} md-open-on-focus When present, the calendar will be opened when the input is focused.
* @param {Boolean=} md-is-open Expression that can be used to open the datepicker's calendar on-demand.
* @param {String=} md-current-view Default open view of the calendar pane. Can be either "month" or "year".
* @param {String=} md-hide-icons Determines which datepicker icons should be hidden. Note that this may cause the
* datepicker to not align properly with other components. **Use at your own risk.** Possible values are:
* * `"all"` - Hides all icons.
* * `"calendar"` - Only hides the calendar icon.
* * `"triangle"` - Only hides the triangle icon.
* @param {boolean=} ng-disabled Whether the datepicker is disabled.
* @param {boolean=} ng-required Whether a value is required for the datepicker.
*
* @description
* `<md-datepicker>` is a component used to select a single date.
* For information on how to configure internationalization for the date picker,
* see `$mdDateLocaleProvider`.
*
* This component supports [ngMessages](https://docs.angularjs.org/api/ngMessages/directive/ngMessages).
* Supported attributes are:
* * `required`: whether a required date is not set.
* * `mindate`: whether the selected date is before the minimum allowed date.
* * `maxdate`: whether the selected date is after the maximum allowed date.
* * `debounceInterval`: ms to delay input processing (since last debounce reset); default value 500ms
*
* @usage
* <hljs lang="html">
* <md-datepicker ng-model="birthday"></md-datepicker>
* </hljs>
*
*/
function datePickerDirective($$mdSvgRegistry, $mdUtil, $mdAria) {
return {
template: function(tElement, tAttrs) {
// Buttons are not in the tab order because users can open the calendar via keyboard
// interaction on the text input, and multiple tab stops for one component (picker)
// may be confusing.
var hiddenIcons = tAttrs.mdHideIcons;
var calendarButton = (hiddenIcons === 'all' || hiddenIcons === 'calendar') ? '' :
'<md-button class="md-datepicker-button md-icon-button" type="button" ' +
'tabindex="-1" aria-hidden="true" ' +
'ng-click="ctrl.openCalendarPane($event)">' +
'<md-icon class="md-datepicker-calendar-icon" aria-label="md-calendar" ' +
'md-svg-src="' + $$mdSvgRegistry.mdCalendar + '"></md-icon>' +
'</md-button>';
var triangleButton = (hiddenIcons === 'all' || hiddenIcons === 'triangle') ? '' :
'<md-button type="button" md-no-ink ' +
'class="md-datepicker-triangle-button md-icon-button" ' +
'ng-click="ctrl.openCalendarPane($event)" ' +
'aria-label="{{::ctrl.dateLocale.msgOpenCalendar}}">' +
'<div class="md-datepicker-expand-triangle"></div>' +
'</md-button>';
return '' +
calendarButton +
'<div class="md-datepicker-input-container" ' +
'ng-class="{\'md-datepicker-focused\': ctrl.isFocused}">' +
'<input class="md-datepicker-input" aria-haspopup="true" ' +
'ng-focus="ctrl.setFocused(true)" ng-blur="ctrl.setFocused(false)">' +
triangleButton +
'</div>' +
// This pane will be detached from here and re-attached to the document body.
'<div class="md-datepicker-calendar-pane md-whiteframe-z1">' +
'<div class="md-datepicker-input-mask">' +
'<div class="md-datepicker-input-mask-opaque"></div>' +
'</div>' +
'<div class="md-datepicker-calendar">' +
'<md-calendar role="dialog" aria-label="{{::ctrl.dateLocale.msgCalendar}}" ' +
'md-current-view="{{::ctrl.currentView}}"' +
'md-min-date="ctrl.minDate"' +
'md-max-date="ctrl.maxDate"' +
'md-date-filter="ctrl.dateFilter"' +
'ng-model="ctrl.date" ng-if="ctrl.isCalendarOpen">' +
'</md-calendar>' +
'</div>' +
'</div>';
},
require: ['ngModel', 'mdDatepicker', '?^mdInputContainer', '?^form'],
scope: {
minDate: '=mdMinDate',
maxDate: '=mdMaxDate',
placeholder: '@mdPlaceholder',
currentView: '@mdCurrentView',
dateFilter: '=mdDateFilter',
isOpen: '=?mdIsOpen',
debounceInterval: '=mdDebounceInterval'
},
controller: DatePickerCtrl,
controllerAs: 'ctrl',
bindToController: true,
link: function(scope, element, attr, controllers) {
var ngModelCtrl = controllers[0];
var mdDatePickerCtrl = controllers[1];
var mdInputContainer = controllers[2];
var parentForm = controllers[3];
var mdNoAsterisk = $mdUtil.parseAttributeBoolean(attr.mdNoAsterisk);
mdDatePickerCtrl.configureNgModel(ngModelCtrl, mdInputContainer);
if (mdInputContainer) {
// We need to move the spacer after the datepicker itself,
// because md-input-container adds it after the
// md-datepicker-input by default. The spacer gets wrapped in a
// div, because it floats and gets aligned next to the datepicker.
// There are easier ways of working around this with CSS (making the
// datepicker 100% wide, change the `display` etc.), however they
// break the alignment with any other form controls.
var spacer = element[0].querySelector('.md-errors-spacer');
if (spacer) {
element.after(angular.element('<div>').append(spacer));
}
mdInputContainer.setHasPlaceholder(attr.mdPlaceholder);
mdInputContainer.input = element;
mdInputContainer.element
.addClass(INPUT_CONTAINER_CLASS)
.toggleClass(HAS_ICON_CLASS, attr.mdHideIcons !== 'calendar' && attr.mdHideIcons !== 'all');
if (!mdInputContainer.label) {
$mdAria.expect(element, 'aria-label', attr.mdPlaceholder);
} else if(!mdNoAsterisk) {
attr.$observe('required', function(value) {
mdInputContainer.label.toggleClass('md-required', !!value);
});
}
scope.$watch(mdInputContainer.isErrorGetter || function() {
return ngModelCtrl.$invalid && (ngModelCtrl.$touched || (parentForm && parentForm.$submitted));
}, mdInputContainer.setInvalid);
} else if (parentForm) {
// If invalid, highlights the input when the parent form is submitted.
var parentSubmittedWatcher = scope.$watch(function() {
return parentForm.$submitted;
}, function(isSubmitted) {
if (isSubmitted) {
mdDatePickerCtrl.updateErrorState();
parentSubmittedWatcher();
}
});
}
}
};
}
datePickerDirective.$inject = ["$$mdSvgRegistry", "$mdUtil", "$mdAria"];
/** Additional offset for the input's `size` attribute, which is updated based on its content. */
var EXTRA_INPUT_SIZE = 3;
/** Class applied to the container if the date is invalid. */
var INVALID_CLASS = 'md-datepicker-invalid';
/** Class applied to the datepicker when it's open. */
var OPEN_CLASS = 'md-datepicker-open';
/** Class applied to the md-input-container, if a datepicker is placed inside it */
var INPUT_CONTAINER_CLASS = '_md-datepicker-floating-label';
/** Class to be applied when the calendar icon is enabled. */
var HAS_ICON_CLASS = '_md-datepicker-has-calendar-icon';
/** Default time in ms to debounce input event by. */
var DEFAULT_DEBOUNCE_INTERVAL = 500;
/**
* Height of the calendar pane used to check if the pane is going outside the boundary of
* the viewport. See calendar.scss for how $md-calendar-height is computed; an extra 20px is
* also added to space the pane away from the exact edge of the screen.
*
* This is computed statically now, but can be changed to be measured if the circumstances
* of calendar sizing are changed.
*/
var CALENDAR_PANE_HEIGHT = 368;
/**
* Width of the calendar pane used to check if the pane is going outside the boundary of
* the viewport. See calendar.scss for how $md-calendar-width is computed; an extra 20px is
* also added to space the pane away from the exact edge of the screen.
*
* This is computed statically now, but can be changed to be measured if the circumstances
* of calendar sizing are changed.
*/
var CALENDAR_PANE_WIDTH = 360;
/**
* Controller for md-datepicker.
*
* ngInject @constructor
*/
function DatePickerCtrl($scope, $element, $attrs, $window, $mdConstant,
$mdTheming, $mdUtil, $mdDateLocale, $$mdDateUtil, $$rAF, $mdGesture) {
/** @final */
this.$window = $window;
/** @final */
this.dateLocale = $mdDateLocale;
/** @final */
this.dateUtil = $$mdDateUtil;
/** @final */
this.$mdConstant = $mdConstant;
/* @final */
this.$mdUtil = $mdUtil;
/** @final */
this.$$rAF = $$rAF;
/**
* The root document element. This is used for attaching a top-level click handler to
* close the calendar panel when a click outside said panel occurs. We use `documentElement`
* instead of body because, when scrolling is disabled, some browsers consider the body element
* to be completely off the screen and propagate events directly to the html element.
* @type {!angular.JQLite}
*/
this.documentElement = angular.element(document.documentElement);
/** @type {!angular.NgModelController} */
this.ngModelCtrl = null;
/** @type {HTMLInputElement} */
this.inputElement = $element[0].querySelector('input');
/** @final {!angular.JQLite} */
this.ngInputElement = angular.element(this.inputElement);
/** @type {HTMLElement} */
this.inputContainer = $element[0].querySelector('.md-datepicker-input-container');
/** @type {HTMLElement} Floating calendar pane. */
this.calendarPane = $element[0].querySelector('.md-datepicker-calendar-pane');
/** @type {HTMLElement} Calendar icon button. */
this.calendarButton = $element[0].querySelector('.md-datepicker-button');
/**
* Element covering everything but the input in the top of the floating calendar pane.
* @type {HTMLElement}
*/
this.inputMask = $element[0].querySelector('.md-datepicker-input-mask-opaque');
/** @final {!angular.JQLite} */
this.$element = $element;
/** @final {!angular.Attributes} */
this.$attrs = $attrs;
/** @final {!angular.Scope} */
this.$scope = $scope;
/** @type {Date} */
this.date = null;
/** @type {boolean} */
this.isFocused = false;
/** @type {boolean} */
this.isDisabled;
this.setDisabled($element[0].disabled || angular.isString($attrs.disabled));
/** @type {boolean} Whether the date-picker's calendar pane is open. */
this.isCalendarOpen = false;
/** @type {boolean} Whether the calendar should open when the input is focused. */
this.openOnFocus = $attrs.hasOwnProperty('mdOpenOnFocus');
/** @final */
this.mdInputContainer = null;
/**
* Element from which the calendar pane was opened. Keep track of this so that we can return
* focus to it when the pane is closed.
* @type {HTMLElement}
*/
this.calendarPaneOpenedFrom = null;
/** @type {String} Unique id for the calendar pane. */
this.calendarPane.id = 'md-date-pane' + $mdUtil.nextUid();
/** Pre-bound click handler is saved so that the event listener can be removed. */
this.bodyClickHandler = angular.bind(this, this.handleBodyClick);
/**
* Name of the event that will trigger a close. Necessary to sniff the browser, because
* the resize event doesn't make sense on mobile and can have a negative impact since it
* triggers whenever the browser zooms in on a focused input.
*/
this.windowEventName = ($mdGesture.isIos || $mdGesture.isAndroid) ? 'orientationchange' : 'resize';
/** Pre-bound close handler so that the event listener can be removed. */
this.windowEventHandler = $mdUtil.debounce(angular.bind(this, this.closeCalendarPane), 100);
/** Pre-bound handler for the window blur event. Allows for it to be removed later. */
this.windowBlurHandler = angular.bind(this, this.handleWindowBlur);
// Unless the user specifies so, the datepicker should not be a tab stop.
// This is necessary because ngAria might add a tabindex to anything with an ng-model
// (based on whether or not the user has turned that particular feature on/off).
if (!$attrs.tabindex) {
$element.attr('tabindex', '-1');
}
$mdTheming($element);
$mdTheming(angular.element(this.calendarPane));
this.installPropertyInterceptors();
this.attachChangeListeners();
this.attachInteractionListeners();
var self = this;
$scope.$on('$destroy', function() {
self.detachCalendarPane();
});
if ($attrs.mdIsOpen) {
$scope.$watch('ctrl.isOpen', function(shouldBeOpen) {
if (shouldBeOpen) {
self.openCalendarPane({
target: self.inputElement
});
} else {
self.closeCalendarPane();
}
});
}
}
DatePickerCtrl.$inject = ["$scope", "$element", "$attrs", "$window", "$mdConstant", "$mdTheming", "$mdUtil", "$mdDateLocale", "$$mdDateUtil", "$$rAF", "$mdGesture"];
/**
* Sets up the controller's reference to ngModelController.
* @param {!angular.NgModelController} ngModelCtrl
*/
DatePickerCtrl.prototype.configureNgModel = function(ngModelCtrl, mdInputContainer) {
this.ngModelCtrl = ngModelCtrl;
this.mdInputContainer = mdInputContainer;
var self = this;
ngModelCtrl.$render = function() {
var value = self.ngModelCtrl.$viewValue;
if (value && !(value instanceof Date)) {
throw Error('The ng-model for md-datepicker must be a Date instance. ' +
'Currently the model is a: ' + (typeof value));
}
self.date = value;
self.inputElement.value = self.dateLocale.formatDate(value);
self.mdInputContainer && self.mdInputContainer.setHasValue(!!value);
self.resizeInputElement();
self.updateErrorState();
};
// Responds to external error state changes (e.g. ng-required based on another input).
ngModelCtrl.$viewChangeListeners.unshift(angular.bind(this, this.updateErrorState));
};
/**
* Attach event listeners for both the text input and the md-calendar.
* Events are used instead of ng-model so that updates don't infinitely update the other
* on a change. This should also be more performant than using a $watch.
*/
DatePickerCtrl.prototype.attachChangeListeners = function() {
var self = this;
self.$scope.$on('md-calendar-change', function(event, date) {
self.ngModelCtrl.$setViewValue(date);
self.date = date;
self.inputElement.value = self.dateLocale.formatDate(date);
self.mdInputContainer && self.mdInputContainer.setHasValue(!!date);
self.closeCalendarPane();
self.resizeInputElement();
self.updateErrorState();
});
self.ngInputElement.on('input', angular.bind(self, self.resizeInputElement));
var debounceInterval = angular.isDefined(this.debounceInterval) ?
this.debounceInterval : DEFAULT_DEBOUNCE_INTERVAL;
self.ngInputElement.on('input', self.$mdUtil.debounce(self.handleInputEvent,
debounceInterval, self));
};
/** Attach event listeners for user interaction. */
DatePickerCtrl.prototype.attachInteractionListeners = function() {
var self = this;
var $scope = this.$scope;
var keyCodes = this.$mdConstant.KEY_CODE;
// Add event listener through angular so that we can triggerHandler in unit tests.
self.ngInputElement.on('keydown', function(event) {
if (event.altKey && event.keyCode == keyCodes.DOWN_ARROW) {
self.openCalendarPane(event);
$scope.$digest();
}
});
if (self.openOnFocus) {
self.ngInputElement.on('focus', angular.bind(self, self.openCalendarPane));
angular.element(self.$window).on('blur', self.windowBlurHandler);
$scope.$on('$destroy', function() {
angular.element(self.$window).off('blur', self.windowBlurHandler);
});
}
$scope.$on('md-calendar-close', function() {
self.closeCalendarPane();
});
};
/**
* Capture properties set to the date-picker and imperitively handle internal changes.
* This is done to avoid setting up additional $watches.
*/
DatePickerCtrl.prototype.installPropertyInterceptors = function() {
var self = this;
if (this.$attrs.ngDisabled) {
// The expression is to be evaluated against the directive element's scope and not
// the directive's isolate scope.
var scope = this.$scope.$parent;
if (scope) {
scope.$watch(this.$attrs.ngDisabled, function(isDisabled) {
self.setDisabled(isDisabled);
});
}
}
Object.defineProperty(this, 'placeholder', {
get: function() { return self.inputElement.placeholder; },
set: function(value) { self.inputElement.placeholder = value || ''; }
});
};
/**
* Sets whether the date-picker is disabled.
* @param {boolean} isDisabled
*/
DatePickerCtrl.prototype.setDisabled = function(isDisabled) {
this.isDisabled = isDisabled;
this.inputElement.disabled = isDisabled;
if (this.calendarButton) {
this.calendarButton.disabled = isDisabled;
}
};
/**
* Sets the custom ngModel.$error flags to be consumed by ngMessages. Flags are:
* - mindate: whether the selected date is before the minimum date.
* - maxdate: whether the selected flag is after the maximum date.
* - filtered: whether the selected date is allowed by the custom filtering function.
* - valid: whether the entered text input is a valid date
*
* The 'required' flag is handled automatically by ngModel.
*
* @param {Date=} opt_date Date to check. If not given, defaults to the datepicker's model value.
*/
DatePickerCtrl.prototype.updateErrorState = function(opt_date) {
var date = opt_date || this.date;
// Clear any existing errors to get rid of anything that's no longer relevant.
this.clearErrorState();
if (this.dateUtil.isValidDate(date)) {
// Force all dates to midnight in order to ignore the time portion.
date = this.dateUtil.createDateAtMidnight(date);
if (this.dateUtil.isValidDate(this.minDate)) {
var minDate = this.dateUtil.createDateAtMidnight(this.minDate);
this.ngModelCtrl.$setValidity('mindate', date >= minDate);
}
if (this.dateUtil.isValidDate(this.maxDate)) {
var maxDate = this.dateUtil.createDateAtMidnight(this.maxDate);
this.ngModelCtrl.$setValidity('maxdate', date <= maxDate);
}
if (angular.isFunction(this.dateFilter)) {
this.ngModelCtrl.$setValidity('filtered', this.dateFilter(date));
}
} else {
// The date is seen as "not a valid date" if there is *something* set
// (i.e.., not null or undefined), but that something isn't a valid date.
this.ngModelCtrl.$setValidity('valid', date == null);
}
// TODO(jelbourn): Change this to classList.toggle when we stop using PhantomJS in unit tests
// because it doesn't conform to the DOMTokenList spec.
// See https://github.com/ariya/phantomjs/issues/12782.
if (!this.ngModelCtrl.$valid) {
this.inputContainer.classList.add(INVALID_CLASS);
}
};
/** Clears any error flags set by `updateErrorState`. */
DatePickerCtrl.prototype.clearErrorState = function() {
this.inputContainer.classList.remove(INVALID_CLASS);
['mindate', 'maxdate', 'filtered', 'valid'].forEach(function(field) {
this.ngModelCtrl.$setValidity(field, true);
}, this);
};
/** Resizes the input element based on the size of its content. */
DatePickerCtrl.prototype.resizeInputElement = function() {
this.inputElement.size = this.inputElement.value.length + EXTRA_INPUT_SIZE;
};
/**
* Sets the model value if the user input is a valid date.
* Adds an invalid class to the input element if not.
*/
DatePickerCtrl.prototype.handleInputEvent = function() {
var inputString = this.inputElement.value;
var parsedDate = inputString ? this.dateLocale.parseDate(inputString) : null;
this.dateUtil.setDateTimeToMidnight(parsedDate);
// An input string is valid if it is either empty (representing no date)
// or if it parses to a valid date that the user is allowed to select.
var isValidInput = inputString == '' || (
this.dateUtil.isValidDate(parsedDate) &&
this.dateLocale.isDateComplete(inputString) &&
this.isDateEnabled(parsedDate)
);
// The datepicker's model is only updated when there is a valid input.
if (isValidInput) {
this.ngModelCtrl.$setViewValue(parsedDate);
this.date = parsedDate;
}
this.updateErrorState(parsedDate);
};
/**
* Check whether date is in range and enabled
* @param {Date=} opt_date
* @return {boolean} Whether the date is enabled.
*/
DatePickerCtrl.prototype.isDateEnabled = function(opt_date) {
return this.dateUtil.isDateWithinRange(opt_date, this.minDate, this.maxDate) &&
(!angular.isFunction(this.dateFilter) || this.dateFilter(opt_date));
};
/** Position and attach the floating calendar to the document. */
DatePickerCtrl.prototype.attachCalendarPane = function() {
var calendarPane = this.calendarPane;
var body = document.body;
calendarPane.style.transform = '';
this.$element.addClass(OPEN_CLASS);
this.mdInputContainer && this.mdInputContainer.element.addClass(OPEN_CLASS);
angular.element(body).addClass('md-datepicker-is-showing');
var elementRect = this.inputContainer.getBoundingClientRect();
var bodyRect = body.getBoundingClientRect();
// Check to see if the calendar pane would go off the screen. If so, adjust position
// accordingly to keep it within the viewport.
var paneTop = elementRect.top - bodyRect.top;
var paneLeft = elementRect.left - bodyRect.left;
// If ng-material has disabled body scrolling (for example, if a dialog is open),
// then it's possible that the already-scrolled body has a negative top/left. In this case,
// we want to treat the "real" top as (0 - bodyRect.top). In a normal scrolling situation,
// though, the top of the viewport should just be the body's scroll position.
var viewportTop = (bodyRect.top < 0 && document.body.scrollTop == 0) ?
-bodyRect.top :
document.body.scrollTop;
var viewportLeft = (bodyRect.left < 0 && document.body.scrollLeft == 0) ?
-bodyRect.left :
document.body.scrollLeft;
var viewportBottom = viewportTop + this.$window.innerHeight;
var viewportRight = viewportLeft + this.$window.innerWidth;
// If the right edge of the pane would be off the screen and shifting it left by the
// difference would not go past the left edge of the screen. If the calendar pane is too
// big to fit on the screen at all, move it to the left of the screen and scale the entire
// element down to fit.
if (paneLeft + CALENDAR_PANE_WIDTH > viewportRight) {
if (viewportRight - CALENDAR_PANE_WIDTH > 0) {
paneLeft = viewportRight - CALENDAR_PANE_WIDTH;
} else {
paneLeft = viewportLeft;
var scale = this.$window.innerWidth / CALENDAR_PANE_WIDTH;
calendarPane.style.transform = 'scale(' + scale + ')';
}
calendarPane.classList.add('md-datepicker-pos-adjusted');
}
// If the bottom edge of the pane would be off the screen and shifting it up by the
// difference would not go past the top edge of the screen.
if (paneTop + CALENDAR_PANE_HEIGHT > viewportBottom &&
viewportBottom - CALENDAR_PANE_HEIGHT > viewportTop) {
paneTop = viewportBottom - CALENDAR_PANE_HEIGHT;
calendarPane.classList.add('md-datepicker-pos-adjusted');
}
calendarPane.style.left = paneLeft + 'px';
calendarPane.style.top = paneTop + 'px';
document.body.appendChild(calendarPane);
// The top of the calendar pane is a transparent box that shows the text input underneath.
// Since the pane is floating, though, the page underneath the pane *adjacent* to the input is
// also shown unless we cover it up. The inputMask does this by filling up the remaining space
// based on the width of the input.
this.inputMask.style.left = elementRect.width + 'px';
// Add CSS class after one frame to trigger open animation.
this.$$rAF(function() {
calendarPane.classList.add('md-pane-open');
});
};
/** Detach the floating calendar pane from the document. */
DatePickerCtrl.prototype.detachCalendarPane = function() {
this.$element.removeClass(OPEN_CLASS);
this.mdInputContainer && this.mdInputContainer.element.removeClass(OPEN_CLASS);
angular.element(document.body).removeClass('md-datepicker-is-showing');
this.calendarPane.classList.remove('md-pane-open');
this.calendarPane.classList.remove('md-datepicker-pos-adjusted');
if (this.isCalendarOpen) {
this.$mdUtil.enableScrolling();
}
if (this.calendarPane.parentNode) {
// Use native DOM removal because we do not want any of the
// angular state of this element to be disposed.
this.calendarPane.parentNode.removeChild(this.calendarPane);
}
};
/**
* Open the floating calendar pane.
* @param {Event} event
*/
DatePickerCtrl.prototype.openCalendarPane = function(event) {
if (!this.isCalendarOpen && !this.isDisabled && !this.inputFocusedOnWindowBlur) {
this.isCalendarOpen = this.isOpen = true;
this.calendarPaneOpenedFrom = event.target;
// Because the calendar pane is attached directly to the body, it is possible that the
// rest of the component (input, etc) is in a different scrolling container, such as
// an md-content. This means that, if the container is scrolled, the pane would remain
// stationary. To remedy this, we disable scrolling while the calendar pane is open, which
// also matches the native behavior for things like `<select>` on Mac and Windows.
this.$mdUtil.disableScrollAround(this.calendarPane);
this.attachCalendarPane();
this.focusCalendar();
this.evalAttr('ngFocus');
// Attach click listener inside of a timeout because, if this open call was triggered by a
// click, we don't want it to be immediately propogated up to the body and handled.
var self = this;
this.$mdUtil.nextTick(function() {
// Use 'touchstart` in addition to click in order to work on iOS Safari, where click
// events aren't propogated under most circumstances.
// See http://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html
self.documentElement.on('click touchstart', self.bodyClickHandler);
}, false);
window.addEventListener(this.windowEventName, this.windowEventHandler);
}
};
/** Close the floating calendar pane. */
DatePickerCtrl.prototype.closeCalendarPane = function() {
if (this.isCalendarOpen) {
var self = this;
self.detachCalendarPane();
self.ngModelCtrl.$setTouched();
self.evalAttr('ngBlur');
self.documentElement.off('click touchstart', self.bodyClickHandler);
window.removeEventListener(self.windowEventName, self.windowEventHandler);
self.calendarPaneOpenedFrom.focus();
self.calendarPaneOpenedFrom = null;
if (self.openOnFocus) {
// Ensures that all focus events have fired before resetting
// the calendar. Prevents the calendar from reopening immediately
// in IE when md-open-on-focus is set. Also it needs to trigger
// a digest, in order to prevent issues where the calendar wasn't
// showing up on the next open.
self.$mdUtil.nextTick(reset);
} else {
reset();
}
}
function reset(){
self.isCalendarOpen = self.isOpen = false;
}
};
/** Gets the controller instance for the calendar in the floating pane. */
DatePickerCtrl.prototype.getCalendarCtrl = function() {
return angular.element(this.calendarPane.querySelector('md-calendar')).controller('mdCalendar');
};
/** Focus the calendar in the floating pane. */
DatePickerCtrl.prototype.focusCalendar = function() {
// Use a timeout in order to allow the calendar to be rendered, as it is gated behind an ng-if.
var self = this;
this.$mdUtil.nextTick(function() {
self.getCalendarCtrl().focus();
}, false);
};
/**
* Sets whether the input is currently focused.
* @param {boolean} isFocused
*/
DatePickerCtrl.prototype.setFocused = function(isFocused) {
if (!isFocused) {
this.ngModelCtrl.$setTouched();
}
// The ng* expressions shouldn't be evaluated when mdOpenOnFocus is on,
// because they also get called when the calendar is opened/closed.
if (!this.openOnFocus) {
this.evalAttr(isFocused ? 'ngFocus' : 'ngBlur');
}
this.isFocused = isFocused;
};
/**
* Handles a click on the document body when the floating calendar pane is open.
* Closes the floating calendar pane if the click is not inside of it.
* @param {MouseEvent} event
*/
DatePickerCtrl.prototype.handleBodyClick = function(event) {
if (this.isCalendarOpen) {
var isInCalendar = this.$mdUtil.getClosest(event.target, 'md-calendar');
if (!isInCalendar) {
this.closeCalendarPane();
}
this.$scope.$digest();
}
};
/**
* Handles the event when the user navigates away from the current tab. Keeps track of
* whether the input was focused when the event happened, in order to prevent the calendar
* from re-opening.
*/
DatePickerCtrl.prototype.handleWindowBlur = function() {
this.inputFocusedOnWindowBlur = document.activeElement === this.inputElement;
};
/**
* Evaluates an attribute expression against the parent scope.
* @param {String} attr Name of the attribute to be evaluated.
*/
DatePickerCtrl.prototype.evalAttr = function(attr) {
if (this.$attrs[attr]) {
this.$scope.$parent.$eval(this.$attrs[attr]);
}
};
})();
})(window, window.angular); | phiphamuet/meanCopy | public/lib/angular-material/modules/js/datepicker/datepicker.js | JavaScript | mit | 104,733 |
var $ = require('jquery');
var BrandingUpdater = function($branding) {
this.$branding = $branding;
};
BrandingUpdater.prototype = {
move: function($branding) {
$branding.detach().prependTo($('.sidebar-wrapper'));
},
run: function() {
var $branding = this.$branding;
try {
this.move($branding);
} catch (e) {
console.error(e, e.stack);
}
$branding.addClass('initialized');
}
};
$(document).ready(function() {
$('#branding').each(function() {
new BrandingUpdater($(this)).run();
});
if ($('body.login').length != 0) {
$('<img>').attr('src', '//jet.geex-arts.com/ping.gif');
}
});
| edwar/repositio.com | static/jet/js/src/layout-updaters/branding.js | JavaScript | mit | 707 |
//= require ./adjacent_pages
pageflow.AdjacentPreparer = pageflow.Object.extend({
initialize: function(adjacentPages) {
this.adjacentPages = adjacentPages;
},
attach: function(events) {
this.listenTo(events, 'page:change', this.schedule);
},
schedule: function(page) {
clearTimeout(this.scheduleTimeout);
var prepare = _.bind(this.prepareAdjacent, this, page.element.page('instance'));
this.scheduleTimeout = setTimeout(prepare, page.prepareNextPageTimeout());
},
prepareAdjacent: function(page) {
var adjacentPages = this.adjacentPages.of(page);
var noLongerAdjacentPages = _.difference(this.lastAdjacentPages, adjacentPages, [page]);
var newAdjacentPages = _.difference(adjacentPages, this.lastAdjacentPages);
_(noLongerAdjacentPages).each(function(page) {
page.unprepare();
});
_(newAdjacentPages).each(function(adjacentPage) {
adjacentPage.prepare();
adjacentPage.preload();
});
this.lastAdjacentPages = adjacentPages;
}
});
pageflow.AdjacentPreparer.create = function(pages, scrollNavigator) {
return new pageflow.AdjacentPreparer(
new pageflow.AdjacentPages(
pages,
scrollNavigator
)
);
}; | luatdolphin/pageflow | app/assets/javascripts/pageflow/slideshow/adjacent_preparer.js | JavaScript | mit | 1,214 |
define(["app/app",
"mixins/CustomErrorRoute"], function(App) {
"use strict";
App.TimelineCommentsRoute = Ember.Route.extend(App.CustomErrorRoute, {
queryParams: {
offset: {
refreshModel: true
}
},
model: function(params) {
return this.store.findOneQuery('timeline', params.username + '/comments', { offset: params.offset })
},
deactivate: function() {
this.get('pubsub').unsubscribe()
},
setupController: function(controller, model) {
this.get('pubsub').set('channel', model)
controller.set('model', model)
}
})
})
| epicmonkey/pepyatka-html | public/js/app/routes/TimelineCommentsRoute.js | JavaScript | mit | 611 |
'use strict';
// Load modules
// Declare internals
const internals = {};
exports.mergeOptions = function (parent, child, ignore) {
ignore = ignore || [];
const options = {};
Object.keys(parent || {}).forEach((key) => {
if (ignore.indexOf(key) === -1) {
options[key] = parent[key];
}
});
Object.keys(child || {}).forEach((key) => {
options[key] = child[key];
});
return options;
};
exports.applyOptions = function (parent, child) {
Object.keys(child).forEach((key) => {
parent[key] = child[key];
});
};
| fahidRM/aqua-couch-test | node_modules/lab/lib/utils.js | JavaScript | mit | 598 |
var ATrue;
(function (ATrue) {
ATrue[ATrue["IsTrue"] = 1] = "IsTrue";
ATrue[ATrue["IsFalse"] = 0] = "IsFalse";
})(ATrue || (ATrue = {}));
if (false) {
console.info('unreachable');
}
else if (true) {
console.info('reachable');
}
else {
console.info('unreachable');
}
function branch(a) {
if (a === ATrue.IsFalse) {
console.info('a = false');
}
else if (a === ATrue.IsTrue) {
throw Error('an exception');
}
else {
console.info('a = ???');
}
}
branch(ATrue.IsTrue);
//# sourceMappingURL=typescript-throw.js.map
| enclose-io/compiler | lts/test/fixtures/source-map/typescript-throw.js | JavaScript | mit | 576 |
module.exports = {
name: '<b:append>',
test: [
{
name: 'nothing happen if no reference',
test: function(){
var a = createTemplate('<span/>');
var b = createTemplate('<b:include src="#' + a.templateId + '"><b:append ref="foo">x</b:append></b:include>');
assert(text(b) === text('<span/>'));
}
},
{
name: 'append to element if no ref attribute',
test: function(){
var a = createTemplate('<span/>');
var b = createTemplate('<b:include src="#' + a.templateId + '"><b:append>x</b:append></b:include>');
assert(text(b) === text('<span>x</span>'));
}
},
{
name: 'nothing happen if ref node is not an element',
test: function(){
var a = createTemplate('<span>{foo}</span>');
var b = createTemplate('<b:include src="#' + a.templateId + '"><b:append ref="foo">x</b:append></b:include>');
assert(text(b) === text('<span>{foo}</span>'));
var a = createTemplate('text');
var b = createTemplate('<b:include src="#' + a.templateId + '"><b:append>x</b:append></b:include>');
assert(text(b) === text('text'));
}
},
{
name: 'append token with single node when no children',
test: function(){
var a = createTemplate('<span/>');
var b = createTemplate('<b:include src="#' + a.templateId + '"><b:append ref="element">x</b:append></b:include>');
assert(text(b) === text('<span>x</span>'));
}
},
{
name: 'append token with single node',
test: function(){
var a = createTemplate('<span><span/></span>');
var b = createTemplate('<b:include src="#' + a.templateId + '"><b:append ref="element">x</b:append></b:include>');
assert(text(b) === text('<span><span/>x</span>'));
}
},
{
name: 'append token with multiple nodes when no children',
test: function(){
var a = createTemplate('<span/>');
var b = createTemplate('<b:include src="#' + a.templateId + '"><b:append ref="element"><br/>x<br/></b:append></b:include>');
assert(text(b) === text('<span><br/>x<br/></span>'));
}
},
{
name: 'append token with multiple nodes',
test: function(){
var a = createTemplate('<span><span/></span>');
var b = createTemplate('<b:include src="#' + a.templateId + '"><b:append ref="element"><br/>x<br/></b:append></b:include>');
assert(text(b) === text('<span><span/><br/>x<br/></span>'));
}
}
]
};
| fateevv/basisjs | test/spec/template/b-include/b-append.js | JavaScript | mit | 2,543 |
'use strict';
var async = require('async');
var S = require('string');
var db = require('../database');
var user = require('../user');
var utils = require('../utils');
var plugins = require('../plugins');
module.exports = function (Messaging) {
Messaging.newMessageCutoff = 1000 * 60 * 3;
Messaging.getMessageField = function (mid, field, callback) {
Messaging.getMessageFields(mid, [field], function (err, fields) {
callback(err, fields ? fields[field] : null);
});
};
Messaging.getMessageFields = function (mid, fields, callback) {
db.getObjectFields('message:' + mid, fields, callback);
};
Messaging.setMessageField = function (mid, field, content, callback) {
db.setObjectField('message:' + mid, field, content, callback);
};
Messaging.setMessageFields = function (mid, data, callback) {
db.setObject('message:' + mid, data, callback);
};
Messaging.getMessagesData = function (mids, uid, roomId, isNew, callback) {
var messages;
async.waterfall([
function (next) {
var keys = mids.map(function (mid) {
return 'message:' + mid;
});
db.getObjects(keys, next);
},
function (_messages, next) {
messages = _messages.map(function (msg, idx) {
if (msg) {
msg.messageId = parseInt(mids[idx], 10);
}
return msg;
}).filter(Boolean);
var uids = messages.map(function (msg) {
return msg && msg.fromuid;
});
user.getUsersFields(uids, ['uid', 'username', 'userslug', 'picture', 'status'], next);
},
function (users, next) {
messages.forEach(function (message, index) {
message.fromUser = users[index];
var self = parseInt(message.fromuid, 10) === parseInt(uid, 10);
message.self = self ? 1 : 0;
message.timestampISO = utils.toISOString(message.timestamp);
message.newSet = false;
message.roomId = String(message.roomId || roomId);
if (message.hasOwnProperty('edited')) {
message.editedISO = new Date(parseInt(message.edited, 10)).toISOString();
}
});
async.map(messages, function (message, next) {
Messaging.parse(message.content, message.fromuid, uid, roomId, isNew, function (err, result) {
if (err) {
return next(err);
}
message.content = result;
message.cleanedContent = S(result).stripTags().decodeHTMLEntities().s;
next(null, message);
});
}, next);
},
function (messages, next) {
if (messages.length > 1) {
// Add a spacer in between messages with time gaps between them
messages = messages.map(function (message, index) {
// Compare timestamps with the previous message, and check if a spacer needs to be added
if (index > 0 && parseInt(message.timestamp, 10) > parseInt(messages[index - 1].timestamp, 10) + Messaging.newMessageCutoff) {
// If it's been 5 minutes, this is a new set of messages
message.newSet = true;
} else if (index > 0 && message.fromuid !== messages[index - 1].fromuid) {
// If the previous message was from the other person, this is also a new set
message.newSet = true;
}
return message;
});
next(undefined, messages);
} else if (messages.length === 1) {
// For single messages, we don't know the context, so look up the previous message and compare
var key = 'uid:' + uid + ':chat:room:' + roomId + ':mids';
async.waterfall([
async.apply(db.sortedSetRank, key, messages[0].messageId),
function (index, next) {
// Continue only if this isn't the first message in sorted set
if (index > 0) {
db.getSortedSetRange(key, index - 1, index - 1, next);
} else {
messages[0].newSet = true;
return next(undefined, messages);
}
},
function (mid, next) {
Messaging.getMessageFields(mid, ['fromuid', 'timestamp'], next);
},
], function (err, fields) {
if (err) {
return next(err);
}
if (
(parseInt(messages[0].timestamp, 10) > parseInt(fields.timestamp, 10) + Messaging.newMessageCutoff) ||
(parseInt(messages[0].fromuid, 10) !== parseInt(fields.fromuid, 10))
) {
// If it's been 5 minutes, this is a new set of messages
messages[0].newSet = true;
}
next(undefined, messages);
});
} else {
next(null, []);
}
},
function (messages, next) {
plugins.fireHook('filter:messaging.getMessages', {
messages: messages,
uid: uid,
roomId: roomId,
isNew: isNew,
mids: mids,
}, function (err, data) {
next(err, data && data.messages);
});
},
], callback);
};
};
| sdonaghey03/hia-forum | src/messaging/data.js | JavaScript | mit | 4,633 |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: >
Result of String conversion from Object value is conversion
from primitive value
es5id: 9.8_A5_T2
description: Some objects convert to String by implicit transformation
---*/
// CHECK#1
if (new Number() + "" !== "0") {
$ERROR('#1: new Number() + "" === "0". Actual: ' + (new Number() + ""));
}
// CHECK#2
if (new Number(0) + "" !== "0") {
$ERROR('#2: new Number(0) + "" === "0". Actual: ' + (new Number(0) + ""));
}
// CHECK#3
if (new Number(Number.NaN) + "" !== "NaN") {
$ERROR('#3: new Number(Number.NaN) + "" === "NaN". Actual: ' + (new Number(Number.NaN) + ""));
}
// CHECK#4
if (new Number(null) + "" !== "0") {
$ERROR('#4: new Number(null) + "" === "0". Actual: ' + (new Number(null) + ""));
}
// CHECK#5
if (new Number(void 0) + "" !== "NaN") {
$ERROR('#5: new Number(void 0) + "" === "NaN. Actual: ' + (new Number(void 0) + ""));
}
// CHECK#6
if (new Number(true) + "" !== "1") {
$ERROR('#6: new Number(true) + "" === "1". Actual: ' + (new Number(true) + ""));
}
// CHECK#7
if (new Number(false) + "" !== "0") {
$ERROR('#7: new Number(false) + "" === "0". Actual: ' + (new Number(false) + ""));
}
// CHECK#8
if (new Boolean(true) + "" !== "true") {
$ERROR('#8: new Boolean(true) + "" === "true". Actual: ' + (new Boolean(true) + ""));
}
// CHECK#9
if (new Boolean(false) + "" !== "false") {
$ERROR('#9: Number(new Boolean(false)) === "false". Actual: ' + (Number(new Boolean(false))));
}
// CHECK#10
if (new Array(2,4,8,16,32) + "" !== "2,4,8,16,32") {
$ERROR('#10: new Array(2,4,8,16,32) + "" === "2,4,8,16,32". Actual: ' + (new Array(2,4,8,16,32) + ""));
}
// CHECK#11
var myobj1 = {
toNumber : function(){return 12345;},
toString : function(){return 67890;},
valueOf : function(){return "[object MyObj]";}
};
if (myobj1 + "" !== "[object MyObj]"){
$ERROR('#11: myobj1 + "" calls ToPrimitive with hint Number. Exptected: "[object MyObj]". Actual: ' + (myobj1 + ""));
}
// CHECK#12
var myobj2 = {
toNumber : function(){return 12345;},
toString : function(){return 67890},
valueOf : function(){return {}}
};
if (myobj2 + "" !== "67890"){
$ERROR('#12: myobj2 + "" calls ToPrimitive with hint Number. Exptected: "67890". Actual: ' + (myobj2 + ""));
}
// CHECK#13
var myobj3 = {
toNumber : function(){return 12345;}
};
if (myobj3 + "" !== "[object Object]"){
$ERROR('#13: myobj3 + "" calls ToPrimitive with hint Number. Exptected: "[object Object]". Actual: ' + (myobj3 + ""));
}
| PiotrDabkowski/Js2Py | tests/test_cases/language/expressions/concatenation/S9.8_A5_T2.js | JavaScript | mit | 2,739 |
/*!
* bootstrap-fileinput v5.0.2
* http://plugins.krajee.com/file-input
*
* Glyphicon (default) theme configuration for bootstrap-fileinput.
*
* Author: Kartik Visweswaran
* Copyright: 2014 - 2019, Kartik Visweswaran, Krajee.com
*
* Licensed under the BSD-3-Clause
* https://github.com/kartik-v/bootstrap-fileinput/blob/master/LICENSE.md
*/
(function ($) {
"use strict";
$.fn.fileinputThemes.gly = {
fileActionSettings: {
removeIcon: '<i class="glyphicon glyphicon-trash"></i>',
uploadIcon: '<i class="glyphicon glyphicon-upload"></i>',
zoomIcon: '<i class="glyphicon glyphicon-zoom-in"></i>',
dragIcon: '<i class="glyphicon glyphicon-move"></i>',
indicatorNew: '<i class="glyphicon glyphicon-plus-sign text-warning"></i>',
indicatorSuccess: '<i class="glyphicon glyphicon-ok-sign text-success"></i>',
indicatorError: '<i class="glyphicon glyphicon-exclamation-sign text-danger"></i>',
indicatorLoading: '<i class="glyphicon glyphicon-hourglass text-muted"></i>'
},
layoutTemplates: {
fileIcon: '<i class="glyphicon glyphicon-file kv-caption-icon"></i>'
},
previewZoomButtonIcons: {
prev: '<i class="glyphicon glyphicon-triangle-left"></i>',
next: '<i class="glyphicon glyphicon-triangle-right"></i>',
toggleheader: '<i class="glyphicon glyphicon-resize-vertical"></i>',
fullscreen: '<i class="glyphicon glyphicon-fullscreen"></i>',
borderless: '<i class="glyphicon glyphicon-resize-full"></i>',
close: '<i class="glyphicon glyphicon-remove"></i>'
},
previewFileIcon: '<i class="glyphicon glyphicon-file"></i>',
browseIcon: '<i class="glyphicon glyphicon-folder-open"></i> ',
removeIcon: '<i class="glyphicon glyphicon-trash"></i>',
cancelIcon: '<i class="glyphicon glyphicon-ban-circle"></i>',
pauseIcon: '<i class="glyphicon glyphicon-pause"></i>',
uploadIcon: '<i class="glyphicon glyphicon-upload"></i>',
msgValidationErrorIcon: '<i class="glyphicon glyphicon-exclamation-sign"></i> '
};
})(window.jQuery);
| extend1994/cdnjs | ajax/libs/bootstrap-fileinput/5.0.2/themes/gly/theme.js | JavaScript | mit | 2,224 |
jQuery(function ($) {
if ( pagenow == 'edit-wpp_popup' ) {
$('.add-new-h2').addClass('button');
$('#wpbody .wrap').wrapInner('<div id="wpp-col-left" />');
$('#wpbody .wrap').wrapInner('<div id="wpp-cols" />');
$('#wpp-col-right').removeClass('hidden').prependTo('#wpp-cols');
$('#wpp-col-left > .icon32').insertBefore('#wpp-cols');
$('#wpp-col-left > h2').insertBefore('#wpp-cols');
$('td.column-date').each(function(index, elem){
var abbr = $(this).find('abbr').text();
$(this).html(abbr);
});
}
if ( pagenow == 'wpp_popup' ) {
$('.add-new-h2').hide();
$('#mask_colorpicker').hide();
$('#mask_colorpicker').farbtastic('#mask_color_field');
$('#mask_color_field').click(function() {
$('#mask_colorpicker').fadeIn();
});
$('#border_colorpicker').hide();
$('#border_colorpicker').farbtastic('#border_color_field');
$('#border_color_field').click(function() {
$('#border_colorpicker').fadeIn();
});
$(document).mousedown(function() {
$('#mask_colorpicker').each(function() {
var display = $(this).css('display');
if ( display == 'block' )
$(this).fadeOut();
});
$('#border_colorpicker').each(function() {
var display = $(this).css('display');
if ( display == 'block' )
$(this).fadeOut();
});
});
}
$('#ibtn-enable').iButton({
labelOn: "Yes",
labelOff: "No"
});
$('#shortcode_text_input').click(function() {
$(this).select();
});
//end
}); | sinned/tadashop | wp-content/plugins/m-wp-popup/js/wpp-popup-admin.js | JavaScript | gpl-2.0 | 1,629 |
/*!
{
"name": "Flexbox (tweener)",
"property": "flexboxtweener",
"tags": ["css"],
"polyfills": ["flexie"],
"notes": [{
"name": "The _inbetween_ flexbox",
"href": "http://www.w3.org/TR/2011/WD-css3-flexbox-20111129/"
}]
}
!*/
define(['Modernizr', 'testAllProps'], function( Modernizr, testAllProps ) {
Modernizr.addTest('flexboxtweener', testAllProps('flexAlign', 'end', true));
});
| JanetteA/dsmsales | sites/all/libraries/modernizr/feature-detects/css/flexboxtweener.js | JavaScript | gpl-2.0 | 404 |
/**
* @license Highcharts JS v7.0.3 (2019-02-06)
* Advanced Highstock tools
*
* (c) 2010-2019 Highsoft AS
* Author: Torstein Honsi
*
* 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(function () {
return factory;
});
} else {
factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined);
}
}(function (Highcharts) {
(function (H) {
/**
*
* Events generator for Stock tools
*
* (c) 2009-2019 Paweł Fus
*
* License: www.highcharts.com/license
*
* */
/**
* A config object for bindings in Stock Tools module.
*
* @interface Highcharts.StockToolsBindingsObject
*//**
* ClassName of the element for a binding.
* @name Highcharts.StockToolsBindingsObject#className
* @type {string|undefined}
*//**
* Last event to be fired after last step event.
* @name Highcharts.StockToolsBindingsObject#end
* @type {Function|undefined}
*//**
* Initial event, fired on a button click.
* @name Highcharts.StockToolsBindingsObject#init
* @type {Function|undefined}
*//**
* Event fired on first click on a chart.
* @name Highcharts.StockToolsBindingsObject#start
* @type {Function|undefined}
*//**
* Last event to be fired after last step event. Array of step events to be
* called sequentially after each user click.
* @name Highcharts.StockToolsBindingsObject#steps
* @type {Array<Function>|undefined}
*/
var fireEvent = H.fireEvent,
defined = H.defined,
pick = H.pick,
extend = H.extend,
isNumber = H.isNumber,
correctFloat = H.correctFloat,
bindingsUtils = H.NavigationBindings.prototype.utils,
PREFIX = 'highcharts-';
/**
* Generates function which will add a flag series using modal in GUI.
* Method fires an event "showPopup" with config:
* `{type, options, callback}`.
*
* Example: NavigationBindings.utils.addFlagFromForm('url(...)') - will
* generate function that shows modal in GUI.
*
* @private
* @function bindingsUtils.addFlagFromForm
*
* @param {string} type
* Type of flag series, e.g. "squarepin"
*
* @return {Function}
* Callback to be used in `start` callback
*/
bindingsUtils.addFlagFromForm = function (type) {
return function (e) {
var navigation = this,
chart = navigation.chart,
toolbar = chart.toolbar,
getFieldType = bindingsUtils.getFieldType,
point = bindingsUtils.attractToPoint(e, chart),
pointConfig = {
x: point.x,
y: point.y
},
seriesOptions = {
type: 'flags',
onSeries: point.series.id,
shape: type,
data: [pointConfig],
point: {
events: {
click: function () {
var point = this,
options = point.options;
fireEvent(
navigation,
'showPopup',
{
point: point,
formType: 'annotation-toolbar',
options: {
langKey: 'flags',
type: 'flags',
title: [
options.title,
getFieldType(
options.title
)
],
name: [
options.name,
getFieldType(
options.name
)
]
},
onSubmit: function (updated) {
point.update(
navigation.fieldsToOptions(
updated.fields,
{}
)
);
}
}
);
}
}
}
};
if (!toolbar || !toolbar.guiEnabled) {
chart.addSeries(seriesOptions);
}
fireEvent(
navigation,
'showPopup',
{
formType: 'flag',
// Enabled options:
options: {
langKey: 'flags',
type: 'flags',
title: ['A', getFieldType('A')],
name: ['Flag A', getFieldType('Flag A')]
},
// Callback on submit:
onSubmit: function (data) {
navigation.fieldsToOptions(
data.fields,
seriesOptions.data[0]
);
chart.addSeries(seriesOptions);
}
}
);
};
};
bindingsUtils.manageIndicators = function (data) {
var navigation = this,
chart = navigation.chart,
seriesConfig = {
linkedTo: data.linkedTo,
type: data.type
},
indicatorsWithVolume = [
'ad',
'cmf',
'mfi',
'vbp',
'vwap'
],
indicatorsWithAxes = [
'ad',
'atr',
'cci',
'cmf',
'macd',
'mfi',
'roc',
'rsi',
'vwap',
'ao',
'aroon',
'aroonoscillator',
'trix',
'apo',
'dpo',
'ppo',
'natr',
'williamsr',
'linearRegression',
'linearRegressionSlope',
'linearRegressionIntercept',
'linearRegressionAngle'
],
yAxis,
series;
if (data.actionType === 'edit') {
navigation.fieldsToOptions(data.fields, seriesConfig);
series = chart.get(data.seriesId);
if (series) {
series.update(seriesConfig, false);
}
} else if (data.actionType === 'remove') {
series = chart.get(data.seriesId);
if (series) {
yAxis = series.yAxis;
if (series.linkedSeries) {
series.linkedSeries.forEach(function (linkedSeries) {
linkedSeries.remove(false);
});
}
series.remove(false);
if (indicatorsWithAxes.indexOf(series.type) >= 0) {
yAxis.remove(false);
navigation.resizeYAxes();
}
}
} else {
seriesConfig.id = H.uniqueKey();
navigation.fieldsToOptions(data.fields, seriesConfig);
if (indicatorsWithAxes.indexOf(data.type) >= 0) {
yAxis = chart.addAxis({
id: H.uniqueKey(),
offset: 0,
opposite: true,
title: {
text: ''
},
tickPixelInterval: 40,
showLastLabel: false,
labels: {
align: 'left',
y: -2
}
}, false, false);
seriesConfig.yAxis = yAxis.options.id;
navigation.resizeYAxes();
}
if (indicatorsWithVolume.indexOf(data.type) >= 0) {
seriesConfig.params.volumeSeriesID = chart.series.filter(
function (series) {
return series.options.type === 'column';
}
)[0].options.id;
}
chart.addSeries(seriesConfig, false);
}
fireEvent(
navigation,
'deselectButton',
{
button: navigation.selectedButtonElement
}
);
chart.redraw();
};
/**
* Update height for an annotation. Height is calculated as a difference
* between last point in `typeOptions` and current position. It's a value,
* not pixels height.
*
* @private
* @function bindingsUtils.updateHeight
*
* @param {global.Event} e
* normalized browser event
*
* @param {Highcharts.Annotation} annotation
* Annotation to be updated
*/
bindingsUtils.updateHeight = function (e, annotation) {
annotation.update({
typeOptions: {
height: this.chart.yAxis[0].toValue(e.chartY) -
annotation.options.typeOptions.points[1].y
}
});
};
// @todo
// Consider using getHoverData(), but always kdTree (columns?)
bindingsUtils.attractToPoint = function (e, chart) {
var x = chart.xAxis[0].toValue(e.chartX),
y = chart.yAxis[0].toValue(e.chartY),
distX = Number.MAX_VALUE,
closestPoint;
chart.series.forEach(function (series) {
series.points.forEach(function (point) {
if (point && distX > Math.abs(point.x - x)) {
distX = Math.abs(point.x - x);
closestPoint = point;
}
});
});
return {
x: closestPoint.x,
y: closestPoint.y,
below: y < closestPoint.y,
series: closestPoint.series,
xAxis: closestPoint.series.xAxis.index || 0,
yAxis: closestPoint.series.yAxis.index || 0
};
};
/**
* Shorthand to check if given yAxis comes from navigator.
*
* @private
* @function bindingsUtils.isNotNavigatorYAxis
*
* @param {Highcharts.Axis} axis
* Axis
*
* @return {boolean}
*/
bindingsUtils.isNotNavigatorYAxis = function (axis) {
return axis.userOptions.className !== PREFIX + 'navigator-yaxis';
};
/**
* Update each point after specified index, most of the annotations use
* this. For example crooked line: logic behind updating each point is the
* same, only index changes when adding an annotation.
*
* Example: NavigationBindings.utils.updateNthPoint(1) - will generate
* function that updates all consecutive points except point with index=0.
*
* @private
* @function bindingsUtils.updateNthPoint
*
* @param {number} startIndex
* Index from each point should udpated
*
* @return {Function}
* Callback to be used in steps array
*/
bindingsUtils.updateNthPoint = function (startIndex) {
return function (e, annotation) {
var options = annotation.options.typeOptions,
x = this.chart.xAxis[0].toValue(e.chartX),
y = this.chart.yAxis[0].toValue(e.chartY);
options.points.forEach(function (point, index) {
if (index >= startIndex) {
point.x = x;
point.y = y;
}
});
annotation.update({
typeOptions: {
points: options.points
}
});
};
};
// Extends NavigationBindigs to support indicators and resizers:
extend(H.NavigationBindings.prototype, {
/**
* Get current positions for all yAxes. If new axis does not have position,
* returned is default height and last available top place.
*
* @private
* @function Highcharts.NavigationBindings#getYAxisPositions
*
* @param {Array<Highcharts.Axis>} yAxes
* Array of yAxes available in the chart.
*
* @param {number} plotHeight
* Available height in the chart.
*
* @param {number} defaultHeight
* Default height in percents.
*
* @return {Array}
* An array of calculated positions in percentages.
* Format: `{top: Number, height: Number}`
*/
getYAxisPositions: function (yAxes, plotHeight, defaultHeight) {
var positions,
allAxesHeight = 0;
function isPercentage(prop) {
return defined(prop) && !isNumber(prop) && prop.match('%');
}
positions = yAxes.map(function (yAxis) {
var height = isPercentage(yAxis.options.height) ?
parseFloat(yAxis.options.height) / 100 :
yAxis.height / plotHeight,
top = isPercentage(yAxis.options.top) ?
parseFloat(yAxis.options.top) / 100 :
correctFloat(
yAxis.top - yAxis.chart.plotTop
) / plotHeight;
// New yAxis does not contain "height" info yet
if (!isNumber(height)) {
height = defaultHeight / 100;
}
allAxesHeight = correctFloat(allAxesHeight + height);
return {
height: height * 100,
top: top * 100
};
});
positions.allAxesHeight = allAxesHeight;
return positions;
},
/**
* Get current resize options for each yAxis. Note that each resize is
* linked to the next axis, except the last one which shouldn't affect
* axes in the navigator. Because indicator can be removed with it's yAxis
* in the middle of yAxis array, we need to bind closest yAxes back.
*
* @private
* @function Highcharts.NavigationBindings#getYAxisResizers
*
* @param {Array<Highcharts.Axis>} yAxes
* Array of yAxes available in the chart
*
* @return {Array<object>}
* An array of resizer options.
* Format: `{enabled: Boolean, controlledAxis: { next: [String]}}`
*/
getYAxisResizers: function (yAxes) {
var resizers = [];
yAxes.forEach(function (yAxis, index) {
var nextYAxis = yAxes[index + 1];
// We have next axis, bind them:
if (nextYAxis) {
resizers[index] = {
enabled: true,
controlledAxis: {
next: [
pick(
nextYAxis.options.id,
nextYAxis.options.index
)
]
}
};
} else {
// Remove binding:
resizers[index] = {
enabled: false
};
}
});
return resizers;
},
/**
* Resize all yAxes (except navigator) to fit the plotting height. Method
* checks if new axis is added, then shrinks other main axis up to 5 panes.
* If added is more thatn 5 panes, it rescales all other axes to fit new
* yAxis.
*
* If axis is removed, and we have more than 5 panes, rescales all other
* axes. If chart has less than 5 panes, first pane receives all extra
* space.
*
* @private
* @function Highcharts.NavigationBindings#resizeYAxes
*
* @param {number} defaultHeight
* Default height for yAxis
*/
resizeYAxes: function (defaultHeight) {
defaultHeight = defaultHeight || 20; // in %, but as a number
var chart = this.chart,
// Only non-navigator axes
yAxes = chart.yAxis.filter(this.utils.isNotNavigatorYAxis),
plotHeight = chart.plotHeight,
allAxesLength = yAxes.length,
// Gather current heights (in %)
positions = this.getYAxisPositions(
yAxes,
plotHeight,
defaultHeight
),
resizers = this.getYAxisResizers(yAxes),
allAxesHeight = positions.allAxesHeight,
changedSpace = defaultHeight;
// More than 100%
if (allAxesHeight > 1) {
// Simple case, add new panes up to 5
if (allAxesLength < 6) {
// Added axis, decrease first pane's height:
positions[0].height = correctFloat(
positions[0].height - changedSpace
);
// And update all other "top" positions:
positions = this.recalculateYAxisPositions(
positions,
changedSpace
);
} else {
// We have more panes, rescale all others to gain some space,
// This is new height for upcoming yAxis:
defaultHeight = 100 / allAxesLength;
// This is how much we need to take from each other yAxis:
changedSpace = defaultHeight / (allAxesLength - 1);
// Now update all positions:
positions = this.recalculateYAxisPositions(
positions,
changedSpace,
true,
-1
);
}
// Set last position manually:
positions[allAxesLength - 1] = {
top: correctFloat(100 - defaultHeight),
height: defaultHeight
};
} else {
// Less than 100%
changedSpace = correctFloat(1 - allAxesHeight) * 100;
// Simple case, return first pane it's space:
if (allAxesLength < 5) {
positions[0].height = correctFloat(
positions[0].height + changedSpace
);
positions = this.recalculateYAxisPositions(
positions,
changedSpace
);
} else {
// There were more panes, return to each pane a bit of space:
changedSpace /= allAxesLength;
// Removed axis, add extra space to the first pane:
// And update all other positions:
positions = this.recalculateYAxisPositions(
positions,
changedSpace,
true,
1
);
}
}
positions.forEach(function (position, index) {
// if (index === 0) debugger;
yAxes[index].update({
height: position.height + '%',
top: position.top + '%',
resize: resizers[index]
}, false);
});
},
/**
* Utility to modify calculated positions according to the remaining/needed
* space. Later, these positions are used in `yAxis.update({ top, height })`
*
* @private
* @function Highcharts.NavigationBindings#recalculateYAxisPositions
*
* @param {Array<object>} positions
* Default positions of all yAxes.
*
* @param {number} changedSpace
* How much space should be added or removed.
* @param {number} adder
* `-1` or `1`, to determine whether we should add or remove space.
*
* @param {boolean} modifyHeight
* Update only `top` or both `top` and `height`.
*
* @return {Array<object>}
* Modified positions,
*/
recalculateYAxisPositions: function (
positions,
changedSpace,
modifyHeight,
adder
) {
positions.forEach(function (position, index) {
var prevPosition = positions[index - 1];
position.top = !prevPosition ? 0 :
correctFloat(prevPosition.height + prevPosition.top);
if (modifyHeight) {
position.height = correctFloat(
position.height + adder * changedSpace
);
}
});
return positions;
}
});
/**
* @type {Highcharts.Dictionary<Highcharts.StockToolsBindingsObject>|*}
* @since 7.0.0
* @optionparent navigation.bindings
*/
var stockToolsBindings = {
// Line type annotations:
/**
* A segment annotation bindings. Includes `start` and one event in `steps`
* array.
*
* @type {Highcharts.StockToolsBindingsObject}
* @product highstock
* @default {"className": "highcharts-segment", "start": function() {}, "steps": [function() {}]}
*/
segment: {
/** @ignore */
className: 'highcharts-segment',
/** @ignore */
start: function (e) {
var x = this.chart.xAxis[0].toValue(e.chartX),
y = this.chart.yAxis[0].toValue(e.chartY);
return this.chart.addAnnotation({
langKey: 'segment',
type: 'crookedLine',
typeOptions: {
points: [{
x: x,
y: y
}, {
x: x,
y: y
}]
}
});
},
/** @ignore */
steps: [
bindingsUtils.updateNthPoint(1)
]
},
/**
* A segment with an arrow annotation bindings. Includes `start` and one
* event in `steps` array.
*
* @type {Highcharts.StockToolsBindingsObject}
* @product highstock
* @default {"className": "highcharts-arrow-segment", "start": function() {}, "steps": [function() {}]}
*/
arrowSegment: {
/** @ignore */
className: 'highcharts-arrow-segment',
/** @ignore */
start: function (e) {
var x = this.chart.xAxis[0].toValue(e.chartX),
y = this.chart.yAxis[0].toValue(e.chartY);
return this.chart.addAnnotation({
langKey: 'arrowSegment',
type: 'crookedLine',
typeOptions: {
line: {
markerEnd: 'arrow'
},
points: [{
x: x,
y: y
}, {
x: x,
y: y
}]
}
});
},
/** @ignore */
steps: [
bindingsUtils.updateNthPoint(1)
]
},
/**
* A ray annotation bindings. Includes `start` and one event in `steps`
* array.
*
* @type {Highcharts.StockToolsBindingsObject}
* @product highstock
* @default {"className": "highcharts-ray", "start": function() {}, "steps": [function() {}]}
*/
ray: {
/** @ignore */
className: 'highcharts-ray',
/** @ignore */
start: function (e) {
var x = this.chart.xAxis[0].toValue(e.chartX),
y = this.chart.yAxis[0].toValue(e.chartY);
return this.chart.addAnnotation({
langKey: 'ray',
type: 'infinityLine',
typeOptions: {
type: 'ray',
points: [{
x: x,
y: y
}, {
x: x,
y: y
}]
}
});
},
/** @ignore */
steps: [
bindingsUtils.updateNthPoint(1)
]
},
/**
* A ray with an arrow annotation bindings. Includes `start` and one event
* in `steps` array.
*
* @type {Highcharts.StockToolsBindingsObject}
* @product highstock
* @default {"className": "highcharts-arrow-ray", "start": function() {}, "steps": [function() {}]}
*/
arrowRay: {
/** @ignore */
className: 'highcharts-arrow-ray',
/** @ignore */
start: function (e) {
var x = this.chart.xAxis[0].toValue(e.chartX),
y = this.chart.yAxis[0].toValue(e.chartY);
return this.chart.addAnnotation({
langKey: 'arrowRay',
type: 'infinityLine',
typeOptions: {
type: 'ray',
line: {
markerEnd: 'arrow'
},
points: [{
x: x,
y: y
}, {
x: x,
y: y
}]
}
});
},
/** @ignore */
steps: [
bindingsUtils.updateNthPoint(1)
]
},
/**
* A line annotation. Includes `start` and one event in `steps` array.
*
* @type {Highcharts.StockToolsBindingsObject}
* @product highstock
* @default {"className": "highcharts-infinity-line", "start": function() {}, "steps": [function() {}]}
*/
infinityLine: {
/** @ignore */
className: 'highcharts-infinity-line',
/** @ignore */
start: function (e) {
var x = this.chart.xAxis[0].toValue(e.chartX),
y = this.chart.yAxis[0].toValue(e.chartY);
return this.chart.addAnnotation({
langKey: 'infinityLine',
type: 'infinityLine',
typeOptions: {
type: 'line',
points: [{
x: x,
y: y
}, {
x: x,
y: y
}]
}
});
},
/** @ignore */
steps: [
bindingsUtils.updateNthPoint(1)
]
},
/**
* A line with arrow annotation. Includes `start` and one event in `steps`
* array.
*
* @type {Highcharts.StockToolsBindingsObject}
* @product highstock
* @default {"className": "highcharts-arrow-infinity-line", "start": function() {}, "steps": [function() {}]}
*/
arrowInfinityLine: {
/** @ignore */
className: 'highcharts-arrow-infinity-line',
/** @ignore */
start: function (e) {
var x = this.chart.xAxis[0].toValue(e.chartX),
y = this.chart.yAxis[0].toValue(e.chartY);
return this.chart.addAnnotation({
langKey: 'arrowInfinityLine',
type: 'infinityLine',
typeOptions: {
type: 'line',
line: {
markerEnd: 'arrow'
},
points: [{
x: x,
y: y
}, {
x: x,
y: y
}]
}
});
},
/** @ignore */
steps: [
bindingsUtils.updateNthPoint(1)
]
},
/**
* A horizontal line annotation. Includes `start` event.
*
* @type {Highcharts.StockToolsBindingsObject}
* @product highstock
* @default {"className": "highcharts-horizontal-line", "start": function() {}}
*/
horizontalLine: {
/** @ignore */
className: 'highcharts-horizontal-line',
/** @ignore */
start: function (e) {
var x = this.chart.xAxis[0].toValue(e.chartX),
y = this.chart.yAxis[0].toValue(e.chartY);
this.chart.addAnnotation({
langKey: 'horizontalLine',
type: 'infinityLine',
typeOptions: {
type: 'horizontalLine',
points: [{
x: x,
y: y
}]
}
});
}
},
/**
* A vertical line annotation. Includes `start` event.
*
* @type {Highcharts.StockToolsBindingsObject}
* @product highstock
* @default {"className": "highcharts-vertical-line", "start": function() {}}
*/
verticalLine: {
/** @ignore */
className: 'highcharts-vertical-line',
/** @ignore */
start: function (e) {
var x = this.chart.xAxis[0].toValue(e.chartX),
y = this.chart.yAxis[0].toValue(e.chartY);
this.chart.addAnnotation({
langKey: 'verticalLine',
type: 'infinityLine',
typeOptions: {
type: 'verticalLine',
points: [{
x: x,
y: y
}]
}
});
}
},
/**
* Crooked line (three points) annotation bindings. Includes `start` and two
* events in `steps` (for second and third points in crooked line) array.
*
* @type {Highcharts.StockToolsBindingsObject}
* @product highstock
* @default {"className": "highcharts-crooked3", "start": function() {}, "steps": [function() {}, function() {}]}
*/
// Crooked Line type annotations:
crooked3: {
/** @ignore */
className: 'highcharts-crooked3',
/** @ignore */
start: function (e) {
var x = this.chart.xAxis[0].toValue(e.chartX),
y = this.chart.yAxis[0].toValue(e.chartY);
return this.chart.addAnnotation({
langKey: 'crooked3',
type: 'crookedLine',
typeOptions: {
points: [{
x: x,
y: y
}, {
x: x,
y: y
}, {
x: x,
y: y
}]
}
});
},
/** @ignore */
steps: [
bindingsUtils.updateNthPoint(1),
bindingsUtils.updateNthPoint(2)
]
},
/**
* Crooked line (five points) annotation bindings. Includes `start` and four
* events in `steps` (for all consequent points in crooked line) array.
*
* @type {Highcharts.StockToolsBindingsObject}
* @product highstock
* @default {"className": "highcharts-crooked3", "start": function() {}, "steps": [function() {}, function() {}, function() {}, function() {}]}
*/
crooked5: {
/** @ignore */
className: 'highcharts-crooked5',
/** @ignore */
start: function (e) {
var x = this.chart.xAxis[0].toValue(e.chartX),
y = this.chart.yAxis[0].toValue(e.chartY);
return this.chart.addAnnotation({
langKey: 'crookedLine',
type: 'crookedLine',
typeOptions: {
points: [{
x: x,
y: y
}, {
x: x,
y: y
}, {
x: x,
y: y
}, {
x: x,
y: y
}, {
x: x,
y: y
}]
}
});
},
/** @ignore */
steps: [
bindingsUtils.updateNthPoint(1),
bindingsUtils.updateNthPoint(2),
bindingsUtils.updateNthPoint(3),
bindingsUtils.updateNthPoint(4)
]
},
/**
* Elliott wave (three points) annotation bindings. Includes `start` and two
* events in `steps` (for second and third points) array.
*
* @type {Highcharts.StockToolsBindingsObject}
* @product highstock
* @default {"className": "highcharts-elliott3", "start": function() {}, "steps": [function() {}, function() {}]}
*/
elliott3: {
/** @ignore */
className: 'highcharts-elliott3',
/** @ignore */
start: function (e) {
var x = this.chart.xAxis[0].toValue(e.chartX),
y = this.chart.yAxis[0].toValue(e.chartY);
return this.chart.addAnnotation({
langKey: 'elliott3',
type: 'elliottWave',
typeOptions: {
points: [{
x: x,
y: y
}, {
x: x,
y: y
}, {
x: x,
y: y
}]
},
labelOptions: {
style: {
color: '#666666'
}
}
});
},
/** @ignore */
steps: [
bindingsUtils.updateNthPoint(1),
bindingsUtils.updateNthPoint(2)
]
},
/**
* Elliott wave (five points) annotation bindings. Includes `start` and four
* event in `steps` (for all consequent points in Elliott wave) array.
*
* @type {Highcharts.StockToolsBindingsObject}
* @product highstock
* @default {"className": "highcharts-elliott3", "start": function() {}, "steps": [function() {}, function() {}, function() {}, function() {}]}
*/
elliott5: {
/** @ignore */
className: 'highcharts-elliott5',
/** @ignore */
start: function (e) {
var x = this.chart.xAxis[0].toValue(e.chartX),
y = this.chart.yAxis[0].toValue(e.chartY);
return this.chart.addAnnotation({
langKey: 'elliott5',
type: 'elliottWave',
typeOptions: {
points: [{
x: x,
y: y
}, {
x: x,
y: y
}, {
x: x,
y: y
}, {
x: x,
y: y
}, {
x: x,
y: y
}]
},
labelOptions: {
style: {
color: '#666666'
}
}
});
},
/** @ignore */
steps: [
bindingsUtils.updateNthPoint(1),
bindingsUtils.updateNthPoint(2),
bindingsUtils.updateNthPoint(3),
bindingsUtils.updateNthPoint(4)
]
},
/**
* A measure (x-dimension) annotation bindings. Includes `start` and one
* event in `steps` array.
*
* @type {Highcharts.StockToolsBindingsObject}
* @product highstock
* @default {"className": "highcharts-measure-x", "start": function() {}, "steps": [function() {}]}
*/
measureX: {
/** @ignore */
className: 'highcharts-measure-x',
/** @ignore */
start: function (e) {
var x = this.chart.xAxis[0].toValue(e.chartX),
y = this.chart.yAxis[0].toValue(e.chartY),
options = {
langKey: 'measure',
type: 'measure',
typeOptions: {
selectType: 'x',
point: {
x: x,
y: y,
xAxis: 0,
yAxis: 0
},
crosshairX: {
strokeWidth: 1,
stroke: '#000000'
},
crosshairY: {
enabled: false,
strokeWidth: 0,
stroke: '#000000'
},
background: {
width: 0,
height: 0,
strokeWidth: 0,
stroke: '#ffffff'
}
},
labelOptions: {
style: {
color: '#666666'
}
}
};
return this.chart.addAnnotation(options);
},
/** @ignore */
steps: [
bindingsUtils.updateRectSize
]
},
/**
* A measure (y-dimension) annotation bindings. Includes `start` and one
* event in `steps` array.
*
* @type {Highcharts.StockToolsBindingsObject}
* @product highstock
* @default {"className": "highcharts-measure-y", "start": function() {}, "steps": [function() {}]}
*/
measureY: {
/** @ignore */
className: 'highcharts-measure-y',
/** @ignore */
start: function (e) {
var x = this.chart.xAxis[0].toValue(e.chartX),
y = this.chart.yAxis[0].toValue(e.chartY),
options = {
langKey: 'measure',
type: 'measure',
typeOptions: {
selectType: 'y',
point: {
x: x,
y: y,
xAxis: 0,
yAxis: 0
},
crosshairX: {
enabled: false,
strokeWidth: 0,
stroke: '#000000'
},
crosshairY: {
strokeWidth: 1,
stroke: '#000000'
},
background: {
width: 0,
height: 0,
strokeWidth: 0,
stroke: '#ffffff'
}
},
labelOptions: {
style: {
color: '#666666'
}
}
};
return this.chart.addAnnotation(options);
},
/** @ignore */
steps: [
bindingsUtils.updateRectSize
]
},
/**
* A measure (xy-dimension) annotation bindings. Includes `start` and one
* event in `steps` array.
*
* @type {Highcharts.StockToolsBindingsObject}
* @product highstock
* @default {"className": "highcharts-measure-xy", "start": function() {}, "steps": [function() {}]}
*/
measureXY: {
/** @ignore */
className: 'highcharts-measure-xy',
/** @ignore */
start: function (e) {
var x = this.chart.xAxis[0].toValue(e.chartX),
y = this.chart.yAxis[0].toValue(e.chartY),
options = {
langKey: 'measure',
type: 'measure',
typeOptions: {
selectType: 'xy',
point: {
x: x,
y: y,
xAxis: 0,
yAxis: 0
},
background: {
width: 0,
height: 0,
strokeWidth: 0,
stroke: '#000000'
},
crosshairX: {
strokeWidth: 1,
stroke: '#000000'
},
crosshairY: {
strokeWidth: 1,
stroke: '#000000'
}
},
labelOptions: {
style: {
color: '#666666'
}
}
};
return this.chart.addAnnotation(options);
},
/** @ignore */
steps: [
bindingsUtils.updateRectSize
]
},
// Advanced type annotations:
/**
* A fibonacci annotation bindings. Includes `start` and two events in
* `steps` array (updates second point, then height).
*
* @type {Highcharts.StockToolsBindingsObject}
* @product highstock
* @default {"className": "highcharts-fibonacci", "start": function() {}, "steps": [function() {}, function() {}]}
*/
fibonacci: {
/** @ignore */
className: 'highcharts-fibonacci',
/** @ignore */
start: function (e) {
var x = this.chart.xAxis[0].toValue(e.chartX),
y = this.chart.yAxis[0].toValue(e.chartY);
return this.chart.addAnnotation({
langKey: 'fibonacci',
type: 'fibonacci',
typeOptions: {
points: [{
x: x,
y: y
}, {
x: x,
y: y
}]
},
labelOptions: {
style: {
color: '#666666'
}
}
});
},
/** @ignore */
steps: [
bindingsUtils.updateNthPoint(1),
bindingsUtils.updateHeight
]
},
/**
* A parallel channel (tunnel) annotation bindings. Includes `start` and
* two events in `steps` array (updates second point, then height).
*
* @type {Highcharts.StockToolsBindingsObject}
* @product highstock
* @default {"className": "highcharts-parallel-channel", "start": function() {}, "steps": [function() {}, function() {}]}
*/
parallelChannel: {
/** @ignore */
className: 'highcharts-parallel-channel',
/** @ignore */
start: function (e) {
var x = this.chart.xAxis[0].toValue(e.chartX),
y = this.chart.yAxis[0].toValue(e.chartY);
return this.chart.addAnnotation({
langKey: 'parallelChannel',
type: 'tunnel',
typeOptions: {
points: [{
x: x,
y: y
}, {
x: x,
y: y
}]
}
});
},
/** @ignore */
steps: [
bindingsUtils.updateNthPoint(1),
bindingsUtils.updateHeight
]
},
/**
* An Andrew's pitchfork annotation bindings. Includes `start` and two
* events in `steps` array (sets second and third control points).
*
* @type {Highcharts.StockToolsBindingsObject}
* @product highstock
* @default {"className": "highcharts-pitchfork", "start": function() {}, "steps": [function() {}, function() {}]}
*/
pitchfork: {
/** @ignore */
className: 'highcharts-pitchfork',
/** @ignore */
start: function (e) {
var x = this.chart.xAxis[0].toValue(e.chartX),
y = this.chart.yAxis[0].toValue(e.chartY);
return this.chart.addAnnotation({
langKey: 'pitchfork',
type: 'pitchfork',
typeOptions: {
points: [{
x: x,
y: y,
controlPoint: {
style: {
fill: 'red'
}
}
}, {
x: x,
y: y
}, {
x: x,
y: y
}],
innerBackground: {
fill: 'rgba(100, 170, 255, 0.8)'
}
},
shapeOptions: {
strokeWidth: 2
}
});
},
/** @ignore */
steps: [
bindingsUtils.updateNthPoint(1),
bindingsUtils.updateNthPoint(2)
]
},
// Labels with arrow and auto increments
/**
* A vertical counter annotation bindings. Includes `start` event. On click,
* finds the closest point and marks it with a numeric annotation -
* incrementing counter on each add.
*
* @type {Highcharts.StockToolsBindingsObject}
* @product highstock
* @default {"className": "highcharts-vertical-counter", "start": function() {}}
*/
verticalCounter: {
/** @ignore */
className: 'highcharts-vertical-counter',
/** @ignore */
start: function (e) {
var closestPoint = bindingsUtils.attractToPoint(e, this.chart),
annotation;
if (!defined(this.verticalCounter)) {
this.verticalCounter = 0;
}
annotation = this.chart.addAnnotation({
langKey: 'verticalCounter',
type: 'verticalLine',
typeOptions: {
point: {
x: closestPoint.x,
y: closestPoint.y,
xAxis: closestPoint.xAxis,
yAxis: closestPoint.yAxis
},
label: {
offset: closestPoint.below ? 40 : -40,
text: this.verticalCounter.toString()
}
},
labelOptions: {
style: {
color: '#666666',
fontSize: '11px'
}
},
shapeOptions: {
stroke: 'rgba(0, 0, 0, 0.75)',
strokeWidth: 1
}
});
this.verticalCounter++;
annotation.options.events.click.call(annotation, {});
}
},
/**
* A vertical arrow annotation bindings. Includes `start` event. On click,
* finds the closest point and marks it with an arrow and a label with
* value.
*
* @type {Highcharts.StockToolsBindingsObject}
* @product highstock
* @default {"className": "highcharts-vertical-label", "start": function() {}}
*/
verticalLabel: {
/** @ignore */
className: 'highcharts-vertical-label',
/** @ignore */
start: function (e) {
var closestPoint = bindingsUtils.attractToPoint(e, this.chart),
annotation;
annotation = this.chart.addAnnotation({
langKey: 'verticalLabel',
type: 'verticalLine',
typeOptions: {
point: {
x: closestPoint.x,
y: closestPoint.y,
xAxis: closestPoint.xAxis,
yAxis: closestPoint.yAxis
},
label: {
offset: closestPoint.below ? 40 : -40
}
},
labelOptions: {
style: {
color: '#666666',
fontSize: '11px'
}
},
shapeOptions: {
stroke: 'rgba(0, 0, 0, 0.75)',
strokeWidth: 1
}
});
annotation.options.events.click.call(annotation, {});
}
},
/**
* A vertical arrow annotation bindings. Includes `start` event. On click,
* finds the closest point and marks it with an arrow. Green arrow when
* pointing from above, red when pointing from below the point.
*
* @type {Highcharts.StockToolsBindingsObject}
* @product highstock
* @default {"className": "highcharts-vertical-arrow", "start": function() {}}
*/
verticalArrow: {
/** @ignore */
className: 'highcharts-vertical-arrow',
/** @ignore */
start: function (e) {
var closestPoint = bindingsUtils.attractToPoint(e, this.chart),
annotation;
annotation = this.chart.addAnnotation({
langKey: 'verticalArrow',
type: 'verticalLine',
typeOptions: {
point: {
x: closestPoint.x,
y: closestPoint.y,
xAxis: closestPoint.xAxis,
yAxis: closestPoint.yAxis
},
label: {
offset: closestPoint.below ? 40 : -40,
format: ' '
},
connector: {
fill: 'none',
stroke: closestPoint.below ? 'red' : 'green'
}
},
shapeOptions: {
stroke: 'rgba(0, 0, 0, 0.75)',
strokeWidth: 1
}
});
annotation.options.events.click.call(annotation, {});
}
},
// Flag types:
/**
* A flag series bindings. Includes `start` event. On click, finds the
* closest point and marks it with a flag with `'circlepin'` shape.
*
* @type {Highcharts.StockToolsBindingsObject}
* @product highstock
* @default {"className": "highcharts-flag-circlepin", "start": function() {}}
*/
flagCirclepin: {
/** @ignore */
className: 'highcharts-flag-circlepin',
/** @ignore */
start: bindingsUtils
.addFlagFromForm('circlepin')
},
/**
* A flag series bindings. Includes `start` event. On click, finds the
* closest point and marks it with a flag with `'diamondpin'` shape.
*
* @type {Highcharts.StockToolsBindingsObject}
* @product highstock
* @default {"className": "highcharts-flag-diamondpin", "start": function() {}}
*/
flagDiamondpin: {
/** @ignore */
className: 'highcharts-flag-diamondpin',
/** @ignore */
start: bindingsUtils
.addFlagFromForm('flag')
},
/**
* A flag series bindings. Includes `start` event.
* On click, finds the closest point and marks it with a flag with
* `'squarepin'` shape.
*
* @type {Highcharts.StockToolsBindingsObject}
* @product highstock
* @default {"className": "highcharts-flag-squarepin", "start": function() {}}
*/
flagSquarepin: {
/** @ignore */
className: 'highcharts-flag-squarepin',
/** @ignore */
start: bindingsUtils
.addFlagFromForm('squarepin')
},
/**
* A flag series bindings. Includes `start` event.
* On click, finds the closest point and marks it with a flag without pin
* shape.
*
* @type {Highcharts.StockToolsBindingsObject}
* @product highstock
* @default {"className": "highcharts-flag-simplepin", "start": function() {}}
*/
flagSimplepin: {
/** @ignore */
className: 'highcharts-flag-simplepin',
/** @ignore */
start: bindingsUtils
.addFlagFromForm('nopin')
},
// Other tools:
/**
* Enables zooming in xAxis on a chart. Includes `start` event which
* changes [chart.zoomType](#chart.zoomType).
*
* @type {Highcharts.StockToolsBindingsObject}
* @product highstock
* @default {"className": "highcharts-zoom-x", "init": function() {}}
*/
zoomX: {
/** @ignore */
className: 'highcharts-zoom-x',
/** @ignore */
init: function (button) {
this.chart.update({
chart: {
zoomType: 'x'
}
});
fireEvent(
this,
'deselectButton',
{ button: button }
);
}
},
/**
* Enables zooming in yAxis on a chart. Includes `start` event which
* changes [chart.zoomType](#chart.zoomType).
*
* @type {Highcharts.StockToolsBindingsObject}
* @product highstock
* @default {"className": "highcharts-zoom-y", "init": function() {}}
*/
zoomY: {
/** @ignore */
className: 'highcharts-zoom-y',
/** @ignore */
init: function (button) {
this.chart.update({
chart: {
zoomType: 'y'
}
});
fireEvent(
this,
'deselectButton',
{ button: button }
);
}
},
/**
* Enables zooming in xAxis and yAxis on a chart. Includes `start` event
* which changes [chart.zoomType](#chart.zoomType).
*
* @type {Highcharts.StockToolsBindingsObject}
* @product highstock
* @default {"className": "highcharts-zoom-xy", "init": function() {}}
*/
zoomXY: {
/** @ignore */
className: 'highcharts-zoom-xy',
/** @ignore */
init: function (button) {
this.chart.update({
chart: {
zoomType: 'xy'
}
});
fireEvent(
this,
'deselectButton',
{ button: button }
);
}
},
/**
* Changes main series to `'line'` type.
*
* @type {Highcharts.StockToolsBindingsObject}
* @product highstock
* @default {"className": "highcharts-series-type-line", "init": function() {}}
*/
seriesTypeLine: {
/** @ignore */
className: 'highcharts-series-type-line',
/** @ignore */
init: function (button) {
this.chart.series[0].update({
type: 'line',
useOhlcData: true
});
fireEvent(
this,
'deselectButton',
{ button: button }
);
}
},
/**
* Changes main series to `'ohlc'` type.
*
* @type {Highcharts.StockToolsBindingsObject}
* @product highstock
* @default {"className": "highcharts-series-type-ohlc", "init": function() {}}
*/
seriesTypeOhlc: {
/** @ignore */
className: 'highcharts-series-type-ohlc',
/** @ignore */
init: function (button) {
this.chart.series[0].update({
type: 'ohlc'
});
fireEvent(
this,
'deselectButton',
{ button: button }
);
}
},
/**
* Changes main series to `'candlestick'` type.
*
* @type {Highcharts.StockToolsBindingsObject}
* @product highstock
* @default {"className": "highcharts-series-type-candlestick", "init": function() {}}
*/
seriesTypeCandlestick: {
/** @ignore */
className: 'highcharts-series-type-candlestick',
/** @ignore */
init: function (button) {
this.chart.series[0].update({
type: 'candlestick'
});
fireEvent(
this,
'deselectButton',
{ button: button }
);
}
},
/**
* Displays chart in fullscreen.
*
* @type {Highcharts.StockToolsBindingsObject}
* @product highstock
* @default {"className": "highcharts-full-screen", "init": function() {}}
*/
fullScreen: {
/** @ignore */
className: 'highcharts-full-screen',
/** @ignore */
init: function (button) {
var chart = this.chart;
chart.fullScreen = new H.FullScreen(chart.container);
fireEvent(
this,
'deselectButton',
{ button: button }
);
}
},
/**
* Hides/shows two price indicators:
* - last price in the dataset
* - last price in the selected range
*
* @type {Highcharts.StockToolsBindingsObject}
* @product highstock
* @default {"className": "highcharts-current-price-indicator", "init": function() {}}
*/
currentPriceIndicator: {
/** @ignore */
className: 'highcharts-current-price-indicator',
/** @ignore */
init: function (button) {
var series = this.chart.series[0],
options = series.options,
lastVisiblePrice = options.lastVisiblePrice &&
options.lastVisiblePrice.enabled,
lastPrice = options.lastPrice && options.lastPrice.enabled,
gui = this.chart.stockToolbar;
if (gui && gui.guiEnabled) {
if (lastPrice) {
button.firstChild.style['background-image'] =
'url("' + gui.options.iconsURL +
'current-price-show.svg")';
} else {
button.firstChild.style['background-image'] =
'url("' + gui.options.iconsURL +
'current-price-hide.svg")';
}
}
series.update({
// line
lastPrice: {
enabled: !lastPrice,
color: 'red'
},
// label
lastVisiblePrice: {
enabled: !lastVisiblePrice,
label: {
enabled: true
}
}
});
fireEvent(
this,
'deselectButton',
{ button: button }
);
}
},
/**
* Indicators bindings. Includes `init` event to show a popup.
*
* @type {Highcharts.StockToolsBindingsObject}
* @product highstock
* @default {"className": "highcharts-indicators", "init": function() {}}
*/
indicators: {
/** @ignore */
className: 'highcharts-indicators',
/** @ignore */
init: function () {
var navigation = this;
fireEvent(
navigation,
'showPopup',
{
formType: 'indicators',
options: {},
// Callback on submit:
onSubmit: function (data) {
navigation.utils.manageIndicators.call(
navigation,
data
);
}
}
);
}
},
/**
* Hides/shows all annotations on a chart.
*
* @type {Highcharts.StockToolsBindingsObject}
* @product highstock
* @default {"className": "highcharts-toggle-annotations", "init": function() {}}
*/
toggleAnnotations: {
/** @ignore */
className: 'highcharts-toggle-annotations',
/** @ignore */
init: function (button) {
var gui = this.chart.stockToolbar;
this.toggledAnnotations = !this.toggledAnnotations;
(this.chart.annotations || []).forEach(function (annotation) {
annotation.setVisibility(!this.toggledAnnotations);
}, this);
if (gui && gui.guiEnabled) {
if (this.toggledAnnotations) {
button.firstChild.style['background-image'] =
'url("' + gui.options.iconsURL +
'annotations-hidden.svg")';
} else {
button.firstChild.style['background-image'] =
'url("' + gui.options.iconsURL +
'annotations-visible.svg")';
}
}
fireEvent(
this,
'deselectButton',
{ button: button }
);
}
},
/**
* Save a chart in localStorage under `highcharts-chart` key.
* Stored items:
* - annotations
* - indicators (with yAxes)
* - flags
*
* @type {Highcharts.StockToolsBindingsObject}
* @product highstock
* @default {"className": "highcharts-save-chart", "init": function() {}}
*/
saveChart: {
/** @ignore */
className: 'highcharts-save-chart',
/** @ignore */
init: function (button) {
var navigation = this,
chart = navigation.chart,
annotations = [],
indicators = [],
flags = [],
yAxes = [];
chart.annotations.forEach(function (annotation, index) {
annotations[index] = annotation.userOptions;
});
chart.series.forEach(function (series) {
if (series instanceof H.seriesTypes.sma) {
indicators.push(series.userOptions);
} else if (series.type === 'flags') {
flags.push(series.userOptions);
}
});
chart.yAxis.forEach(function (yAxis) {
if (navigation.utils.isNotNavigatorYAxis(yAxis)) {
yAxes.push(yAxis.options);
}
});
H.win.localStorage.setItem(
PREFIX + 'chart',
JSON.stringify({
annotations: annotations,
indicators: indicators,
flags: flags,
yAxes: yAxes
})
);
fireEvent(
this,
'deselectButton',
{ button: button }
);
}
}
};
H.setOptions({
navigation: {
bindings: stockToolsBindings
}
});
}(Highcharts));
(function (H) {
/**
* GUI generator for Stock tools
*
* (c) 2009-2017 Sebastian Bochan
*
* License: www.highcharts.com/license
*/
var addEvent = H.addEvent,
createElement = H.createElement,
pick = H.pick,
isArray = H.isArray,
fireEvent = H.fireEvent,
getStyle = H.getStyle,
merge = H.merge,
css = H.css,
win = H.win,
DIV = 'div',
SPAN = 'span',
UL = 'ul',
LI = 'li',
PREFIX = 'highcharts-',
activeClass = PREFIX + 'active';
H.setOptions({
/**
* @optionparent lang
*/
lang: {
/**
* Configure the stockTools GUI titles(hints) in the chart. Requires
* the `stock-tools.js` module to be loaded.
*
* @product highstock
* @since 7.0.0
* @type {Object}
*/
stockTools: {
gui: {
// Main buttons:
simpleShapes: 'Simple shapes',
lines: 'Lines',
crookedLines: 'Crooked lines',
measure: 'Measure',
advanced: 'Advanced',
toggleAnnotations: 'Toggle annotations',
verticalLabels: 'Vertical labels',
flags: 'Flags',
zoomChange: 'Zoom change',
typeChange: 'Type change',
saveChart: 'Save chart',
indicators: 'Indicators',
currentPriceIndicator: 'Current Price Indicators',
// Other features:
zoomX: 'Zoom X',
zoomY: 'Zoom Y',
zoomXY: 'Zooom XY',
fullScreen: 'Fullscreen',
typeOHLC: 'OHLC',
typeLine: 'Line',
typeCandlestick: 'Candlestick',
// Basic shapes:
circle: 'Circle',
label: 'Label',
rectangle: 'Rectangle',
// Flags:
flagCirclepin: 'Flag circle',
flagDiamondpin: 'Flag diamond',
flagSquarepin: 'Flag square',
flagSimplepin: 'Flag simple',
// Measures:
measureXY: 'Measure XY',
measureX: 'Measure X',
measureY: 'Measure Y',
// Segment, ray and line:
segment: 'Segment',
arrowSegment: 'Arrow segment',
ray: 'Ray',
arrowRay: 'Arrow ray',
line: 'Line',
arrowLine: 'Arrow line',
horizontalLine: 'Horizontal line',
verticalLine: 'Vertical line',
infinityLine: 'Infinity line',
// Crooked lines:
crooked3: 'Crooked 3 line',
crooked5: 'Crooked 5 line',
elliott3: 'Elliott 3 line',
elliott5: 'Elliott 5 line',
// Counters:
verticalCounter: 'Vertical counter',
verticalLabel: 'Vertical label',
verticalArrow: 'Vertical arrow',
// Advanced:
fibonacci: 'Fibonacci',
pitchfork: 'Pitchfork',
parallelChannel: 'Parallel channel'
}
},
navigation: {
popup: {
// Annotations:
circle: 'Circle',
rectangle: 'Rectangle',
label: 'Label',
segment: 'Segment',
arrowSegment: 'Arrow segment',
ray: 'Ray',
arrowRay: 'Arrow ray',
line: 'Line',
arrowLine: 'Arrow line',
horizontalLine: 'Horizontal line',
verticalLine: 'Vertical line',
crooked3: 'Crooked 3 line',
crooked5: 'Crooked 5 line',
elliott3: 'Elliott 3 line',
elliott5: 'Elliott 5 line',
verticalCounter: 'Vertical counter',
verticalLabel: 'Vertical label',
verticalArrow: 'Vertical arrow',
fibonacci: 'Fibonacci',
pitchfork: 'Pitchfork',
parallelChannel: 'Parallel channel',
infinityLine: 'Infinity line',
measure: 'Measure',
measureXY: 'Measure XY',
measureX: 'Measure X',
measureY: 'Measure Y',
// Flags:
flags: 'Flags',
// GUI elements:
addButton: 'add',
saveButton: 'save',
editButton: 'edit',
removeButton: 'remove',
series: 'Series',
volume: 'Volume',
connector: 'Connector',
// Field names:
innerBackground: 'Inner background',
outerBackground: 'Outer background',
crosshairX: 'Crosshair X',
crosshairY: 'Crosshair Y',
tunnel: 'Tunnel',
background: 'Background'
}
}
},
/**
* Configure the stockTools gui strings in the chart. Requires the
* [stockTools module]() to be loaded. For a description of the module
* and information on its features, see [Highcharts StockTools]().
*
* @product highstock
*
* @sample stock/demo/stock-tools-gui Stock Tools GUI
*
* @sample stock/demo/stock-tools-custom-gui Stock Tools customized GUI
*
* @since 7.0.0
* @type {Object}
* @optionparent stockTools
*/
stockTools: {
/**
* Definitions of buttons in Stock Tools GUI.
*/
gui: {
/**
* Enable or disable the stockTools gui.
*
* @type {boolean}
* @default true
*/
enabled: true,
/**
* A CSS class name to apply to the stocktools' div,
* allowing unique CSS styling for each chart.
*
* @type {string}
* @default 'highcharts-bindings-wrapper'
*
*/
className: 'highcharts-bindings-wrapper',
/**
* A CSS class name to apply to the container of buttons,
* allowing unique CSS styling for each chart.
*
* @type {string}
* @default 'stocktools-toolbar'
*
*/
toolbarClassName: 'stocktools-toolbar',
/**
* Path where Highcharts will look for icons. Change this to use
* icons from a different server.
*/
iconsURL: 'https://code.highcharts.com/7.0.3/gfx/stock-icons/',
/**
* A collection of strings pointing to config options for the
* toolbar items. Each name refers to unique key from definitions
* object.
*
* @type {array}
*
* @default [
* 'indicators',
* 'separator',
* 'simpleShapes',
* 'lines',
* 'crookedLines',
* 'measure',
* 'advanced',
* 'toggleAnnotations',
* 'separator',
* 'verticalLabels',
* 'flags',
* 'separator',
* 'zoomChange',
* 'fullScreen',
* 'typeChange',
* 'separator',
* 'currentPriceIndicator',
* 'saveChart'
* ]
*/
buttons: [
'indicators',
'separator',
'simpleShapes',
'lines',
'crookedLines',
'measure',
'advanced',
'toggleAnnotations',
'separator',
'verticalLabels',
'flags',
'separator',
'zoomChange',
'fullScreen',
'typeChange',
'separator',
'currentPriceIndicator',
'saveChart'
],
/**
* An options object of the buttons definitions. Each name refers to
* unique key from buttons array.
*
* @type {object}
*
*/
definitions: {
separator: {
/**
* A predefined background symbol for the button.
*
* @type {string}
*/
symbol: 'separator.svg'
},
simpleShapes: {
/**
* A collection of strings pointing to config options for
* the items.
*
* @type {array}
* @default [
* 'label',
* 'circle',
* 'rectangle'
* ]
*
*/
items: [
'label',
'circle',
'rectangle'
],
circle: {
/**
* A predefined background symbol for the button.
*
* @type {string}
*
*/
symbol: 'circle.svg'
},
rectangle: {
/**
* A predefined background symbol for the button.
*
* @type {string}
*
*/
symbol: 'rectangle.svg'
},
label: {
/**
* A predefined background symbol for the button.
*
* @type {string}
*
*/
symbol: 'label.svg'
}
},
flags: {
/**
* A collection of strings pointing to config options for
* the items.
*
* @type {array}
* @default [
* 'flagCirclepin',
* 'flagDiamondpin',
* 'flagSquarepin',
* 'flagSimplepin'
* ]
*
*/
items: [
'flagCirclepin',
'flagDiamondpin',
'flagSquarepin',
'flagSimplepin'
],
flagSimplepin: {
/**
* A predefined background symbol for the button.
*
* @type {string}
*
*/
symbol: 'flag-basic.svg'
},
flagDiamondpin: {
/**
* A predefined background symbol for the button.
*
* @type {string}
*
*/
symbol: 'flag-diamond.svg'
},
flagSquarepin: {
/**
* A predefined background symbol for the button.
*
* @type {string}
*/
symbol: 'flag-trapeze.svg'
},
flagCirclepin: {
/**
* A predefined background symbol for the button.
*
* @type {string}
*/
symbol: 'flag-elipse.svg'
}
},
lines: {
/**
* A collection of strings pointing to config options for
* the items.
*
* @type {array}
* @default [
* 'segment',
* 'arrowSegment',
* 'ray',
* 'arrowRay',
* 'line',
* 'arrowLine',
* 'horizontalLine',
* 'verticalLine'
* ]
*/
items: [
'segment',
'arrowSegment',
'ray',
'arrowRay',
'line',
'arrowLine',
'horizontalLine',
'verticalLine'
],
segment: {
/**
* A predefined background symbol for the button.
*
* @type {string}
*/
symbol: 'segment.svg'
},
arrowSegment: {
/**
* A predefined background symbol for the button.
*
* @type {string}
*/
symbol: 'arrow-segment.svg'
},
ray: {
/**
* A predefined background symbol for the button.
*
* @type {string}
*/
symbol: 'ray.svg'
},
arrowRay: {
/**
* A predefined background symbol for the button.
*
* @type {string}
*/
symbol: 'arrow-ray.svg'
},
line: {
/**
* A predefined background symbol for the button.
*
* @type {string}
*/
symbol: 'line.svg'
},
arrowLine: {
/**
* A predefined background symbol for the button.
*
* @type {string}
*/
symbol: 'arrow-line.svg'
},
verticalLine: {
/**
* A predefined background symbol for the button.
*
* @type {string}
*/
symbol: 'vertical-line.svg'
},
horizontalLine: {
/**
* A predefined background symbol for the button.
*
* @type {string}
*/
symbol: 'horizontal-line.svg'
}
},
crookedLines: {
/**
* A collection of strings pointing to config options for
* the items.
*
* @type {array}
* @default [
* 'elliott3',
* 'elliott5',
* 'crooked3',
* 'crooked5'
* ]
*
*/
items: [
'elliott3',
'elliott5',
'crooked3',
'crooked5'
],
crooked3: {
/**
* A predefined background symbol for the button.
*
* @type {string}
*/
symbol: 'crooked-3.svg'
},
crooked5: {
/**
* A predefined background symbol for the button.
*
* @type {string}
*/
symbol: 'crooked-5.svg'
},
elliott3: {
/**
* A predefined background symbol for the button.
*
* @type {string}
*/
symbol: 'elliott-3.svg'
},
elliott5: {
/**
* A predefined background symbol for the button.
*
* @type {string}
*/
symbol: 'elliott-5.svg'
}
},
verticalLabels: {
/**
* A collection of strings pointing to config options for
* the items.
*
* @type {array}
* @default [
* 'verticalCounter',
* 'verticalLabel',
* 'verticalArrow'
* ]
*/
items: [
'verticalCounter',
'verticalLabel',
'verticalArrow'
],
verticalCounter: {
/**
* A predefined background symbol for the button.
*
* @type {string}
*/
symbol: 'vertical-counter.svg'
},
verticalLabel: {
/**
* A predefined background symbol for the button.
*
* @type {string}
*/
symbol: 'vertical-label.svg'
},
verticalArrow: {
/**
* A predefined background symbol for the button.
*
* @type {string}
*/
symbol: 'vertical-arrow.svg'
}
},
advanced: {
/**
* A collection of strings pointing to config options for
* the items.
*
* @type {array}
* @default [
* 'fibonacci',
* 'pitchfork',
* 'parallelChannel'
* ]
*/
items: [
'fibonacci',
'pitchfork',
'parallelChannel'
],
pitchfork: {
/**
* A predefined background symbol for the button.
*
* @type {string}
*/
symbol: 'pitchfork.svg'
},
fibonacci: {
/**
* A predefined background symbol for the button.
*
* @type {string}
*/
symbol: 'fibonacci.svg'
},
parallelChannel: {
/**
* A predefined background symbol for the button.
*
* @type {string}
*/
symbol: 'parallel-channel.svg'
}
},
measure: {
/**
* A collection of strings pointing to config options for
* the items.
*
* @type {array}
* @default [
* 'measureXY',
* 'measureX',
* 'measureY'
* ]
*/
items: [
'measureXY',
'measureX',
'measureY'
],
measureX: {
/**
* A predefined background symbol for the button.
*
* @type {string}
*/
symbol: 'measure-x.svg'
},
measureY: {
/**
* A predefined background symbol for the button.
*
* @type {string}
*/
symbol: 'measure-y.svg'
},
measureXY: {
/**
* A predefined background symbol for the button.
*
* @type {string}
*/
symbol: 'measure-xy.svg'
}
},
toggleAnnotations: {
/**
* A predefined background symbol for the button.
*
* @type {string}
*/
symbol: 'annotations-visible.svg'
},
currentPriceIndicator: {
/**
* A predefined background symbol for the button.
*
* @type {string}
*/
symbol: 'current-price-show.svg'
},
indicators: {
/**
* A predefined background symbol for the button.
*
* @type {string}
*/
symbol: 'indicators.svg'
},
zoomChange: {
/**
* A collection of strings pointing to config options for
* the items.
*
* @type {array}
* @default [
* 'zoomX',
* 'zoomY',
* 'zoomXY'
* ]
*/
items: [
'zoomX',
'zoomY',
'zoomXY'
],
zoomX: {
/**
* A predefined background symbol for the button.
*
* @type {string}
*/
symbol: 'zoom-x.svg'
},
zoomY: {
/**
* A predefined background symbol for the button.
*
* @type {string}
*/
symbol: 'zoom-y.svg'
},
zoomXY: {
/**
* A predefined background symbol for the button.
*
* @type {string}
*/
symbol: 'zoom-xy.svg'
}
},
typeChange: {
/**
* A collection of strings pointing to config options for
* the items.
*
* @type {array}
* @default [
* 'typeOHLC',
* 'typeLine',
* 'typeCandlestick'
* ]
*/
items: [
'typeOHLC',
'typeLine',
'typeCandlestick'
],
typeOHLC: {
/**
* A predefined background symbol for the button.
*
* @type {string}
*/
symbol: 'series-ohlc.svg'
},
typeLine: {
/**
* A predefined background symbol for the button.
*
* @type {string}
*/
symbol: 'series-line.svg'
},
typeCandlestick: {
/**
* A predefined background symbol for the button.
*
* @type {string}
*/
symbol: 'series-candlestick.svg'
}
},
fullScreen: {
/**
* A predefined background symbol for the button.
*
* @type {string}
*/
symbol: 'fullscreen.svg'
},
saveChart: {
/**
* A predefined background symbol for the button.
*
* @type {string}
*/
symbol: 'save-chart.svg'
}
}
}
}
});
// Run HTML generator
addEvent(H.Chart, 'afterGetContainer', function () {
this.setStockTools();
});
addEvent(H.Chart, 'getMargins', function () {
var offsetWidth = (
this.stockTools &&
this.stockTools.listWrapper &&
this.stockTools.listWrapper.offsetWidth
);
if (offsetWidth && offsetWidth < this.plotWidth) {
this.plotLeft += offsetWidth;
}
});
addEvent(H.Chart, 'destroy', function () {
if (this.stockTools) {
this.stockTools.destroy();
}
});
addEvent(H.Chart, 'redraw', function () {
if (this.stockTools && this.stockTools.guiEnabled) {
this.stockTools.redraw();
}
});
/*
* Toolbar Class
*
* @param {Object} - options of toolbar
* @param {Chart} - Reference to chart
*
*/
H.Toolbar = function (options, langOptions, chart) {
this.chart = chart;
this.options = options;
this.lang = langOptions;
this.guiEnabled = options.enabled;
this.visible = pick(options.visible, true);
this.placed = pick(options.placed, false);
// General events collection which should be removed upon destroy/update:
this.eventsToUnbind = [];
if (this.guiEnabled) {
this.createHTML();
this.init();
this.showHideNavigatorion();
}
fireEvent(this, 'afterInit');
};
H.extend(H.Chart.prototype, {
/*
* Verify if Toolbar should be added.
*
* @param {Object} - chart options
*
*/
setStockTools: function (options) {
var chartOptions = this.options,
lang = chartOptions.lang,
guiOptions = merge(
chartOptions.stockTools && chartOptions.stockTools.gui,
options && options.gui
),
langOptions = lang.stockTools && lang.stockTools.gui;
this.stockTools = new H.Toolbar(guiOptions, langOptions, this);
if (this.stockTools.guiEnabled) {
this.isDirtyBox = true;
}
}
});
H.Toolbar.prototype = {
/*
* Initialize the toolbar. Create buttons and submenu for each option
* defined in `stockTools.gui`.
*
*/
init: function () {
var _self = this,
lang = this.lang,
guiOptions = this.options,
toolbar = this.toolbar,
addSubmenu = _self.addSubmenu,
buttons = guiOptions.buttons,
defs = guiOptions.definitions,
allButtons = toolbar.childNodes,
inIframe = this.inIframe(),
button;
// create buttons
buttons.forEach(function (btnName) {
button = _self.addButton(toolbar, defs, btnName, lang);
if (inIframe && btnName === 'fullScreen') {
button.buttonWrapper.className += ' ' + PREFIX + 'disabled-btn';
}
['click', 'touchstart'].forEach(function (eventName) {
addEvent(button.buttonWrapper, eventName, function () {
_self.eraseActiveButtons(
allButtons,
button.buttonWrapper
);
});
});
if (isArray(defs[btnName].items)) {
// create submenu buttons
addSubmenu.call(_self, button, defs[btnName]);
}
});
},
/*
* Create submenu (list of buttons) for the option. In example main button
* is Line, in submenu will be buttons with types of lines.
*
* @param {Object} - button which has submenu
* @param {Array} - list of all buttons
*
*/
addSubmenu: function (parentBtn, button) {
var _self = this,
submenuArrow = parentBtn.submenuArrow,
buttonWrapper = parentBtn.buttonWrapper,
buttonWidth = getStyle(buttonWrapper, 'width'),
wrapper = this.wrapper,
menuWrapper = this.listWrapper,
allButtons = this.toolbar.childNodes,
topMargin = 0,
submenuWrapper;
// create submenu container
this.submenu = submenuWrapper = createElement(UL, {
className: PREFIX + 'submenu-wrapper'
}, null, buttonWrapper);
// create submenu buttons and select the first one
this.addSubmenuItems(buttonWrapper, button);
// show / hide submenu
['click', 'touchstart'].forEach(function (eventName) {
addEvent(submenuArrow, eventName, function (e) {
e.stopPropagation();
// Erase active class on all other buttons
_self.eraseActiveButtons(allButtons, buttonWrapper);
// hide menu
if (buttonWrapper.className.indexOf(PREFIX + 'current') >= 0) {
menuWrapper.style.width = menuWrapper.startWidth + 'px';
buttonWrapper.classList.remove(PREFIX + 'current');
submenuWrapper.style.display = 'none';
} else {
// show menu
// to calculate height of element
submenuWrapper.style.display = 'block';
topMargin = submenuWrapper.offsetHeight -
buttonWrapper.offsetHeight - 3;
// calculate position of submenu in the box
// if submenu is inside, reset top margin
if (
// cut on the bottom
!(submenuWrapper.offsetHeight +
buttonWrapper.offsetTop >
wrapper.offsetHeight &&
// cut on the top
buttonWrapper.offsetTop > topMargin)
) {
topMargin = 0;
}
// apply calculated styles
css(submenuWrapper, {
top: -topMargin + 'px',
left: buttonWidth + 3 + 'px'
});
buttonWrapper.className += ' ' + PREFIX + 'current';
menuWrapper.startWidth = wrapper.offsetWidth;
menuWrapper.style.width = menuWrapper.startWidth +
H.getStyle(menuWrapper, 'padding-left') +
submenuWrapper.offsetWidth + 3 + 'px';
}
});
});
},
/*
* Create buttons in submenu
*
* @param {HTMLDOMElement} - button where submenu is placed
* @param {Array} - list of all buttons options
*
*/
addSubmenuItems: function (buttonWrapper, button) {
var _self = this,
submenuWrapper = this.submenu,
lang = this.lang,
menuWrapper = this.listWrapper,
items = button.items,
firstSubmenuItem,
submenuBtn;
// add items to submenu
items.forEach(function (btnName) {
// add buttons to submenu
submenuBtn = _self.addButton(
submenuWrapper,
button,
btnName,
lang
);
['click', 'touchstart'].forEach(function (eventName) {
addEvent(submenuBtn.mainButton, eventName, function () {
_self.switchSymbol(this, buttonWrapper, true);
menuWrapper.style.width = menuWrapper.startWidth + 'px';
submenuWrapper.style.display = 'none';
});
});
});
// select first submenu item
firstSubmenuItem = submenuWrapper
.querySelectorAll('li > .' + PREFIX + 'menu-item-btn')[0];
// replace current symbol, in main button, with submenu's button style
_self.switchSymbol(firstSubmenuItem, false);
},
/*
* Erase active class on all other buttons.
*
* @param {Array} - Array of HTML buttons
* @param {HTMLDOMElement} - Current HTML button
*
*/
eraseActiveButtons: function (buttons, currentButton, submenuItems) {
[].forEach.call(buttons, function (btn) {
if (btn !== currentButton) {
btn.classList.remove(PREFIX + 'current');
btn.classList.remove(PREFIX + 'active');
submenuItems =
btn.querySelectorAll('.' + PREFIX + 'submenu-wrapper');
// hide submenu
if (submenuItems.length > 0) {
submenuItems[0].style.display = 'none';
}
}
});
},
/*
* Create single button. Consist of `<li>` , `<span>` and (if exists)
* submenu container.
*
* @param {HTMLDOMElement} - HTML reference, where button should be added
* @param {Object} - all options, by btnName refer to particular button
* @param {String} - name of functionality mapped for specific class
* @param {Object} - All titles, by btnName refer to particular button
*
* @return {Object} - references to all created HTML elements
*/
addButton: function (target, options, btnName, lang) {
var guiOptions = this.options,
btnOptions = options[btnName],
items = btnOptions.items,
classMapping = H.Toolbar.prototype.classMapping,
userClassName = btnOptions.className || '',
mainButton,
submenuArrow,
buttonWrapper;
// main button wrapper
buttonWrapper = createElement(LI, {
className: pick(classMapping[btnName], '') + ' ' + userClassName,
title: lang[btnName] || btnName
}, null, target);
// single button
mainButton = createElement(SPAN, {
className: PREFIX + 'menu-item-btn'
}, null, buttonWrapper);
// submenu
if (items && items.length > 1) {
// arrow is a hook to show / hide submenu
submenuArrow = createElement(SPAN, {
className: PREFIX + 'submenu-item-arrow ' +
PREFIX + 'arrow-right'
}, null, buttonWrapper);
} else {
mainButton.style['background-image'] = 'url(' +
guiOptions.iconsURL + btnOptions.symbol + ')';
}
return {
buttonWrapper: buttonWrapper,
mainButton: mainButton,
submenuArrow: submenuArrow
};
},
/*
* Create navigation's HTML elements: container and arrows.
*
*/
addNavigation: function () {
var stockToolbar = this,
wrapper = stockToolbar.wrapper;
// arrow wrapper
stockToolbar.arrowWrapper = createElement(DIV, {
className: PREFIX + 'arrow-wrapper'
});
stockToolbar.arrowUp = createElement(DIV, {
className: PREFIX + 'arrow-up'
}, null, stockToolbar.arrowWrapper);
stockToolbar.arrowDown = createElement(DIV, {
className: PREFIX + 'arrow-down'
}, null, stockToolbar.arrowWrapper);
wrapper.insertBefore(
stockToolbar.arrowWrapper,
wrapper.childNodes[0]
);
// attach scroll events
stockToolbar.scrollButtons();
},
/*
* Add events to navigation (two arrows) which allows user to scroll
* top/down GUI buttons, if container's height is not enough.
*
*/
scrollButtons: function () {
var targetY = 0,
_self = this,
wrapper = _self.wrapper,
toolbar = _self.toolbar,
step = 0.1 * wrapper.offsetHeight; // 0.1 = 10%
['click', 'touchstart'].forEach(function (eventName) {
addEvent(_self.arrowUp, eventName, function () {
if (targetY > 0) {
targetY -= step;
toolbar.style['margin-top'] = -targetY + 'px';
}
});
addEvent(_self.arrowDown, eventName, function () {
if (
wrapper.offsetHeight + targetY <=
toolbar.offsetHeight + step
) {
targetY += step;
toolbar.style['margin-top'] = -targetY + 'px';
}
});
});
},
/*
* Create stockTools HTML main elements.
*
*/
createHTML: function () {
var stockToolbar = this,
chart = stockToolbar.chart,
guiOptions = stockToolbar.options,
container = chart.container,
listWrapper,
toolbar,
wrapper;
// create main container
stockToolbar.wrapper = wrapper = createElement(DIV, {
className: PREFIX + 'stocktools-wrapper ' +
guiOptions.className
});
container.parentNode.insertBefore(wrapper, container);
// toolbar
stockToolbar.toolbar = toolbar = createElement(UL, {
className: PREFIX + 'stocktools-toolbar ' +
guiOptions.toolbarClassName
});
// add container for list of buttons
stockToolbar.listWrapper = listWrapper = createElement(DIV, {
className: PREFIX + 'menu-wrapper'
});
wrapper.insertBefore(listWrapper, wrapper.childNodes[0]);
listWrapper.insertBefore(toolbar, listWrapper.childNodes[0]);
stockToolbar.showHideToolbar();
// add navigation which allows user to scroll down / top GUI buttons
stockToolbar.addNavigation();
},
/*
* Function called in redraw verifies if the navigation should be visible.
*
*/
showHideNavigatorion: function () {
// arrows
// 50px space for arrows
if (
this.visible &&
this.toolbar.offsetHeight > (this.wrapper.offsetHeight - 50)
) {
this.arrowWrapper.style.display = 'block';
} else {
// reset margin if whole toolbar is visible
this.toolbar.style.marginTop = '0px';
// hide arrows
this.arrowWrapper.style.display = 'none';
}
},
/*
* Create button which shows or hides GUI toolbar.
*
*/
showHideToolbar: function () {
var stockToolbar = this,
chart = this.chart,
wrapper = stockToolbar.wrapper,
toolbar = this.listWrapper,
submenu = this.submenu,
visible = this.visible,
showhideBtn;
// Show hide toolbar
this.showhideBtn = showhideBtn = createElement(DIV, {
className: PREFIX + 'toggle-toolbar ' + PREFIX + 'arrow-left'
}, null, wrapper);
if (!visible) {
// hide
if (submenu) {
submenu.style.display = 'none';
}
showhideBtn.style.left = '0px';
stockToolbar.visible = visible = false;
toolbar.classList.add(PREFIX + 'hide');
showhideBtn.classList.toggle(PREFIX + 'arrow-right');
wrapper.style.height = showhideBtn.offsetHeight + 'px';
} else {
wrapper.style.height = '100%';
showhideBtn.style.top = H.getStyle(toolbar, 'padding-top') + 'px';
showhideBtn.style.left = (
wrapper.offsetWidth +
H.getStyle(toolbar, 'padding-left')
) + 'px';
}
// toggle menu
['click', 'touchstart'].forEach(function (eventName) {
addEvent(showhideBtn, eventName, function () {
chart.update({
stockTools: {
gui: {
visible: !visible,
placed: true
}
}
});
});
});
},
/*
* In main GUI button, replace icon and class with submenu button's
* class / symbol.
*
* @param {HTMLDOMElement} - submenu button
* @param {Boolean} - true or false
*
*/
switchSymbol: function (button, redraw) {
var buttonWrapper = button.parentNode,
buttonWrapperClass = buttonWrapper.classList.value,
// main button in first level og GUI
mainNavButton = buttonWrapper.parentNode.parentNode;
// set class
mainNavButton.className = '';
if (buttonWrapperClass) {
mainNavButton.classList.add(buttonWrapperClass.trim());
}
// set icon
mainNavButton.querySelectorAll('.' + PREFIX + 'menu-item-btn')[0]
.style['background-image'] = button.style['background-image'];
// set active class
if (redraw) {
this.selectButton(mainNavButton);
}
},
/*
* Set select state (active class) on button.
*
* @param {HTMLDOMElement} - button
*
*/
selectButton: function (btn) {
if (btn.className.indexOf(activeClass) >= 0) {
btn.classList.remove(activeClass);
} else {
btn.classList.add(activeClass);
}
},
/*
* Remove active class from all buttons except defined.
*
* @param {HTMLDOMElement} - button which should not be deactivated
*
*/
unselectAllButtons: function (btn) {
var activeButtons = btn.parentNode.querySelectorAll('.' + activeClass);
[].forEach.call(activeButtons, function (activeBtn) {
if (activeBtn !== btn) {
activeBtn.classList.remove(activeClass);
}
});
},
/*
* Verify if chart is in iframe.
*
* @return {Object} - elements translations.
*/
inIframe: function () {
try {
return win.self !== win.top;
} catch (e) {
return true;
}
},
/*
* Update GUI with given options.
*
* @param {Object} - general options for Stock Tools
*/
update: function (options) {
merge(true, this.chart.options.stockTools, options);
this.destroy();
this.chart.setStockTools(options);
// If Stock Tools are updated, then bindings should be updated too:
if (this.chart.navigationBindings) {
this.chart.navigationBindings.update();
}
},
/*
* Destroy all HTML GUI elements.
*
*/
destroy: function () {
var stockToolsDiv = this.wrapper,
parent = stockToolsDiv && stockToolsDiv.parentNode;
this.eventsToUnbind.forEach(function (unbinder) {
unbinder();
});
// Remove the empty element
if (parent) {
parent.removeChild(stockToolsDiv);
}
// redraw
this.chart.isDirtyBox = true;
this.chart.redraw();
},
/*
* Redraw, GUI requires to verify if the navigation should be visible.
*
*/
redraw: function () {
this.showHideNavigatorion();
},
/*
* Mapping JSON fields to CSS classes.
*
*/
classMapping: {
circle: PREFIX + 'circle-annotation',
rectangle: PREFIX + 'rectangle-annotation',
label: PREFIX + 'label-annotation',
segment: PREFIX + 'segment',
arrowSegment: PREFIX + 'arrow-segment',
ray: PREFIX + 'ray',
arrowRay: PREFIX + 'arrow-ray',
line: PREFIX + 'infinity-line',
arrowLine: PREFIX + 'arrow-infinity-line',
verticalLine: PREFIX + 'vertical-line',
horizontalLine: PREFIX + 'horizontal-line',
crooked3: PREFIX + 'crooked3',
crooked5: PREFIX + 'crooked5',
elliott3: PREFIX + 'elliott3',
elliott5: PREFIX + 'elliott5',
pitchfork: PREFIX + 'pitchfork',
fibonacci: PREFIX + 'fibonacci',
parallelChannel: PREFIX + 'parallel-channel',
measureX: PREFIX + 'measure-x',
measureY: PREFIX + 'measure-y',
measureXY: PREFIX + 'measure-xy',
verticalCounter: PREFIX + 'vertical-counter',
verticalLabel: PREFIX + 'vertical-label',
verticalArrow: PREFIX + 'vertical-arrow',
currentPriceIndicator: PREFIX + 'current-price-indicator',
indicators: PREFIX + 'indicators',
flagCirclepin: PREFIX + 'flag-circlepin',
flagDiamondpin: PREFIX + 'flag-diamondpin',
flagSquarepin: PREFIX + 'flag-squarepin',
flagSimplepin: PREFIX + 'flag-simplepin',
zoomX: PREFIX + 'zoom-x',
zoomY: PREFIX + 'zoom-y',
zoomXY: PREFIX + 'zoom-xy',
typeLine: PREFIX + 'series-type-line',
typeOHLC: PREFIX + 'series-type-ohlc',
typeCandlestick: PREFIX + 'series-type-candlestick',
fullScreen: PREFIX + 'full-screen',
toggleAnnotations: PREFIX + 'toggle-annotations',
saveChart: PREFIX + 'save-chart',
separator: PREFIX + 'separator'
}
};
// Comunication with bindings:
addEvent(H.NavigationBindings, 'selectButton', function (event) {
var button = event.button,
className = PREFIX + 'submenu-wrapper',
gui = this.chart.stockTools;
if (gui && gui.guiEnabled) {
// Unslect other active buttons
gui.unselectAllButtons(event.button);
// If clicked on a submenu, select state for it's parent
if (button.parentNode.className.indexOf(className) >= 0) {
button = button.parentNode.parentNode;
}
// Set active class on the current button
gui.selectButton(button);
}
});
addEvent(H.NavigationBindings, 'deselectButton', function (event) {
var button = event.button,
className = PREFIX + 'submenu-wrapper',
gui = this.chart.stockTools;
if (gui && gui.guiEnabled) {
// If deselecting a button from a submenu, select state for it's parent
if (button.parentNode.className.indexOf(className) >= 0) {
button = button.parentNode.parentNode;
}
gui.selectButton(button);
}
});
}(Highcharts));
return (function () {
}());
})); | blue-eyed-devil/testCMS | externals/highcharts/modules/stock-tools.src.js | JavaScript | gpl-3.0 | 136,919 |
/**
* @defgroup js_controllers_grid_users_user_form User form javascript
*/
/**
* @file js/controllers/grid/settings/user/form/UserDetailsFormHandler.js
*
* Copyright (c) 2014-2016 Simon Fraser University Library
* Copyright (c) 2000-2016 John Willinsky
* Distributed under the GNU GPL v2. For full terms see the file docs/COPYING.
*
* @class UserDetailsFormHandler
* @ingroup js_controllers_grid_settings_user_form
*
* @brief Handle the user settings form.
*/
(function($) {
/** @type {Object} */
$.pkp.controllers.grid.settings =
$.pkp.controllers.grid.settings || { user: { form: { } }};
/**
* @constructor
*
* @extends $.pkp.controllers.form.UserFormHandler
*
* @param {jQueryObject} $form the wrapped HTML form element.
* @param {Object} options form options.
*/
$.pkp.controllers.grid.settings.user.form.UserDetailsFormHandler =
function($form, options) {
this.parent($form, options);
// Attach form elements events.
$('[id^="generatePassword"]', $form).click(
this.callbackWrapper(this.setGenerateRandom));
// Check the generate password check box.
if ($('[id^="generatePassword"]', $form).attr('checked')) {
this.setGenerateRandom('[id^="generatePassword"]');
}
};
$.pkp.classes.Helper.inherits(
$.pkp.controllers.grid.settings.user.form.UserDetailsFormHandler,
$.pkp.controllers.form.UserFormHandler);
//
// Public methods.
//
/**
* @see AjaxFormHandler::submitForm
* @param {Object} validator The validator plug-in.
* @param {HTMLElement} formElement The wrapped HTML form.
*/
$.pkp.controllers.grid.settings.user.form.UserDetailsFormHandler.prototype.
submitForm = function(validator, formElement) {
var $form = this.getHtmlElement();
$(':password', $form).removeAttr('disabled');
this.parent('submitForm', validator, formElement);
};
/**
* Event handler that is called when generate password checkbox is
* clicked.
* @param {string} checkbox The checkbox input element.
*/
$.pkp.controllers.grid.settings.user.form.UserDetailsFormHandler.prototype.
setGenerateRandom = function(checkbox) {
// JQuerify the element
var $checkbox = $(checkbox),
$form = this.getHtmlElement(),
passwordValue = '',
activeAndCheck = 0;
if ($checkbox.prop('checked')) {
passwordValue = '********';
activeAndCheck = 'disabled';
} else {
passwordValue = '';
activeAndCheck = '';
}
$(':password', $form).
prop('disabled', activeAndCheck).val(passwordValue);
$('[id^="sendNotify"]', $form).attr('disabled', activeAndCheck).
prop('checked', activeAndCheck);
};
/** @param {jQuery} $ jQuery closure. */
}(jQuery));
| hmorrin/uk.ac.nsamr.journal | jsamr/lib/pkp/js/controllers/grid/settings/user/form/UserDetailsFormHandler.js | JavaScript | gpl-3.0 | 2,662 |
'use strict';
exports.__esModule = true;
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
exports['default'] = timeout;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var _Subscriber2 = require('../Subscriber');
var _Subscriber3 = _interopRequireDefault(_Subscriber2);
var _schedulersImmediate = require('../schedulers/immediate');
var _schedulersImmediate2 = _interopRequireDefault(_schedulersImmediate);
var _utilIsDate = require('../util/isDate');
var _utilIsDate2 = _interopRequireDefault(_utilIsDate);
function timeout(due) {
var errorToSend = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
var scheduler = arguments.length <= 2 || arguments[2] === undefined ? _schedulersImmediate2['default'] : arguments[2];
var absoluteTimeout = _utilIsDate2['default'](due);
var waitFor = absoluteTimeout ? +due - scheduler.now() : due;
return this.lift(new TimeoutOperator(waitFor, absoluteTimeout, errorToSend, scheduler));
}
var TimeoutOperator = (function () {
function TimeoutOperator(waitFor, absoluteTimeout, errorToSend, scheduler) {
_classCallCheck(this, TimeoutOperator);
this.waitFor = waitFor;
this.absoluteTimeout = absoluteTimeout;
this.errorToSend = errorToSend;
this.scheduler = scheduler;
}
TimeoutOperator.prototype.call = function call(subscriber) {
return new TimeoutSubscriber(subscriber, this.absoluteTimeout, this.waitFor, this.errorToSend, this.scheduler);
};
return TimeoutOperator;
})();
var TimeoutSubscriber = (function (_Subscriber) {
_inherits(TimeoutSubscriber, _Subscriber);
function TimeoutSubscriber(destination, absoluteTimeout, waitFor, errorToSend, scheduler) {
_classCallCheck(this, TimeoutSubscriber);
_Subscriber.call(this, destination);
this.absoluteTimeout = absoluteTimeout;
this.waitFor = waitFor;
this.errorToSend = errorToSend;
this.scheduler = scheduler;
this.index = 0;
this._previousIndex = 0;
this._hasCompleted = false;
this.scheduleTimeout();
}
TimeoutSubscriber.dispatchTimeout = function dispatchTimeout(state) {
var source = state.subscriber;
var currentIndex = state.index;
if (!source.hasCompleted && source.previousIndex === currentIndex) {
source.notifyTimeout();
}
};
TimeoutSubscriber.prototype.scheduleTimeout = function scheduleTimeout() {
var currentIndex = this.index;
this.scheduler.schedule(TimeoutSubscriber.dispatchTimeout, this.waitFor, { subscriber: this, index: currentIndex });
this.index++;
this._previousIndex = currentIndex;
};
TimeoutSubscriber.prototype._next = function _next(value) {
this.destination.next(value);
if (!this.absoluteTimeout) {
this.scheduleTimeout();
}
};
TimeoutSubscriber.prototype._error = function _error(err) {
this.destination.error(err);
this._hasCompleted = true;
};
TimeoutSubscriber.prototype._complete = function _complete() {
this.destination.complete();
this._hasCompleted = true;
};
TimeoutSubscriber.prototype.notifyTimeout = function notifyTimeout() {
this.error(this.errorToSend || new Error('timeout'));
};
_createClass(TimeoutSubscriber, [{
key: 'previousIndex',
get: function get() {
return this._previousIndex;
}
}, {
key: 'hasCompleted',
get: function get() {
return this._hasCompleted;
}
}]);
return TimeoutSubscriber;
})(_Subscriber3['default']);
module.exports = exports['default']; | NodeVision/NodeVision | node_modules/angular2/node_modules/@reactivex/rxjs/dist/cjs/operators/timeout.js | JavaScript | gpl-3.0 | 4,939 |
describe('text.label', function () {
'use strict';
var fixture = document.getElementById('fixture');
afterEach(function () {
fixture.innerHTML = '';
});
describe('aria-labelledby', function () {
it('should join text with a single space', function () {
fixture.innerHTML = '<div id="monkeys">monkeys</div><div id="bananas">bananas</div>' +
'<input id="target" aria-labelledby="monkeys bananas">';
var target = document.getElementById('target');
assert.equal(commons.text.label(target), 'monkeys bananas');
});
it('should filter invisible elements', function () {
fixture.innerHTML = '<div id="monkeys">monkeys</div><div id="bananas" style="display: none">bananas</div>' +
'<input id="target" aria-labelledby="monkeys bananas">';
var target = document.getElementById('target');
assert.equal(commons.text.label(target), 'monkeys');
});
it('should take precedence over aria-label', function () {
fixture.innerHTML = '<div id="monkeys">monkeys</div><div id="bananas">bananas</div>' +
'<input id="target" aria-labelledby="monkeys bananas" aria-label="nope">';
var target = document.getElementById('target');
assert.equal(commons.text.label(target), 'monkeys bananas');
});
it('should take precedence over explicit labels', function () {
fixture.innerHTML = '<div id="monkeys">monkeys</div><div id="bananas">bananas</div>' +
'<label for="target">nope</label>' +
'<input id="target" aria-labelledby="monkeys bananas">';
var target = document.getElementById('target');
assert.equal(commons.text.label(target), 'monkeys bananas');
});
it('should take precedence over implicit labels', function () {
fixture.innerHTML = '<div id="monkeys">monkeys</div><div id="bananas">bananas</div>' +
'<label>nope' +
'<input id="target" aria-labelledby="monkeys bananas"></label>';
var target = document.getElementById('target');
assert.equal(commons.text.label(target), 'monkeys bananas');
});
it('should ignore whitespace only labels', function () {
fixture.innerHTML = '<div id="monkeys"> \n </div><div id="bananas"></div>' +
'<input id="target" aria-labelledby="monkeys bananas">';
var target = document.getElementById('target');
assert.isNull(commons.text.label(target));
});
});
describe('aria-label', function () {
it('should detect it', function () {
fixture.innerHTML = '<input id="target" aria-label="monkeys">';
var target = document.getElementById('target');
assert.equal(commons.text.label(target), 'monkeys');
});
it('should ignore whitespace only labels', function () {
fixture.innerHTML = '<input id="target" aria-label=" \n ">';
var target = document.getElementById('target');
assert.isNull(commons.text.label(target));
});
it('should take precedence over explicit labels', function () {
fixture.innerHTML = '<label for="target">nope</label>' +
'<input id="target" aria-label="monkeys">';
var target = document.getElementById('target');
assert.equal(commons.text.label(target), 'monkeys');
});
it('should take precedence over implicit labels', function () {
fixture.innerHTML = '<label>nope' +
'<input id="target" aria-label="monkeys"></label>';
var target = document.getElementById('target');
assert.equal(commons.text.label(target), 'monkeys');
});
});
describe('explicit label', function () {
it('should detect it', function () {
fixture.innerHTML = '<label for="target">monkeys</label>' +
'<input id="target">';
var target = document.getElementById('target');
assert.equal(commons.text.label(target), 'monkeys');
});
it('should ignore whitespace only or empty labels', function () {
fixture.innerHTML = '<label for="target"> \n\r </label>' +
'<input id="target">';
var target = document.getElementById('target');
assert.isNull(commons.text.label(target));
});
it('should take precedence over implicit labels', function () {
fixture.innerHTML = '<label for="target">monkeys</label>' +
'<label>nope' +
'<input id="target"></label>';
var target = document.getElementById('target');
assert.equal(commons.text.label(target), 'monkeys');
});
});
describe('implicit label', function () {
it('should detect it', function () {
fixture.innerHTML = '<label>monkeys' +
'<input id="target"><label>';
var target = document.getElementById('target');
assert.equal(commons.text.label(target), 'monkeys');
});
it('should ignore whitespace only or empty labels', function () {
fixture.innerHTML = '<label> ' +
'<input id="target"><label>';
var target = document.getElementById('target');
assert.isNull(commons.text.label(target));
});
});
});
| jasonkarns/axe-core | test/commons/text/label.js | JavaScript | mpl-2.0 | 4,729 |
load(libdir + 'asserts.js');
assertEq(Array.prototype.toSource.call([1, 'hi']), '[1, "hi"]');
assertEq(Array.prototype.toSource.call({1: 10, 0: 42, length: 2}), "[42, 10]");
assertEq(Array.prototype.toSource.call({1: 10, 0: 42, length: 1}), "[42]");
assertThrowsInstanceOf(() => Array.prototype.toSource.call("someString"), TypeError);
assertThrowsInstanceOf(() => Array.prototype.toSource.call(42), TypeError);
assertThrowsInstanceOf(() => Array.prototype.toSource.call(undefined), TypeError);
| cstipkovic/spidermonkey-research | js/src/jit-test/tests/basic/array-tosource.js | JavaScript | mpl-2.0 | 496 |
(function (module) {
mifosX.controllers = _.extend(module, {
CashierFundsAllocationSettlementController: function (scope, routeParams, route, location, dateFilter, resourceFactory) {
scope.formData = {};
scope.formData.txnDate = new Date();
scope.settle = routeParams.settle;
resourceFactory.cashierTxnTemplateResource.get({tellerId: routeParams.tellerId, cashierId: routeParams.cashierId}, function (data) {
scope.cashierTxnTemplate = data;
scope.formData.currencyCode = data.currencyOptions[0].code;
});
scope.tellersId=routeParams.tellerId;
scope.ifAllocate = function(){
if ( routeParams.action == 'allocate') {
return true;
}
};
scope.ifSettle = function(){
if ( routeParams.action == 'settle') {
return true;
}
};
/* scope.cancel="#tellers";*/
scope.allocate = function () {
this.formData.locale = scope.optlang.code;
var tDate = dateFilter(scope.formData.txnDate, scope.df);
this.formData.dateFormat = scope.df;
this.formData.txnDate = tDate;
resourceFactory.tellerCashierTxnsAllocateResource.allocate(
{'tellerId': routeParams.tellerId, 'cashierId': routeParams.cashierId},
this.formData, function (data) {
location.path('tellers/' + routeParams.tellerId + '/cashiers/' + routeParams.cashierId + '/txns/' + scope.formData.currencyCode);
});
};
scope.settle = function () {
this.formData.locale = scope.optlang.code;
var tDate = dateFilter(scope.formData.txnDate, scope.df);
this.formData.dateFormat = scope.df;
this.formData.txnDate = tDate;
resourceFactory.tellerCashierTxnsSettleResource.settle(
{'tellerId': routeParams.tellerId, 'cashierId': routeParams.cashierId},
this.formData, function (data) {
location.path('tellers/' + routeParams.tellerId + '/cashiers/' + routeParams.cashierId + '/txns/' + scope.formData.currencyCode);
});
};
}
});
mifosX.ng.application.controller('CashierFundsAllocationSettlementController', ['$scope', '$routeParams', '$route', '$location', 'dateFilter', 'ResourceFactory', mifosX.controllers.CashierFundsAllocationSettlementController]).run(function ($log) {
$log.info("CashierFundsAllocationSettlementController initialized");
});
}(mifosX.controllers || {}));
| dtsuran/community-app | app/scripts/controllers/organization/cashmgmt/CashierFundsAllocationSettlementController.js | JavaScript | mpl-2.0 | 2,787 |
/**
* Copyright (c) 2015 "Fronteer LTD"
* Grasshopper Event Engine
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
var _ = require('lodash');
var CambridgeConstants = require('./constants');
/**
* The model that holds information about which week of a term a date is in
*
* @param {Moment} date The date for which to get the Termweek
*/
var TermWeek = module.exports.TermWeek = function(date) {
// Get the term that contains or is closest to the given date
var term = getTerm(date);
var that = {
'term': term,
// Get the week in which the date falls
'week': term.weekOffset(date)
};
/**
* Compare this TermWeek instance to another
*
* @param {TermWeek} other The TermWeek instance to compare to
* @return {Boolean} `true` if the other TermWeek instance is the same
*/
that.equals = function(other) {
return (that.term.termIndex === other.term.termIndex && that.week === other.week);
};
return that;
};
/**
* Given a date, get the the term that either contains it or is closest to it
*
* @param {Moment} date The date for which to get the term
* @return {Term} The term that either contains the date or that is closests to it
* @api private
*/
var getTerm = function(date) {
var closest = {'distance': Number.MAX_VALUE, 'term': null};
// Iterate over each term and find the term that either contains the date
// or that's closest to it by calculating the offset between the date and
// the beginning and end of each term. The term with the smallest offset
// is the term closest to or contains the date
_.each(CambridgeConstants.ALL_TERMS, function(term) {
var distance = _.min([
Math.abs(term.startDate.diff(date, 'second')),
Math.abs(term.endDate.diff(date, 'second'))
]);
if (distance < closest.distance) {
closest.distance = distance;
closest.term = term;
}
});
return closest.term;
};
| fronteerio/grasshopper | node_modules/gh-series/lib/internal/patterns/cambridge/termweek.js | JavaScript | agpl-3.0 | 2,696 |
// This file is generated automatically by `scripts/build/fp.js`. Please, don't change it.
import fn from '../../eachYearOfInterval/index.js';
import convertToFP from '../_lib/convertToFP/index.js';
var eachYearOfInterval = convertToFP(fn, 1);
export default eachYearOfInterval; | BigBoss424/portfolio | v8/development/node_modules/date-fns/esm/fp/eachYearOfInterval/index.js | JavaScript | apache-2.0 | 278 |
define(function(require) {
var $ = require("jquery");
var justep = require("$UI/system/lib/justep");
var WindowContainer = require("$UI/system/components/justep/windowContainer/windowContainer");
var templateService = require("$UI/system/templates/common/js/templateService");
var Component = require("$UI/system/lib/base/component");
// var loadTreeJs = require("$UI/system/components/designerCommon/tree/tree");
// loadTreeJs($);
var Model = function() {
this.callParent();
this.composeObj = {};
this.preId;
};
Model.prototype.modelLoad = function(event) {
this.templateEngine = this.getParent().templateEngine;
this.templateFile = this.getContext().getRequestParameter("templateFile");
};
Model.prototype.pageClick = function(event) {
var data = this.comp("data");
data.to(data.getRowID(event.bindingContext.$object));
};
Model.prototype.dataIndexChanged = function(event) {
var data = event.source;
var currentId = data.val("id");
if (this.preId != undefined && currentId != 1) {
var compose = this.composeObj[currentId];
if (compose != undefined) {
compose.getInnerModel().getField();
}
}
this._openPage(data.val("id"), require.toUrl(data.val("configPage")));
};
Model.prototype.validate = function(wizard) {
var msg = "";
var composes = $(".rep-compose");
if (composes.length < 3) {
msg += "还没完成配置,";
}
for ( var i = 0; i < composes.length; i++) {
msg += Component.getComponent(composes[i]).getInnerModel().validate(wizard);
}
return msg;
}
Model.prototype.finish = function(wizard) {
var data = []
var options = [];
options.dataId = this.templateEngine.getConfig().current.mainData.dataId;
var composes = $(".rep-compose");
for ( var i = 0; i < composes.length; i++) {
data.push(Component.getComponent(composes[i]).getInnerModel().finish(wizard));
}
for ( var i = 0; i < data.length; i++) {
var jsonObj = data[i];
for ( var key in jsonObj) {
if (key == "groupcolumns") {
options.groupcolumns = jsonObj[key];
} else if (key == "selectcolumns") {
options.selectcolumns = jsonObj[key];
} else {
options.groupField = jsonObj[key];
}
}
}
options.title = "分组报表";
options.excelName = "/"+this.templateEngine.targetFileName+"Report.xls";
options.excelType = "groupReport";
this.createExcel(options);
this.templateEngine.addContext(this.templateFile, "fileName", this.templateEngine.targetFileName+"Report");
};
Model.prototype.createExcel = function(options) {
var targetPath = this.templateEngine.targetPath;
var realPath = targetPath.substring(0, targetPath.indexOf('UI2')) + "UI2/system/templates/report/grid/template";
var url = require.toUrl("$UI/system/templates/report/server/createGridExcel2.j");
var data = {
dataId : options.dataId,
selectcolumns : options.selectcolumns,
groupcolumns : options.groupcolumns,
title : options.title,
groupField : options.groupField,
pathname : targetPath + options.excelName,
excelType : options.excelType
};
$.post(url, data, function(data) {
alert(data)
});
};
Model.prototype._createCompose = function(id, src, templateFile) {
var src = require.toUrl(src + (src.indexOf("?") != -1 ? "&" : "?") + "id=" + id + (templateFile ? ("&templateFile=" + templateFile) : ""));
var compose = new WindowContainer({
parentNode : this.getElementByXid("composeParent"),
src : src,
onLoad : this._composeLoaded.bind(this)
});
$(compose.domNode).attr('id', id);
$(compose.domNode).addClass('rep-compose');
return compose;
};
Model.prototype._composeLoaded = function(event) {
};
Model.prototype._openPage = function(id, url, templateFile, refresh) {
var composes = $(".rep-compose");
for ( var i = 0; i < composes.length; i += 1) {
composes[i].style.display = "none";
}
var composeNode = document.getElementById(id);
if (!composeNode) {
this.currentCompose = this._createCompose(id, url, templateFile);
composeNode = this.currentCompose.domNode;
this.composeObj[id] = this.currentCompose;
} else {
this.currentCompose = Component.getComponent(composeNode);
if (refresh) {
this.currentCompose.refresh();
}
}
composeNode.style.display = "block";
};
Model.prototype.dataIndexChanging = function(event) {
var data = event.source;
this.preId = data.val("id");
};
return Model;
}); | glustful/WeX5 | UI2/system/templates/common/fieldConfig.js | JavaScript | apache-2.0 | 4,394 |
/* jshint globalstrict:false, strict:false, unused : false */
/* global assertEqual, assertFalse */
// //////////////////////////////////////////////////////////////////////////////
// / @brief recovery tests for views
// /
// / @file
// /
// / DISCLAIMER
// /
// / Copyright 2010-2012 triagens GmbH, Cologne, Germany
// /
// / 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.
// /
// / Copyright holder is triAGENS GmbH, Cologne, Germany
// /
// / @author Jan Steemann
// / @author Copyright 2013, triAGENS GmbH, Cologne, Germany
// //////////////////////////////////////////////////////////////////////////////
var db = require('@arangodb').db;
var internal = require('internal');
var jsunity = require('jsunity');
function runSetup () {
'use strict';
internal.debugClearFailAt();
db._drop('UnitTestsRecoveryDummy');
var c = db._create('UnitTestsRecoveryDummy');
db._dropView('UnitTestsRecovery1');
var v = db._createView('UnitTestsRecovery1', 'arangosearch', {});
// setup link
var meta = { links: { 'UnitTestsRecoveryDummy': { includeAllFields: true } } };
v.properties(meta);
// remove link
v.properties({ links: { 'UnitTestsRecoveryDummy': null } });
c.save({ name: 'crashme' }, true);
internal.debugTerminate('crashing server');
}
// //////////////////////////////////////////////////////////////////////////////
// / @brief test suite
// //////////////////////////////////////////////////////////////////////////////
function recoverySuite () {
'use strict';
jsunity.jsUnity.attachAssertions();
return {
setUp: function () {},
tearDown: function () {},
// //////////////////////////////////////////////////////////////////////////////
// / @brief test whether we can restore the trx data
// //////////////////////////////////////////////////////////////////////////////
testIResearchLinkDrop: function () {
var v1 = db._view('UnitTestsRecovery1');
assertEqual(v1.properties().links, {});
}
};
}
// //////////////////////////////////////////////////////////////////////////////
// / @brief executes the test suite
// //////////////////////////////////////////////////////////////////////////////
function main (argv) {
'use strict';
if (argv[1] === 'setup') {
runSetup();
return 0;
} else {
jsunity.run(recoverySuite);
return jsunity.writeDone().status ? 0 : 1;
}
}
| wiltonlazary/arangodb | tests/js/server/recovery/view-arangosearch-link-drop.js | JavaScript | apache-2.0 | 2,909 |
/*
* PhantomJS Runner QUnit Plugin 1.2.0
*
* PhantomJS binaries: http://phantomjs.org/download.html
* Requires PhantomJS 1.6+ (1.7+ recommended)
*
* Run with:
* phantomjs runner.js [url-of-your-qunit-testsuite]
*
* e.g.
* phantomjs runner.js http://localhost/qunit/test/index.html
*/
/*global phantom:false, require:false, console:false, window:false, QUnit:false */
(function () {
'use strict';
var url, page, timeout,
args = require('system').args;
// arg[0]: scriptName, args[1...]: arguments
if (args.length < 2 || args.length > 3) {
console.error('Usage:\n phantomjs runner.js [url-of-your-qunit-testsuite] [timeout-in-seconds]');
phantom.exit(1);
}
url = args[1];
page = require('webpage').create();
if (args[2] !== undefined) {
timeout = parseInt(args[2], 10);
}
// Route `console.log()` calls from within the Page context to the main Phantom context (i.e. current `this`)
page.onConsoleMessage = function (msg) {
console.log(msg);
};
page.onInitialized = function () {
page.evaluate(addLogging);
};
page.onCallback = function (message) {
var result,
failed;
if (message) {
if (message.name === 'QUnit.done') {
result = message.data;
failed = !result || !result.total || result.failed;
if (!result.total) {
console.error('No tests were executed. Are you loading tests asynchronously?');
}
phantom.exit(failed ? 1 : 0);
}
}
};
page.open(url, function (status) {
if (status !== 'success') {
console.error('Unable to access network: ' + status);
phantom.exit(1);
} else {
// Cannot do this verification with the 'DOMContentLoaded' handler because it
// will be too late to attach it if a page does not have any script tags.
var qunitMissing = page.evaluate(function () {
return (typeof QUnit === 'undefined' || !QUnit);
});
if (qunitMissing) {
console.error('The `QUnit` object is not present on this page.');
phantom.exit(1);
}
// Set a timeout on the test running, otherwise tests with async problems will hang forever
if (typeof timeout === 'number') {
setTimeout(function () {
console.error('The specified timeout of ' + timeout + ' seconds has expired. Aborting...');
phantom.exit(1);
}, timeout * 1000);
}
// Do nothing... the callback mechanism will handle everything!
}
});
function addLogging() {
window.document.addEventListener('DOMContentLoaded', function () {
var currentTestAssertions = [];
QUnit.log(function (details) {
var response;
// Ignore passing assertions
if (details.result) {
return;
}
response = details.message || '';
if (typeof details.expected !== 'undefined') {
if (response) {
response += ', ';
}
response += 'expected: ' + details.expected + ', but was: ' + details.actual;
}
if (details.source) {
response += '\n' + details.source;
}
currentTestAssertions.push('Failed assertion: ' + response);
});
QUnit.testDone(function (result) {
var i,
len,
name = '';
if (result.module) {
name += result.module + ': ';
}
name += result.name;
if (result.failed) {
console.log('\n' + 'Test failed: ' + name);
for (i = 0, len = currentTestAssertions.length; i < len; i++) {
console.log(' ' + currentTestAssertions[i]);
}
}
currentTestAssertions.length = 0;
});
QUnit.done(function (result) {
console.log('\n' + 'Took ' + result.runtime + 'ms to run ' + result.total + ' tests. ' + result.passed + ' passed, ' + result.failed + ' failed.');
if (typeof window.callPhantom === 'function') {
window.callPhantom({
'name': 'QUnit.done',
'data': result
});
}
});
}, false);
}
})(); | TWOUDIA/bootstrap_player | tests/runner.js | JavaScript | apache-2.0 | 4,797 |
//// [privacyGloImport.ts]
module m1 {
export module m1_M1_public {
export class c1 {
}
export function f1() {
return new c1;
}
export var v1 = c1;
export var v2: c1;
}
module m1_M2_private {
export class c1 {
}
export function f1() {
return new c1;
}
export var v1 = c1;
export var v2: c1;
}
//export declare module "m1_M3_public" {
// export function f1();
// export class c1 {
// }
// export var v1: { new (): c1; };
// export var v2: c1;
//}
//declare module "m1_M4_private" {
// export function f1();
// export class c1 {
// }
// export var v1: { new (): c1; };
// export var v2: c1;
//}
import m1_im1_private = m1_M1_public;
export var m1_im1_private_v1_public = m1_im1_private.c1;
export var m1_im1_private_v2_public = new m1_im1_private.c1();
export var m1_im1_private_v3_public = m1_im1_private.f1;
export var m1_im1_private_v4_public = m1_im1_private.f1();
var m1_im1_private_v1_private = m1_im1_private.c1;
var m1_im1_private_v2_private = new m1_im1_private.c1();
var m1_im1_private_v3_private = m1_im1_private.f1;
var m1_im1_private_v4_private = m1_im1_private.f1();
import m1_im2_private = m1_M2_private;
export var m1_im2_private_v1_public = m1_im2_private.c1;
export var m1_im2_private_v2_public = new m1_im2_private.c1();
export var m1_im2_private_v3_public = m1_im2_private.f1;
export var m1_im2_private_v4_public = m1_im2_private.f1();
var m1_im2_private_v1_private = m1_im2_private.c1;
var m1_im2_private_v2_private = new m1_im2_private.c1();
var m1_im2_private_v3_private = m1_im2_private.f1;
var m1_im2_private_v4_private = m1_im2_private.f1();
//import m1_im3_private = require("m1_M3_public");
//export var m1_im3_private_v1_public = m1_im3_private.c1;
//export var m1_im3_private_v2_public = new m1_im3_private.c1();
//export var m1_im3_private_v3_public = m1_im3_private.f1;
//export var m1_im3_private_v4_public = m1_im3_private.f1();
//var m1_im3_private_v1_private = m1_im3_private.c1;
//var m1_im3_private_v2_private = new m1_im3_private.c1();
//var m1_im3_private_v3_private = m1_im3_private.f1;
//var m1_im3_private_v4_private = m1_im3_private.f1();
//import m1_im4_private = require("m1_M4_private");
//export var m1_im4_private_v1_public = m1_im4_private.c1;
//export var m1_im4_private_v2_public = new m1_im4_private.c1();
//export var m1_im4_private_v3_public = m1_im4_private.f1;
//export var m1_im4_private_v4_public = m1_im4_private.f1();
//var m1_im4_private_v1_private = m1_im4_private.c1;
//var m1_im4_private_v2_private = new m1_im4_private.c1();
//var m1_im4_private_v3_private = m1_im4_private.f1;
//var m1_im4_private_v4_private = m1_im4_private.f1();
export import m1_im1_public = m1_M1_public;
export import m1_im2_public = m1_M2_private;
//export import m1_im3_public = require("m1_M3_public");
//export import m1_im4_public = require("m1_M4_private");
}
module glo_M1_public {
export class c1 {
}
export function f1() {
return new c1;
}
export var v1 = c1;
export var v2: c1;
}
declare module "glo_M2_public" {
export function f1();
export class c1 {
}
export var v1: { new (): c1; };
export var v2: c1;
}
declare module "use_glo_M1_public" {
import use_glo_M1_public = glo_M1_public;
export var use_glo_M1_public_v1_public: { new (): use_glo_M1_public.c1; };
export var use_glo_M1_public_v2_public: typeof use_glo_M1_public;
export var use_glo_M1_public_v3_public: ()=> use_glo_M1_public.c1;
var use_glo_M1_public_v1_private: { new (): use_glo_M1_public.c1; };
var use_glo_M1_public_v2_private: typeof use_glo_M1_public;
var use_glo_M1_public_v3_private: () => use_glo_M1_public.c1;
import use_glo_M2_public = require("glo_M2_public");
export var use_glo_M2_public_v1_public: { new (): use_glo_M2_public.c1; };
export var use_glo_M2_public_v2_public: typeof use_glo_M2_public;
export var use_glo_M2_public_v3_public: () => use_glo_M2_public.c1;
var use_glo_M2_public_v1_private: { new (): use_glo_M2_public.c1; };
var use_glo_M2_public_v2_private: typeof use_glo_M2_public;
var use_glo_M2_public_v3_private: () => use_glo_M2_public.c1;
module m2 {
//import errorImport = require("glo_M2_public");
import nonerrorImport = glo_M1_public;
module m5 {
//import m5_errorImport = require("glo_M2_public");
import m5_nonerrorImport = glo_M1_public;
}
}
}
declare module "anotherParseError" {
module m2 {
//declare module "abc" {
//}
}
module m2 {
//module "abc2" {
//}
}
//module "abc3" {
//}
}
module m2 {
//import m3 = require("use_glo_M1_public");
module m4 {
var a = 10;
//import m2 = require("use_glo_M1_public");
}
}
//// [privacyGloImport.js]
var m1;
(function (m1) {
var m1_M1_public;
(function (m1_M1_public) {
var c1 = /** @class */ (function () {
function c1() {
}
return c1;
}());
m1_M1_public.c1 = c1;
function f1() {
return new c1;
}
m1_M1_public.f1 = f1;
m1_M1_public.v1 = c1;
})(m1_M1_public = m1.m1_M1_public || (m1.m1_M1_public = {}));
var m1_M2_private;
(function (m1_M2_private) {
var c1 = /** @class */ (function () {
function c1() {
}
return c1;
}());
m1_M2_private.c1 = c1;
function f1() {
return new c1;
}
m1_M2_private.f1 = f1;
m1_M2_private.v1 = c1;
})(m1_M2_private || (m1_M2_private = {}));
//export declare module "m1_M3_public" {
// export function f1();
// export class c1 {
// }
// export var v1: { new (): c1; };
// export var v2: c1;
//}
//declare module "m1_M4_private" {
// export function f1();
// export class c1 {
// }
// export var v1: { new (): c1; };
// export var v2: c1;
//}
var m1_im1_private = m1_M1_public;
m1.m1_im1_private_v1_public = m1_im1_private.c1;
m1.m1_im1_private_v2_public = new m1_im1_private.c1();
m1.m1_im1_private_v3_public = m1_im1_private.f1;
m1.m1_im1_private_v4_public = m1_im1_private.f1();
var m1_im1_private_v1_private = m1_im1_private.c1;
var m1_im1_private_v2_private = new m1_im1_private.c1();
var m1_im1_private_v3_private = m1_im1_private.f1;
var m1_im1_private_v4_private = m1_im1_private.f1();
var m1_im2_private = m1_M2_private;
m1.m1_im2_private_v1_public = m1_im2_private.c1;
m1.m1_im2_private_v2_public = new m1_im2_private.c1();
m1.m1_im2_private_v3_public = m1_im2_private.f1;
m1.m1_im2_private_v4_public = m1_im2_private.f1();
var m1_im2_private_v1_private = m1_im2_private.c1;
var m1_im2_private_v2_private = new m1_im2_private.c1();
var m1_im2_private_v3_private = m1_im2_private.f1;
var m1_im2_private_v4_private = m1_im2_private.f1();
//import m1_im3_private = require("m1_M3_public");
//export var m1_im3_private_v1_public = m1_im3_private.c1;
//export var m1_im3_private_v2_public = new m1_im3_private.c1();
//export var m1_im3_private_v3_public = m1_im3_private.f1;
//export var m1_im3_private_v4_public = m1_im3_private.f1();
//var m1_im3_private_v1_private = m1_im3_private.c1;
//var m1_im3_private_v2_private = new m1_im3_private.c1();
//var m1_im3_private_v3_private = m1_im3_private.f1;
//var m1_im3_private_v4_private = m1_im3_private.f1();
//import m1_im4_private = require("m1_M4_private");
//export var m1_im4_private_v1_public = m1_im4_private.c1;
//export var m1_im4_private_v2_public = new m1_im4_private.c1();
//export var m1_im4_private_v3_public = m1_im4_private.f1;
//export var m1_im4_private_v4_public = m1_im4_private.f1();
//var m1_im4_private_v1_private = m1_im4_private.c1;
//var m1_im4_private_v2_private = new m1_im4_private.c1();
//var m1_im4_private_v3_private = m1_im4_private.f1;
//var m1_im4_private_v4_private = m1_im4_private.f1();
m1.m1_im1_public = m1_M1_public;
m1.m1_im2_public = m1_M2_private;
//export import m1_im3_public = require("m1_M3_public");
//export import m1_im4_public = require("m1_M4_private");
})(m1 || (m1 = {}));
var glo_M1_public;
(function (glo_M1_public) {
var c1 = /** @class */ (function () {
function c1() {
}
return c1;
}());
glo_M1_public.c1 = c1;
function f1() {
return new c1;
}
glo_M1_public.f1 = f1;
glo_M1_public.v1 = c1;
})(glo_M1_public || (glo_M1_public = {}));
var m2;
(function (m2) {
//import m3 = require("use_glo_M1_public");
var m4;
(function (m4) {
var a = 10;
//import m2 = require("use_glo_M1_public");
})(m4 || (m4 = {}));
})(m2 || (m2 = {}));
//// [privacyGloImport.d.ts]
declare module m1 {
module m1_M1_public {
class c1 {
}
function f1(): c1;
var v1: typeof c1;
var v2: c1;
}
module m1_M2_private {
class c1 {
}
function f1(): c1;
var v1: typeof c1;
var v2: c1;
}
import m1_im1_private = m1_M1_public;
var m1_im1_private_v1_public: typeof m1_im1_private.c1;
var m1_im1_private_v2_public: m1_im1_private.c1;
var m1_im1_private_v3_public: typeof m1_im1_private.f1;
var m1_im1_private_v4_public: m1_im1_private.c1;
import m1_im2_private = m1_M2_private;
var m1_im2_private_v1_public: typeof m1_im2_private.c1;
var m1_im2_private_v2_public: m1_im2_private.c1;
var m1_im2_private_v3_public: typeof m1_im2_private.f1;
var m1_im2_private_v4_public: m1_im2_private.c1;
export import m1_im1_public = m1_M1_public;
export import m1_im2_public = m1_M2_private;
}
declare module glo_M1_public {
class c1 {
}
function f1(): c1;
var v1: typeof c1;
var v2: c1;
}
declare module "glo_M2_public" {
function f1(): any;
class c1 {
}
var v1: {
new (): c1;
};
var v2: c1;
}
declare module "use_glo_M1_public" {
import use_glo_M1_public = glo_M1_public;
var use_glo_M1_public_v1_public: {
new (): use_glo_M1_public.c1;
};
var use_glo_M1_public_v2_public: typeof use_glo_M1_public;
var use_glo_M1_public_v3_public: () => use_glo_M1_public.c1;
var use_glo_M1_public_v1_private: {
new (): use_glo_M1_public.c1;
};
var use_glo_M1_public_v2_private: typeof use_glo_M1_public;
var use_glo_M1_public_v3_private: () => use_glo_M1_public.c1;
import use_glo_M2_public = require("glo_M2_public");
var use_glo_M2_public_v1_public: {
new (): use_glo_M2_public.c1;
};
var use_glo_M2_public_v2_public: typeof use_glo_M2_public;
var use_glo_M2_public_v3_public: () => use_glo_M2_public.c1;
var use_glo_M2_public_v1_private: {
new (): use_glo_M2_public.c1;
};
var use_glo_M2_public_v2_private: typeof use_glo_M2_public;
var use_glo_M2_public_v3_private: () => use_glo_M2_public.c1;
module m2 {
module m5 {
}
}
}
declare module "anotherParseError" {
module m2 {
}
module m2 {
}
}
declare module m2 {
}
| domchen/typescript-plus | tests/baselines/reference/privacyGloImport.js | JavaScript | apache-2.0 | 11,743 |
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
var ng = require("angular2/core");
var MyClass1 = (function () {
function MyClass1(_elementRef) {
this._elementRef = _elementRef;
}
return MyClass1;
}());
MyClass1 = __decorate([
fooexport,
__metadata("design:paramtypes", [typeof (_a = (typeof ng !== "undefined" && ng).ElementRef) === "function" && _a || Object])
], MyClass1);
var _a;
//# sourceMappingURL=file.js.map | mkusher/TypeScript | tests/baselines/reference/transpile/Correctly serialize metadata when transpile with CommonJS option.js | JavaScript | apache-2.0 | 1,246 |
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export default [
[
['mi', 'n', 'in the morning', 'in the afternoon', 'in the evening', 'at night'],
['midnight', 'noon', 'in the morning', 'in the afternoon', 'in the evening', 'at night'],
],
[
['midnight', 'noon', 'morning', 'afternoon', 'evening', 'night'],
,
],
[
'00:00', '12:00', ['06:00', '12:00'], ['12:00', '18:00'], ['18:00', '21:00'],
['21:00', '06:00']
]
];
//# sourceMappingURL=en-KN.js.map | rospilot/rospilot | share/web_assets/nodejs_deps/node_modules/@angular/common/locales/extra/en-KN.js | JavaScript | apache-2.0 | 678 |
/**
* @license
* Visual Blocks Editor
*
* Copyright 2013 Google Inc.
* https://blockly.googlecode.com/
*
* 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 A div that floats on top of Blockly. This singleton contains
* temporary HTML UI widgets that the user is currently interacting with.
* E.g. text input areas, colour pickers, context menus.
* @author fraser@google.com (Neil Fraser)
*/
'use strict';
goog.provide('Blockly.WidgetDiv');
goog.require('Blockly.Css');
goog.require('goog.dom');
/**
* The HTML container. Set once by inject.js's Blockly.createDom_.
* @type Element
*/
Blockly.WidgetDiv.DIV = null;
/**
* The object currently using this container.
* @private
* @type Object
*/
Blockly.WidgetDiv.owner_ = null;
/**
* Optional cleanup function set by whichever object uses the widget.
* @private
* @type Function
*/
Blockly.WidgetDiv.dispose_ = null;
/**
* Initialize and display the widget div. Close the old one if needed.
* @param {!Object} newOwner The object that will be using this container.
* @param {Function} dispose Optional cleanup function to be run when the widget
* is closed.
*/
Blockly.WidgetDiv.show = function(newOwner, dispose) {
Blockly.WidgetDiv.hide();
Blockly.WidgetDiv.owner_ = newOwner;
Blockly.WidgetDiv.dispose_ = dispose;
Blockly.WidgetDiv.DIV.style.display = 'block';
};
/**
* Destroy the widget and hide the div.
*/
Blockly.WidgetDiv.hide = function() {
if (Blockly.WidgetDiv.owner_) {
Blockly.WidgetDiv.DIV.style.display = 'none';
Blockly.WidgetDiv.dispose_ && Blockly.WidgetDiv.dispose_();
Blockly.WidgetDiv.owner_ = null;
Blockly.WidgetDiv.dispose_ = null;
goog.dom.removeChildren(Blockly.WidgetDiv.DIV);
}
};
/**
* Is the container visible?
* @return {boolean} True if visible.
*/
Blockly.WidgetDiv.isVisible = function() {
return !!Blockly.WidgetDiv.owner_;
};
/**
* Destroy the widget and hide the div if it is being used by the specified
* object.
* @param {!Object} oldOwner The object that was using this container.
*/
Blockly.WidgetDiv.hideIfOwner = function(oldOwner) {
if (Blockly.WidgetDiv.owner_ == oldOwner) {
Blockly.WidgetDiv.hide();
}
};
/**
* Position the widget at a given location. Prevent the widget from going
* offscreen top or left (right in RTL).
* @param {number} anchorX Horizontal location (window coorditates, not body).
* @param {number} anchorY Vertical location (window coorditates, not body).
* @param {!goog.math.Size} widowSize Height/width of window.
* @param {!goog.math.Coordinate} scrollOffset X/y of window scrollbars.
*/
Blockly.WidgetDiv.position = function(anchorX, anchorY, windowSize,
scrollOffset) {
// Don't let the widget go above the top edge of the window.
if (anchorY < scrollOffset.y) {
anchorY = scrollOffset.y;
}
if (Blockly.RTL) {
// Don't let the menu go right of the right edge of the window.
if (anchorX > windowSize.width + scrollOffset.x) {
anchorX = windowSize.width + scrollOffset.x;
}
} else {
// Don't let the widget go left of the left edge of the window.
if (anchorX < scrollOffset.x) {
anchorX = scrollOffset.x;
}
}
Blockly.WidgetDiv.DIV.style.left = anchorX + 'px';
Blockly.WidgetDiv.DIV.style.top = anchorY + 'px';
};
| zrdev/zrdev.github.io | blockly/core/widgetdiv.js | JavaScript | apache-2.0 | 3,865 |
import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { TodoStoreService } from '../../services/todo-store.service';
import template from './todo-list.template.html';
@Component({
selector: 'todo-list',
template: template
})
export class TodoListComponent {
constructor(todoStore: TodoStoreService, route: ActivatedRoute) {
this._todoStore = todoStore;
this._route = route;
this._currentStatus = '';
}
ngOnInit() {
this._route.params
.map(params => params.status)
.subscribe((status) => {
this._currentStatus = status;
});
}
remove(uid) {
this._todoStore.remove(uid);
}
update() {
this._todoStore.persist();
}
getTodos() {
if (this._currentStatus == 'completed') {
return this._todoStore.getCompleted();
} else if (this._currentStatus == 'active') {
return this._todoStore.getRemaining();
} else {
return this._todoStore.todos;
}
}
allCompleted() {
return this._todoStore.allCompleted();
}
setAllTo(toggleAll) {
this._todoStore.setAllTo(toggleAll.checked);
}
}
| gabrielmancini/interactor | src/demo/angular2_es2015/app/components/todo-list/todo-list.component.js | JavaScript | bsd-2-clause | 1,077 |
/* eslint-disable no-underscore-dangle */
import { v4 as uuidv4 } from 'uuid';
import {
BaseSequenceBlock,
BaseSequenceChild,
BaseInsertionControl,
} from './BaseSequenceBlock';
import { escapeHtml as h } from '../../../utils/text';
/* global $ */
export class StreamBlockValidationError {
constructor(nonBlockErrors, blockErrors) {
this.nonBlockErrors = nonBlockErrors;
this.blockErrors = blockErrors;
}
}
class StreamChild extends BaseSequenceChild {
/*
wrapper for a block inside a StreamBlock, handling StreamBlock-specific metadata
such as id
*/
getState() {
return {
type: this.type,
value: this.block.getState(),
id: this.id,
};
}
getValue() {
return {
type: this.type,
value: this.block.getValue(),
id: this.id,
};
}
}
class StreamBlockMenu extends BaseInsertionControl {
constructor(placeholder, opts) {
super(placeholder, opts);
this.groupedChildBlockDefs = opts.groupedChildBlockDefs;
const animate = opts.animate;
const dom = $(`
<div>
<button data-streamblock-menu-open type="button" title="${h(
opts.strings.ADD,
)}"
class="c-sf-add-button c-sf-add-button--visible">
<i aria-hidden="true">+</i>
</button>
<div data-streamblock-menu-outer>
<div data-streamblock-menu-inner class="c-sf-add-panel"></div>
</div>
</div>
`);
$(placeholder).replaceWith(dom);
this.element = dom.get(0);
this.addButton = dom.find('[data-streamblock-menu-open]');
this.addButton.click(() => {
this.toggle();
});
this.outerContainer = dom.find('[data-streamblock-menu-outer]');
this.innerContainer = dom.find('[data-streamblock-menu-inner]');
this.hasRenderedMenu = false;
this.isOpen = false;
this.canAddBlock = true;
this.disabledBlockTypes = new Set();
this.close({ animate: false });
if (animate) {
dom.hide().slideDown();
}
}
renderMenu() {
if (this.hasRenderedMenu) return;
this.hasRenderedMenu = true;
this.groupedChildBlockDefs.forEach(([group, blockDefs]) => {
if (group) {
const heading = $('<h4 class="c-sf-add-panel__group-title"></h4>').text(
group,
);
this.innerContainer.append(heading);
}
const grid = $('<div class="c-sf-add-panel__grid"></div>');
this.innerContainer.append(grid);
blockDefs.forEach((blockDef) => {
const button = $(`
<button type="button" class="c-sf-button action-add-block-${h(
blockDef.name,
)}">
<svg class="icon icon-${h(
blockDef.meta.icon,
)} c-sf-button__icon" aria-hidden="true">
<use href="#icon-${h(blockDef.meta.icon)}"></use>
</svg>
${h(blockDef.meta.label)}
</button>
`);
grid.append(button);
button.click(() => {
if (this.onRequestInsert) {
this.onRequestInsert(this.index, { type: blockDef.name });
}
this.close({ animate: true });
});
});
});
// Disable buttons for any disabled block types
this.disabledBlockTypes.forEach((blockType) => {
$(`button.action-add-block-${h(blockType)}`, this.innerContainer).attr(
'disabled',
'true',
);
});
}
setNewBlockRestrictions(canAddBlock, disabledBlockTypes) {
this.canAddBlock = canAddBlock;
this.disabledBlockTypes = disabledBlockTypes;
// Disable/enable menu open button
if (this.canAddBlock) {
this.addButton.removeAttr('disabled');
} else {
this.addButton.attr('disabled', 'true');
}
// Close menu if its open and we no longer can add blocks
if (!canAddBlock && this.isOpen) {
this.close({ animate: true });
}
// Disable/enable individual block type buttons
$('button', this.innerContainer).removeAttr('disabled');
disabledBlockTypes.forEach((blockType) => {
$(`button.action-add-block-${h(blockType)}`, this.innerContainer).attr(
'disabled',
'true',
);
});
}
toggle() {
if (this.isOpen) {
this.close({ animate: true });
} else {
this.open({ animate: true });
}
}
open(opts) {
if (!this.canAddBlock) {
return;
}
this.renderMenu();
if (opts && opts.animate) {
this.outerContainer.slideDown();
} else {
this.outerContainer.show();
}
this.addButton.addClass('c-sf-add-button--close');
this.outerContainer.attr('aria-hidden', 'false');
this.isOpen = true;
}
close(opts) {
if (opts && opts.animate) {
this.outerContainer.slideUp();
} else {
this.outerContainer.hide();
}
this.addButton.removeClass('c-sf-add-button--close');
this.outerContainer.attr('aria-hidden', 'true');
this.isOpen = false;
}
}
export class StreamBlock extends BaseSequenceBlock {
constructor(blockDef, placeholder, prefix, initialState, initialError) {
this.blockDef = blockDef;
this.type = blockDef.name;
this.prefix = prefix;
const dom = $(`
<div class="c-sf-container ${h(this.blockDef.meta.classname || '')}">
<input type="hidden" name="${h(
prefix,
)}-count" data-streamfield-stream-count value="0">
<div data-streamfield-stream-container></div>
</div>
`);
$(placeholder).replaceWith(dom);
if (this.blockDef.meta.helpText) {
// help text is left unescaped as per Django conventions
$(`
<span>
<div class="help">
${this.blockDef.meta.helpIcon}
${this.blockDef.meta.helpText}
</div>
</span>
`).insertBefore(dom);
}
// StreamChild objects for the current (non-deleted) child blocks
this.children = [];
// Insertion control objects - there are one more of these than there are children.
// The control at index n will insert a block at index n
this.inserters = [];
// Incrementing counter used to generate block prefixes, also reflected in the
// 'count' hidden input. This count includes deleted items
this.blockCounter = 0;
this.countInput = dom.find('[data-streamfield-stream-count]');
// Parent element of insert control and block elements (potentially including deleted items,
// which are left behind as hidden elements with a '-deleted' input so that the
// server-side form handler knows to skip it)
this.sequenceContainer = dom.find('[data-streamfield-stream-container]');
this.setState(initialState || []);
if (this.blockDef.meta.collapsed) {
this.children.forEach((block) => {
block.collapse();
});
}
this.container = dom;
if (initialError) {
this.setError(initialError);
}
}
/*
* Called whenever a block is added or removed
*
* Updates the state of add / duplicate block buttons to prevent too many blocks being inserted.
*/
blockCountChanged() {
super.blockCountChanged();
this.canAddBlock = true;
if (
typeof this.blockDef.meta.maxNum === 'number' &&
this.children.length >= this.blockDef.meta.maxNum
) {
this.canAddBlock = false;
}
// If we can add blocks, check if there are any block types that have count limits
this.disabledBlockTypes = new Set();
if (this.canAddBlock) {
for (const blockType in this.blockDef.meta.blockCounts) {
if (this.blockDef.meta.blockCounts.hasOwnProperty(blockType)) {
const counts = this.blockDef.meta.blockCounts[blockType];
if (typeof counts.max_num === 'number') {
const currentBlockCount = this.children.filter(
(child) => child.type === blockType,
).length;
if (currentBlockCount >= counts.max_num) {
this.disabledBlockTypes.add(blockType);
}
}
}
}
}
for (let i = 0; i < this.children.length; i++) {
const canDuplicate =
this.canAddBlock && !this.disabledBlockTypes.has(this.children[i].type);
if (canDuplicate) {
this.children[i].enableDuplication();
} else {
this.children[i].disableDuplication();
}
}
for (let i = 0; i < this.inserters.length; i++) {
this.inserters[i].setNewBlockRestrictions(
this.canAddBlock,
this.disabledBlockTypes,
);
}
}
_createChild(
blockDef,
placeholder,
prefix,
index,
id,
initialState,
sequence,
opts,
) {
return new StreamChild(
blockDef,
placeholder,
prefix,
index,
id,
initialState,
sequence,
opts,
);
}
_createInsertionControl(placeholder, opts) {
// eslint-disable-next-line no-param-reassign
opts.groupedChildBlockDefs = this.blockDef.groupedChildBlockDefs;
return new StreamBlockMenu(placeholder, opts);
}
insert({ type, value, id }, index, opts) {
const childBlockDef = this.blockDef.childBlockDefsByName[type];
return this._insert(childBlockDef, value, id, index, opts);
}
_getChildDataForInsertion({ type }) {
/* Called when an 'insert new block' action is triggered: given a dict of data from the insertion control,
return the block definition and initial state to be used for the new block.
For a StreamBlock, the dict of data consists of 'type' (the chosen block type name, as a string).
*/
const blockDef = this.blockDef.childBlockDefsByName[type];
const initialState = this.blockDef.initialChildStates[type];
return [blockDef, initialState, uuidv4()];
}
duplicateBlock(index, opts) {
const child = this.children[index];
const childState = child.getState();
const animate = opts && opts.animate;
childState.id = null;
this.insert(childState, index + 1, { animate, collapsed: child.collapsed });
// focus the newly added field if we can do so without obtrusive UI behaviour
this.children[index + 1].focus({ soft: true });
}
setState(values) {
super.setState(values);
if (values.length === 0) {
/* for an empty list, begin with the menu open */
this.inserters[0].open({ animate: false });
}
}
setError(errorList) {
if (errorList.length !== 1) {
return;
}
const error = errorList[0];
// Non block errors
const container = this.container[0];
container
.querySelectorAll(':scope > .help-block.help-critical')
.forEach((element) => element.remove());
if (error.nonBlockErrors.length > 0) {
// Add a help block for each error raised
error.nonBlockErrors.forEach((nonBlockError) => {
const errorElement = document.createElement('p');
errorElement.classList.add('help-block');
errorElement.classList.add('help-critical');
errorElement.innerHTML = h(nonBlockError.messages[0]);
container.insertBefore(errorElement, container.childNodes[0]);
});
}
// Block errors
for (const blockIndex in error.blockErrors) {
if (error.blockErrors.hasOwnProperty(blockIndex)) {
this.children[blockIndex].setError(error.blockErrors[blockIndex]);
}
}
}
}
export class StreamBlockDefinition {
constructor(name, groupedChildBlockDefs, initialChildStates, meta) {
this.name = name;
this.groupedChildBlockDefs = groupedChildBlockDefs;
this.initialChildStates = initialChildStates;
this.childBlockDefsByName = {};
// eslint-disable-next-line @typescript-eslint/no-unused-vars
this.groupedChildBlockDefs.forEach(([group, blockDefs]) => {
blockDefs.forEach((blockDef) => {
this.childBlockDefsByName[blockDef.name] = blockDef;
});
});
this.meta = meta;
}
render(placeholder, prefix, initialState, initialError) {
return new StreamBlock(
this,
placeholder,
prefix,
initialState,
initialError,
);
}
}
| jnns/wagtail | client/src/components/StreamField/blocks/StreamBlock.js | JavaScript | bsd-3-clause | 12,002 |
/*! Copyright (c) 2016, Salesforce.com, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Salesforce.com nor the names of its contributors may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
angular.module("argus.urlConfig", [])
.constant('CONFIG', {
version: '4.0-SNAPSHOT',
wsUrl: 'http://localhost:8080/argusws/',
emailUrl: 'https://mail.google.com/mail/?view=cm&fs=1&tf=1&to=argus-dev@mycompany.com',
feedUrl: 'https://groups.google.com/a/mycompany.com/forum/?hl=en#!forum/argus-user',
wikiUrl: 'https://sites.google.com/a/mycompany.com/argus',
issueUrl: 'https://groups.google.com/a/mycompany.com/forum/?hl=en#!forum/argus-dev',
templatePath: '/app/views/argus_custom_directives/templates/',
piwikUrl: (('https:' == document.location.protocol) ? 'https' : 'http') + '://localhost/piwik/',
piwikSiteId: '3'
}); | prestonfff/Argus | ArgusWeb/app/js/config.js | JavaScript | bsd-3-clause | 2,221 |
/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactEmptyComponent
*/
'use strict';
var ReactElement = require('ReactElement');
var ReactEmptyComponentRegistry = require('ReactEmptyComponentRegistry');
var ReactReconciler = require('ReactReconciler');
var assign = require('Object.assign');
var placeholderElement;
var ReactEmptyComponentInjection = {
injectEmptyComponent: function(component) {
placeholderElement = ReactElement.createElement(component);
},
};
var ReactEmptyComponent = function(instantiate) {
this._currentElement = null;
this._rootNodeID = null;
this._renderedComponent = instantiate(placeholderElement);
};
assign(ReactEmptyComponent.prototype, {
construct: function(element) {
},
mountComponent: function(rootID, transaction, context) {
ReactEmptyComponentRegistry.registerNullComponentID(rootID);
this._rootNodeID = rootID;
return ReactReconciler.mountComponent(
this._renderedComponent,
rootID,
transaction,
context
);
},
receiveComponent: function() {
},
unmountComponent: function(rootID, transaction, context) {
var nativeNode = ReactReconciler.unmountComponent(this._renderedComponent);
ReactEmptyComponentRegistry.deregisterNullComponentID(this._rootNodeID);
this._rootNodeID = null;
this._renderedComponent = null;
return nativeNode;
},
});
ReactEmptyComponent.injection = ReactEmptyComponentInjection;
module.exports = ReactEmptyComponent;
| Jyrno42/react | src/renderers/shared/reconciler/ReactEmptyComponent.js | JavaScript | bsd-3-clause | 1,743 |
// Mocha (https://mochajs.org/) JavaScript tests for the calculator in site.js.
describe("Calculator", function () {
var calculator;
before(function () {
// Runs before all tests in this block.
});
after(function () {
// Runs after all tests in this block.
});
beforeEach(function () {
// Runs before each test in this block.
calculator = new framework.Calculator();
});
afterEach(function () {
// Runs after each test in this block.
});
describe("Add", function () {
it("Should return 2 when you pass it 1 and 1.", function () {
assert.strictEqual(calculator.add(1, 1), 2, "2 + 2 failed. This is an optional custom error message.");
});
});
describe("Subtract", function () {
it("Should return 0 when you pass it 1 and 1.", function () {
assert.strictEqual(calculator.subtract(1, 1), 0);
});
});
describe("Multiply", function () {
// it.skip - Skips a specific test case. You can also add this to a 'describe' to skip several test cases.
it.skip("Should return 4 when you pass it 2 and 2.", function () {
assert.strictEqual(calculator.multiply(2, 2), 4);
});
});
describe("Divide", function () {
// it.only - Only runs a specific test case. You can also add this to a 'describe' to run only those test cases.
// it.only("Should return 2 when you pass it 4 and 2.", function () {
// assert.strictEqual(calculator.multiply(4, 2), 2);
// });
});
});
// An example of how to test asynchronous code.
describe("setTimeout", function () {
// A 'done' function delegate must be called to tell Mocha when the test has finished.
it("should complete after one second.", function (done) {
setTimeout(function () {
done();
},
1000);
})
}) | backendeveloper/ASP.NET-MVC-Boilerplate | Source/MVC6/Boilerplate.Web.Mvc6.Sample/Test/site-test.js | JavaScript | mit | 1,923 |
var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, render: render });
function preload() {
// Phaser can load Text files.
// It does this using an XMLHttpRequest.
// If loading a file from outside of the domain in which the game is running
// a 'Access-Control-Allow-Origin' header must be present on the server.
// No parsing of the text file is performed, it's literally just the raw data.
game.load.text('html', 'http://phaser.io');
}
var text;
function create() {
game.stage.backgroundColor = '#0072bc';
var html = game.cache.getText('html');
text = html.split('\n');
}
function render() {
for (var i = 0; i < 30; i++)
{
game.debug.renderText(text[i], 32, i * 20);
}
}
| seacloud9/ds.fracVader | scripts/phaser/examples/loader/load text file.js | JavaScript | mit | 810 |
angular.module('angular-jwt.jwt', [])
.service('jwtHelper', function() {
this.urlBase64Decode = function(str) {
var output = str.replace(/-/g, '+').replace(/_/g, '/');
switch (output.length % 4) {
case 0: { break; }
case 2: { output += '=='; break; }
case 3: { output += '='; break; }
default: {
throw 'Illegal base64url string!';
}
}
return decodeURIComponent(escape(window.atob(output))); //polifyll https://github.com/davidchambers/Base64.js
}
this.decodeToken = function(token) {
var parts = token.split('.');
if (parts.length !== 3) {
throw new Error('JWT must have 3 parts');
}
var decoded = this.urlBase64Decode(parts[1]);
if (!decoded) {
throw new Error('Cannot decode the token');
}
return JSON.parse(decoded);
}
this.getTokenExpirationDate = function(token) {
var decoded;
decoded = this.decodeToken(token);
if(typeof decoded.exp === "undefined") {
return null;
}
var d = new Date(0); // The 0 here is the key, which sets the date to the epoch
d.setUTCSeconds(decoded.exp);
return d;
};
this.isTokenExpired = function(token, offsetSeconds) {
var d = this.getTokenExpirationDate(token);
offsetSeconds = offsetSeconds || 0;
if (d === null) {
return false;
}
// Token expired?
return !(d.valueOf() > (new Date().valueOf() + (offsetSeconds * 1000)));
};
});
| mohamadir/15-minutes | temp/node_modules/angular-jwt/src/angularJwt/services/jwt.js | JavaScript | mit | 1,539 |
var Mode = require('./mode');
var Polynomial = require('./Polynomial');
var math = require('./math');
var QRMaskPattern = {
PATTERN000 : 0,
PATTERN001 : 1,
PATTERN010 : 2,
PATTERN011 : 3,
PATTERN100 : 4,
PATTERN101 : 5,
PATTERN110 : 6,
PATTERN111 : 7
};
var QRUtil = {
PATTERN_POSITION_TABLE : [
[],
[6, 18],
[6, 22],
[6, 26],
[6, 30],
[6, 34],
[6, 22, 38],
[6, 24, 42],
[6, 26, 46],
[6, 28, 50],
[6, 30, 54],
[6, 32, 58],
[6, 34, 62],
[6, 26, 46, 66],
[6, 26, 48, 70],
[6, 26, 50, 74],
[6, 30, 54, 78],
[6, 30, 56, 82],
[6, 30, 58, 86],
[6, 34, 62, 90],
[6, 28, 50, 72, 94],
[6, 26, 50, 74, 98],
[6, 30, 54, 78, 102],
[6, 28, 54, 80, 106],
[6, 32, 58, 84, 110],
[6, 30, 58, 86, 114],
[6, 34, 62, 90, 118],
[6, 26, 50, 74, 98, 122],
[6, 30, 54, 78, 102, 126],
[6, 26, 52, 78, 104, 130],
[6, 30, 56, 82, 108, 134],
[6, 34, 60, 86, 112, 138],
[6, 30, 58, 86, 114, 142],
[6, 34, 62, 90, 118, 146],
[6, 30, 54, 78, 102, 126, 150],
[6, 24, 50, 76, 102, 128, 154],
[6, 28, 54, 80, 106, 132, 158],
[6, 32, 58, 84, 110, 136, 162],
[6, 26, 54, 82, 110, 138, 166],
[6, 30, 58, 86, 114, 142, 170]
],
G15 : (1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0),
G18 : (1 << 12) | (1 << 11) | (1 << 10) | (1 << 9) | (1 << 8) | (1 << 5) | (1 << 2) | (1 << 0),
G15_MASK : (1 << 14) | (1 << 12) | (1 << 10) | (1 << 4) | (1 << 1),
getBCHTypeInfo : function(data) {
var d = data << 10;
while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15) >= 0) {
d ^= (QRUtil.G15 << (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15) ) );
}
return ( (data << 10) | d) ^ QRUtil.G15_MASK;
},
getBCHTypeNumber : function(data) {
var d = data << 12;
while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18) >= 0) {
d ^= (QRUtil.G18 << (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18) ) );
}
return (data << 12) | d;
},
getBCHDigit : function(data) {
var digit = 0;
while (data != 0) {
digit++;
data >>>= 1;
}
return digit;
},
getPatternPosition : function(typeNumber) {
return QRUtil.PATTERN_POSITION_TABLE[typeNumber - 1];
},
getMask : function(maskPattern, i, j) {
switch (maskPattern) {
case QRMaskPattern.PATTERN000 : return (i + j) % 2 == 0;
case QRMaskPattern.PATTERN001 : return i % 2 == 0;
case QRMaskPattern.PATTERN010 : return j % 3 == 0;
case QRMaskPattern.PATTERN011 : return (i + j) % 3 == 0;
case QRMaskPattern.PATTERN100 : return (Math.floor(i / 2) + Math.floor(j / 3) ) % 2 == 0;
case QRMaskPattern.PATTERN101 : return (i * j) % 2 + (i * j) % 3 == 0;
case QRMaskPattern.PATTERN110 : return ( (i * j) % 2 + (i * j) % 3) % 2 == 0;
case QRMaskPattern.PATTERN111 : return ( (i * j) % 3 + (i + j) % 2) % 2 == 0;
default :
throw new Error("bad maskPattern:" + maskPattern);
}
},
getErrorCorrectPolynomial : function(errorCorrectLength) {
var a = new Polynomial([1], 0);
for (var i = 0; i < errorCorrectLength; i++) {
a = a.multiply(new Polynomial([1, math.gexp(i)], 0) );
}
return a;
},
getLengthInBits : function(mode, type) {
if (1 <= type && type < 10) {
// 1 - 9
switch(mode) {
case Mode.MODE_NUMBER : return 10;
case Mode.MODE_ALPHA_NUM : return 9;
case Mode.MODE_8BIT_BYTE : return 8;
case Mode.MODE_KANJI : return 8;
default :
throw new Error("mode:" + mode);
}
} else if (type < 27) {
// 10 - 26
switch(mode) {
case Mode.MODE_NUMBER : return 12;
case Mode.MODE_ALPHA_NUM : return 11;
case Mode.MODE_8BIT_BYTE : return 16;
case Mode.MODE_KANJI : return 10;
default :
throw new Error("mode:" + mode);
}
} else if (type < 41) {
// 27 - 40
switch(mode) {
case Mode.MODE_NUMBER : return 14;
case Mode.MODE_ALPHA_NUM : return 13;
case Mode.MODE_8BIT_BYTE : return 16;
case Mode.MODE_KANJI : return 12;
default :
throw new Error("mode:" + mode);
}
} else {
throw new Error("type:" + type);
}
},
getLostPoint : function(qrCode) {
var moduleCount = qrCode.getModuleCount();
var lostPoint = 0;
// LEVEL1
for (var row = 0; row < moduleCount; row++) {
for (var col = 0; col < moduleCount; col++) {
var sameCount = 0;
var dark = qrCode.isDark(row, col);
for (var r = -1; r <= 1; r++) {
if (row + r < 0 || moduleCount <= row + r) {
continue;
}
for (var c = -1; c <= 1; c++) {
if (col + c < 0 || moduleCount <= col + c) {
continue;
}
if (r == 0 && c == 0) {
continue;
}
if (dark == qrCode.isDark(row + r, col + c) ) {
sameCount++;
}
}
}
if (sameCount > 5) {
lostPoint += (3 + sameCount - 5);
}
}
}
// LEVEL2
for (var row = 0; row < moduleCount - 1; row++) {
for (var col = 0; col < moduleCount - 1; col++) {
var count = 0;
if (qrCode.isDark(row, col ) ) count++;
if (qrCode.isDark(row + 1, col ) ) count++;
if (qrCode.isDark(row, col + 1) ) count++;
if (qrCode.isDark(row + 1, col + 1) ) count++;
if (count == 0 || count == 4) {
lostPoint += 3;
}
}
}
// LEVEL3
for (var row = 0; row < moduleCount; row++) {
for (var col = 0; col < moduleCount - 6; col++) {
if (qrCode.isDark(row, col)
&& !qrCode.isDark(row, col + 1)
&& qrCode.isDark(row, col + 2)
&& qrCode.isDark(row, col + 3)
&& qrCode.isDark(row, col + 4)
&& !qrCode.isDark(row, col + 5)
&& qrCode.isDark(row, col + 6) ) {
lostPoint += 40;
}
}
}
for (var col = 0; col < moduleCount; col++) {
for (var row = 0; row < moduleCount - 6; row++) {
if (qrCode.isDark(row, col)
&& !qrCode.isDark(row + 1, col)
&& qrCode.isDark(row + 2, col)
&& qrCode.isDark(row + 3, col)
&& qrCode.isDark(row + 4, col)
&& !qrCode.isDark(row + 5, col)
&& qrCode.isDark(row + 6, col) ) {
lostPoint += 40;
}
}
}
// LEVEL4
var darkCount = 0;
for (var col = 0; col < moduleCount; col++) {
for (var row = 0; row < moduleCount; row++) {
if (qrCode.isDark(row, col) ) {
darkCount++;
}
}
}
var ratio = Math.abs(100 * darkCount / moduleCount / moduleCount - 50) / 5;
lostPoint += ratio * 10;
return lostPoint;
}
};
module.exports = QRUtil;
| skyvow/wux | src/qrcode/qr.js/lib/util.js | JavaScript | mit | 7,037 |
/**
* @dgService ngdocFileReader
* @description
* This file reader will pull the contents from a text file (by default .ngdoc)
*
* The doc will initially have the form:
* ```
* {
* content: 'the content of the file',
* startingLine: 1
* }
* ```
*/
module.exports = function ngdocFileReader() {
return {
name: 'ngdocFileReader',
defaultPattern: /\.ngdoc$/,
getDocs: function(fileInfo) {
// We return a single element array because ngdoc files only contain one document
return [{
content: fileInfo.content,
startingLine: 1
}];
}
};
}; | uistyleguide/uistyleguide.github.io | node_modules/dgeni-packages/ngdoc/file-readers/ngdoc.js | JavaScript | mit | 602 |
/*
* ------------------------------------------
* 标签列表模块实现文件
* @version 1.0
* @author genify(caijf@corp.netease.com)
* ------------------------------------------
*/
NEJ.define([
'base/klass',
'base/element',
'util/tab/view',
'util/template/tpl',
'pro/module/module'
], function(_k,_e,_t,_l,_m,_p,_pro){
/**
* 标签列表模块
* @class {wd.m._$$ModuleSettingTab}
* @extends {nej.ut._$$AbstractModuleTagList}
* @param {Object} 可选配置参数,已处理参数列表如下所示
*/
_p._$$ModuleSettingTab = _k._$klass();
_pro = _p._$$ModuleSettingTab._$extend(_m._$$Module);
/**
* 构建模块
* @return {Void}
*/
_pro.__doBuild = function(){
this.__super();
this.__body = _e._$html2node(
_l._$getTextTemplate('module-id-8')
);
this.__tbview = _t._$$TabView._$allocate({
list:_e._$getChildren(this.__body),
oncheck:this.__doCheckMatchEQ._$bind(this)
});
};
/**
* 刷新模块
* @param {Object} 配置信息
* @return {Void}
*/
_pro.__onRefresh = function(_options){
this.__super(_options);
this.__tbview._$match(
this.__doParseUMIFromOpt(_options)
);
};
/**
* 验证选中项
* @param {Object} 事件信息
* @return {Void}
*/
_pro.__doCheckMatchEQ = function(_event){
if (_event.target=='/setting/'){
_event.target = '/setting/account/'
}
_event.matched = _event.target.indexOf(_event.source)==0
};
// notify dispatcher
_m._$regist(
'setting-tab',
_p._$$ModuleSettingTab
);
}); | NEYouFan/nej-toolkit | test/cases/nej_0.1.0/webapp/src/html/module/setting/tab/index.js | JavaScript | mit | 1,741 |
'use strict';
module.exports = require('./lib/extIP'); | tajddin/voiceplay | node_modules/external-ip/index.js | JavaScript | mit | 54 |
version https://git-lfs.github.com/spec/v1
oid sha256:2d445c32b8da04f4b401b315c26c9e56c080a4aa38414551b4b8b809aad7df28
size 100012
| yogeshsaroya/new-cdnjs | ajax/libs/yui/3.14.1/graphics-vml/graphics-vml.js | JavaScript | mit | 131 |
import { Vector3 } from './Vector3.js';
import { Sphere } from './Sphere.js';
/**
* @author bhouston / http://clara.io
* @author WestLangley / http://github.com/WestLangley
*/
function Box3( min, max ) {
this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity );
this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity );
}
Object.assign( Box3.prototype, {
isBox3: true,
set: function ( min, max ) {
this.min.copy( min );
this.max.copy( max );
return this;
},
setFromArray: function ( array ) {
var minX = + Infinity;
var minY = + Infinity;
var minZ = + Infinity;
var maxX = - Infinity;
var maxY = - Infinity;
var maxZ = - Infinity;
for ( var i = 0, l = array.length; i < l; i += 3 ) {
var x = array[ i ];
var y = array[ i + 1 ];
var z = array[ i + 2 ];
if ( x < minX ) minX = x;
if ( y < minY ) minY = y;
if ( z < minZ ) minZ = z;
if ( x > maxX ) maxX = x;
if ( y > maxY ) maxY = y;
if ( z > maxZ ) maxZ = z;
}
this.min.set( minX, minY, minZ );
this.max.set( maxX, maxY, maxZ );
return this;
},
setFromBufferAttribute: function ( attribute ) {
var minX = + Infinity;
var minY = + Infinity;
var minZ = + Infinity;
var maxX = - Infinity;
var maxY = - Infinity;
var maxZ = - Infinity;
for ( var i = 0, l = attribute.count; i < l; i ++ ) {
var x = attribute.getX( i );
var y = attribute.getY( i );
var z = attribute.getZ( i );
if ( x < minX ) minX = x;
if ( y < minY ) minY = y;
if ( z < minZ ) minZ = z;
if ( x > maxX ) maxX = x;
if ( y > maxY ) maxY = y;
if ( z > maxZ ) maxZ = z;
}
this.min.set( minX, minY, minZ );
this.max.set( maxX, maxY, maxZ );
return this;
},
setFromPoints: function ( points ) {
this.makeEmpty();
for ( var i = 0, il = points.length; i < il; i ++ ) {
this.expandByPoint( points[ i ] );
}
return this;
},
setFromCenterAndSize: function () {
var v1 = new Vector3();
return function setFromCenterAndSize( center, size ) {
var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
this.min.copy( center ).sub( halfSize );
this.max.copy( center ).add( halfSize );
return this;
};
}(),
setFromObject: function ( object ) {
this.makeEmpty();
return this.expandByObject( object );
},
clone: function () {
return new this.constructor().copy( this );
},
copy: function ( box ) {
this.min.copy( box.min );
this.max.copy( box.max );
return this;
},
makeEmpty: function () {
this.min.x = this.min.y = this.min.z = + Infinity;
this.max.x = this.max.y = this.max.z = - Infinity;
return this;
},
isEmpty: function () {
// this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
},
getCenter: function ( optionalTarget ) {
var result = optionalTarget || new Vector3();
return this.isEmpty() ? result.set( 0, 0, 0 ) : result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
},
getSize: function ( optionalTarget ) {
var result = optionalTarget || new Vector3();
return this.isEmpty() ? result.set( 0, 0, 0 ) : result.subVectors( this.max, this.min );
},
expandByPoint: function ( point ) {
this.min.min( point );
this.max.max( point );
return this;
},
expandByVector: function ( vector ) {
this.min.sub( vector );
this.max.add( vector );
return this;
},
expandByScalar: function ( scalar ) {
this.min.addScalar( - scalar );
this.max.addScalar( scalar );
return this;
},
expandByObject: function () {
// Computes the world-axis-aligned bounding box of an object (including its children),
// accounting for both the object's, and children's, world transforms
var scope, i, l;
var v1 = new Vector3();
function traverse( node ) {
var geometry = node.geometry;
if ( geometry !== undefined ) {
if ( geometry.isGeometry ) {
var vertices = geometry.vertices;
for ( i = 0, l = vertices.length; i < l; i ++ ) {
v1.copy( vertices[ i ] );
v1.applyMatrix4( node.matrixWorld );
scope.expandByPoint( v1 );
}
} else if ( geometry.isBufferGeometry ) {
var attribute = geometry.attributes.position;
if ( attribute !== undefined ) {
for ( i = 0, l = attribute.count; i < l; i ++ ) {
v1.fromBufferAttribute( attribute, i ).applyMatrix4( node.matrixWorld );
scope.expandByPoint( v1 );
}
}
}
}
}
return function expandByObject( object ) {
scope = this;
object.updateMatrixWorld( true );
object.traverse( traverse );
return this;
};
}(),
containsPoint: function ( point ) {
return point.x < this.min.x || point.x > this.max.x ||
point.y < this.min.y || point.y > this.max.y ||
point.z < this.min.z || point.z > this.max.z ? false : true;
},
containsBox: function ( box ) {
return this.min.x <= box.min.x && box.max.x <= this.max.x &&
this.min.y <= box.min.y && box.max.y <= this.max.y &&
this.min.z <= box.min.z && box.max.z <= this.max.z;
},
getParameter: function ( point, optionalTarget ) {
// This can potentially have a divide by zero if the box
// has a size dimension of 0.
var result = optionalTarget || new Vector3();
return result.set(
( point.x - this.min.x ) / ( this.max.x - this.min.x ),
( point.y - this.min.y ) / ( this.max.y - this.min.y ),
( point.z - this.min.z ) / ( this.max.z - this.min.z )
);
},
intersectsBox: function ( box ) {
// using 6 splitting planes to rule out intersections.
return box.max.x < this.min.x || box.min.x > this.max.x ||
box.max.y < this.min.y || box.min.y > this.max.y ||
box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
},
intersectsSphere: ( function () {
var closestPoint = new Vector3();
return function intersectsSphere( sphere ) {
// Find the point on the AABB closest to the sphere center.
this.clampPoint( sphere.center, closestPoint );
// If that point is inside the sphere, the AABB and sphere intersect.
return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
};
} )(),
intersectsPlane: function ( plane ) {
// We compute the minimum and maximum dot product values. If those values
// are on the same side (back or front) of the plane, then there is no intersection.
var min, max;
if ( plane.normal.x > 0 ) {
min = plane.normal.x * this.min.x;
max = plane.normal.x * this.max.x;
} else {
min = plane.normal.x * this.max.x;
max = plane.normal.x * this.min.x;
}
if ( plane.normal.y > 0 ) {
min += plane.normal.y * this.min.y;
max += plane.normal.y * this.max.y;
} else {
min += plane.normal.y * this.max.y;
max += plane.normal.y * this.min.y;
}
if ( plane.normal.z > 0 ) {
min += plane.normal.z * this.min.z;
max += plane.normal.z * this.max.z;
} else {
min += plane.normal.z * this.max.z;
max += plane.normal.z * this.min.z;
}
return ( min <= plane.constant && max >= plane.constant );
},
clampPoint: function ( point, optionalTarget ) {
var result = optionalTarget || new Vector3();
return result.copy( point ).clamp( this.min, this.max );
},
distanceToPoint: function () {
var v1 = new Vector3();
return function distanceToPoint( point ) {
var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
return clampedPoint.sub( point ).length();
};
}(),
getBoundingSphere: function () {
var v1 = new Vector3();
return function getBoundingSphere( optionalTarget ) {
var result = optionalTarget || new Sphere();
this.getCenter( result.center );
result.radius = this.getSize( v1 ).length() * 0.5;
return result;
};
}(),
intersect: function ( box ) {
this.min.max( box.min );
this.max.min( box.max );
// ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values.
if ( this.isEmpty() ) this.makeEmpty();
return this;
},
union: function ( box ) {
this.min.min( box.min );
this.max.max( box.max );
return this;
},
applyMatrix4: function () {
var points = [
new Vector3(),
new Vector3(),
new Vector3(),
new Vector3(),
new Vector3(),
new Vector3(),
new Vector3(),
new Vector3()
];
return function applyMatrix4( matrix ) {
// transform of empty box is an empty box.
if ( this.isEmpty() ) return this;
// NOTE: I am using a binary pattern to specify all 2^3 combinations below
points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
this.setFromPoints( points );
return this;
};
}(),
translate: function ( offset ) {
this.min.add( offset );
this.max.add( offset );
return this;
},
equals: function ( box ) {
return box.min.equals( this.min ) && box.max.equals( this.max );
}
} );
export { Box3 };
| sasha240100/three.js | src/math/Box3.js | JavaScript | mit | 9,781 |
/**
@license
* @pnp/odata v1.1.5-4 - pnp - provides shared odata functionality and base classes
* MIT (https://github.com/pnp/pnpjs/blob/master/LICENSE)
* Copyright (c) 2018 Microsoft
* docs: https://pnp.github.io/pnpjs/
* source: https:github.com/pnp/pnpjs
* bugs: https://github.com/pnp/pnpjs/issues
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@pnp/common'), require('tslib'), require('@pnp/logging')) :
typeof define === 'function' && define.amd ? define(['exports', '@pnp/common', 'tslib', '@pnp/logging'], factory) :
(factory((global.pnp = global.pnp || {}, global.pnp.odata = {}),global.pnp.common,global.tslib_1,global.pnp.logging));
}(this, (function (exports,common,tslib_1,logging) { 'use strict';
var CachingOptions = /** @class */ (function () {
function CachingOptions(key) {
this.key = key;
this.expiration = common.dateAdd(new Date(), "second", common.RuntimeConfig.defaultCachingTimeoutSeconds);
this.storeName = common.RuntimeConfig.defaultCachingStore;
}
Object.defineProperty(CachingOptions.prototype, "store", {
get: function () {
if (this.storeName === "local") {
return CachingOptions.storage.local;
}
else {
return CachingOptions.storage.session;
}
},
enumerable: true,
configurable: true
});
CachingOptions.storage = new common.PnPClientStorage();
return CachingOptions;
}());
var CachingParserWrapper = /** @class */ (function () {
function CachingParserWrapper(parser, cacheOptions) {
this.parser = parser;
this.cacheOptions = cacheOptions;
}
CachingParserWrapper.prototype.parse = function (response) {
var _this = this;
return this.parser.parse(response).then(function (r) { return _this.cacheData(r); });
};
CachingParserWrapper.prototype.cacheData = function (data) {
if (this.cacheOptions.store !== null) {
this.cacheOptions.store.put(this.cacheOptions.key, data, this.cacheOptions.expiration);
}
return data;
};
return CachingParserWrapper;
}());
var ODataParserBase = /** @class */ (function () {
function ODataParserBase() {
}
ODataParserBase.prototype.parse = function (r) {
var _this = this;
return new Promise(function (resolve, reject) {
if (_this.handleError(r, reject)) {
_this.parseImpl(r, resolve, reject);
}
});
};
ODataParserBase.prototype.parseImpl = function (r, resolve, reject) {
var _this = this;
if ((r.headers.has("Content-Length") && parseFloat(r.headers.get("Content-Length")) === 0) || r.status === 204) {
resolve({});
}
else {
// patch to handle cases of 200 response with no or whitespace only bodies (#487 & #545)
r.text()
.then(function (txt) { return txt.replace(/\s/ig, "").length > 0 ? JSON.parse(txt) : {}; })
.then(function (json) { return resolve(_this.parseODataJSON(json)); })
.catch(function (e) { return reject(e); });
}
};
/**
* Handles a response with ok === false by parsing the body and creating a ProcessHttpClientResponseException
* which is passed to the reject delegate. This method returns true if there is no error, otherwise false
*
* @param r Current response object
* @param reject reject delegate for the surrounding promise
*/
ODataParserBase.prototype.handleError = function (r, reject) {
if (!r.ok) {
// read the response as text, it may not be valid json
r.json().then(function (json) {
// include the headers as they contain diagnostic information
var data = {
responseBody: json,
responseHeaders: r.headers,
};
reject(new Error("Error making HttpClient request in queryable: [" + r.status + "] " + r.statusText + " ::> " + JSON.stringify(data)));
}).catch(function (e) {
reject(new Error("Error making HttpClient request in queryable: [" + r.status + "] " + r.statusText + " ::> " + e));
});
}
return r.ok;
};
/**
* Normalizes the json response by removing the various nested levels
*
* @param json json object to parse
*/
ODataParserBase.prototype.parseODataJSON = function (json) {
var result = json;
if (common.hOP(json, "d")) {
if (common.hOP(json.d, "results")) {
result = json.d.results;
}
else {
result = json.d;
}
}
else if (common.hOP(json, "value")) {
result = json.value;
}
return result;
};
return ODataParserBase;
}());
var ODataDefaultParser = /** @class */ (function (_super) {
tslib_1.__extends(ODataDefaultParser, _super);
function ODataDefaultParser() {
return _super !== null && _super.apply(this, arguments) || this;
}
return ODataDefaultParser;
}(ODataParserBase));
var TextParser = /** @class */ (function (_super) {
tslib_1.__extends(TextParser, _super);
function TextParser() {
return _super !== null && _super.apply(this, arguments) || this;
}
TextParser.prototype.parseImpl = function (r, resolve) {
r.text().then(resolve);
};
return TextParser;
}(ODataParserBase));
var BlobParser = /** @class */ (function (_super) {
tslib_1.__extends(BlobParser, _super);
function BlobParser() {
return _super !== null && _super.apply(this, arguments) || this;
}
BlobParser.prototype.parseImpl = function (r, resolve) {
r.blob().then(resolve);
};
return BlobParser;
}(ODataParserBase));
var JSONParser = /** @class */ (function (_super) {
tslib_1.__extends(JSONParser, _super);
function JSONParser() {
return _super !== null && _super.apply(this, arguments) || this;
}
JSONParser.prototype.parseImpl = function (r, resolve) {
r.json().then(resolve);
};
return JSONParser;
}(ODataParserBase));
var BufferParser = /** @class */ (function (_super) {
tslib_1.__extends(BufferParser, _super);
function BufferParser() {
return _super !== null && _super.apply(this, arguments) || this;
}
BufferParser.prototype.parseImpl = function (r, resolve) {
if (common.isFunc(r.arrayBuffer)) {
r.arrayBuffer().then(resolve);
}
else {
r.buffer().then(resolve);
}
};
return BufferParser;
}(ODataParserBase));
var LambdaParser = /** @class */ (function () {
function LambdaParser(parser) {
this.parser = parser;
}
LambdaParser.prototype.parse = function (r) {
return this.parser(r);
};
return LambdaParser;
}());
/**
* Resolves the context's result value
*
* @param context The current context
*/
function returnResult(context) {
logging.Logger.log({
data: logging.Logger.activeLogLevel === 0 /* Verbose */ ? context.result : {},
level: 1 /* Info */,
message: "[" + context.requestId + "] (" + (new Date()).getTime() + ") Returning result from pipeline. Set logging to verbose to see data.",
});
return Promise.resolve(context.result || null);
}
/**
* Sets the result on the context
*/
function setResult(context, value) {
return new Promise(function (resolve) {
context.result = value;
context.hasResult = true;
resolve(context);
});
}
/**
* Invokes the next method in the provided context's pipeline
*
* @param c The current request context
*/
function next(c) {
if (c.pipeline.length > 0) {
return c.pipeline.shift()(c);
}
else {
return Promise.resolve(c);
}
}
/**
* Executes the current request context's pipeline
*
* @param context Current context
*/
function pipe(context) {
if (context.pipeline.length < 1) {
logging.Logger.write("[" + context.requestId + "] (" + (new Date()).getTime() + ") Request pipeline contains no methods!", 2 /* Warning */);
}
var promise = next(context).then(function (ctx) { return returnResult(ctx); }).catch(function (e) {
logging.Logger.error(e);
throw e;
});
if (context.isBatched) {
// this will block the batch's execute method from returning until the child requets have been resolved
context.batch.addResolveBatchDependency(promise);
}
return promise;
}
/**
* decorator factory applied to methods in the pipeline to control behavior
*/
function requestPipelineMethod(alwaysRun) {
if (alwaysRun === void 0) { alwaysRun = false; }
return function (target, propertyKey, descriptor) {
var method = descriptor.value;
descriptor.value = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
// if we have a result already in the pipeline, pass it along and don't call the tagged method
if (!alwaysRun && args.length > 0 && common.hOP(args[0], "hasResult") && args[0].hasResult) {
logging.Logger.write("[" + args[0].requestId + "] (" + (new Date()).getTime() + ") Skipping request pipeline method " + propertyKey + ", existing result in pipeline.", 0 /* Verbose */);
return Promise.resolve(args[0]);
}
// apply the tagged method
logging.Logger.write("[" + args[0].requestId + "] (" + (new Date()).getTime() + ") Calling request pipeline method " + propertyKey + ".", 0 /* Verbose */);
// then chain the next method in the context's pipeline - allows for dynamic pipeline
return method.apply(target, args).then(function (ctx) { return next(ctx); });
};
};
}
/**
* Contains the methods used within the request pipeline
*/
var PipelineMethods = /** @class */ (function () {
function PipelineMethods() {
}
/**
* Logs the start of the request
*/
PipelineMethods.logStart = function (context) {
return new Promise(function (resolve) {
logging.Logger.log({
data: logging.Logger.activeLogLevel === 1 /* Info */ ? {} : context,
level: 1 /* Info */,
message: "[" + context.requestId + "] (" + (new Date()).getTime() + ") Beginning " + context.verb + " request (" + context.requestAbsoluteUrl + ")",
});
resolve(context);
});
};
/**
* Handles caching of the request
*/
PipelineMethods.caching = function (context) {
return new Promise(function (resolve) {
// handle caching, if applicable
if (context.isCached) {
logging.Logger.write("[" + context.requestId + "] (" + (new Date()).getTime() + ") Caching is enabled for request, checking cache...", 1 /* Info */);
var cacheOptions = new CachingOptions(context.requestAbsoluteUrl.toLowerCase());
if (context.cachingOptions !== undefined) {
cacheOptions = common.extend(cacheOptions, context.cachingOptions);
}
// we may not have a valid store
if (cacheOptions.store !== null) {
// check if we have the data in cache and if so resolve the promise and return
var data = cacheOptions.store.get(cacheOptions.key);
if (data !== null) {
// ensure we clear any held batch dependency we are resolving from the cache
logging.Logger.log({
data: logging.Logger.activeLogLevel === 1 /* Info */ ? {} : data,
level: 1 /* Info */,
message: "[" + context.requestId + "] (" + (new Date()).getTime() + ") Value returned from cache.",
});
if (common.isFunc(context.batchDependency)) {
context.batchDependency();
}
// handle the case where a parser needs to take special actions with a cached result
if (common.hOP(context.parser, "hydrate")) {
data = context.parser.hydrate(data);
}
return setResult(context, data).then(function (ctx) { return resolve(ctx); });
}
}
logging.Logger.write("[" + context.requestId + "] (" + (new Date()).getTime() + ") Value not found in cache.", 1 /* Info */);
// if we don't then wrap the supplied parser in the caching parser wrapper
// and send things on their way
context.parser = new CachingParserWrapper(context.parser, cacheOptions);
}
return resolve(context);
});
};
/**
* Sends the request
*/
PipelineMethods.send = function (context) {
return new Promise(function (resolve, reject) {
// send or batch the request
if (context.isBatched) {
// we are in a batch, so add to batch, remove dependency, and resolve with the batch's promise
var p = context.batch.add(context.requestAbsoluteUrl, context.verb, context.options, context.parser, context.requestId);
// we release the dependency here to ensure the batch does not execute until the request is added to the batch
if (common.isFunc(context.batchDependency)) {
context.batchDependency();
}
logging.Logger.write("[" + context.requestId + "] (" + (new Date()).getTime() + ") Batching request in batch " + context.batch.batchId + ".", 1 /* Info */);
// we set the result as the promise which will be resolved by the batch's execution
resolve(setResult(context, p));
}
else {
logging.Logger.write("[" + context.requestId + "] (" + (new Date()).getTime() + ") Sending request.", 1 /* Info */);
// we are not part of a batch, so proceed as normal
var client = context.clientFactory();
var opts = common.extend(context.options || {}, { method: context.verb });
client.fetch(context.requestAbsoluteUrl, opts)
.then(function (response) { return context.parser.parse(response); })
.then(function (result) { return setResult(context, result); })
.then(function (ctx) { return resolve(ctx); })
.catch(function (e) { return reject(e); });
}
});
};
/**
* Logs the end of the request
*/
PipelineMethods.logEnd = function (context) {
return new Promise(function (resolve) {
if (context.isBatched) {
logging.Logger.log({
data: logging.Logger.activeLogLevel === 1 /* Info */ ? {} : context,
level: 1 /* Info */,
message: "[" + context.requestId + "] (" + (new Date()).getTime() + ") " + context.verb + " request will complete in batch " + context.batch.batchId + ".",
});
}
else {
logging.Logger.log({
data: logging.Logger.activeLogLevel === 1 /* Info */ ? {} : context,
level: 1 /* Info */,
message: "[" + context.requestId + "] (" + (new Date()).getTime() + ") Completing " + context.verb + " request.",
});
}
resolve(context);
});
};
tslib_1.__decorate([
requestPipelineMethod(true)
], PipelineMethods, "logStart", null);
tslib_1.__decorate([
requestPipelineMethod()
], PipelineMethods, "caching", null);
tslib_1.__decorate([
requestPipelineMethod()
], PipelineMethods, "send", null);
tslib_1.__decorate([
requestPipelineMethod(true)
], PipelineMethods, "logEnd", null);
return PipelineMethods;
}());
function getDefaultPipeline() {
return [
PipelineMethods.logStart,
PipelineMethods.caching,
PipelineMethods.send,
PipelineMethods.logEnd,
].slice(0);
}
var Queryable = /** @class */ (function () {
function Queryable() {
this._query = new Map();
this._options = {};
this._url = "";
this._parentUrl = "";
this._useCaching = false;
this._cachingOptions = null;
}
/**
* Gets the currentl url
*
*/
Queryable.prototype.toUrl = function () {
return this._url;
};
/**
* Directly concatonates the supplied string to the current url, not normalizing "/" chars
*
* @param pathPart The string to concatonate to the url
*/
Queryable.prototype.concat = function (pathPart) {
this._url += pathPart;
return this;
};
Object.defineProperty(Queryable.prototype, "query", {
/**
* Provides access to the query builder for this url
*
*/
get: function () {
return this._query;
},
enumerable: true,
configurable: true
});
/**
* Sets custom options for current object and all derived objects accessible via chaining
*
* @param options custom options
*/
Queryable.prototype.configure = function (options) {
common.mergeOptions(this._options, options);
return this;
};
/**
* Configures this instance from the configure options of the supplied instance
*
* @param o Instance from which options should be taken
*/
Queryable.prototype.configureFrom = function (o) {
common.mergeOptions(this._options, o._options);
return this;
};
/**
* Enables caching for this request
*
* @param options Defines the options used when caching this request
*/
Queryable.prototype.usingCaching = function (options) {
if (!common.RuntimeConfig.globalCacheDisable) {
this._useCaching = true;
if (options !== undefined) {
this._cachingOptions = options;
}
}
return this;
};
Queryable.prototype.getCore = function (parser, options) {
if (parser === void 0) { parser = new JSONParser(); }
if (options === void 0) { options = {}; }
return this.toRequestContext("GET", options, parser, getDefaultPipeline()).then(function (context) { return pipe(context); });
};
Queryable.prototype.postCore = function (options, parser) {
if (options === void 0) { options = {}; }
if (parser === void 0) { parser = new JSONParser(); }
return this.toRequestContext("POST", options, parser, getDefaultPipeline()).then(function (context) { return pipe(context); });
};
Queryable.prototype.patchCore = function (options, parser) {
if (options === void 0) { options = {}; }
if (parser === void 0) { parser = new JSONParser(); }
return this.toRequestContext("PATCH", options, parser, getDefaultPipeline()).then(function (context) { return pipe(context); });
};
Queryable.prototype.deleteCore = function (options, parser) {
if (options === void 0) { options = {}; }
if (parser === void 0) { parser = new JSONParser(); }
return this.toRequestContext("DELETE", options, parser, getDefaultPipeline()).then(function (context) { return pipe(context); });
};
Queryable.prototype.putCore = function (options, parser) {
if (options === void 0) { options = {}; }
if (parser === void 0) { parser = new JSONParser(); }
return this.toRequestContext("PUT", options, parser, getDefaultPipeline()).then(function (context) { return pipe(context); });
};
/**
* Appends the given string and normalizes "/" chars
*
* @param pathPart The string to append
*/
Queryable.prototype.append = function (pathPart) {
this._url = common.combine(this._url, pathPart);
};
Object.defineProperty(Queryable.prototype, "parentUrl", {
/**
* Gets the parent url used when creating this instance
*
*/
get: function () {
return this._parentUrl;
},
enumerable: true,
configurable: true
});
/**
* Extends this queryable from the provided parent
*
* @param parent Parent queryable from which we will derive a base url
* @param path Additional path
*/
Queryable.prototype.extend = function (parent, path) {
this._parentUrl = parent._url;
this._url = common.combine(this._parentUrl, path);
this.configureFrom(parent);
};
return Queryable;
}());
var ODataQueryable = /** @class */ (function (_super) {
tslib_1.__extends(ODataQueryable, _super);
function ODataQueryable() {
var _this = _super.call(this) || this;
_this._batch = null;
return _this;
}
/**
* Adds this query to the supplied batch
*
* @example
* ```
*
* let b = pnp.sp.createBatch();
* pnp.sp.web.inBatch(b).get().then(...);
* b.execute().then(...)
* ```
*/
ODataQueryable.prototype.inBatch = function (batch) {
if (this.batch !== null) {
throw new Error("This query is already part of a batch.");
}
this._batch = batch;
return this;
};
/**
* Gets the currentl url
*
*/
ODataQueryable.prototype.toUrl = function () {
return this._url;
};
/**
* Executes the currently built request
*
* @param parser Allows you to specify a parser to handle the result
* @param getOptions The options used for this request
*/
ODataQueryable.prototype.get = function (parser, options) {
if (parser === void 0) { parser = new ODataDefaultParser(); }
if (options === void 0) { options = {}; }
return this.getCore(parser, options);
};
ODataQueryable.prototype.getCore = function (parser, options) {
if (parser === void 0) { parser = new ODataDefaultParser(); }
if (options === void 0) { options = {}; }
return this.toRequestContext("GET", options, parser, getDefaultPipeline()).then(function (context) { return pipe(context); });
};
ODataQueryable.prototype.postCore = function (options, parser) {
if (options === void 0) { options = {}; }
if (parser === void 0) { parser = new ODataDefaultParser(); }
return this.toRequestContext("POST", options, parser, getDefaultPipeline()).then(function (context) { return pipe(context); });
};
ODataQueryable.prototype.patchCore = function (options, parser) {
if (options === void 0) { options = {}; }
if (parser === void 0) { parser = new ODataDefaultParser(); }
return this.toRequestContext("PATCH", options, parser, getDefaultPipeline()).then(function (context) { return pipe(context); });
};
ODataQueryable.prototype.deleteCore = function (options, parser) {
if (options === void 0) { options = {}; }
if (parser === void 0) { parser = new ODataDefaultParser(); }
return this.toRequestContext("DELETE", options, parser, getDefaultPipeline()).then(function (context) { return pipe(context); });
};
ODataQueryable.prototype.putCore = function (options, parser) {
if (options === void 0) { options = {}; }
if (parser === void 0) { parser = new ODataDefaultParser(); }
return this.toRequestContext("PUT", options, parser, getDefaultPipeline()).then(function (context) { return pipe(context); });
};
/**
* Blocks a batch call from occuring, MUST be cleared by calling the returned function
*/
ODataQueryable.prototype.addBatchDependency = function () {
if (this._batch !== null) {
return this._batch.addDependency();
}
return function () { return null; };
};
Object.defineProperty(ODataQueryable.prototype, "hasBatch", {
/**
* Indicates if the current query has a batch associated
*
*/
get: function () {
return common.objectDefinedNotNull(this._batch);
},
enumerable: true,
configurable: true
});
Object.defineProperty(ODataQueryable.prototype, "batch", {
/**
* The batch currently associated with this query or null
*
*/
get: function () {
return this.hasBatch ? this._batch : null;
},
enumerable: true,
configurable: true
});
return ODataQueryable;
}(Queryable));
var ODataBatch = /** @class */ (function () {
function ODataBatch(_batchId) {
if (_batchId === void 0) { _batchId = common.getGUID(); }
this._batchId = _batchId;
this._reqs = [];
this._deps = [];
this._rDeps = [];
}
Object.defineProperty(ODataBatch.prototype, "batchId", {
get: function () {
return this._batchId;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ODataBatch.prototype, "requests", {
/**
* The requests contained in this batch
*/
get: function () {
return this._reqs;
},
enumerable: true,
configurable: true
});
/**
*
* @param url Request url
* @param method Request method (GET, POST, etc)
* @param options Any request options
* @param parser The parser used to handle the eventual return from the query
* @param id An identifier used to track a request within a batch
*/
ODataBatch.prototype.add = function (url, method, options, parser, id) {
var info = {
id: id,
method: method.toUpperCase(),
options: options,
parser: parser,
reject: null,
resolve: null,
url: url,
};
var p = new Promise(function (resolve, reject) {
info.resolve = resolve;
info.reject = reject;
});
this._reqs.push(info);
return p;
};
/**
* Adds a dependency insuring that some set of actions will occur before a batch is processed.
* MUST be cleared using the returned resolve delegate to allow batches to run
*/
ODataBatch.prototype.addDependency = function () {
var resolver = function () { return void (0); };
this._deps.push(new Promise(function (resolve) {
resolver = resolve;
}));
return resolver;
};
/**
* The batch's execute method will not resolve util any promises added here resolve
*
* @param p The dependent promise
*/
ODataBatch.prototype.addResolveBatchDependency = function (p) {
this._rDeps.push(p);
};
/**
* Execute the current batch and resolve the associated promises
*
* @returns A promise which will be resolved once all of the batch's child promises have resolved
*/
ODataBatch.prototype.execute = function () {
var _this = this;
// we need to check the dependencies twice due to how different engines handle things.
// We can get a second set of promises added during the first set resolving
return Promise.all(this._deps)
.then(function () { return Promise.all(_this._deps); })
.then(function () { return _this.executeImpl(); })
.then(function () { return Promise.all(_this._rDeps); })
.then(function () { return void (0); });
};
return ODataBatch;
}());
exports.CachingOptions = CachingOptions;
exports.CachingParserWrapper = CachingParserWrapper;
exports.ODataParserBase = ODataParserBase;
exports.ODataDefaultParser = ODataDefaultParser;
exports.TextParser = TextParser;
exports.BlobParser = BlobParser;
exports.JSONParser = JSONParser;
exports.BufferParser = BufferParser;
exports.LambdaParser = LambdaParser;
exports.setResult = setResult;
exports.pipe = pipe;
exports.requestPipelineMethod = requestPipelineMethod;
exports.PipelineMethods = PipelineMethods;
exports.getDefaultPipeline = getDefaultPipeline;
exports.Queryable = Queryable;
exports.ODataQueryable = ODataQueryable;
exports.ODataBatch = ODataBatch;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=odata.es5.umd.js.map
| cdnjs/cdnjs | ajax/libs/pnp-odata/1.1.5-4/odata.es5.umd.js | JavaScript | mit | 32,377 |
$data.ServiceBase.extend('$data.JayStormAPI.FunctionImport', {
/*addEntity: (function(name, fullname, namespace){
return function(success, error){
var self = this;
this.context.Entities.filter(function(it){ return it.FullName === this.fullname; }, { fullname: fullname }).length(function(cnt){
if (cnt) self.error('Entity type already exists.');
else{
self.context.Entities.add(new $data.JayStormAPI.Entity({
Name: name,
FullName: fullname,
Namespace: namespace
}));
self.context.saveChanges(self);
}
});
};
}).toServiceOperation().params([
{ name: 'name', type: 'string' },
{ name: 'fullname', type: 'string' },
{ name: 'namespace', type: 'string' }
]).returns('int'),
removeEntityByID: (function(id){
return function(success, error){
var self = this;
this.context.Entities.single(function(it){ return it.EntityID === this.id; }, { id: id }, {
success: function(entity){
self.context.Entities.remove(entity);
self.context.EntityFields.filter(function(it){ return it.EntityID === this.entityid; }, { entityid: entity.EntityID }).toArray({
success: function(fields){
for (var i = 0; i < fields.length; i++) self.context.EntityFields.remove(fields[i]);
self.context.saveChanges(self);
},
error: self.error
});
},
error: self.error
});
};
}).toServiceOperation().params([{ name: 'id', type: 'id' }]).returns('int'),
removeEntityByName: (function(name){
return function(success, error){
var self = this;
this.context.Entities.single(function(it){ return it.Name === this.name; }, { name: name }, {
success: function(entity){
self.context.Entities.remove(entity);
self.context.EntityFields.filter(function(it){ return it.EntityID === this.entityid; }, { entityid: entity.EntityID }).toArray({
success: function(fields){
for (var i = 0; i < fields.length; i++) self.context.EntityFields.remove(fields[i]);
self.context.saveChanges(self);
},
error: self.error
});
},
error: self.error
});
};
}).toServiceOperation().params([{ name: 'name', type: 'string' }]).returns('int'),
removeEntityByFullName: (function(fullname){
return function(success, error){
var self = this;
this.context.Entities.single(function(it){ return it.FullName === this.fullname; }, { fullname: fullname }, {
success: function(entity){
self.context.Entities.remove(entity);
self.context.EntityFields.filter(function(it){ return it.EntityID === this.entityid; }, { entityid: entity.EntityID }).toArray({
success: function(fields){
for (var i = 0; i < fields.length; i++) self.context.EntityFields.remove(fields[i]);
self.context.saveChanges(self);
},
error: self.error
});
},
error: self.error
});
};
}).toServiceOperation().params([{ name: 'fullname', type: 'string' }]).returns('int'),
getAllEntities: (function(){
return this.context.Entities.toArray(this);
}).toServiceOperation().returns($data.Array, $data.JayStormAPI.Entity),
getEntityByID: (function(id){
return this.context.Entities.single(function(it){ return it.EntityID === this.id; }, { id: id }, this);
}).toServiceOperation().params([{ name: 'id', type: 'id' }]).returns($data.JayStormAPI.Entity),
getEntityByName: (function(name){
return this.context.Entities.single(function(it){ return it.Name === this.name; }, { name: name }, this);
}).toServiceOperation().params([{ name: 'name', type: 'string' }]).returns($data.JayStormAPI.Entity),
getEntityByFullName: (function(fullname){
return this.context.Entities.single(function(it){ return it.FullName === this.fullname; }, { fullname: fullname }, this);
}).toServiceOperation().params([{ name: 'fullname', type: 'string' }]).returns($data.JayStormAPI.Entity),
getEntityByNamespace: (function(namespace){
return this.context.Entities.single(function(it){ return it.Namespace === this.namespace; }, { namespace: namespace }, this);
}).toServiceOperation().params([{ name: 'namespace', type: 'string' }]).returns($data.JayStormAPI.Entity),
addFieldToEntity: (function(entity, name, type, elementType, inverseProperty, key, computed, nullable, required, customValidator, minValue, maxValue, minLength, maxLength, length, regex){
return function(success, error){
var self = this;
this.context.Entities.single(function(it){ return it.Name === this.entity || it.FullName === this.entity; }, { entity: entity }, {
success: function(result){
self.context.EntityFields.add(new $data.JayStormAPI.EntityField({
EntityID: result.EntityID,
Name: name,
Type: type,
ElementType: elementType,
InverseProperty: inverseProperty,
Key: key,
Computed: computed,
Nullable: nullable,
Required: required,
CustomValidator: customValidator,
MinValue: minValue,
MaxValue: maxValue,
MinLength: minLength,
MaxLength: maxLength,
Length: length,
RegExp: regex
}));
self.context.saveChanges(self);
},
error: self.error
});
};
}).toServiceOperation().params([
{ name: 'entity', type: 'string' },
{ name: 'name', type: 'string' },
{ name: 'type', type: 'string' },
{ name: 'elementType', type: 'string' },
{ name: 'inverseProperty', type: 'string' },
{ name: 'key', type: 'bool' },
{ name: 'computed', type: 'bool' },
{ name: 'nullable', type: 'bool' },
{ name: 'required', type: 'bool' },
{ name: 'customValidator', type: 'string' },
{ name: 'minValue', type: 'string' },
{ name: 'maxValue', type: 'string' },
{ name: 'minLength', type: 'int' },
{ name: 'maxLength', type: 'int' },
{ name: 'length', type: 'int' },
{ name: 'regex', type: 'string' }
]).returns('int'),
removeFieldByEntityIDAndName: (function(entityid, name){
return function(success, error){
var self = this;
this.context.EntityFields.single(function(it){ return it.EntityID === this.entityid && it.Name === this.name; }, { entityid: entityid, name: name }, {
success: function(field){
self.context.EntityFields.remove(field);
self.context.saveChanges(self);
},
error: self.error
});
};
}).toServiceOperation().params([
{ name: 'entityid', type: 'id' },
{ name: 'name', type: 'string' }
]).returns('int'),
removeAllFieldsByEntityID: (function(entityid){
return function(success, error){
var self = this;
this.context.EntityFields.filter(function(it){ return it.EntityID === this.entityid; }, { entityid: entityid }).toArray({
success: function(result){
if (result.length){
for (var i = 0; i < result.length; i++) self.context.EntityFields.remove(result[i]);
self.context.saveChanges(self);
}
},
error: self.error
});
};
}).toServiceOperation().params([{ name: 'entityid', type: 'id' }]).returns('int'),
getAllFields: (function(){
return this.context.EntityFields.toArray(this);
}).toServiceOperation().returns($data.Array, $data.JayStormAPI.EntityField),
getAllFieldsByEntityID: (function(entityid){
return this.context.EntityFields.filter(function(it){ return it.EntityID === this.entityid; }, { entityid: entityid }).toArray(this);
}).toServiceOperation().params([{ name: 'entityid', type: 'id' }]).returns($data.Array, $data.JayStormAPI.EntityField),
addEntitySet: (function(name, elementType, tableName, publish){
return function(success, error){
var self = this;
console.log(name, elementType, tableName, publish);
this.context.Entities.single(function(it){ return it.Name === this.elementType || it.FullName === this.elementType; }, { elementType: elementType }, {
success: function(result){
self.context.EntitySets.filter(function(it){ return it.Name === this.name; }, { name: name }).length(function(cnt){
if (cnt) self.error('EntitySet already exists.');
else{
self.context.EntitySets.add(new $data.JayStormAPI.EntitySet({
Name: name,
ElementType: elementType,
ElementTypeID: result.EntityID,
TableName: tableName,
Publish: publish
}));
self.context.saveChanges(self);
}
});
},
error: self.error
});
};
}).toServiceOperation().params([
{ name: 'name', type: 'string' },
{ name: 'elementType', type: 'string' },
{ name: 'tableName', type: 'string' },
{ name: 'publish', type: 'bool' }
]).returns('int'),
removeEntitySetByName: (function(name){
return function(success, error){
var self = this;
this.context.EntitySets.first(function(it){ return it.Name === this.name; }, { name: name }, {
success: function(entitySet){
self.context.EntitySets.remove(entitySet);
self.context.saveChanges(self);
},
error: self.error
});
};
}).toServiceOperation().params([{ name: 'name', type: 'string' }]).returns('int'),
getAllEntitySets: (function(){
return this.context.EntitySets.toArray(this);
}).toServiceOperation().returns($data.Array, $data.JayStormAPI.EntitySet),
getEntitySetByID: (function(id){
return this.context.EntitySets.single(function(it){ return it.EntitySetID === this.id; }, { id: id }, this);
}).toServiceOperation().params([{ name: 'id', type: 'id' }]).returns($data.JayStormAPI.EntitySet),
getEntitySetByName: (function(name){
return this.context.EntitySets.single(function(it){ return it.Name === this.name; }, { name: name }, this);
}).toServiceOperation().params([{ name: 'name', type: 'string' }]).returns($data.JayStormAPI.EntitySet),
getEntitySetByEntityID: (function(id){
return this.context.EntitySets.single(function(it){ return it.EntitySetID === this.id; }, { id: id }, this);
}).toServiceOperation().params([{ name: 'id', type: 'id' }]).returns($data.JayStormAPI.EntitySet),*/
getContext: (function(db){
return function(success, error){
var self = this;
var nsContext;
var context = {};
var entities = [];
var entityIds = [];
var entitySets = {};
this.context.Databases.single(function(it){ return it.Name == this.db; }, { db: db }, function(db){
nsContext = db.Namespace + '.Context';
context.ContextName = nsContext;
self.context.EntitySets.filter(function(it){ return it.Publish && it.DatabaseID == this.db; }, { db: db.DatabaseID }).toArray({
success: function(result){
var ret = {};
for (var i = 0; i < result.length; i++){
var r = result[i];
ret[r.Name] = {
type: '$data.EntitySet',
elementType: db.Namespace + '.' + r.ElementType
};
if (r.TableName) ret[r.Name].tableName = r.TableName;
entitySets[r.EntitySetID] = ret[r.Name];
//entities.push(r.ElementType);
}
context[nsContext] = ret;
//console.log(entities);
},
error: self.error
}).then(function(){
self.context.Entities.filter(function(it){ return it.DatabaseID == this.db; }, { db: db.DatabaseID }) /*.filter(function(it){ return it.FullName in this.entities; }, { entities: entities })*/.toArray({
success: function(result){
entities = result;
self.context.ComplexTypes.filter(function(it){ return it.DatabaseID == this.db; }, { db: db.DatabaseID }).toArray(function(result){
if (result.length) entities = entities.concat(result);
entityIds = entities.map(function(it){ return it.EntityID; });
/*for (var i = 0; i < result.length; i++){
var r = result[i];
//entityIds.push(r.EntityID);
context[r.FullName] = {};
for (var j = 0; j < r.Fields.length; j++){
var rf = r.Fields[j];
var f = {};
f.type = rf.Type;
if (rf.ElementType) f.elementType = rf.ElementType;
if (rf.InverseProperty) f.inverseProperty = rf.InverseProperty;
if (rf.Key) f.key = true;
if (rf.Computed) f.computed = true;
if (rf.Nullable !== undefined && r.Nullable !== null) f.nullable = !!rf.Nullable;
if (rf.Required) f.required = true;
if (rf.CustomValidator) f.customValidator = rf.CustomValidator;
if (rf.MinValue !== undefined && rf.MinValue !== null) f.minValue = rf.MinValue;
if (rf.MaxValue !== undefined && rf.MaxValue !== null) f.maxValue = rf.MaxValue;
if (rf.MinLength !== undefined && rf.MinLength !== null) f.minLength = rf.MinLength;
if (rf.MaxLength !== undefined && rf.MaxLength !== null) f.maxLength = rf.MaxLength;
if (rf.Length !== undefined && rf.Length !== null) f.length = rf.Length;
if (rf.RegExp) f.regex = rf.RegExp;
if (rf.ExtensionAttributes && rf.ExtensionAttributes.length){
for (var k = 0; k < rf.ExtensionAttributes.length; k++){
var kv = rf.ExtensionAttributes[k];
f[kv.Key] = kv.Value;
}
}
context[r.FullName][rf.Name] = f;
}
}
self.success(context);*/
self.context.EntityFields.filter(function(it){ return it.EntityID in this.entityid && it.DatabaseID == this.db; }, { db: db.DatabaseID, entityid: entityIds }).toArray({
success: function(result){
for (var i = 0; i < result.length; i++){
var r = result[i];
var e = entities.filter(function(it){ return it.EntityID === r.EntityID; })[0];
var f = {};
if (!context[e.FullName || ((e.Namespace || db.Namespace) + e.Name)]) context[e.FullName || ((e.Namespace || db.Namespace) + e.Name)] = {};
f.type = r.Type;
if (r.ElementType) f.elementType = r.ElementType;
if (r.InverseProperty) f.inverseProperty = r.InverseProperty;
if (r.Key) f.key = true;
if (r.Computed) f.computed = true;
if (r.Nullable !== undefined && r.Nullable !== null) f.nullable = !!r.Nullable;
if (r.Required) f.required = true;
if (r.CustomValidator) f.customValidator = r.CustomValidator;
if (r.MinValue !== undefined && r.MinValue !== null) f.minValue = r.MinValue;
if (r.MaxValue !== undefined && r.MaxValue !== null) f.maxValue = r.MaxValue;
if (r.MinLength !== undefined && r.MinLength !== null) f.minLength = r.MinLength;
if (r.MaxLength !== undefined && r.MaxLength !== null) f.maxLength = r.MaxLength;
if (r.Length !== undefined && r.Length !== null) f.length = r.Length;
if (r.RegExp) f.regex = r.RegExp;
context[e.FullName || ((e.Namespace || db.Namespace) + e.Name)][r.Name] = f;
}
self.context.EventHandlers.filter(function(it){ return it.DatabaseID == this.db; }, { db: db.DatabaseID }).toArray({
success: function(result){
for (var i = 0; i < result.length; i++){
var r = result[i];
entitySets[r.EntitySetID][r.Type] = r.Handler;
}
self.success(context);
},
error: self.error
});
},
error: self.error
});
});
},
error: self.error
});
});
});
};
}).toServiceOperation().params([{ name: 'db', type: 'string' }]).returns($data.Object),
getContextJS: (function(db){
return function(success, error){
var self = this;
this.context.getContext.asFunction(db).apply({
context: this.context,
success: function(context){
var js = '';
var events = {
afterCreate: true,
afterRead: true,
afterUpdate: true,
afterDelete: true,
beforeCreate: true,
beforeRead: true,
beforeUpdate: true,
beforeDelete: true
};
for (var i in context){
var c = context[i];
if (i != context.ContextName && i != 'ContextName'){
js += '$data.Entity.extend("' + i + '", {\n';
var trim = false;
for (var prop in c){
var p = c[prop];
js += ' ' + prop + ': { ';
for (var attr in p){
js += attr + ': ' + JSON.stringify(p[attr]) + ', ';
}
var lio = js.lastIndexOf(', ');
js = js.substring(0, lio);
js += ' },\n';
trim = true;
}
if (trim){
var lio = js.lastIndexOf(',');
js = js.substring(0, lio);
}
js += '\n});\n\n';
}
}
var c = context[context.ContextName];
js += '$data.EntityContext.extend("' + context.ContextName + '", {\n';
for (var i in c){
var es = c[i];
js += ' ' + i + ': { type: $data.EntitySet, elementType: ' + es.elementType + (es.tableName ? ', tableName: "' + es.tableName + '" ' : '');
for (var e in events){
console.log(i, e, es[e]);
if (es[e]) js += (',\n ' + e + ': ' + es[e]);
}
js += ' },\n';
}
var lio = js.lastIndexOf(',');
js = js.substring(0, lio);
js += '\n});';
console.log(js);
self.success(js);
},
error: this.error
}, success, error);
};
}).toServiceOperation().params([{ name: 'db', type: 'string' }]).returns('string')//.asResult($data.JavaScriptResult)
});
| gerzhan/jaydata | ContextAPI/contextapi-api.js | JavaScript | gpl-2.0 | 23,437 |
class Forcescheduler {
constructor(Base, dataService) {
let ForceschedulerInstance;
return (ForceschedulerInstance = class ForceschedulerInstance extends Base {
constructor(object, endpoint) {
super(object, endpoint);
}
});
}
}
angular.module('bbData')
.factory('Forcescheduler', ['Base', 'dataService', Forcescheduler]);
| cmouse/buildbot | www/data_module/src/classes/forcescheduler.service.js | JavaScript | gpl-2.0 | 396 |
// Copyright 2013 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Flags: --harmony-arrays
assertEquals(1, Array.prototype.findIndex.length);
var a = [21, 22, 23, 24];
assertEquals(-1, a.findIndex(function() { return false; }));
assertEquals(-1, a.findIndex(function(val) { return 121 === val; }));
assertEquals(0, a.findIndex(function() { return true; }));
assertEquals(1, a.findIndex(function(val) { return 22 === val; }), undefined);
assertEquals(2, a.findIndex(function(val) { return 23 === val; }), null);
assertEquals(3, a.findIndex(function(val) { return 24 === val; }));
//
// Test predicate is not called when array is empty
//
(function() {
var a = [];
var l = -1;
var o = -1;
var v = -1;
var k = -1;
a.findIndex(function(val, key, obj) {
o = obj;
l = obj.length;
v = val;
k = key;
return false;
});
assertEquals(-1, l);
assertEquals(-1, o);
assertEquals(-1, v);
assertEquals(-1, k);
})();
//
// Test predicate is called with correct argumetns
//
(function() {
var a = ["b"];
var l = -1;
var o = -1;
var v = -1;
var k = -1;
var index = a.findIndex(function(val, key, obj) {
o = obj;
l = obj.length;
v = val;
k = key;
return false;
});
assertArrayEquals(a, o);
assertEquals(a.length, l);
assertEquals("b", v);
assertEquals(0, k);
assertEquals(-1, index);
})();
//
// Test predicate is called array.length times
//
(function() {
var a = [1, 2, 3, 4, 5];
var l = 0;
a.findIndex(function() {
l++;
return false;
});
assertEquals(a.length, l);
})();
//
// Test Array.prototype.findIndex works with String
//
(function() {
var a = "abcd";
var l = -1;
var o = -1;
var v = -1;
var k = -1;
var index = Array.prototype.findIndex.call(a, function(val, key, obj) {
o = obj.toString();
l = obj.length;
v = val;
k = key;
return false;
});
assertEquals(a, o);
assertEquals(a.length, l);
assertEquals("d", v);
assertEquals(3, k);
assertEquals(-1, index);
index = Array.prototype.findIndex.apply(a, [function(val, key, obj) {
o = obj.toString();
l = obj.length;
v = val;
k = key;
return true;
}]);
assertEquals(a, o);
assertEquals(a.length, l);
assertEquals("a", v);
assertEquals(0, k);
assertEquals(0, index);
})();
//
// Test Array.prototype.findIndex works with exotic object
//
(function() {
var l = -1;
var o = -1;
var v = -1;
var k = -1;
var a = {
prop1: "val1",
prop2: "val2",
isValid: function() {
return this.prop1 === "val1" && this.prop2 === "val2";
}
};
Array.prototype.push.apply(a, [30, 31, 32]);
var index = Array.prototype.findIndex.call(a, function(val, key, obj) {
o = obj;
l = obj.length;
v = val;
k = key;
return !obj.isValid();
});
assertArrayEquals(a, o);
assertEquals(3, l);
assertEquals(32, v);
assertEquals(2, k);
assertEquals(-1, index);
})();
//
// Test array modifications
//
(function() {
var a = [1, 2, 3];
a.findIndex(function(val) { a.push(val); return false; });
assertArrayEquals([1, 2, 3, 1, 2, 3], a);
assertEquals(6, a.length);
a = [1, 2, 3];
a.findIndex(function(val, key) { a[key] = ++val; return false; });
assertArrayEquals([2, 3, 4], a);
assertEquals(3, a.length);
})();
//
// Test predicate is called for holes
//
(function() {
var a = new Array(30);
a[11] = 21;
a[7] = 10;
a[29] = 31;
var count = 0;
a.findIndex(function() { count++; return false; });
assertEquals(30, count);
})();
(function() {
var a = [0, 1, , 3];
var count = 0;
var index = a.findIndex(function(val) { return val === undefined; });
assertEquals(2, index);
})();
(function() {
var a = [0, 1, , 3];
a.__proto__ = {
__proto__: Array.prototype,
2: 42,
};
var count = 0;
var index = a.findIndex(function(val) { return val === 42; });
assertEquals(2, index);
})();
//
// Test thisArg
//
(function() {
// Test String as a thisArg
var index = [1, 2, 3].findIndex(function(val, key) {
return this.charAt(Number(key)) === String(val);
}, "321");
assertEquals(1, index);
// Test object as a thisArg
var thisArg = {
elementAt: function(key) {
return this[key];
}
};
Array.prototype.push.apply(thisArg, ["c", "b", "a"]);
index = ["a", "b", "c"].findIndex(function(val, key) {
return this.elementAt(key) === val;
}, thisArg);
assertEquals(1, index);
// Create a new object in each function call when receiver is a
// primitive value. See ECMA-262, Annex C.
a = [];
[1, 2].findIndex(function() { a.push(this) }, "");
assertTrue(a[0] !== a[1]);
// Do not create a new object otherwise.
a = [];
[1, 2].findIndex(function() { a.push(this) }, {});
assertEquals(a[0], a[1]);
// In strict mode primitive values should not be coerced to an object.
a = [];
[1, 2].findIndex(function() { 'use strict'; a.push(this); }, "");
assertEquals("", a[0]);
assertEquals(a[0], a[1]);
})();
// Test exceptions
assertThrows('Array.prototype.findIndex.call(null, function() { })',
TypeError);
assertThrows('Array.prototype.findIndex.call(undefined, function() { })',
TypeError);
assertThrows('Array.prototype.findIndex.apply(null, function() { }, [])',
TypeError);
assertThrows('Array.prototype.findIndex.apply(undefined, function() { }, [])',
TypeError);
assertThrows('[].findIndex(null)', TypeError);
assertThrows('[].findIndex(undefined)', TypeError);
assertThrows('[].findIndex(0)', TypeError);
assertThrows('[].findIndex(true)', TypeError);
assertThrows('[].findIndex(false)', TypeError);
assertThrows('[].findIndex("")', TypeError);
assertThrows('[].findIndex({})', TypeError);
assertThrows('[].findIndex([])', TypeError);
assertThrows('[].findIndex(/\d+/)', TypeError);
assertThrows('Array.prototype.findIndex.call({}, null)', TypeError);
assertThrows('Array.prototype.findIndex.call({}, undefined)', TypeError);
assertThrows('Array.prototype.findIndex.call({}, 0)', TypeError);
assertThrows('Array.prototype.findIndex.call({}, true)', TypeError);
assertThrows('Array.prototype.findIndex.call({}, false)', TypeError);
assertThrows('Array.prototype.findIndex.call({}, "")', TypeError);
assertThrows('Array.prototype.findIndex.call({}, {})', TypeError);
assertThrows('Array.prototype.findIndex.call({}, [])', TypeError);
assertThrows('Array.prototype.findIndex.call({}, /\d+/)', TypeError);
assertThrows('Array.prototype.findIndex.apply({}, null, [])', TypeError);
assertThrows('Array.prototype.findIndex.apply({}, undefined, [])', TypeError);
assertThrows('Array.prototype.findIndex.apply({}, 0, [])', TypeError);
assertThrows('Array.prototype.findIndex.apply({}, true, [])', TypeError);
assertThrows('Array.prototype.findIndex.apply({}, false, [])', TypeError);
assertThrows('Array.prototype.findIndex.apply({}, "", [])', TypeError);
assertThrows('Array.prototype.findIndex.apply({}, {}, [])', TypeError);
assertThrows('Array.prototype.findIndex.apply({}, [], [])', TypeError);
assertThrows('Array.prototype.findIndex.apply({}, /\d+/, [])', TypeError);
| victorzhao/miniblink49 | v8_4_5/test/mjsunit/harmony/array-findindex.js | JavaScript | gpl-3.0 | 8,606 |
define('app/controllers/datapoints', ['app/models/datapoint', 'ember'],
//
// Datapoints Controller
//
// @returns Class
//
function (Datapoint) {
'use strict';
// Cache an array of null datapoints to
// display when there is no data
var EMPTY_DATAPOINTS = [];
return Ember.ArrayController.extend({
//
//
// Properties
//
//
content: null,
loading: null,
});
}
);
| munkiat/mist.io | src/mist/io/static/js/app/controllers/datapoints.js | JavaScript | agpl-3.0 | 534 |
tinymce.addI18n('zh_CN',{
"Cut": "\u526a\u5207",
"Heading 5": "\u6807\u98985",
"Header 2": "\u6807\u98982",
"Your browser doesn't support direct access to the clipboard. Please use the Ctrl+X\/C\/V keyboard shortcuts instead.": "\u4f60\u7684\u6d4f\u89c8\u5668\u4e0d\u652f\u6301\u5bf9\u526a\u8d34\u677f\u7684\u8bbf\u95ee\uff0c\u8bf7\u4f7f\u7528Ctrl+X\/C\/V\u952e\u8fdb\u884c\u590d\u5236\u7c98\u8d34\u3002",
"Heading 4": "\u6807\u98984",
"Div": "Div\u533a\u5757",
"Heading 2": "\u6807\u98982",
"Paste": "\u7c98\u8d34",
"Close": "\u5173\u95ed",
"Font Family": "\u5b57\u4f53",
"Pre": "\u9884\u683c\u5f0f\u6587\u672c",
"Align right": "\u53f3\u5bf9\u9f50",
"New document": "\u65b0\u6587\u6863",
"Blockquote": "\u5f15\u7528",
"Numbered list": "\u7f16\u53f7\u5217\u8868",
"Heading 1": "\u6807\u98981",
"Headings": "\u6807\u9898",
"Increase indent": "\u589e\u52a0\u7f29\u8fdb",
"Formats": "\u683c\u5f0f",
"Headers": "\u6807\u9898",
"Select all": "\u5168\u9009",
"Header 3": "\u6807\u98983",
"Blocks": "\u533a\u5757",
"Undo": "\u64a4\u6d88",
"Strikethrough": "\u5220\u9664\u7ebf",
"Bullet list": "\u9879\u76ee\u7b26\u53f7",
"Header 1": "\u6807\u98981",
"Superscript": "\u4e0a\u6807",
"Clear formatting": "\u6e05\u9664\u683c\u5f0f",
"Font Sizes": "\u5b57\u53f7",
"Subscript": "\u4e0b\u6807",
"Header 6": "\u6807\u98986",
"Redo": "\u91cd\u590d",
"Paragraph": "\u6bb5\u843d",
"Ok": "\u786e\u5b9a",
"Bold": "\u7c97\u4f53",
"Code": "\u4ee3\u7801",
"Italic": "\u659c\u4f53",
"Align center": "\u5c45\u4e2d",
"Header 5": "\u6807\u98985",
"Heading 6": "\u6807\u98986",
"Heading 3": "\u6807\u98983",
"Decrease indent": "\u51cf\u5c11\u7f29\u8fdb",
"Header 4": "\u6807\u98984",
"Paste is now in plain text mode. Contents will now be pasted as plain text until you toggle this option off.": "\u5f53\u524d\u4e3a\u7eaf\u6587\u672c\u7c98\u8d34\u6a21\u5f0f\uff0c\u518d\u6b21\u70b9\u51fb\u53ef\u4ee5\u56de\u5230\u666e\u901a\u7c98\u8d34\u6a21\u5f0f\u3002",
"Underline": "\u4e0b\u5212\u7ebf",
"Cancel": "\u53d6\u6d88",
"Justify": "\u4e24\u7aef\u5bf9\u9f50",
"Inline": "\u6587\u672c",
"Copy": "\u590d\u5236",
"Align left": "\u5de6\u5bf9\u9f50",
"Visual aids": "\u7f51\u683c\u7ebf",
"Lower Greek": "\u5c0f\u5199\u5e0c\u814a\u5b57\u6bcd",
"Square": "\u65b9\u5757",
"Default": "\u9ed8\u8ba4",
"Lower Alpha": "\u5c0f\u5199\u82f1\u6587\u5b57\u6bcd",
"Circle": "\u7a7a\u5fc3\u5706",
"Disc": "\u5b9e\u5fc3\u5706",
"Upper Alpha": "\u5927\u5199\u82f1\u6587\u5b57\u6bcd",
"Upper Roman": "\u5927\u5199\u7f57\u9a6c\u5b57\u6bcd",
"Lower Roman": "\u5c0f\u5199\u7f57\u9a6c\u5b57\u6bcd",
"Name": "\u540d\u79f0",
"Anchor": "\u951a\u70b9",
"You have unsaved changes are you sure you want to navigate away?": "\u4f60\u8fd8\u6709\u6587\u6863\u5c1a\u672a\u4fdd\u5b58\uff0c\u786e\u5b9a\u8981\u79bb\u5f00\uff1f",
"Restore last draft": "\u6062\u590d\u4e0a\u6b21\u7684\u8349\u7a3f",
"Special character": "\u7279\u6b8a\u7b26\u53f7",
"Source code": "\u6e90\u4ee3\u7801",
"Color": "\u989c\u8272",
"Right to left": "\u4ece\u53f3\u5230\u5de6",
"Left to right": "\u4ece\u5de6\u5230\u53f3",
"Emoticons": "\u8868\u60c5",
"Robots": "\u673a\u5668\u4eba",
"Document properties": "\u6587\u6863\u5c5e\u6027",
"Title": "\u6807\u9898",
"Keywords": "\u5173\u952e\u8bcd",
"Encoding": "\u7f16\u7801",
"Description": "\u63cf\u8ff0",
"Author": "\u4f5c\u8005",
"Fullscreen": "\u5168\u5c4f",
"Horizontal line": "\u6c34\u5e73\u5206\u5272\u7ebf",
"Horizontal space": "\u6c34\u5e73\u8fb9\u8ddd",
"Insert\/edit image": "\u63d2\u5165\/\u7f16\u8f91\u56fe\u7247",
"General": "\u666e\u901a",
"Advanced": "\u9ad8\u7ea7",
"Source": "\u5730\u5740",
"Border": "\u8fb9\u6846",
"Constrain proportions": "\u4fdd\u6301\u7eb5\u6a2a\u6bd4",
"Vertical space": "\u5782\u76f4\u8fb9\u8ddd",
"Image description": "\u56fe\u7247\u63cf\u8ff0",
"Style": "\u6837\u5f0f",
"Dimensions": "\u5927\u5c0f",
"Insert image": "\u63d2\u5165\u56fe\u7247",
"Insert date\/time": "\u63d2\u5165\u65e5\u671f\/\u65f6\u95f4",
"Remove link": "\u5220\u9664\u94fe\u63a5",
"Url": "\u5730\u5740",
"Text to display": "\u663e\u793a\u6587\u5b57",
"Anchors": "\u951a\u70b9",
"Insert link": "\u63d2\u5165\u94fe\u63a5",
"New window": "\u5728\u65b0\u7a97\u53e3\u6253\u5f00",
"None": "\u65e0",
"The URL you entered seems to be an external link. Do you want to add the required http:\/\/ prefix?": "\u4f60\u6240\u586b\u5199\u7684URL\u5730\u5740\u5c5e\u4e8e\u5916\u90e8\u94fe\u63a5\uff0c\u9700\u8981\u52a0\u4e0ahttp:\/\/:\u524d\u7f00\u5417\uff1f",
"Target": "\u6253\u5f00\u65b9\u5f0f",
"The URL you entered seems to be an email address. Do you want to add the required mailto: prefix?": "\u4f60\u6240\u586b\u5199\u7684URL\u5730\u5740\u8c8c\u4f3c\u662f\u90ae\u4ef6\u5730\u5740\uff0c\u9700\u8981\u52a0\u4e0amailto:\u524d\u7f00\u5417\uff1f",
"Insert\/edit link": "\u63d2\u5165\/\u7f16\u8f91\u94fe\u63a5",
"Insert\/edit video": "\u63d2\u5165\/\u7f16\u8f91\u89c6\u9891",
"Poster": "\u5c01\u9762",
"Alternative source": "\u955c\u50cf",
"Paste your embed code below:": "\u5c06\u5185\u5d4c\u4ee3\u7801\u7c98\u8d34\u5728\u4e0b\u9762:",
"Insert video": "\u63d2\u5165\u89c6\u9891",
"Embed": "\u5185\u5d4c",
"Nonbreaking space": "\u4e0d\u95f4\u65ad\u7a7a\u683c",
"Page break": "\u5206\u9875\u7b26",
"Paste as text": "\u7c98\u8d34\u4e3a\u6587\u672c",
"Preview": "\u9884\u89c8",
"Print": "\u6253\u5370",
"Save": "\u4fdd\u5b58",
"Could not find the specified string.": "\u672a\u627e\u5230\u641c\u7d22\u5185\u5bb9.",
"Replace": "\u66ff\u6362",
"Next": "\u4e0b\u4e00\u4e2a",
"Whole words": "\u5168\u5b57\u5339\u914d",
"Find and replace": "\u67e5\u627e\u548c\u66ff\u6362",
"Replace with": "\u66ff\u6362\u4e3a",
"Find": "\u67e5\u627e",
"Replace all": "\u5168\u90e8\u66ff\u6362",
"Match case": "\u533a\u5206\u5927\u5c0f\u5199",
"Prev": "\u4e0a\u4e00\u4e2a",
"Spellcheck": "\u62fc\u5199\u68c0\u67e5",
"Finish": "\u5b8c\u6210",
"Ignore all": "\u5168\u90e8\u5ffd\u7565",
"Ignore": "\u5ffd\u7565",
"Add to Dictionary": "\u6dfb\u52a0\u5230\u5b57\u5178",
"Insert row before": "\u5728\u4e0a\u65b9\u63d2\u5165",
"Rows": "\u884c",
"Height": "\u9ad8",
"Paste row after": "\u7c98\u8d34\u5230\u4e0b\u65b9",
"Alignment": "\u5bf9\u9f50\u65b9\u5f0f",
"Border color": "\u8fb9\u6846\u989c\u8272",
"Column group": "\u5217\u7ec4",
"Row": "\u884c",
"Insert column before": "\u5728\u5de6\u4fa7\u63d2\u5165",
"Split cell": "\u62c6\u5206\u5355\u5143\u683c",
"Cell padding": "\u5355\u5143\u683c\u5185\u8fb9\u8ddd",
"Cell spacing": "\u5355\u5143\u683c\u5916\u95f4\u8ddd",
"Row type": "\u884c\u7c7b\u578b",
"Insert table": "\u63d2\u5165\u8868\u683c",
"Body": "\u8868\u4f53",
"Caption": "\u6807\u9898",
"Footer": "\u8868\u5c3e",
"Delete row": "\u5220\u9664\u884c",
"Paste row before": "\u7c98\u8d34\u5230\u4e0a\u65b9",
"Scope": "\u8303\u56f4",
"Delete table": "\u5220\u9664\u8868\u683c",
"H Align": "\u6c34\u5e73\u5bf9\u9f50",
"Top": "\u9876\u90e8\u5bf9\u9f50",
"Header cell": "\u8868\u5934\u5355\u5143\u683c",
"Column": "\u5217",
"Row group": "\u884c\u7ec4",
"Cell": "\u5355\u5143\u683c",
"Middle": "\u5782\u76f4\u5c45\u4e2d",
"Cell type": "\u5355\u5143\u683c\u7c7b\u578b",
"Copy row": "\u590d\u5236\u884c",
"Row properties": "\u884c\u5c5e\u6027",
"Table properties": "\u8868\u683c\u5c5e\u6027",
"Bottom": "\u5e95\u90e8\u5bf9\u9f50",
"V Align": "\u5782\u76f4\u5bf9\u9f50",
"Header": "\u8868\u5934",
"Right": "\u53f3\u5bf9\u9f50",
"Insert column after": "\u5728\u53f3\u4fa7\u63d2\u5165",
"Cols": "\u5217",
"Insert row after": "\u5728\u4e0b\u65b9\u63d2\u5165",
"Width": "\u5bbd",
"Cell properties": "\u5355\u5143\u683c\u5c5e\u6027",
"Left": "\u5de6\u5bf9\u9f50",
"Cut row": "\u526a\u5207\u884c",
"Delete column": "\u5220\u9664\u5217",
"Center": "\u5c45\u4e2d",
"Merge cells": "\u5408\u5e76\u5355\u5143\u683c",
"Insert template": "\u63d2\u5165\u6a21\u677f",
"Templates": "\u6a21\u677f",
"Background color": "\u80cc\u666f\u8272",
"Custom...": "\u81ea\u5b9a\u4e49...",
"Custom color": "\u81ea\u5b9a\u4e49\u989c\u8272",
"No color": "\u65e0",
"Text color": "\u6587\u5b57\u989c\u8272",
"Show blocks": "\u663e\u793a\u533a\u5757\u8fb9\u6846",
"Show invisible characters": "\u663e\u793a\u4e0d\u53ef\u89c1\u5b57\u7b26",
"Words: {0}": "\u5b57\u6570\uff1a{0}",
"Insert": "\u63d2\u5165",
"File": "\u6587\u4ef6",
"Edit": "\u7f16\u8f91",
"Rich Text Area. Press ALT-F9 for menu. Press ALT-F10 for toolbar. Press ALT-0 for help": "\u5728\u7f16\u8f91\u533a\u6309ALT-F9\u6253\u5f00\u83dc\u5355\uff0c\u6309ALT-F10\u6253\u5f00\u5de5\u5177\u680f\uff0c\u6309ALT-0\u67e5\u770b\u5e2e\u52a9",
"Tools": "\u5de5\u5177",
"View": "\u89c6\u56fe",
"Table": "\u8868\u683c",
"Preformatted": "Pre\u9884\u683c\u5f0f\u5316",
"Crop": "\u526a\u5207",
"Back": "\u8fd4\u56de",
"Apply": "\u5e94\u7528",
"Resize": "\u8c03\u6574\u5927\u5c0f",
"Orientation": "\u65b9\u5411",
"Flip horizontally": "\u6c34\u5e73\u7ffb\u8f6c",
"Flip vertically": "\u5782\u76f4\u7ffb\u8f6c",
"Rotate counterclockwise": "\u9006\u65f6\u9488\u65cb\u8f6c",
"Rotate clockwise": "\u987a\u65f6\u9488\u65cb\u8f6c",
"Brightness": "\u4eae\u5ea6",
"Sharpen": "\u9510\u5316",
"Contrast": "\u5bf9\u6bd4\u5ea6",
"Color levels": "\u989c\u8272\u7ea7\u522b",
"Gamma": "\u7070\u5ea6",
"Invert": "\u53cd\u8f6c",
"Zoom in": "\u653e\u5927",
"Zoom out": "\u7f29\u5c0f",
"Edit image": "\u56fe\u7247\u7f16\u8f91",
"Image options": "\u56fe\u7247\u9009\u9879",
"Format": "\u683c\u5f0f",
"Insert/Edit code sample":"\u63d2\u5165/\u7f16\u8f91\u4ee3\u7801",
"Language":"\u8bed\u8a00"
}); | NewGr8Player/jpress | jpress/jpress-web-core/src/main/webapp/static/tinymce/langs/zh_CN.js | JavaScript | lgpl-3.0 | 9,304 |
/*!
* Bootstrap v3.3.2 (http://getbootstrap.com)
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
*/
/*!
* Generated using the Bootstrap Customizer (http://getbootstrap.com/customize/?id=9cc0baa232277d5dcc77)
* Config saved to config.json and https://gist.github.com/9cc0baa232277d5dcc77
*/
if (typeof jQuery === 'undefined') {
throw new Error('Bootstrap\'s JavaScript requires jQuery')
}
+function ($) {
'use strict';
var version = $.fn.jquery.split(' ')[0].split('.')
if ((version[0] < 2 && version[1] < 9) || (version[0] == 1 && version[1] == 9 && version[2] < 1)) {
throw new Error('Bootstrap\'s JavaScript requires jQuery version 1.9.1 or higher')
}
}(jQuery);
/* ========================================================================
* Bootstrap: alert.js v3.3.2
* http://getbootstrap.com/javascript/#alerts
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// ALERT CLASS DEFINITION
// ======================
var dismiss = '[data-dismiss="alert"]'
var Alert = function (el) {
$(el).on('click', dismiss, this.close)
}
Alert.VERSION = '3.3.2'
Alert.TRANSITION_DURATION = 150
Alert.prototype.close = function (e) {
var $this = $(this)
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = $(selector)
if (e) e.preventDefault()
if (!$parent.length) {
$parent = $this.closest('.alert')
}
$parent.trigger(e = $.Event('close.bs.alert'))
if (e.isDefaultPrevented()) return
$parent.removeClass('in')
function removeElement() {
// detach from parent, fire event then clean up data
$parent.detach().trigger('closed.bs.alert').remove()
}
$.support.transition && $parent.hasClass('fade') ?
$parent
.one('bsTransitionEnd', removeElement)
.emulateTransitionEnd(Alert.TRANSITION_DURATION) :
removeElement()
}
// ALERT PLUGIN DEFINITION
// =======================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.alert')
if (!data) $this.data('bs.alert', (data = new Alert(this)))
if (typeof option == 'string') data[option].call($this)
})
}
var old = $.fn.alert
$.fn.alert = Plugin
$.fn.alert.Constructor = Alert
// ALERT NO CONFLICT
// =================
$.fn.alert.noConflict = function () {
$.fn.alert = old
return this
}
// ALERT DATA-API
// ==============
$(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close)
}(jQuery);
/* ========================================================================
* Bootstrap: button.js v3.3.2
* http://getbootstrap.com/javascript/#buttons
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// BUTTON PUBLIC CLASS DEFINITION
// ==============================
var Button = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, Button.DEFAULTS, options)
this.isLoading = false
}
Button.VERSION = '3.3.2'
Button.DEFAULTS = {
loadingText: 'loading...'
}
Button.prototype.setState = function (state) {
var d = 'disabled'
var $el = this.$element
var val = $el.is('input') ? 'val' : 'html'
var data = $el.data()
state = state + 'Text'
if (data.resetText == null) $el.data('resetText', $el[val]())
// push to event loop to allow forms to submit
setTimeout($.proxy(function () {
$el[val](data[state] == null ? this.options[state] : data[state])
if (state == 'loadingText') {
this.isLoading = true
$el.addClass(d).attr(d, d)
} else if (this.isLoading) {
this.isLoading = false
$el.removeClass(d).removeAttr(d)
}
}, this), 0)
}
Button.prototype.toggle = function () {
var changed = true
var $parent = this.$element.closest('[data-toggle="buttons"]')
if ($parent.length) {
var $input = this.$element.find('input')
if ($input.prop('type') == 'radio') {
if ($input.prop('checked') && this.$element.hasClass('active')) changed = false
else $parent.find('.active').removeClass('active')
}
if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change')
} else {
this.$element.attr('aria-pressed', !this.$element.hasClass('active'))
}
if (changed) this.$element.toggleClass('active')
}
// BUTTON PLUGIN DEFINITION
// ========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.button')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.button', (data = new Button(this, options)))
if (option == 'toggle') data.toggle()
else if (option) data.setState(option)
})
}
var old = $.fn.button
$.fn.button = Plugin
$.fn.button.Constructor = Button
// BUTTON NO CONFLICT
// ==================
$.fn.button.noConflict = function () {
$.fn.button = old
return this
}
// BUTTON DATA-API
// ===============
$(document)
.on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) {
var $btn = $(e.target)
if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn')
Plugin.call($btn, 'toggle')
e.preventDefault()
})
.on('focus.bs.button.data-api blur.bs.button.data-api', '[data-toggle^="button"]', function (e) {
$(e.target).closest('.btn').toggleClass('focus', /^focus(in)?$/.test(e.type))
})
}(jQuery);
/* ========================================================================
* Bootstrap: carousel.js v3.3.2
* http://getbootstrap.com/javascript/#carousel
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// CAROUSEL CLASS DEFINITION
// =========================
var Carousel = function (element, options) {
this.$element = $(element)
this.$indicators = this.$element.find('.carousel-indicators')
this.options = options
this.paused =
this.sliding =
this.interval =
this.$active =
this.$items = null
this.options.keyboard && this.$element.on('keydown.bs.carousel', $.proxy(this.keydown, this))
this.options.pause == 'hover' && !('ontouchstart' in document.documentElement) && this.$element
.on('mouseenter.bs.carousel', $.proxy(this.pause, this))
.on('mouseleave.bs.carousel', $.proxy(this.cycle, this))
}
Carousel.VERSION = '3.3.2'
Carousel.TRANSITION_DURATION = 600
Carousel.DEFAULTS = {
interval: 5000,
pause: 'hover',
wrap: true,
keyboard: true
}
Carousel.prototype.keydown = function (e) {
if (/input|textarea/i.test(e.target.tagName)) return
switch (e.which) {
case 37: this.prev(); break
case 39: this.next(); break
default: return
}
e.preventDefault()
}
Carousel.prototype.cycle = function (e) {
e || (this.paused = false)
this.interval && clearInterval(this.interval)
this.options.interval
&& !this.paused
&& (this.interval = setInterval($.proxy(this.next, this), this.options.interval))
return this
}
Carousel.prototype.getItemIndex = function (item) {
this.$items = item.parent().children('.item')
return this.$items.index(item || this.$active)
}
Carousel.prototype.getItemForDirection = function (direction, active) {
var activeIndex = this.getItemIndex(active)
var willWrap = (direction == 'prev' && activeIndex === 0)
|| (direction == 'next' && activeIndex == (this.$items.length - 1))
if (willWrap && !this.options.wrap) return active
var delta = direction == 'prev' ? -1 : 1
var itemIndex = (activeIndex + delta) % this.$items.length
return this.$items.eq(itemIndex)
}
Carousel.prototype.to = function (pos) {
var that = this
var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active'))
if (pos > (this.$items.length - 1) || pos < 0) return
if (this.sliding) return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) // yes, "slid"
if (activeIndex == pos) return this.pause().cycle()
return this.slide(pos > activeIndex ? 'next' : 'prev', this.$items.eq(pos))
}
Carousel.prototype.pause = function (e) {
e || (this.paused = true)
if (this.$element.find('.next, .prev').length && $.support.transition) {
this.$element.trigger($.support.transition.end)
this.cycle(true)
}
this.interval = clearInterval(this.interval)
return this
}
Carousel.prototype.next = function () {
if (this.sliding) return
return this.slide('next')
}
Carousel.prototype.prev = function () {
if (this.sliding) return
return this.slide('prev')
}
Carousel.prototype.slide = function (type, next) {
var $active = this.$element.find('.item.active')
var $next = next || this.getItemForDirection(type, $active)
var isCycling = this.interval
var direction = type == 'next' ? 'left' : 'right'
var that = this
if ($next.hasClass('active')) return (this.sliding = false)
var relatedTarget = $next[0]
var slideEvent = $.Event('slide.bs.carousel', {
relatedTarget: relatedTarget,
direction: direction
})
this.$element.trigger(slideEvent)
if (slideEvent.isDefaultPrevented()) return
this.sliding = true
isCycling && this.pause()
if (this.$indicators.length) {
this.$indicators.find('.active').removeClass('active')
var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)])
$nextIndicator && $nextIndicator.addClass('active')
}
var slidEvent = $.Event('slid.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) // yes, "slid"
if ($.support.transition && this.$element.hasClass('slide')) {
$next.addClass(type)
$next[0].offsetWidth // force reflow
$active.addClass(direction)
$next.addClass(direction)
$active
.one('bsTransitionEnd', function () {
$next.removeClass([type, direction].join(' ')).addClass('active')
$active.removeClass(['active', direction].join(' '))
that.sliding = false
setTimeout(function () {
that.$element.trigger(slidEvent)
}, 0)
})
.emulateTransitionEnd(Carousel.TRANSITION_DURATION)
} else {
$active.removeClass('active')
$next.addClass('active')
this.sliding = false
this.$element.trigger(slidEvent)
}
isCycling && this.cycle()
return this
}
// CAROUSEL PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.carousel')
var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option)
var action = typeof option == 'string' ? option : options.slide
if (!data) $this.data('bs.carousel', (data = new Carousel(this, options)))
if (typeof option == 'number') data.to(option)
else if (action) data[action]()
else if (options.interval) data.pause().cycle()
})
}
var old = $.fn.carousel
$.fn.carousel = Plugin
$.fn.carousel.Constructor = Carousel
// CAROUSEL NO CONFLICT
// ====================
$.fn.carousel.noConflict = function () {
$.fn.carousel = old
return this
}
// CAROUSEL DATA-API
// =================
var clickHandler = function (e) {
var href
var $this = $(this)
var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) // strip for ie7
if (!$target.hasClass('carousel')) return
var options = $.extend({}, $target.data(), $this.data())
var slideIndex = $this.attr('data-slide-to')
if (slideIndex) options.interval = false
Plugin.call($target, options)
if (slideIndex) {
$target.data('bs.carousel').to(slideIndex)
}
e.preventDefault()
}
$(document)
.on('click.bs.carousel.data-api', '[data-slide]', clickHandler)
.on('click.bs.carousel.data-api', '[data-slide-to]', clickHandler)
$(window).on('load', function () {
$('[data-ride="carousel"]').each(function () {
var $carousel = $(this)
Plugin.call($carousel, $carousel.data())
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: dropdown.js v3.3.2
* http://getbootstrap.com/javascript/#dropdowns
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// DROPDOWN CLASS DEFINITION
// =========================
var backdrop = '.dropdown-backdrop'
var toggle = '[data-toggle="dropdown"]'
var Dropdown = function (element) {
$(element).on('click.bs.dropdown', this.toggle)
}
Dropdown.VERSION = '3.3.2'
Dropdown.prototype.toggle = function (e) {
var $this = $(this)
if ($this.is('.disabled, :disabled')) return
var $parent = getParent($this)
var isActive = $parent.hasClass('open')
clearMenus()
if (!isActive) {
if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) {
// if mobile we use a backdrop because click events don't delegate
$('<div class="dropdown-backdrop"/>').insertAfter($(this)).on('click', clearMenus)
}
var relatedTarget = { relatedTarget: this }
$parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget))
if (e.isDefaultPrevented()) return
$this
.trigger('focus')
.attr('aria-expanded', 'true')
$parent
.toggleClass('open')
.trigger('shown.bs.dropdown', relatedTarget)
}
return false
}
Dropdown.prototype.keydown = function (e) {
if (!/(38|40|27|32)/.test(e.which) || /input|textarea/i.test(e.target.tagName)) return
var $this = $(this)
e.preventDefault()
e.stopPropagation()
if ($this.is('.disabled, :disabled')) return
var $parent = getParent($this)
var isActive = $parent.hasClass('open')
if ((!isActive && e.which != 27) || (isActive && e.which == 27)) {
if (e.which == 27) $parent.find(toggle).trigger('focus')
return $this.trigger('click')
}
var desc = ' li:not(.divider):visible a'
var $items = $parent.find('[role="menu"]' + desc + ', [role="listbox"]' + desc)
if (!$items.length) return
var index = $items.index(e.target)
if (e.which == 38 && index > 0) index-- // up
if (e.which == 40 && index < $items.length - 1) index++ // down
if (!~index) index = 0
$items.eq(index).trigger('focus')
}
function clearMenus(e) {
if (e && e.which === 3) return
$(backdrop).remove()
$(toggle).each(function () {
var $this = $(this)
var $parent = getParent($this)
var relatedTarget = { relatedTarget: this }
if (!$parent.hasClass('open')) return
$parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget))
if (e.isDefaultPrevented()) return
$this.attr('aria-expanded', 'false')
$parent.removeClass('open').trigger('hidden.bs.dropdown', relatedTarget)
})
}
function getParent($this) {
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = selector && $(selector)
return $parent && $parent.length ? $parent : $this.parent()
}
// DROPDOWN PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.dropdown')
if (!data) $this.data('bs.dropdown', (data = new Dropdown(this)))
if (typeof option == 'string') data[option].call($this)
})
}
var old = $.fn.dropdown
$.fn.dropdown = Plugin
$.fn.dropdown.Constructor = Dropdown
// DROPDOWN NO CONFLICT
// ====================
$.fn.dropdown.noConflict = function () {
$.fn.dropdown = old
return this
}
// APPLY TO STANDARD DROPDOWN ELEMENTS
// ===================================
$(document)
.on('click.bs.dropdown.data-api', clearMenus)
.on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })
.on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle)
.on('keydown.bs.dropdown.data-api', toggle, Dropdown.prototype.keydown)
.on('keydown.bs.dropdown.data-api', '[role="menu"]', Dropdown.prototype.keydown)
.on('keydown.bs.dropdown.data-api', '[role="listbox"]', Dropdown.prototype.keydown)
}(jQuery);
/* ========================================================================
* Bootstrap: modal.js v3.3.2
* http://getbootstrap.com/javascript/#modals
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// MODAL CLASS DEFINITION
// ======================
var Modal = function (element, options) {
this.options = options
this.$body = $(document.body)
this.$element = $(element)
this.$backdrop =
this.isShown = null
this.scrollbarWidth = 0
if (this.options.remote) {
this.$element
.find('.modal-content')
.load(this.options.remote, $.proxy(function () {
this.$element.trigger('loaded.bs.modal')
}, this))
}
}
Modal.VERSION = '3.3.2'
Modal.TRANSITION_DURATION = 300
Modal.BACKDROP_TRANSITION_DURATION = 150
Modal.DEFAULTS = {
backdrop: true,
keyboard: true,
show: true
}
Modal.prototype.toggle = function (_relatedTarget) {
return this.isShown ? this.hide() : this.show(_relatedTarget)
}
Modal.prototype.show = function (_relatedTarget) {
var that = this
var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget })
this.$element.trigger(e)
if (this.isShown || e.isDefaultPrevented()) return
this.isShown = true
this.checkScrollbar()
this.setScrollbar()
this.$body.addClass('modal-open')
this.escape()
this.resize()
this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this))
this.backdrop(function () {
var transition = $.support.transition && that.$element.hasClass('fade')
if (!that.$element.parent().length) {
that.$element.appendTo(that.$body) // don't move modals dom position
}
that.$element
.show()
.scrollTop(0)
if (that.options.backdrop) that.adjustBackdrop()
that.adjustDialog()
if (transition) {
that.$element[0].offsetWidth // force reflow
}
that.$element
.addClass('in')
.attr('aria-hidden', false)
that.enforceFocus()
var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget })
transition ?
that.$element.find('.modal-dialog') // wait for modal to slide in
.one('bsTransitionEnd', function () {
that.$element.trigger('focus').trigger(e)
})
.emulateTransitionEnd(Modal.TRANSITION_DURATION) :
that.$element.trigger('focus').trigger(e)
})
}
Modal.prototype.hide = function (e) {
if (e) e.preventDefault()
e = $.Event('hide.bs.modal')
this.$element.trigger(e)
if (!this.isShown || e.isDefaultPrevented()) return
this.isShown = false
this.escape()
this.resize()
$(document).off('focusin.bs.modal')
this.$element
.removeClass('in')
.attr('aria-hidden', true)
.off('click.dismiss.bs.modal')
$.support.transition && this.$element.hasClass('fade') ?
this.$element
.one('bsTransitionEnd', $.proxy(this.hideModal, this))
.emulateTransitionEnd(Modal.TRANSITION_DURATION) :
this.hideModal()
}
Modal.prototype.enforceFocus = function () {
$(document)
.off('focusin.bs.modal') // guard against infinite focus loop
.on('focusin.bs.modal', $.proxy(function (e) {
if (this.$element[0] !== e.target && !this.$element.has(e.target).length) {
this.$element.trigger('focus')
}
}, this))
}
Modal.prototype.escape = function () {
if (this.isShown && this.options.keyboard) {
this.$element.on('keydown.dismiss.bs.modal', $.proxy(function (e) {
e.which == 27 && this.hide()
}, this))
} else if (!this.isShown) {
this.$element.off('keydown.dismiss.bs.modal')
}
}
Modal.prototype.resize = function () {
if (this.isShown) {
$(window).on('resize.bs.modal', $.proxy(this.handleUpdate, this))
} else {
$(window).off('resize.bs.modal')
}
}
Modal.prototype.hideModal = function () {
var that = this
this.$element.hide()
this.backdrop(function () {
that.$body.removeClass('modal-open')
that.resetAdjustments()
that.resetScrollbar()
that.$element.trigger('hidden.bs.modal')
})
}
Modal.prototype.removeBackdrop = function () {
this.$backdrop && this.$backdrop.remove()
this.$backdrop = null
}
Modal.prototype.backdrop = function (callback) {
var that = this
var animate = this.$element.hasClass('fade') ? 'fade' : ''
if (this.isShown && this.options.backdrop) {
var doAnimate = $.support.transition && animate
this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />')
.prependTo(this.$element)
.on('click.dismiss.bs.modal', $.proxy(function (e) {
if (e.target !== e.currentTarget) return
this.options.backdrop == 'static'
? this.$element[0].focus.call(this.$element[0])
: this.hide.call(this)
}, this))
if (doAnimate) this.$backdrop[0].offsetWidth // force reflow
this.$backdrop.addClass('in')
if (!callback) return
doAnimate ?
this.$backdrop
.one('bsTransitionEnd', callback)
.emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
callback()
} else if (!this.isShown && this.$backdrop) {
this.$backdrop.removeClass('in')
var callbackRemove = function () {
that.removeBackdrop()
callback && callback()
}
$.support.transition && this.$element.hasClass('fade') ?
this.$backdrop
.one('bsTransitionEnd', callbackRemove)
.emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
callbackRemove()
} else if (callback) {
callback()
}
}
// these following methods are used to handle overflowing modals
Modal.prototype.handleUpdate = function () {
if (this.options.backdrop) this.adjustBackdrop()
this.adjustDialog()
}
Modal.prototype.adjustBackdrop = function () {
this.$backdrop
.css('height', 0)
.css('height', this.$element[0].scrollHeight)
}
Modal.prototype.adjustDialog = function () {
var modalIsOverflowing = this.$element[0].scrollHeight > document.documentElement.clientHeight
this.$element.css({
paddingLeft: !this.bodyIsOverflowing && modalIsOverflowing ? this.scrollbarWidth : '',
paddingRight: this.bodyIsOverflowing && !modalIsOverflowing ? this.scrollbarWidth : ''
})
}
Modal.prototype.resetAdjustments = function () {
this.$element.css({
paddingLeft: '',
paddingRight: ''
})
}
Modal.prototype.checkScrollbar = function () {
this.bodyIsOverflowing = document.body.scrollHeight > document.documentElement.clientHeight
this.scrollbarWidth = this.measureScrollbar()
}
Modal.prototype.setScrollbar = function () {
var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10)
if (this.bodyIsOverflowing) this.$body.css('padding-right', bodyPad + this.scrollbarWidth)
}
Modal.prototype.resetScrollbar = function () {
this.$body.css('padding-right', '')
}
Modal.prototype.measureScrollbar = function () { // thx walsh
var scrollDiv = document.createElement('div')
scrollDiv.className = 'modal-scrollbar-measure'
this.$body.append(scrollDiv)
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth
this.$body[0].removeChild(scrollDiv)
return scrollbarWidth
}
// MODAL PLUGIN DEFINITION
// =======================
function Plugin(option, _relatedTarget) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.modal')
var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data) $this.data('bs.modal', (data = new Modal(this, options)))
if (typeof option == 'string') data[option](_relatedTarget)
else if (options.show) data.show(_relatedTarget)
})
}
var old = $.fn.modal
$.fn.modal = Plugin
$.fn.modal.Constructor = Modal
// MODAL NO CONFLICT
// =================
$.fn.modal.noConflict = function () {
$.fn.modal = old
return this
}
// MODAL DATA-API
// ==============
$(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) {
var $this = $(this)
var href = $this.attr('href')
var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7
var option = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())
if ($this.is('a')) e.preventDefault()
$target.one('show.bs.modal', function (showEvent) {
if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown
$target.one('hidden.bs.modal', function () {
$this.is(':visible') && $this.trigger('focus')
})
})
Plugin.call($target, option, this)
})
}(jQuery);
/* ========================================================================
* Bootstrap: tooltip.js v3.3.2
* http://getbootstrap.com/javascript/#tooltip
* Inspired by the original jQuery.tipsy by Jason Frame
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// TOOLTIP PUBLIC CLASS DEFINITION
// ===============================
var Tooltip = function (element, options) {
this.type =
this.options =
this.enabled =
this.timeout =
this.hoverState =
this.$element = null
this.init('tooltip', element, options)
}
Tooltip.VERSION = '3.3.2'
Tooltip.TRANSITION_DURATION = 150
Tooltip.DEFAULTS = {
animation: true,
placement: 'top',
selector: false,
template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
trigger: 'hover focus',
title: '',
delay: 0,
html: false,
container: false,
viewport: {
selector: 'body',
padding: 0
}
}
Tooltip.prototype.init = function (type, element, options) {
this.enabled = true
this.type = type
this.$element = $(element)
this.options = this.getOptions(options)
this.$viewport = this.options.viewport && $(this.options.viewport.selector || this.options.viewport)
var triggers = this.options.trigger.split(' ')
for (var i = triggers.length; i--;) {
var trigger = triggers[i]
if (trigger == 'click') {
this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
} else if (trigger != 'manual') {
var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin'
var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout'
this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
}
}
this.options.selector ?
(this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) :
this.fixTitle()
}
Tooltip.prototype.getDefaults = function () {
return Tooltip.DEFAULTS
}
Tooltip.prototype.getOptions = function (options) {
options = $.extend({}, this.getDefaults(), this.$element.data(), options)
if (options.delay && typeof options.delay == 'number') {
options.delay = {
show: options.delay,
hide: options.delay
}
}
return options
}
Tooltip.prototype.getDelegateOptions = function () {
var options = {}
var defaults = this.getDefaults()
this._options && $.each(this._options, function (key, value) {
if (defaults[key] != value) options[key] = value
})
return options
}
Tooltip.prototype.enter = function (obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget).data('bs.' + this.type)
if (self && self.$tip && self.$tip.is(':visible')) {
self.hoverState = 'in'
return
}
if (!self) {
self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
$(obj.currentTarget).data('bs.' + this.type, self)
}
clearTimeout(self.timeout)
self.hoverState = 'in'
if (!self.options.delay || !self.options.delay.show) return self.show()
self.timeout = setTimeout(function () {
if (self.hoverState == 'in') self.show()
}, self.options.delay.show)
}
Tooltip.prototype.leave = function (obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
$(obj.currentTarget).data('bs.' + this.type, self)
}
clearTimeout(self.timeout)
self.hoverState = 'out'
if (!self.options.delay || !self.options.delay.hide) return self.hide()
self.timeout = setTimeout(function () {
if (self.hoverState == 'out') self.hide()
}, self.options.delay.hide)
}
Tooltip.prototype.show = function () {
var e = $.Event('show.bs.' + this.type)
if (this.hasContent() && this.enabled) {
this.$element.trigger(e)
var inDom = $.contains(this.$element[0].ownerDocument.documentElement, this.$element[0])
if (e.isDefaultPrevented() || !inDom) return
var that = this
var $tip = this.tip()
var tipId = this.getUID(this.type)
this.setContent()
$tip.attr('id', tipId)
this.$element.attr('aria-describedby', tipId)
if (this.options.animation) $tip.addClass('fade')
var placement = typeof this.options.placement == 'function' ?
this.options.placement.call(this, $tip[0], this.$element[0]) :
this.options.placement
var autoToken = /\s?auto?\s?/i
var autoPlace = autoToken.test(placement)
if (autoPlace) placement = placement.replace(autoToken, '') || 'top'
$tip
.detach()
.css({ top: 0, left: 0, display: 'block' })
.addClass(placement)
.data('bs.' + this.type, this)
this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)
var pos = this.getPosition()
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (autoPlace) {
var orgPlacement = placement
var $container = this.options.container ? $(this.options.container) : this.$element.parent()
var containerDim = this.getPosition($container)
placement = placement == 'bottom' && pos.bottom + actualHeight > containerDim.bottom ? 'top' :
placement == 'top' && pos.top - actualHeight < containerDim.top ? 'bottom' :
placement == 'right' && pos.right + actualWidth > containerDim.width ? 'left' :
placement == 'left' && pos.left - actualWidth < containerDim.left ? 'right' :
placement
$tip
.removeClass(orgPlacement)
.addClass(placement)
}
var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight)
this.applyPlacement(calculatedOffset, placement)
var complete = function () {
var prevHoverState = that.hoverState
that.$element.trigger('shown.bs.' + that.type)
that.hoverState = null
if (prevHoverState == 'out') that.leave(that)
}
$.support.transition && this.$tip.hasClass('fade') ?
$tip
.one('bsTransitionEnd', complete)
.emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
complete()
}
}
Tooltip.prototype.applyPlacement = function (offset, placement) {
var $tip = this.tip()
var width = $tip[0].offsetWidth
var height = $tip[0].offsetHeight
// manually read margins because getBoundingClientRect includes difference
var marginTop = parseInt($tip.css('margin-top'), 10)
var marginLeft = parseInt($tip.css('margin-left'), 10)
// we must check for NaN for ie 8/9
if (isNaN(marginTop)) marginTop = 0
if (isNaN(marginLeft)) marginLeft = 0
offset.top = offset.top + marginTop
offset.left = offset.left + marginLeft
// $.fn.offset doesn't round pixel values
// so we use setOffset directly with our own function B-0
$.offset.setOffset($tip[0], $.extend({
using: function (props) {
$tip.css({
top: Math.round(props.top),
left: Math.round(props.left)
})
}
}, offset), 0)
$tip.addClass('in')
// check to see if placing tip in new offset caused the tip to resize itself
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (placement == 'top' && actualHeight != height) {
offset.top = offset.top + height - actualHeight
}
var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight)
if (delta.left) offset.left += delta.left
else offset.top += delta.top
var isVertical = /top|bottom/.test(placement)
var arrowDelta = isVertical ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight
var arrowOffsetPosition = isVertical ? 'offsetWidth' : 'offsetHeight'
$tip.offset(offset)
this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], isVertical)
}
Tooltip.prototype.replaceArrow = function (delta, dimension, isHorizontal) {
this.arrow()
.css(isHorizontal ? 'left' : 'top', 50 * (1 - delta / dimension) + '%')
.css(isHorizontal ? 'top' : 'left', '')
}
Tooltip.prototype.setContent = function () {
var $tip = this.tip()
var title = this.getTitle()
$tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
$tip.removeClass('fade in top bottom left right')
}
Tooltip.prototype.hide = function (callback) {
var that = this
var $tip = this.tip()
var e = $.Event('hide.bs.' + this.type)
function complete() {
if (that.hoverState != 'in') $tip.detach()
that.$element
.removeAttr('aria-describedby')
.trigger('hidden.bs.' + that.type)
callback && callback()
}
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
$tip.removeClass('in')
$.support.transition && this.$tip.hasClass('fade') ?
$tip
.one('bsTransitionEnd', complete)
.emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
complete()
this.hoverState = null
return this
}
Tooltip.prototype.fixTitle = function () {
var $e = this.$element
if ($e.attr('title') || typeof ($e.attr('data-original-title')) != 'string') {
$e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
}
}
Tooltip.prototype.hasContent = function () {
return this.getTitle()
}
Tooltip.prototype.getPosition = function ($element) {
$element = $element || this.$element
var el = $element[0]
var isBody = el.tagName == 'BODY'
var elRect = el.getBoundingClientRect()
if (elRect.width == null) {
// width and height are missing in IE8, so compute them manually; see https://github.com/twbs/bootstrap/issues/14093
elRect = $.extend({}, elRect, { width: elRect.right - elRect.left, height: elRect.bottom - elRect.top })
}
var elOffset = isBody ? { top: 0, left: 0 } : $element.offset()
var scroll = { scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop() }
var outerDims = isBody ? { width: $(window).width(), height: $(window).height() } : null
return $.extend({}, elRect, scroll, outerDims, elOffset)
}
Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) {
return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } :
placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } :
placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } :
/* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width }
}
Tooltip.prototype.getViewportAdjustedDelta = function (placement, pos, actualWidth, actualHeight) {
var delta = { top: 0, left: 0 }
if (!this.$viewport) return delta
var viewportPadding = this.options.viewport && this.options.viewport.padding || 0
var viewportDimensions = this.getPosition(this.$viewport)
if (/right|left/.test(placement)) {
var topEdgeOffset = pos.top - viewportPadding - viewportDimensions.scroll
var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight
if (topEdgeOffset < viewportDimensions.top) { // top overflow
delta.top = viewportDimensions.top - topEdgeOffset
} else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow
delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset
}
} else {
var leftEdgeOffset = pos.left - viewportPadding
var rightEdgeOffset = pos.left + viewportPadding + actualWidth
if (leftEdgeOffset < viewportDimensions.left) { // left overflow
delta.left = viewportDimensions.left - leftEdgeOffset
} else if (rightEdgeOffset > viewportDimensions.width) { // right overflow
delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset
}
}
return delta
}
Tooltip.prototype.getTitle = function () {
var title
var $e = this.$element
var o = this.options
title = $e.attr('data-original-title')
|| (typeof o.title == 'function' ? o.title.call($e[0]) : o.title)
return title
}
Tooltip.prototype.getUID = function (prefix) {
do prefix += ~~(Math.random() * 1000000)
while (document.getElementById(prefix))
return prefix
}
Tooltip.prototype.tip = function () {
return (this.$tip = this.$tip || $(this.options.template))
}
Tooltip.prototype.arrow = function () {
return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow'))
}
Tooltip.prototype.enable = function () {
this.enabled = true
}
Tooltip.prototype.disable = function () {
this.enabled = false
}
Tooltip.prototype.toggleEnabled = function () {
this.enabled = !this.enabled
}
Tooltip.prototype.toggle = function (e) {
var self = this
if (e) {
self = $(e.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(e.currentTarget, this.getDelegateOptions())
$(e.currentTarget).data('bs.' + this.type, self)
}
}
self.tip().hasClass('in') ? self.leave(self) : self.enter(self)
}
Tooltip.prototype.destroy = function () {
var that = this
clearTimeout(this.timeout)
this.hide(function () {
that.$element.off('.' + that.type).removeData('bs.' + that.type)
})
}
// TOOLTIP PLUGIN DEFINITION
// =========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.tooltip')
var options = typeof option == 'object' && option
if (!data && option == 'destroy') return
if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.tooltip
$.fn.tooltip = Plugin
$.fn.tooltip.Constructor = Tooltip
// TOOLTIP NO CONFLICT
// ===================
$.fn.tooltip.noConflict = function () {
$.fn.tooltip = old
return this
}
}(jQuery);
/* ========================================================================
* Bootstrap: popover.js v3.3.2
* http://getbootstrap.com/javascript/#popovers
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// POPOVER PUBLIC CLASS DEFINITION
// ===============================
var Popover = function (element, options) {
this.init('popover', element, options)
}
if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js')
Popover.VERSION = '3.3.2'
Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, {
placement: 'right',
trigger: 'click',
content: '',
template: '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
})
// NOTE: POPOVER EXTENDS tooltip.js
// ================================
Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype)
Popover.prototype.constructor = Popover
Popover.prototype.getDefaults = function () {
return Popover.DEFAULTS
}
Popover.prototype.setContent = function () {
var $tip = this.tip()
var title = this.getTitle()
var content = this.getContent()
$tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title)
$tip.find('.popover-content').children().detach().end()[ // we use append for html objects to maintain js events
this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text'
](content)
$tip.removeClass('fade top bottom left right in')
// IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do
// this manually by checking the contents.
if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide()
}
Popover.prototype.hasContent = function () {
return this.getTitle() || this.getContent()
}
Popover.prototype.getContent = function () {
var $e = this.$element
var o = this.options
return $e.attr('data-content')
|| (typeof o.content == 'function' ?
o.content.call($e[0]) :
o.content)
}
Popover.prototype.arrow = function () {
return (this.$arrow = this.$arrow || this.tip().find('.arrow'))
}
Popover.prototype.tip = function () {
if (!this.$tip) this.$tip = $(this.options.template)
return this.$tip
}
// POPOVER PLUGIN DEFINITION
// =========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.popover')
var options = typeof option == 'object' && option
if (!data && option == 'destroy') return
if (!data) $this.data('bs.popover', (data = new Popover(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.popover
$.fn.popover = Plugin
$.fn.popover.Constructor = Popover
// POPOVER NO CONFLICT
// ===================
$.fn.popover.noConflict = function () {
$.fn.popover = old
return this
}
}(jQuery);
/* ========================================================================
* Bootstrap: tab.js v3.3.2
* http://getbootstrap.com/javascript/#tabs
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// TAB CLASS DEFINITION
// ====================
var Tab = function (element) {
this.element = $(element)
}
Tab.VERSION = '3.3.2'
Tab.TRANSITION_DURATION = 150
Tab.prototype.show = function () {
var $this = this.element
var $ul = $this.closest('ul:not(.dropdown-menu)')
var selector = $this.data('target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
if ($this.parent('li').hasClass('active')) return
var $previous = $ul.find('.active:last a')
var hideEvent = $.Event('hide.bs.tab', {
relatedTarget: $this[0]
})
var showEvent = $.Event('show.bs.tab', {
relatedTarget: $previous[0]
})
$previous.trigger(hideEvent)
$this.trigger(showEvent)
if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) return
var $target = $(selector)
this.activate($this.closest('li'), $ul)
this.activate($target, $target.parent(), function () {
$previous.trigger({
type: 'hidden.bs.tab',
relatedTarget: $this[0]
})
$this.trigger({
type: 'shown.bs.tab',
relatedTarget: $previous[0]
})
})
}
Tab.prototype.activate = function (element, container, callback) {
var $active = container.find('> .active')
var transition = callback
&& $.support.transition
&& (($active.length && $active.hasClass('fade')) || !!container.find('> .fade').length)
function next() {
$active
.removeClass('active')
.find('> .dropdown-menu > .active')
.removeClass('active')
.end()
.find('[data-toggle="tab"]')
.attr('aria-expanded', false)
element
.addClass('active')
.find('[data-toggle="tab"]')
.attr('aria-expanded', true)
if (transition) {
element[0].offsetWidth // reflow for transition
element.addClass('in')
} else {
element.removeClass('fade')
}
if (element.parent('.dropdown-menu')) {
element
.closest('li.dropdown')
.addClass('active')
.end()
.find('[data-toggle="tab"]')
.attr('aria-expanded', true)
}
callback && callback()
}
$active.length && transition ?
$active
.one('bsTransitionEnd', next)
.emulateTransitionEnd(Tab.TRANSITION_DURATION) :
next()
$active.removeClass('in')
}
// TAB PLUGIN DEFINITION
// =====================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.tab')
if (!data) $this.data('bs.tab', (data = new Tab(this)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.tab
$.fn.tab = Plugin
$.fn.tab.Constructor = Tab
// TAB NO CONFLICT
// ===============
$.fn.tab.noConflict = function () {
$.fn.tab = old
return this
}
// TAB DATA-API
// ============
var clickHandler = function (e) {
e.preventDefault()
Plugin.call($(this), 'show')
}
$(document)
.on('click.bs.tab.data-api', '[data-toggle="tab"]', clickHandler)
.on('click.bs.tab.data-api', '[data-toggle="pill"]', clickHandler)
}(jQuery);
/* ========================================================================
* Bootstrap: affix.js v3.3.2
* http://getbootstrap.com/javascript/#affix
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// AFFIX CLASS DEFINITION
// ======================
var Affix = function (element, options) {
this.options = $.extend({}, Affix.DEFAULTS, options)
this.$target = $(this.options.target)
.on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this))
.on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this))
this.$element = $(element)
this.affixed =
this.unpin =
this.pinnedOffset = null
this.checkPosition()
}
Affix.VERSION = '3.3.2'
Affix.RESET = 'affix affix-top affix-bottom'
Affix.DEFAULTS = {
offset: 0,
target: window
}
Affix.prototype.getState = function (scrollHeight, height, offsetTop, offsetBottom) {
var scrollTop = this.$target.scrollTop()
var position = this.$element.offset()
var targetHeight = this.$target.height()
if (offsetTop != null && this.affixed == 'top') return scrollTop < offsetTop ? 'top' : false
if (this.affixed == 'bottom') {
if (offsetTop != null) return (scrollTop + this.unpin <= position.top) ? false : 'bottom'
return (scrollTop + targetHeight <= scrollHeight - offsetBottom) ? false : 'bottom'
}
var initializing = this.affixed == null
var colliderTop = initializing ? scrollTop : position.top
var colliderHeight = initializing ? targetHeight : height
if (offsetTop != null && scrollTop <= offsetTop) return 'top'
if (offsetBottom != null && (colliderTop + colliderHeight >= scrollHeight - offsetBottom)) return 'bottom'
return false
}
Affix.prototype.getPinnedOffset = function () {
if (this.pinnedOffset) return this.pinnedOffset
this.$element.removeClass(Affix.RESET).addClass('affix')
var scrollTop = this.$target.scrollTop()
var position = this.$element.offset()
return (this.pinnedOffset = position.top - scrollTop)
}
Affix.prototype.checkPositionWithEventLoop = function () {
setTimeout($.proxy(this.checkPosition, this), 1)
}
Affix.prototype.checkPosition = function () {
if (!this.$element.is(':visible')) return
var height = this.$element.height()
var offset = this.options.offset
var offsetTop = offset.top
var offsetBottom = offset.bottom
var scrollHeight = $('body').height()
if (typeof offset != 'object') offsetBottom = offsetTop = offset
if (typeof offsetTop == 'function') offsetTop = offset.top(this.$element)
if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element)
var affix = this.getState(scrollHeight, height, offsetTop, offsetBottom)
if (this.affixed != affix) {
if (this.unpin != null) this.$element.css('top', '')
var affixType = 'affix' + (affix ? '-' + affix : '')
var e = $.Event(affixType + '.bs.affix')
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
this.affixed = affix
this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null
this.$element
.removeClass(Affix.RESET)
.addClass(affixType)
.trigger(affixType.replace('affix', 'affixed') + '.bs.affix')
}
if (affix == 'bottom') {
this.$element.offset({
top: scrollHeight - height - offsetBottom
})
}
}
// AFFIX PLUGIN DEFINITION
// =======================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.affix')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.affix', (data = new Affix(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.affix
$.fn.affix = Plugin
$.fn.affix.Constructor = Affix
// AFFIX NO CONFLICT
// =================
$.fn.affix.noConflict = function () {
$.fn.affix = old
return this
}
// AFFIX DATA-API
// ==============
$(window).on('load', function () {
$('[data-spy="affix"]').each(function () {
var $spy = $(this)
var data = $spy.data()
data.offset = data.offset || {}
if (data.offsetBottom != null) data.offset.bottom = data.offsetBottom
if (data.offsetTop != null) data.offset.top = data.offsetTop
Plugin.call($spy, data)
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: collapse.js v3.3.2
* http://getbootstrap.com/javascript/#collapse
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// COLLAPSE PUBLIC CLASS DEFINITION
// ================================
var Collapse = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, Collapse.DEFAULTS, options)
this.$trigger = $(this.options.trigger).filter('[href="#' + element.id + '"], [data-target="#' + element.id + '"]')
this.transitioning = null
if (this.options.parent) {
this.$parent = this.getParent()
} else {
this.addAriaAndCollapsedClass(this.$element, this.$trigger)
}
if (this.options.toggle) this.toggle()
}
Collapse.VERSION = '3.3.2'
Collapse.TRANSITION_DURATION = 350
Collapse.DEFAULTS = {
toggle: true,
trigger: '[data-toggle="collapse"]'
}
Collapse.prototype.dimension = function () {
var hasWidth = this.$element.hasClass('width')
return hasWidth ? 'width' : 'height'
}
Collapse.prototype.show = function () {
if (this.transitioning || this.$element.hasClass('in')) return
var activesData
var actives = this.$parent && this.$parent.children('.panel').children('.in, .collapsing')
if (actives && actives.length) {
activesData = actives.data('bs.collapse')
if (activesData && activesData.transitioning) return
}
var startEvent = $.Event('show.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
if (actives && actives.length) {
Plugin.call(actives, 'hide')
activesData || actives.data('bs.collapse', null)
}
var dimension = this.dimension()
this.$element
.removeClass('collapse')
.addClass('collapsing')[dimension](0)
.attr('aria-expanded', true)
this.$trigger
.removeClass('collapsed')
.attr('aria-expanded', true)
this.transitioning = 1
var complete = function () {
this.$element
.removeClass('collapsing')
.addClass('collapse in')[dimension]('')
this.transitioning = 0
this.$element
.trigger('shown.bs.collapse')
}
if (!$.support.transition) return complete.call(this)
var scrollSize = $.camelCase(['scroll', dimension].join('-'))
this.$element
.one('bsTransitionEnd', $.proxy(complete, this))
.emulateTransitionEnd(Collapse.TRANSITION_DURATION)[dimension](this.$element[0][scrollSize])
}
Collapse.prototype.hide = function () {
if (this.transitioning || !this.$element.hasClass('in')) return
var startEvent = $.Event('hide.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
var dimension = this.dimension()
this.$element[dimension](this.$element[dimension]())[0].offsetHeight
this.$element
.addClass('collapsing')
.removeClass('collapse in')
.attr('aria-expanded', false)
this.$trigger
.addClass('collapsed')
.attr('aria-expanded', false)
this.transitioning = 1
var complete = function () {
this.transitioning = 0
this.$element
.removeClass('collapsing')
.addClass('collapse')
.trigger('hidden.bs.collapse')
}
if (!$.support.transition) return complete.call(this)
this.$element
[dimension](0)
.one('bsTransitionEnd', $.proxy(complete, this))
.emulateTransitionEnd(Collapse.TRANSITION_DURATION)
}
Collapse.prototype.toggle = function () {
this[this.$element.hasClass('in') ? 'hide' : 'show']()
}
Collapse.prototype.getParent = function () {
return $(this.options.parent)
.find('[data-toggle="collapse"][data-parent="' + this.options.parent + '"]')
.each($.proxy(function (i, element) {
var $element = $(element)
this.addAriaAndCollapsedClass(getTargetFromTrigger($element), $element)
}, this))
.end()
}
Collapse.prototype.addAriaAndCollapsedClass = function ($element, $trigger) {
var isOpen = $element.hasClass('in')
$element.attr('aria-expanded', isOpen)
$trigger
.toggleClass('collapsed', !isOpen)
.attr('aria-expanded', isOpen)
}
function getTargetFromTrigger($trigger) {
var href
var target = $trigger.attr('data-target')
|| (href = $trigger.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') // strip for ie7
return $(target)
}
// COLLAPSE PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.collapse')
var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data && options.toggle && option == 'show') options.toggle = false
if (!data) $this.data('bs.collapse', (data = new Collapse(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.collapse
$.fn.collapse = Plugin
$.fn.collapse.Constructor = Collapse
// COLLAPSE NO CONFLICT
// ====================
$.fn.collapse.noConflict = function () {
$.fn.collapse = old
return this
}
// COLLAPSE DATA-API
// =================
$(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function (e) {
var $this = $(this)
if (!$this.attr('data-target')) e.preventDefault()
var $target = getTargetFromTrigger($this)
var data = $target.data('bs.collapse')
var option = data ? 'toggle' : $.extend({}, $this.data(), { trigger: this })
Plugin.call($target, option)
})
}(jQuery);
/* ========================================================================
* Bootstrap: scrollspy.js v3.3.2
* http://getbootstrap.com/javascript/#scrollspy
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// SCROLLSPY CLASS DEFINITION
// ==========================
function ScrollSpy(element, options) {
var process = $.proxy(this.process, this)
this.$body = $('body')
this.$scrollElement = $(element).is('body') ? $(window) : $(element)
this.options = $.extend({}, ScrollSpy.DEFAULTS, options)
this.selector = (this.options.target || '') + ' .nav li > a'
this.offsets = []
this.targets = []
this.activeTarget = null
this.scrollHeight = 0
this.$scrollElement.on('scroll.bs.scrollspy', process)
this.refresh()
this.process()
}
ScrollSpy.VERSION = '3.3.2'
ScrollSpy.DEFAULTS = {
offset: 10
}
ScrollSpy.prototype.getScrollHeight = function () {
return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight)
}
ScrollSpy.prototype.refresh = function () {
var offsetMethod = 'offset'
var offsetBase = 0
if (!$.isWindow(this.$scrollElement[0])) {
offsetMethod = 'position'
offsetBase = this.$scrollElement.scrollTop()
}
this.offsets = []
this.targets = []
this.scrollHeight = this.getScrollHeight()
var self = this
this.$body
.find(this.selector)
.map(function () {
var $el = $(this)
var href = $el.data('target') || $el.attr('href')
var $href = /^#./.test(href) && $(href)
return ($href
&& $href.length
&& $href.is(':visible')
&& [[$href[offsetMethod]().top + offsetBase, href]]) || null
})
.sort(function (a, b) { return a[0] - b[0] })
.each(function () {
self.offsets.push(this[0])
self.targets.push(this[1])
})
}
ScrollSpy.prototype.process = function () {
var scrollTop = this.$scrollElement.scrollTop() + this.options.offset
var scrollHeight = this.getScrollHeight()
var maxScroll = this.options.offset + scrollHeight - this.$scrollElement.height()
var offsets = this.offsets
var targets = this.targets
var activeTarget = this.activeTarget
var i
if (this.scrollHeight != scrollHeight) {
this.refresh()
}
if (scrollTop >= maxScroll) {
return activeTarget != (i = targets[targets.length - 1]) && this.activate(i)
}
if (activeTarget && scrollTop < offsets[0]) {
this.activeTarget = null
return this.clear()
}
for (i = offsets.length; i--;) {
activeTarget != targets[i]
&& scrollTop >= offsets[i]
&& (!offsets[i + 1] || scrollTop <= offsets[i + 1])
&& this.activate(targets[i])
}
}
ScrollSpy.prototype.activate = function (target) {
this.activeTarget = target
this.clear()
var selector = this.selector +
'[data-target="' + target + '"],' +
this.selector + '[href="' + target + '"]'
var active = $(selector)
.parents('li')
.addClass('active')
if (active.parent('.dropdown-menu').length) {
active = active
.closest('li.dropdown')
.addClass('active')
}
active.trigger('activate.bs.scrollspy')
}
ScrollSpy.prototype.clear = function () {
$(this.selector)
.parentsUntil(this.options.target, '.active')
.removeClass('active')
}
// SCROLLSPY PLUGIN DEFINITION
// ===========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.scrollspy')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.scrollspy
$.fn.scrollspy = Plugin
$.fn.scrollspy.Constructor = ScrollSpy
// SCROLLSPY NO CONFLICT
// =====================
$.fn.scrollspy.noConflict = function () {
$.fn.scrollspy = old
return this
}
// SCROLLSPY DATA-API
// ==================
$(window).on('load.bs.scrollspy.data-api', function () {
$('[data-spy="scroll"]').each(function () {
var $spy = $(this)
Plugin.call($spy, $spy.data())
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: transition.js v3.3.2
* http://getbootstrap.com/javascript/#transitions
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
// ============================================================
function transitionEnd() {
var el = document.createElement('bootstrap')
var transEndEventNames = {
WebkitTransition : 'webkitTransitionEnd',
MozTransition : 'transitionend',
OTransition : 'oTransitionEnd otransitionend',
transition : 'transitionend'
}
for (var name in transEndEventNames) {
if (el.style[name] !== undefined) {
return { end: transEndEventNames[name] }
}
}
return false // explicit for ie8 ( ._.)
}
// http://blog.alexmaccaw.com/css-transitions
$.fn.emulateTransitionEnd = function (duration) {
var called = false
var $el = this
$(this).one('bsTransitionEnd', function () { called = true })
var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
setTimeout(callback, duration)
return this
}
$(function () {
$.support.transition = transitionEnd()
if (!$.support.transition) return
$.event.special.bsTransitionEnd = {
bindType: $.support.transition.end,
delegateType: $.support.transition.end,
handle: function (e) {
if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments)
}
}
})
}(jQuery);
| kenhys/redpen | redpen-server/src/main/webapp/js/bootstrap.js | JavaScript | apache-2.0 | 66,924 |
var group___s_p_i__events =
[
[ "ARM_SPI_EVENT_DATA_LOST", "group___s_p_i__events.html#ga8e63d99c80ea56de596a8d0a51fd8244", null ],
[ "ARM_SPI_EVENT_MODE_FAULT", "group___s_p_i__events.html#ga7eaa229003689aa18598273490b3e630", null ],
[ "ARM_SPI_EVENT_TRANSFER_COMPLETE", "group___s_p_i__events.html#gaabdfc9e17641144cd50d36d15511a1b8", null ]
]; | LabAixBidouille/EmbeddedTeam | courses/examples/CMSIS/CMSIS/Documentation/Driver/html/group___s_p_i__events.js | JavaScript | apache-2.0 | 358 |
/**
* Sitespeed.io - How speedy is your site? (https://www.sitespeed.io)
* Copyright (c) 2014, Peter Hedenskog, Tobias Lidskog
* and other contributors
* Released under the Apache 2.0 License
*/
'use strict';
var path = require('path'),
util = require('../util/util'),
fs = require('fs'),
inspect = require('util').inspect,
pagespeed = require('gpagespeed'),
winston = require('winston'),
async = require('async');
module.exports = {
analyze: function(urls, config, callback) {
var log = winston.loggers.get('sitespeed.io');
var gpsiResultDir = path.join(config.run.absResultDir, config.dataDir, 'gpsi');
fs.mkdir(gpsiResultDir, function(err) {
if (err) {
log.error('Couldn\'t create gpsi result dir: %s %s', gpsiResultDir, inspect(err));
callback(err, {
'type': 'gpsi',
'data': {},
'errors': {}
});
} else {
var queue = async.queue(analyzeUrl, config.threads);
var errors = {};
var pageData = {};
urls.forEach(function(u) {
queue.push({
'url': u,
'config': config
}, function(error, data) {
if (error) {
log.error('Error running gpsi: %s', inspect(error));
errors[u] = error;
} else {
pageData[u] = data;
}
});
});
queue.drain = function() {
callback(undefined, {
'type': 'gpsi',
'data': pageData,
'errors': errors
});
};
}
});
}
};
function analyzeUrl(args, asyncDoneCallback) {
var url = args.url;
var config = args.config;
var opts = {
url: url,
strategy: config.profile,
key: config.gpsiKey
};
var log = winston.loggers.get('sitespeed.io');
log.info('Running Google Page Speed Insights for %s', url);
pagespeed(opts, function(err, data) {
if (err) {
log.error('Error running gpsi for url %s (%s)', url, inspect(err));
return asyncDoneCallback(err);
}
log.verbose('Got the following from GPSI:' + JSON.stringify(data));
if (data.error) {
// TODO parse the error
log.error('Error running gpsi:' + url + '(' + JSON.stringify(data) + ')');
return asyncDoneCallback(data.error);
}
var jsonPath = path.join(config.run.absResultDir, config.dataDir,
'gpsi',
util.getFileName(url) + '-gpsi.json');
fs.writeFile(jsonPath, JSON.stringify(data), function(error) {
if (error) {
log.error('GPSI couldn\'t store file for url %s (%s)', url, inspect(error));
return asyncDoneCallback(error);
}
return asyncDoneCallback(undefined, data);
});
});
}
| yesman82/sitespeed.io | lib/analyze/gpsi.js | JavaScript | apache-2.0 | 2,754 |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* The production QuantifierPrefix :: * evaluates by returning the two results 0 and \infty
*
* @path ch15/15.10/15.10.2/15.10.2.7/S15.10.2.7_A4_T3.js
* @description Execute /[^"]* /.exec("before\'i\'start") and check results
*/
__executed = /[^"]*/.exec("before\'i\'start");
__expected = ["before\'i\'start"];
__expected.index = 0;
__expected.input = "before\'i\'start";
//CHECK#1
if (__executed.length !== __expected.length) {
$ERROR('#1: __executed = /[^"]*/.exec("before\'i\'start"); __executed.length === ' + __expected.length + '. Actual: ' + __executed.length);
}
//CHECK#2
if (__executed.index !== __expected.index) {
$ERROR('#2: __executed = /[^"]*/.exec("before\'i\'start"); __executed.index === ' + __expected.index + '. Actual: ' + __executed.index);
}
//CHECK#3
if (__executed.input !== __expected.input) {
$ERROR('#3: __executed = /[^"]*/.exec("before\'i\'start"); __executed.input === ' + __expected.input + '. Actual: ' + __executed.input);
}
//CHECK#4
for(var index=0; index<__expected.length; index++) {
if (__executed[index] !== __expected[index]) {
$ERROR('#4: __executed = /[^"]*/.exec("before\'i\'start"); __executed[' + index + '] === ' + __expected[index] + '. Actual: ' + __executed[index]);
}
}
| hippich/typescript | tests/Fidelity/test262/suite/ch15/15.10/15.10.2/15.10.2.7/S15.10.2.7_A4_T3.js | JavaScript | apache-2.0 | 1,377 |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* String.prototype.split (separator, limit) returns an Array object into which substrings of the result of converting this object to a string have
* been stored. The substrings are determined by searching from left to right for occurrences of
* separator; these occurrences are not part of any substring in the returned array, but serve to divide up
* the string value. The value of separator may be a string of any length or it may be a RegExp object
*
* @path ch15/15.5/15.5.4/15.5.4.14/S15.5.4.14_A2_T12.js
* @description Call split("r-42"), instance is String("one-1 two-2 four-4")
*/
var __string = new String("one-1 two-2 four-4");
var __split = __string.split("r-42");
//////////////////////////////////////////////////////////////////////////////
//CHECK#1
if (__split.constructor !== Array) {
$ERROR('#1: var __string = new String("one-1 two-2 four-4"); __split = __string.split("r-42"); __split.constructor === Array. Actual: '+__split.constructor );
}
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//CHECK#2
if (__split.length !== 1) {
$ERROR('#2: var __string = new String("one-1 two-2 four-4"); __split = __string.split("r-42"); __split.length === 1. Actual: '+__split.length );
}
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//CHECK#3
if (__split[0] !== "one-1 two-2 four-4") {
$ERROR('#3: var __string = new String("one-1 two-2 four-4"); __split = __string.split("r-42"); __split[0] === "one-1 two-2 four-4". Actual: '+__split[0] );
}
//
//////////////////////////////////////////////////////////////////////////////
| hippich/typescript | tests/Fidelity/test262/suite/ch15/15.5/15.5.4/15.5.4.14/S15.5.4.14_A2_T12.js | JavaScript | apache-2.0 | 1,920 |
Package.describe({
name: "telescope:settings",
summary: "Telescope settings package",
version: "0.25.6",
git: "https://github.com/TelescopeJS/Telescope.git"
});
Package.onUse(function(api) {
var both = ['server', 'client'];
api.versionsFrom(['METEOR@1.0']);
api.use([
'telescope:lib@0.25.6',
'telescope:i18n@0.25.6'
]);
api.addFiles([
'lib/settings.js',
'lib/routes.js',
'lib/menus.js',
'package-tap.i18n'
], both);
api.addFiles([
'lib/server/publications.js',
], 'server');
api.addFiles([
'lib/client/language_changer.js',
'lib/client/helpers.js',
'lib/client/templates/settings.html',
'lib/client/templates/settings.js'
], 'client');
var languages = ["ar", "bg", "cs", "da", "de", "el", "en", "es", "et", "fr", "hu", "id", "it", "ja", "kk", "ko", "nl", "pl", "pt-BR", "ro", "ru", "sl", "sv", "th", "tr", "vi", "zh-CN"];
var languagesPaths = languages.map(function (language) {
return "i18n/"+language+".i18n.json";
});
api.addFiles(languagesPaths, ["client", "server"]);
api.export('Settings', both);
});
| eyaltoledano/streamhuntio | packages/telescope-settings/package.js | JavaScript | mit | 1,102 |
angular.module('bucketList', ['ionic', 'bucketList.controllers', 'bucketList.services'])
.run(function ($ionicPlatform) {
$ionicPlatform.ready(function () {
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
})
.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('auth', {
url: "/auth",
abstract: true,
templateUrl: "templates/auth.html"
})
.state('auth.signin', {
url: '/signin',
views: {
'auth-signin': {
templateUrl: 'templates/auth-signin.html',
controller: 'SignInCtrl'
}
}
})
.state('auth.signup', {
url: '/signup',
views: {
'auth-signup': {
templateUrl: 'templates/auth-signup.html',
controller: 'SignUpCtrl'
}
}
})
.state('bucket', {
url: "/bucket",
abstract: true,
templateUrl: "templates/bucket.html"
})
.state('bucket.list', {
url: '/list',
views: {
'bucket-list': {
templateUrl: 'templates/bucket-list.html',
controller: 'myListCtrl'
}
}
})
.state('bucket.completed', {
url: '/completed',
views: {
'bucket-completed': {
templateUrl: 'templates/bucket-completed.html',
controller: 'completedCtrl'
}
}
})
$urlRouterProvider.otherwise('/auth/signin');
}); | andrejoe/DON | prod/client/www/js/app.js | JavaScript | mit | 2,024 |
import Section from './_section';
import { CARD_TYPE } from './types';
import { shallowCopyObject } from '../utils/copy';
export const CARD_MODES = {
DISPLAY: 'display',
EDIT: 'edit'
};
const CARD_LENGTH = 1;
const DEFAULT_INITIAL_MODE = CARD_MODES.DISPLAY;
export default class Card extends Section {
constructor(name, payload) {
super(CARD_TYPE);
this.name = name;
this.payload = payload;
this.setInitialMode(DEFAULT_INITIAL_MODE);
this.isCardSection = true;
}
get isBlank() {
return false;
}
canJoin() {
return false;
}
get length() {
return CARD_LENGTH;
}
clone() {
let payload = shallowCopyObject(this.payload);
let card = this.builder.createCardSection(this.name, payload);
// If this card is currently rendered, clone the mode it is
// currently in as the default mode of the new card.
let mode = this._initialMode;
if (this.renderNode && this.renderNode.cardNode) {
mode = this.renderNode.cardNode.mode;
}
card.setInitialMode(mode);
return card;
}
/**
* set the mode that this will be rendered into initially
* @private
*/
setInitialMode(initialMode) {
// TODO validate initialMode
this._initialMode = initialMode;
}
}
| atonse/mobiledoc-kit | src/js/models/card.js | JavaScript | mit | 1,257 |
/**
* Inline development version. Only to be used while developing since it uses document.write to load scripts.
*/
/*jshint smarttabs:true, undef:true, latedef:true, curly:true, bitwise:true, camelcase:true */
/*globals $code */
(function(exports) {
"use strict";
var html = "", baseDir;
var modules = {}, exposedModules = [], moduleCount = 0;
var scripts = document.getElementsByTagName('script');
for (var i = 0; i < scripts.length; i++) {
var src = scripts[i].src;
if (src.indexOf('/plugin.dev.js') != -1) {
baseDir = src.substring(0, src.lastIndexOf('/'));
}
}
function require(ids, callback) {
var module, defs = [];
for (var i = 0; i < ids.length; ++i) {
module = modules[ids[i]] || resolve(ids[i]);
if (!module) {
throw 'module definition dependecy not found: ' + ids[i];
}
defs.push(module);
}
callback.apply(null, defs);
}
function resolve(id) {
if (exports.privateModules && id in exports.privateModules) {
return;
}
var target = exports;
var fragments = id.split(/[.\/]/);
for (var fi = 0; fi < fragments.length; ++fi) {
if (!target[fragments[fi]]) {
return;
}
target = target[fragments[fi]];
}
return target;
}
function register(id) {
var target = exports;
var fragments = id.split(/[.\/]/);
for (var fi = 0; fi < fragments.length - 1; ++fi) {
if (target[fragments[fi]] === undefined) {
target[fragments[fi]] = {};
}
target = target[fragments[fi]];
}
target[fragments[fragments.length - 1]] = modules[id];
}
function define(id, dependencies, definition) {
var privateModules, i;
if (typeof id !== 'string') {
throw 'invalid module definition, module id must be defined and be a string';
}
if (dependencies === undefined) {
throw 'invalid module definition, dependencies must be specified';
}
if (definition === undefined) {
throw 'invalid module definition, definition function must be specified';
}
require(dependencies, function() {
modules[id] = definition.apply(null, arguments);
});
if (--moduleCount === 0) {
for (i = 0; i < exposedModules.length; i++) {
register(exposedModules[i]);
}
}
// Expose private modules for unit tests
if (exports.AMDLC_TESTS) {
privateModules = exports.privateModules || {};
for (id in modules) {
privateModules[id] = modules[id];
}
for (i = 0; i < exposedModules.length; i++) {
delete privateModules[exposedModules[i]];
}
exports.privateModules = privateModules;
}
}
function expose(ids) {
exposedModules = ids;
}
function writeScripts() {
document.write(html);
}
function load(path) {
html += '<script type="text/javascript" src="' + baseDir + '/' + path + '"></script>\n';
moduleCount++;
}
// Expose globally
exports.define = define;
exports.require = require;
expose(["tinymce/spellcheckerplugin/DomTextMatcher"]);
load('classes/DomTextMatcher.js');
load('classes/Plugin.js');
writeScripts();
})(this);
// $hash: c127be7adad8852ba59852dcf5f71754 | oncebuilder/OnceBuilder | libs/tinymce/js/tinymce/plugins/spellchecker/plugin.dev.js | JavaScript | mit | 3,032 |
/*
Language: PowerShell
Description: PowerShell is a task-based command-line shell and scripting language built on .NET.
Author: David Mohundro <david@mohundro.com>
Contributors: Nicholas Blumhardt <nblumhardt@nblumhardt.com>, Victor Zhou <OiCMudkips@users.noreply.github.com>, Nicolas Le Gall <contact@nlegall.fr>
Website: https://docs.microsoft.com/en-us/powershell/
*/
function powershell(hljs) {
const TYPES = [
"string",
"char",
"byte",
"int",
"long",
"bool",
"decimal",
"single",
"double",
"DateTime",
"xml",
"array",
"hashtable",
"void"
];
// https://docs.microsoft.com/en-us/powershell/scripting/developer/cmdlet/approved-verbs-for-windows-powershell-commands
const VALID_VERBS =
'Add|Clear|Close|Copy|Enter|Exit|Find|Format|Get|Hide|Join|Lock|' +
'Move|New|Open|Optimize|Pop|Push|Redo|Remove|Rename|Reset|Resize|' +
'Search|Select|Set|Show|Skip|Split|Step|Switch|Undo|Unlock|' +
'Watch|Backup|Checkpoint|Compare|Compress|Convert|ConvertFrom|' +
'ConvertTo|Dismount|Edit|Expand|Export|Group|Import|Initialize|' +
'Limit|Merge|Mount|Out|Publish|Restore|Save|Sync|Unpublish|Update|' +
'Approve|Assert|Build|Complete|Confirm|Deny|Deploy|Disable|Enable|Install|Invoke|' +
'Register|Request|Restart|Resume|Start|Stop|Submit|Suspend|Uninstall|' +
'Unregister|Wait|Debug|Measure|Ping|Repair|Resolve|Test|Trace|Connect|' +
'Disconnect|Read|Receive|Send|Write|Block|Grant|Protect|Revoke|Unblock|' +
'Unprotect|Use|ForEach|Sort|Tee|Where';
const COMPARISON_OPERATORS =
'-and|-as|-band|-bnot|-bor|-bxor|-casesensitive|-ccontains|-ceq|-cge|-cgt|' +
'-cle|-clike|-clt|-cmatch|-cne|-cnotcontains|-cnotlike|-cnotmatch|-contains|' +
'-creplace|-csplit|-eq|-exact|-f|-file|-ge|-gt|-icontains|-ieq|-ige|-igt|' +
'-ile|-ilike|-ilt|-imatch|-in|-ine|-inotcontains|-inotlike|-inotmatch|' +
'-ireplace|-is|-isnot|-isplit|-join|-le|-like|-lt|-match|-ne|-not|' +
'-notcontains|-notin|-notlike|-notmatch|-or|-regex|-replace|-shl|-shr|' +
'-split|-wildcard|-xor';
const KEYWORDS = {
$pattern: /-?[A-z\.\-]+\b/,
keyword:
'if else foreach return do while until elseif begin for trap data dynamicparam ' +
'end break throw param continue finally in switch exit filter try process catch ' +
'hidden static parameter',
// "echo" relevance has been set to 0 to avoid auto-detect conflicts with shell transcripts
built_in:
'ac asnp cat cd CFS chdir clc clear clhy cli clp cls clv cnsn compare copy cp ' +
'cpi cpp curl cvpa dbp del diff dir dnsn ebp echo|0 epal epcsv epsn erase etsn exsn fc fhx ' +
'fl ft fw gal gbp gc gcb gci gcm gcs gdr gerr ghy gi gin gjb gl gm gmo gp gps gpv group ' +
'gsn gsnp gsv gtz gu gv gwmi h history icm iex ihy ii ipal ipcsv ipmo ipsn irm ise iwmi ' +
'iwr kill lp ls man md measure mi mount move mp mv nal ndr ni nmo npssc nsn nv ogv oh ' +
'popd ps pushd pwd r rbp rcjb rcsn rd rdr ren ri rjb rm rmdir rmo rni rnp rp rsn rsnp ' +
'rujb rv rvpa rwmi sajb sal saps sasv sbp sc scb select set shcm si sl sleep sls sort sp ' +
'spjb spps spsv start stz sujb sv swmi tee trcm type wget where wjb write'
// TODO: 'validate[A-Z]+' can't work in keywords
};
const TITLE_NAME_RE = /\w[\w\d]*((-)[\w\d]+)*/;
const BACKTICK_ESCAPE = {
begin: '`[\\s\\S]',
relevance: 0
};
const VAR = {
className: 'variable',
variants: [
{
begin: /\$\B/
},
{
className: 'keyword',
begin: /\$this/
},
{
begin: /\$[\w\d][\w\d_:]*/
}
]
};
const LITERAL = {
className: 'literal',
begin: /\$(null|true|false)\b/
};
const QUOTE_STRING = {
className: "string",
variants: [
{
begin: /"/,
end: /"/
},
{
begin: /@"/,
end: /^"@/
}
],
contains: [
BACKTICK_ESCAPE,
VAR,
{
className: 'variable',
begin: /\$[A-z]/,
end: /[^A-z]/
}
]
};
const APOS_STRING = {
className: 'string',
variants: [
{
begin: /'/,
end: /'/
},
{
begin: /@'/,
end: /^'@/
}
]
};
const PS_HELPTAGS = {
className: "doctag",
variants: [
/* no paramater help tags */
{
begin: /\.(synopsis|description|example|inputs|outputs|notes|link|component|role|functionality)/
},
/* one parameter help tags */
{
begin: /\.(parameter|forwardhelptargetname|forwardhelpcategory|remotehelprunspace|externalhelp)\s+\S+/
}
]
};
const PS_COMMENT = hljs.inherit(
hljs.COMMENT(null, null),
{
variants: [
/* single-line comment */
{
begin: /#/,
end: /$/
},
/* multi-line comment */
{
begin: /<#/,
end: /#>/
}
],
contains: [ PS_HELPTAGS ]
}
);
const CMDLETS = {
className: 'built_in',
variants: [
{
begin: '('.concat(VALID_VERBS, ')+(-)[\\w\\d]+')
}
]
};
const PS_CLASS = {
className: 'class',
beginKeywords: 'class enum',
end: /\s*[{]/,
excludeEnd: true,
relevance: 0,
contains: [ hljs.TITLE_MODE ]
};
const PS_FUNCTION = {
className: 'function',
begin: /function\s+/,
end: /\s*\{|$/,
excludeEnd: true,
returnBegin: true,
relevance: 0,
contains: [
{
begin: "function",
relevance: 0,
className: "keyword"
},
{
className: "title",
begin: TITLE_NAME_RE,
relevance: 0
},
{
begin: /\(/,
end: /\)/,
className: "params",
relevance: 0,
contains: [ VAR ]
}
// CMDLETS
]
};
// Using statment, plus type, plus assembly name.
const PS_USING = {
begin: /using\s/,
end: /$/,
returnBegin: true,
contains: [
QUOTE_STRING,
APOS_STRING,
{
className: 'keyword',
begin: /(using|assembly|command|module|namespace|type)/
}
]
};
// Comperison operators & function named parameters.
const PS_ARGUMENTS = {
variants: [
// PS literals are pretty verbose so it's a good idea to accent them a bit.
{
className: 'operator',
begin: '('.concat(COMPARISON_OPERATORS, ')\\b')
},
{
className: 'literal',
begin: /(-)[\w\d]+/,
relevance: 0
}
]
};
const HASH_SIGNS = {
className: 'selector-tag',
begin: /@\B/,
relevance: 0
};
// It's a very general rule so I'll narrow it a bit with some strict boundaries
// to avoid any possible false-positive collisions!
const PS_METHODS = {
className: 'function',
begin: /\[.*\]\s*[\w]+[ ]??\(/,
end: /$/,
returnBegin: true,
relevance: 0,
contains: [
{
className: 'keyword',
begin: '('.concat(
KEYWORDS.keyword.toString().replace(/\s/g, '|'
), ')\\b'),
endsParent: true,
relevance: 0
},
hljs.inherit(hljs.TITLE_MODE, {
endsParent: true
})
]
};
const GENTLEMANS_SET = [
// STATIC_MEMBER,
PS_METHODS,
PS_COMMENT,
BACKTICK_ESCAPE,
hljs.NUMBER_MODE,
QUOTE_STRING,
APOS_STRING,
// PS_NEW_OBJECT_TYPE,
CMDLETS,
VAR,
LITERAL,
HASH_SIGNS
];
const PS_TYPE = {
begin: /\[/,
end: /\]/,
excludeBegin: true,
excludeEnd: true,
relevance: 0,
contains: [].concat(
'self',
GENTLEMANS_SET,
{
begin: "(" + TYPES.join("|") + ")",
className: "built_in",
relevance: 0
},
{
className: 'type',
begin: /[\.\w\d]+/,
relevance: 0
}
)
};
PS_METHODS.contains.unshift(PS_TYPE);
return {
name: 'PowerShell',
aliases: [
"ps",
"ps1"
],
case_insensitive: true,
keywords: KEYWORDS,
contains: GENTLEMANS_SET.concat(
PS_CLASS,
PS_FUNCTION,
PS_USING,
PS_ARGUMENTS,
PS_TYPE
)
};
}
module.exports = powershell;
| ealbertos/dotfiles | vscode.symlink/extensions/bierner.markdown-preview-github-styles-0.2.0/node_modules/highlight.js/lib/languages/powershell.js | JavaScript | mit | 8,194 |
// This file was automatically generated. Do not modify.
'use strict';
goog.provide('Blockly.Msg.cs');
goog.require('Blockly.Msg');
Blockly.Msg.ADD_COMMENT = "Přidat komentář";
Blockly.Msg.AUTH = "Please authorize this app to enable your work to be saved and to allow it to be shared by you."; // untranslated
Blockly.Msg.CHANGE_VALUE_TITLE = "Změna hodnoty:";
Blockly.Msg.CHAT = "Chat with your collaborator by typing in this box!"; // untranslated
Blockly.Msg.COLLAPSE_ALL = "Skrýt bloky";
Blockly.Msg.COLLAPSE_BLOCK = "Skrýt blok";
Blockly.Msg.COLOUR_BLEND_COLOUR1 = "barva 1";
Blockly.Msg.COLOUR_BLEND_COLOUR2 = "barva 2";
Blockly.Msg.COLOUR_BLEND_HELPURL = "http://meyerweb.com/eric/tools/color-blend/"; // untranslated
Blockly.Msg.COLOUR_BLEND_RATIO = "poměr";
Blockly.Msg.COLOUR_BLEND_TITLE = "smíchat";
Blockly.Msg.COLOUR_BLEND_TOOLTIP = "Smíchá dvě barvy v daném poměru (0.0–1.0).";
Blockly.Msg.COLOUR_PICKER_HELPURL = "https://cs.wikipedia.org/wiki/Barva";
Blockly.Msg.COLOUR_PICKER_TOOLTIP = "Vyberte barvu z palety.";
Blockly.Msg.COLOUR_RANDOM_HELPURL = "http://randomcolour.com"; // untranslated
Blockly.Msg.COLOUR_RANDOM_TITLE = "náhodná barva";
Blockly.Msg.COLOUR_RANDOM_TOOLTIP = "Zvolte barvu náhodně.";
Blockly.Msg.COLOUR_RGB_BLUE = "modrá";
Blockly.Msg.COLOUR_RGB_GREEN = "zelená";
Blockly.Msg.COLOUR_RGB_HELPURL = "http://www.december.com/html/spec/colorper.html"; // untranslated
Blockly.Msg.COLOUR_RGB_RED = "červená";
Blockly.Msg.COLOUR_RGB_TITLE = "barva s";
Blockly.Msg.COLOUR_RGB_TOOLTIP = "Vytvoř barvu se zadaným množstvím červené, zelené a modré. Všechny hodnoty musí být mezi 0 a 100.";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_HELPURL = "https://code.google.com/p/blockly/wiki/Loops#Loop_Termination_Blocks"; // untranslated
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_BREAK = "vymanit se ze smyčky";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_CONTINUE = "pokračuj dalším opakováním smyčky";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_BREAK = "Přeruš vnitřní smyčku.";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_CONTINUE = "Přeskoč zbytek této smyčky a pokračuj dalším opakováním.";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_WARNING = "Upozornění: Tento blok může být použit pouze uvnitř smyčky.";
Blockly.Msg.CONTROLS_FOREACH_HELPURL = "https://code.google.com/p/blockly/wiki/Loops#for_each for each block"; // untranslated
Blockly.Msg.CONTROLS_FOREACH_INPUT_INLIST = "v seznamu";
Blockly.Msg.CONTROLS_FOREACH_INPUT_INLIST_TAIL = ""; // untranslated
Blockly.Msg.CONTROLS_FOREACH_INPUT_ITEM = "pro každou položku";
Blockly.Msg.CONTROLS_FOREACH_TOOLTIP = "Pro každou položku v seznamu nastavte do proměnné '%1' danou položku a proveďte nějaké operace.";
Blockly.Msg.CONTROLS_FOR_HELPURL = "https://code.google.com/p/blockly/wiki/Loops#count_with"; // untranslated
Blockly.Msg.CONTROLS_FOR_INPUT_FROM_TO_BY = "od %1 do %2 po %3";
Blockly.Msg.CONTROLS_FOR_INPUT_WITH = "počítat s";
Blockly.Msg.CONTROLS_FOR_TOOLTIP = "Nechá proměnnou %1 nabývat hodnot od počátečního do koncového čísla po daném přírůstku a provádí s ní příslušné bloky.";
Blockly.Msg.CONTROLS_IF_ELSEIF_TOOLTIP = "Přidat podmínku do \"pokud\" bloku.";
Blockly.Msg.CONTROLS_IF_ELSE_TOOLTIP = "Přidej konečnou podmínku zahrnující ostatní případy do bloku pokud.";
Blockly.Msg.CONTROLS_IF_HELPURL = "http://code.google.com/p/blockly/wiki/If_Then";
Blockly.Msg.CONTROLS_IF_IF_TOOLTIP = "Přidej, odstraň či uspořádej sekce k přenastavení tohoto bloku pokud.";
Blockly.Msg.CONTROLS_IF_MSG_ELSE = "jinak";
Blockly.Msg.CONTROLS_IF_MSG_ELSEIF = "nebo pokud";
Blockly.Msg.CONTROLS_IF_MSG_IF = "pokud";
Blockly.Msg.CONTROLS_IF_TOOLTIP_1 = "Je-li hodnota pravda, proveď určité příkazy.";
Blockly.Msg.CONTROLS_IF_TOOLTIP_2 = "Je-li hodnota pravda, proveď první blok příkazů. V opačném případě proveď druhý blok příkazů.";
Blockly.Msg.CONTROLS_IF_TOOLTIP_3 = "Je-li první hodnota pravdivá, proveď první blok příkazů. V opačném případě, je-li pravdivá druhá hodnota, proveď druhý blok příkazů.";
Blockly.Msg.CONTROLS_IF_TOOLTIP_4 = "Je-li první hodnota pravda, proveď první blok příkazů. Je-li druhá hodnota pravda, proveď druhý blok příkazů. Pokud žádná hodnota není pravda, proveď poslední blok příkazů.";
Blockly.Msg.CONTROLS_REPEAT_HELPURL = "https://cs.wikipedia.org/wiki/Cyklus_for";
Blockly.Msg.CONTROLS_REPEAT_INPUT_DO = "udělej";
Blockly.Msg.CONTROLS_REPEAT_TITLE = "opakovat %1 krát";
Blockly.Msg.CONTROLS_REPEAT_TITLE_REPEAT = "opakovat";
Blockly.Msg.CONTROLS_REPEAT_TITLE_TIMES = "krát";
Blockly.Msg.CONTROLS_REPEAT_TOOLTIP = "Proveď určité příkazy několikrát.";
Blockly.Msg.CONTROLS_WHILEUNTIL_HELPURL = "http://code.google.com/p/blockly/wiki/Repeat";
Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_UNTIL = "opakovat dokud";
Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_WHILE = "opakovat když";
Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_UNTIL = "Dokud je hodnota nepravdivá, prováděj určité příkazy.";
Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_WHILE = "Dokud je hodnota pravdivá, prováděj určité příkazy.";
Blockly.Msg.DELETE_BLOCK = "Odstranit blok";
Blockly.Msg.DELETE_X_BLOCKS = "Odstranit %1 bloky";
Blockly.Msg.DISABLE_BLOCK = "Zakázat blok";
Blockly.Msg.DUPLICATE_BLOCK = "zdvojit";
Blockly.Msg.ENABLE_BLOCK = "Povolit blok";
Blockly.Msg.EXPAND_ALL = "Rozbalit bloky";
Blockly.Msg.EXPAND_BLOCK = "Rozbalení bloku";
Blockly.Msg.EXTERNAL_INPUTS = "vnější vstupy";
Blockly.Msg.HELP = "Nápověda";
Blockly.Msg.INLINE_INPUTS = "Vložené vstupy";
Blockly.Msg.LISTS_CREATE_EMPTY_HELPURL = "https://en.wikipedia.org/wiki/Linked_list#Empty_lists"; // untranslated
Blockly.Msg.LISTS_CREATE_EMPTY_TITLE = "vytvořit prázdný seznam";
Blockly.Msg.LISTS_CREATE_EMPTY_TOOLTIP = "Vrátí seznam nulové délky, který neobsahuje žádné datové záznamy";
Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD = "seznam";
Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TOOLTIP = "Přidat, odebrat nebo změnit pořadí oddílů tohoto seznamu bloku.";
Blockly.Msg.LISTS_CREATE_WITH_INPUT_WITH = "vytvořit seznam s";
Blockly.Msg.LISTS_CREATE_WITH_ITEM_TOOLTIP = "Přidat položku do seznamu.";
Blockly.Msg.LISTS_CREATE_WITH_TOOLTIP = "Vytvoř seznam s libovolným počtem položek.";
Blockly.Msg.LISTS_GET_INDEX_FIRST = "první";
Blockly.Msg.LISTS_GET_INDEX_FROM_END = "# od konce";
Blockly.Msg.LISTS_GET_INDEX_FROM_START = "#";
Blockly.Msg.LISTS_GET_INDEX_GET = "získat";
Blockly.Msg.LISTS_GET_INDEX_GET_REMOVE = "získat a odstranit";
Blockly.Msg.LISTS_GET_INDEX_LAST = "poslední";
Blockly.Msg.LISTS_GET_INDEX_RANDOM = "náhodné";
Blockly.Msg.LISTS_GET_INDEX_REMOVE = "odstranit";
Blockly.Msg.LISTS_GET_INDEX_TAIL = ""; // untranslated
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FIRST = "Vrátí první položku v seznamu.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM_END = "Vrátí položku z určené pozice v seznamu. #1 je poslední položka.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM_START = "Vrátí položku z určené pozice v seznamu. #1 je první položka.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_LAST = "Vrátí poslední položku v seznamu.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_RANDOM = "Vrátí náhodnou položku ze seznamu.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FIRST = "Odstraní a vrátí první položku v seznamu.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM_END = "Odstraní a vrátí položku z určené pozice v seznamu. #1 je poslední položka.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM_START = "Odstraní a vrátí položku z určené pozice v seznamu. #1 je první položka.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_LAST = "Odstraní a vrátí poslední položku v seznamu.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_RANDOM = "Odstraní a vrátí náhodnou položku v seznamu.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FIRST = "Odstraní první položku v seznamu.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM_END = "Odstraní položku na konkrétním místu v seznamu. #1 je poslední položka.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM_START = "Odebere položku na konkrétním místě v seznamu. #1 je první položka.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_LAST = "Odstraní poslední položku v seznamu.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_RANDOM = "Odstraní náhodou položku v seznamu.";
Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_END = "do # od konce";
Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_START = "do #";
Blockly.Msg.LISTS_GET_SUBLIST_END_LAST = "jako poslední";
Blockly.Msg.LISTS_GET_SUBLIST_HELPURL = "https://code.google.com/p/blockly/wiki/Lists#Getting_a_sublist";
Blockly.Msg.LISTS_GET_SUBLIST_START_FIRST = "získat podseznam od první položky";
Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_END = "získat podseznam od # od konce";
Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_START = "získat podseznam od #";
Blockly.Msg.LISTS_GET_SUBLIST_TAIL = ""; // untranslated
Blockly.Msg.LISTS_GET_SUBLIST_TOOLTIP = "Vytvoří kopii určené části seznamu.";
Blockly.Msg.LISTS_INDEX_OF_FIRST = "najít první výskyt položky";
Blockly.Msg.LISTS_INDEX_OF_HELPURL = "https://code.google.com/p/blockly/wiki/Lists#Getting_Items_from_a_List"; // untranslated
Blockly.Msg.LISTS_INDEX_OF_LAST = "najít poslední výskyt položky";
Blockly.Msg.LISTS_INDEX_OF_TOOLTIP = "Returns the index of the first/last occurrence of the item in the list. Returns 0 if text is not found."; // untranslated
Blockly.Msg.LISTS_INLIST = "v seznamu";
Blockly.Msg.LISTS_IS_EMPTY_HELPURL = "https://code.google.com/p/blockly/wiki/Lists#is_empty"; // untranslated
Blockly.Msg.LISTS_IS_EMPTY_TITLE = "%1 je prázdné";
Blockly.Msg.LISTS_LENGTH_HELPURL = "https://code.google.com/p/blockly/wiki/Lists#length_of";
Blockly.Msg.LISTS_LENGTH_TITLE = "délka %1";
Blockly.Msg.LISTS_LENGTH_TOOLTIP = "Vrací počet položek v seznamu.";
Blockly.Msg.LISTS_REPEAT_HELPURL = "https://code.google.com/p/blockly/wiki/Lists#create_list_with";
Blockly.Msg.LISTS_REPEAT_TITLE = "vytvoř seznam s položkou %1 opakovanou %1 krát";
Blockly.Msg.LISTS_REPEAT_TOOLTIP = "Vytváří seznam obsahující danou hodnotu n-krát.";
Blockly.Msg.LISTS_SET_INDEX_HELPURL = "https://code.google.com/p/blockly/wiki/Lists#in_list_..._set"; // untranslated
Blockly.Msg.LISTS_SET_INDEX_INPUT_TO = "jako";
Blockly.Msg.LISTS_SET_INDEX_INSERT = "vložit na";
Blockly.Msg.LISTS_SET_INDEX_SET = "nastavit";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FIRST = "Vložit položku na začátek seznamu.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM_END = "Vloží položku na určenou pozici v seznamu. #1 je poslední položka.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM_START = "Vloží položku na určenou pozici v seznamu. #1 je první položka.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_LAST = "Připojí položku na konec seznamu.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_RANDOM = "Připojí položku náhodně do seznamu.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FIRST = "Nastaví první položku v seznamu.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM_END = "Nastaví položku na konkrétní místo v seznamu. #1 je poslední položka.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM_START = "Nastaví položku na konkrétní místo v seznamu. #1 je první položka.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_LAST = "Nastaví poslední položku v seznamu.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_RANDOM = "Nastaví náhodnou položku v seznamu.";
Blockly.Msg.LISTS_TOOLTIP = "Returns true if the list is empty."; // untranslated
Blockly.Msg.LOGIC_BOOLEAN_FALSE = "nepravda";
Blockly.Msg.LOGIC_BOOLEAN_HELPURL = "https://code.google.com/p/blockly/wiki/True_False"; // untranslated
Blockly.Msg.LOGIC_BOOLEAN_TOOLTIP = "Vrací pravda nebo nepravda.";
Blockly.Msg.LOGIC_BOOLEAN_TRUE = "pravda";
Blockly.Msg.LOGIC_COMPARE_HELPURL = "https://cs.wikipedia.org/wiki/Nerovnost_(matematika)";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_EQ = "Vrátí hodnotu pravda, pokud se oba vstupy rovnají jeden druhému.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GT = "Navrátí hodnotu pravda, pokud první vstup je větší než druhý vstup.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GTE = "Navrátí hodnotu pravda, pokud je první vstup větší a nebo rovný druhému vstupu.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LT = "Navrátí hodnotu pravda, pokud je první vstup menší než druhý vstup.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LTE = "Navrátí hodnotu pravda, pokud je první vstup menší a nebo rovný druhému vstupu.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_NEQ = "Vrátí hodnotu pravda, pokud se oba vstupy nerovnají sobě navzájem.";
Blockly.Msg.LOGIC_NEGATE_HELPURL = "https://code.google.com/p/blockly/wiki/Not"; // untranslated
Blockly.Msg.LOGIC_NEGATE_TITLE = "není %1";
Blockly.Msg.LOGIC_NEGATE_TOOLTIP = "Navrátí hodnotu pravda, pokud je vstup nepravda. Navrátí hodnotu nepravda, pokud je vstup pravda.";
Blockly.Msg.LOGIC_NULL = "nula";
Blockly.Msg.LOGIC_NULL_HELPURL = "https://en.wikipedia.org/wiki/Nullable_type"; // untranslated
Blockly.Msg.LOGIC_NULL_TOOLTIP = "Vrátí nulovou hodnotu";
Blockly.Msg.LOGIC_OPERATION_AND = "a";
Blockly.Msg.LOGIC_OPERATION_HELPURL = "https://code.google.com/p/blockly/wiki/And_Or"; // untranslated
Blockly.Msg.LOGIC_OPERATION_OR = "nebo";
Blockly.Msg.LOGIC_OPERATION_TOOLTIP_AND = "Vrátí hodnotu pravda, pokud oba dva vstupy jsou pravdivé.";
Blockly.Msg.LOGIC_OPERATION_TOOLTIP_OR = "Vrátí hodnotu pravda, pokud alespoň jeden ze vstupů má hodnotu pravda.";
Blockly.Msg.LOGIC_TERNARY_CONDITION = "test";
Blockly.Msg.LOGIC_TERNARY_HELPURL = "https://en.wikipedia.org/wiki/%3F:"; // untranslated
Blockly.Msg.LOGIC_TERNARY_IF_FALSE = "je-li nepravda";
Blockly.Msg.LOGIC_TERNARY_IF_TRUE = "je-li to pravda";
Blockly.Msg.LOGIC_TERNARY_TOOLTIP = "Zkontroluje podmínku v \"testu\". Když je podmínka pravda, vrátí hodnotu \"pokud pravda\"; v opačném případě vrátí hodnotu \"pokud nepravda\".";
Blockly.Msg.MATH_ADDITION_SYMBOL = "+"; // untranslated
Blockly.Msg.MATH_ARITHMETIC_HELPURL = "https://cs.wikipedia.org/wiki/Aritmetika";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_ADD = "Vrátí součet dvou čísel.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_DIVIDE = "Vrátí podíl dvou čísel.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MINUS = "Vrátí rozdíl dvou čísel.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MULTIPLY = "Vrátí součin dvou čísel.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_POWER = "Vrátí první číslo umocněné na druhé číslo.";
Blockly.Msg.MATH_CHANGE_HELPURL = "https://pt.wikipedia.org/wiki/Adi%C3%A7%C3%A3o";
Blockly.Msg.MATH_CHANGE_INPUT_BY = "od";
Blockly.Msg.MATH_CHANGE_TITLE_CHANGE = "změnit";
Blockly.Msg.MATH_CHANGE_TOOLTIP = "Přičti číslo k proměnné '%1'.";
Blockly.Msg.MATH_CONSTANT_HELPURL = "https://en.wikipedia.org/wiki/Mathematical_constant";
Blockly.Msg.MATH_CONSTANT_TOOLTIP = "Vraťte jednu z následujících konstant: π (3.141…), e (2.718…), φ (1.618…), sqrt(2) (1.414…), sqrt(½) (0.707…), or ∞ (infinity).";
Blockly.Msg.MATH_CONSTRAIN_HELPURL = "http://en.wikipedia.org/wiki/Clamping_%28graphics%29";
Blockly.Msg.MATH_CONSTRAIN_TITLE = "omez %1 na rozmezí od %2 do %3";
Blockly.Msg.MATH_CONSTRAIN_TOOLTIP = "Omezí číslo tak, aby bylo ve stanovených mezích (včetně).";
Blockly.Msg.MATH_DIVISION_SYMBOL = "÷";
Blockly.Msg.MATH_IS_DIVISIBLE_BY = "je dělitelné";
Blockly.Msg.MATH_IS_EVEN = "je sudé";
Blockly.Msg.MATH_IS_NEGATIVE = "je záporné";
Blockly.Msg.MATH_IS_ODD = "je liché";
Blockly.Msg.MATH_IS_POSITIVE = "je kladné";
Blockly.Msg.MATH_IS_PRIME = "je prvočíslo";
Blockly.Msg.MATH_IS_TOOLTIP = "Kontrola, zda je číslo sudé, liché, prvočíslo, celé, kladné, záporné nebo zda je dělitelné daným číslem. Vrací pravdu nebo nepravdu.";
Blockly.Msg.MATH_IS_WHOLE = "je celé";
Blockly.Msg.MATH_MODULO_HELPURL = "https://cs.wikipedia.org/wiki/Modul%C3%A1rn%C3%AD_aritmetika";
Blockly.Msg.MATH_MODULO_TITLE = "zbytek po dělení %1 ÷ %2";
Blockly.Msg.MATH_MODULO_TOOLTIP = "Vrátí zbytek po dělení dvou čísel.";
Blockly.Msg.MATH_MULTIPLICATION_SYMBOL = "×";
Blockly.Msg.MATH_NUMBER_HELPURL = "https://cs.wikipedia.org/wiki/Číslo";
Blockly.Msg.MATH_NUMBER_TOOLTIP = "Číslo.";
Blockly.Msg.MATH_ONLIST_HELPURL = ""; // untranslated
Blockly.Msg.MATH_ONLIST_OPERATOR_AVERAGE = "průměr v seznamu";
Blockly.Msg.MATH_ONLIST_OPERATOR_MAX = "největší v seznamu";
Blockly.Msg.MATH_ONLIST_OPERATOR_MEDIAN = "medián v seznamu";
Blockly.Msg.MATH_ONLIST_OPERATOR_MIN = "nejmenší v seznamu";
Blockly.Msg.MATH_ONLIST_OPERATOR_MODE = "modes of list"; // untranslated
Blockly.Msg.MATH_ONLIST_OPERATOR_RANDOM = "náhodná položka seznamu";
Blockly.Msg.MATH_ONLIST_OPERATOR_STD_DEV = "směrodatná odchylka ze seznamu";
Blockly.Msg.MATH_ONLIST_OPERATOR_SUM = "suma seznamu";
Blockly.Msg.MATH_ONLIST_TOOLTIP_AVERAGE = "Vrátí průměr (aritmetický průměr) číselných hodnot v seznamu.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MAX = "Vrátí největší číslo v seznamu.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MEDIAN = "Vrátí medián seznamu.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MIN = "Vrátí nejmenší číslo v seznamu.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MODE = "Vrátí seznam nejčastějších položek seznamu.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_RANDOM = "Vrátí náhodnou položku ze seznamu.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_STD_DEV = "Vrátí směrodatnou odchylku seznamu.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_SUM = "Vrátí součet všech čísel v seznamu.";
Blockly.Msg.MATH_POWER_SYMBOL = "^";
Blockly.Msg.MATH_RANDOM_FLOAT_HELPURL = "https://cs.wikipedia.org/wiki/Gener%C3%A1tor_n%C3%A1hodn%C3%BDch_%C4%8D%C3%ADsel";
Blockly.Msg.MATH_RANDOM_FLOAT_TITLE_RANDOM = "náhodné číslo mezi 0 (včetně) do 1";
Blockly.Msg.MATH_RANDOM_FLOAT_TOOLTIP = "Vrátí náhodné číslo mezi 0,0 (včetně) až 1,0";
Blockly.Msg.MATH_RANDOM_INT_HELPURL = "https://cs.wikipedia.org/wiki/Gener%C3%A1tor_n%C3%A1hodn%C3%BDch_%C4%8D%C3%ADsel";
Blockly.Msg.MATH_RANDOM_INT_TITLE = "náhodné celé číslo od %1 do %2";
Blockly.Msg.MATH_RANDOM_INT_TOOLTIP = "Vrací náhodné celé číslo mezi dvěma určenými mezemi, včetně mezních hodnot.";
Blockly.Msg.MATH_ROUND_HELPURL = "https://cs.wikipedia.org/wiki/Zaokrouhlení";
Blockly.Msg.MATH_ROUND_OPERATOR_ROUND = "zaokrouhlit";
Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDDOWN = "zaokrouhlit dolu";
Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDUP = "zaokrouhlit nahoru";
Blockly.Msg.MATH_ROUND_TOOLTIP = "Zaokrouhlit číslo nahoru nebo dolů.";
Blockly.Msg.MATH_SINGLE_HELPURL = "https://cs.wikipedia.org/wiki/Druhá_odmocnina";
Blockly.Msg.MATH_SINGLE_OP_ABSOLUTE = "absolutní";
Blockly.Msg.MATH_SINGLE_OP_ROOT = "druhá odmocnina";
Blockly.Msg.MATH_SINGLE_TOOLTIP_ABS = "Vrátí absolutní hodnotu čísla.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_EXP = "Vrátí mocninu čísla e.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_LN = "Vrátí přirozený logaritmus čísla.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_LOG10 = "Vrátí desítkový logaritmus čísla.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_NEG = "Vrátí zápornou hodnotu čísla.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_POW10 = "Vrátí mocninu čísla 10.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_ROOT = "Vrátí druhou odmocninu čísla.";
Blockly.Msg.MATH_SUBTRACTION_SYMBOL = "-";
Blockly.Msg.MATH_TRIG_ACOS = "acos";
Blockly.Msg.MATH_TRIG_ASIN = "arcsin";
Blockly.Msg.MATH_TRIG_ATAN = "arctan";
Blockly.Msg.MATH_TRIG_COS = "cos";
Blockly.Msg.MATH_TRIG_HELPURL = "https://cs.wikipedia.org/wiki/Goniometrická_funkce";
Blockly.Msg.MATH_TRIG_SIN = "sin";
Blockly.Msg.MATH_TRIG_TAN = "tan";
Blockly.Msg.MATH_TRIG_TOOLTIP_ACOS = "Vrátí arckosinus čísla.";
Blockly.Msg.MATH_TRIG_TOOLTIP_ASIN = "Vrátí arcsinus čísla.";
Blockly.Msg.MATH_TRIG_TOOLTIP_ATAN = "Vrátí arctangens čísla.";
Blockly.Msg.MATH_TRIG_TOOLTIP_COS = "Vrátí kosinus úhlu ve stupních.";
Blockly.Msg.MATH_TRIG_TOOLTIP_SIN = "Vrátí sinus úhlu ve stupních.";
Blockly.Msg.MATH_TRIG_TOOLTIP_TAN = "Vrátí tangens úhlu ve stupních.";
Blockly.Msg.NEW_VARIABLE = "Nová proměnná...";
Blockly.Msg.NEW_VARIABLE_TITLE = "Nový název proměnné:";
Blockly.Msg.ORDINAL_NUMBER_SUFFIX = ""; // untranslated
Blockly.Msg.PROCEDURES_BEFORE_PARAMS = "s:";
Blockly.Msg.PROCEDURES_CALLNORETURN_CALL = ""; // untranslated
Blockly.Msg.PROCEDURES_CALLNORETURN_HELPURL = "https://cs.wikipedia.org/wiki/Funkce_(programov%C3%A1n%C3%AD)";
Blockly.Msg.PROCEDURES_CALLNORETURN_TOOLTIP = "Spustí uživatelem definovanou funkci '%1'.";
Blockly.Msg.PROCEDURES_CALLRETURN_HELPURL = "https://cs.wikipedia.org/wiki/Funkce_(programov%C3%A1n%C3%AD)";
Blockly.Msg.PROCEDURES_CALLRETURN_TOOLTIP = "Spustí uživatelem definovanou funkci '%1' a použije její výstup.";
Blockly.Msg.PROCEDURES_CREATE_DO = "Vytvořit '%1'";
Blockly.Msg.PROCEDURES_DEFNORETURN_DO = ""; // untranslated
Blockly.Msg.PROCEDURES_DEFNORETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29"; // untranslated
Blockly.Msg.PROCEDURES_DEFNORETURN_PROCEDURE = "proveď něco";
Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE = "k provedení";
Blockly.Msg.PROCEDURES_DEFNORETURN_TOOLTIP = "Vytvořit funkci bez výstupu.";
Blockly.Msg.PROCEDURES_DEFRETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29"; // untranslated
Blockly.Msg.PROCEDURES_DEFRETURN_RETURN = "navrátit";
Blockly.Msg.PROCEDURES_DEFRETURN_TOOLTIP = "Vytvořit funkci s výstupem.";
Blockly.Msg.PROCEDURES_DEF_DUPLICATE_WARNING = "Upozornění: Tato funkce má duplicitní parametry.";
Blockly.Msg.PROCEDURES_HIGHLIGHT_DEF = "Zvýraznit definici funkce";
Blockly.Msg.PROCEDURES_IFRETURN_TOOLTIP = "Je-li hodnota pravda, pak vrátí druhou hodnotu.";
Blockly.Msg.PROCEDURES_IFRETURN_WARNING = "Varování: Tento blok může být použit pouze uvnitř definici funkce.";
Blockly.Msg.PROCEDURES_MUTATORARG_TITLE = "vstupní jméno:";
Blockly.Msg.PROCEDURES_MUTATORARG_TOOLTIP = "Add an input to the function."; // untranslated
Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TITLE = "vstupy";
Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TOOLTIP = "Add, remove, or reorder inputs to this function."; // untranslated
Blockly.Msg.REMOVE_COMMENT = "Odstranit komentář";
Blockly.Msg.RENAME_VARIABLE = "Přejmenovat proměnné...";
Blockly.Msg.RENAME_VARIABLE_TITLE = "Přejmenujte všechny proměnné '%1':";
Blockly.Msg.TEXT_APPEND_APPENDTEXT = "přidat text";
Blockly.Msg.TEXT_APPEND_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Text_modification"; // untranslated
Blockly.Msg.TEXT_APPEND_TO = "do";
Blockly.Msg.TEXT_APPEND_TOOLTIP = "Přidá určitý text k proměnné '%1'.";
Blockly.Msg.TEXT_CHANGECASE_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Adjusting_text_case";
Blockly.Msg.TEXT_CHANGECASE_OPERATOR_LOWERCASE = "na malá písmena";
Blockly.Msg.TEXT_CHANGECASE_OPERATOR_TITLECASE = "na Počáteční Velká Písmena";
Blockly.Msg.TEXT_CHANGECASE_OPERATOR_UPPERCASE = "na VELKÁ PÍSMENA";
Blockly.Msg.TEXT_CHANGECASE_TOOLTIP = "Vrátí kopii textu s jinou velikostí písmen.";
Blockly.Msg.TEXT_CHARAT_FIRST = "získat první písmeno";
Blockly.Msg.TEXT_CHARAT_FROM_END = "získat # písmeno od konce";
Blockly.Msg.TEXT_CHARAT_FROM_START = "získat písmeno #";
Blockly.Msg.TEXT_CHARAT_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Extracting_text"; // untranslated
Blockly.Msg.TEXT_CHARAT_INPUT_INTEXT = "v textu";
Blockly.Msg.TEXT_CHARAT_LAST = "získat poslední písmeno";
Blockly.Msg.TEXT_CHARAT_RANDOM = "získat náhodné písmeno";
Blockly.Msg.TEXT_CHARAT_TAIL = ""; // untranslated
Blockly.Msg.TEXT_CHARAT_TOOLTIP = "Získat písmeno na konkrétní pozici.";
Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TOOLTIP = "Přidat položku do textu.";
Blockly.Msg.TEXT_CREATE_JOIN_TITLE_JOIN = "spojit";
Blockly.Msg.TEXT_CREATE_JOIN_TOOLTIP = "Přidat, odebrat nebo změnit pořadí oddílů tohoto textového bloku.";
Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_END = "do # písmene od konce";
Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_START = "do písmene #";
Blockly.Msg.TEXT_GET_SUBSTRING_END_LAST = "do posledního písmene";
Blockly.Msg.TEXT_GET_SUBSTRING_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Extracting_a_region_of_text"; // untranslated
Blockly.Msg.TEXT_GET_SUBSTRING_INPUT_IN_TEXT = "v textu";
Blockly.Msg.TEXT_GET_SUBSTRING_START_FIRST = "získat podřetězec od prvního písmene";
Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_END = "získat podřetězec od písmene # od konce";
Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_START = "získat podřetězec od písmene #";
Blockly.Msg.TEXT_GET_SUBSTRING_TAIL = ""; // untranslated
Blockly.Msg.TEXT_GET_SUBSTRING_TOOLTIP = "Získat zadanou část textu.";
Blockly.Msg.TEXT_INDEXOF_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Finding_text"; // untranslated
Blockly.Msg.TEXT_INDEXOF_INPUT_INTEXT = "v textu";
Blockly.Msg.TEXT_INDEXOF_OPERATOR_FIRST = "najít první výskyt textu";
Blockly.Msg.TEXT_INDEXOF_OPERATOR_LAST = "najít poslední výskyt textu";
Blockly.Msg.TEXT_INDEXOF_TAIL = ""; // untranslated
Blockly.Msg.TEXT_INDEXOF_TOOLTIP = "Vrátí index prvního/posledního výskytu prvního textu v druhém textu. Pokud text není nalezen, vrátí hodnotu 0.";
Blockly.Msg.TEXT_ISEMPTY_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Checking_for_empty_text"; // untranslated
Blockly.Msg.TEXT_ISEMPTY_TITLE = "%1 je prázdný";
Blockly.Msg.TEXT_ISEMPTY_TOOLTIP = "Vrátí pravda pokud je zadaný text prázdný.";
Blockly.Msg.TEXT_JOIN_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Text_creation"; // untranslated
Blockly.Msg.TEXT_JOIN_TITLE_CREATEWITH = "vytvořit text s";
Blockly.Msg.TEXT_JOIN_TOOLTIP = "Vytvoří kousek textu spojením libovolného počtu položek.";
Blockly.Msg.TEXT_LENGTH_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Text_modification"; // untranslated
Blockly.Msg.TEXT_LENGTH_TITLE = "délka %1";
Blockly.Msg.TEXT_LENGTH_TOOLTIP = "Vrátí počet písmen (včetně mezer) v zadaném textu.";
Blockly.Msg.TEXT_PRINT_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Printing_text"; // untranslated
Blockly.Msg.TEXT_PRINT_TITLE = "tisk %1";
Blockly.Msg.TEXT_PRINT_TOOLTIP = "Tisk zadaného textu, čísla nebo jiné hodnoty.";
Blockly.Msg.TEXT_PROMPT_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Getting_input_from_the_user";
Blockly.Msg.TEXT_PROMPT_TOOLTIP_NUMBER = "Výzva pro uživatele k zadání čísla.";
Blockly.Msg.TEXT_PROMPT_TOOLTIP_TEXT = "Výzva pro uživatele k zadání nějakého textu.";
Blockly.Msg.TEXT_PROMPT_TYPE_NUMBER = "výzva k zadání čísla se zprávou";
Blockly.Msg.TEXT_PROMPT_TYPE_TEXT = "výzva k zadání textu se zprávou";
Blockly.Msg.TEXT_TEXT_HELPURL = "https://cs.wikipedia.org/wiki/Textov%C3%BD_%C5%99et%C4%9Bzec";
Blockly.Msg.TEXT_TEXT_TOOLTIP = "Písmeno, slovo nebo řádek textu.";
Blockly.Msg.TEXT_TRIM_HELPURL = "https://code.google.com/p/blockly/wiki/Text#Trimming_%28removing%29_spaces"; // untranslated
Blockly.Msg.TEXT_TRIM_OPERATOR_BOTH = "odstranit mezery z obou stran";
Blockly.Msg.TEXT_TRIM_OPERATOR_LEFT = "odstranit mezery z levé strany";
Blockly.Msg.TEXT_TRIM_OPERATOR_RIGHT = "odstranit mezery z pravé strany";
Blockly.Msg.TEXT_TRIM_TOOLTIP = "Vrátí kopii textu s odstraněnými mezerami z jednoho nebo obou konců.";
Blockly.Msg.VARIABLES_DEFAULT_NAME = "položka";
Blockly.Msg.VARIABLES_GET_CREATE_SET = "Vytvořit \"nastavit %1\"";
Blockly.Msg.VARIABLES_GET_HELPURL = "http://code.google.com/p/blockly/wiki/Variables#Get";
Blockly.Msg.VARIABLES_GET_TAIL = ""; // untranslated
Blockly.Msg.VARIABLES_GET_TITLE = ""; // untranslated
Blockly.Msg.VARIABLES_GET_TOOLTIP = "Vrátí hodnotu této proměnné.";
Blockly.Msg.VARIABLES_SET_CREATE_GET = "Vytvořit \"získat %1\"";
Blockly.Msg.VARIABLES_SET_HELPURL = "http://code.google.com/p/blockly/wiki/Variables#Set";
Blockly.Msg.VARIABLES_SET_TAIL = "na";
Blockly.Msg.VARIABLES_SET_TITLE = "nastavit";
Blockly.Msg.VARIABLES_SET_TOOLTIP = "Nastaví tuto proměnnou, aby se rovnala vstupu.";
Blockly.Msg.PROCEDURES_DEFRETURN_TITLE = Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE;
Blockly.Msg.LISTS_GET_SUBLIST_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.LISTS_SET_INDEX_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.PROCEDURES_DEFRETURN_PROCEDURE = Blockly.Msg.PROCEDURES_DEFNORETURN_PROCEDURE;
Blockly.Msg.VARIABLES_SET_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.LISTS_CREATE_WITH_ITEM_TITLE = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.MATH_CHANGE_TITLE_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.VARIABLES_GET_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.PROCEDURES_DEFRETURN_DO = Blockly.Msg.PROCEDURES_DEFNORETURN_DO;
Blockly.Msg.LISTS_GET_INDEX_HELPURL = Blockly.Msg.LISTS_INDEX_OF_HELPURL;
Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TITLE_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.CONTROLS_IF_MSG_THEN = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.LISTS_INDEX_OF_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.PROCEDURES_CALLRETURN_CALL = Blockly.Msg.PROCEDURES_CALLNORETURN_CALL;
Blockly.Msg.LISTS_GET_INDEX_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.CONTROLS_FOR_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.CONTROLS_FOREACH_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.CONTROLS_IF_IF_TITLE_IF = Blockly.Msg.CONTROLS_IF_MSG_IF;
Blockly.Msg.CONTROLS_WHILEUNTIL_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.CONTROLS_IF_ELSEIF_TITLE_ELSEIF = Blockly.Msg.CONTROLS_IF_MSG_ELSEIF;
Blockly.Msg.TEXT_APPEND_VARIABLE = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.CONTROLS_IF_ELSE_TITLE_ELSE = Blockly.Msg.CONTROLS_IF_MSG_ELSE; | RubyRios/Pet | public/js/blockly/msg/js/cs.js | JavaScript | mit | 29,842 |
var debug = require('ghost-ignition').debug('admin:serviceworker'),
path = require('path');
// Route: index
// Path: /ghost/sw.js|sw-registration.js
// Method: GET
module.exports = function adminController(req, res) {
debug('serviceworker called');
var sw = path.join(__dirname, '..', '..', '..', 'built', 'assets', 'sw.js'),
swr = path.join(__dirname, '..', '..', '..', 'built', 'assets', 'sw-registration.js'),
fileToSend = req.url === '/sw.js' ? sw : swr;
res.sendFile(fileToSend);
};
| chadwallacehart/cwh.com-ghost | versions/1.21.5/core/server/web/admin/serviceworker.js | JavaScript | mit | 523 |
// const MongoClient = require('mongodb').MongoClient;
const {MongoClient, ObjectID} = require('mongodb');
MongoClient.connect('mongodb://localhost:27017/TodoApp', (err, db) => {
if (err) {
return console.log('Unable to connect to MongoDB server');
}
console.log('Connected to MongoDB server');
// db.collection('Todos').findOneAndUpdate({
// _id: new ObjectID('57bc4b15b3b6a3801d8c47a2')
// }, {
// $set: {
// completed: true
// }
// }, {
// returnOriginal: false
// }).then((result) => {
// console.log(result);
// });
db.collection('Users').findOneAndUpdate({
_id: new ObjectID('57abbcf4fd13a094e481cf2c')
}, {
$set: {
name: 'Andrew'
},
$inc: {
age: 1
}
}, {
returnOriginal: false
}).then((result) => {
console.log(result);
});
// db.close();
});
| ajchaii/CloudDev | user-model/playground/mongodb-update.js | JavaScript | gpl-3.0 | 852 |
/**----------------------------------------------------------------------------------
* [ Title ] The common JS in System AccessControl.
* [ Invoke ] var jsAccessControl = new JSAccessControl("#ff0000","#ffffff","#eeeeee");
*----------------------------------------------------------------------------------*/
//Color Control
//For 1.onmouseout 2.onmouseover 3.onclick
function JSAccessControl(heightLightColor,darkLightColor,onMouseOverColor){
this.heightLightColor = heightLightColor;
this.darkLightColor = darkLightColor;
this.onMouseOverColor = onMouseOverColor;
//action onmouseout
this.actionOnmouseout =
function actionOnmouseout(){
var st = window.event.srcElement.parentElement;
if(st.style.backgroundColor == this.onMouseOverColor){
st.style.backgroundColor = this.darkLightColor;
}
}
//action onmouseover
this.actionOnmouseover =
function actionOnmouseover(){
var st = window.event.srcElement.parentElement;
if(st.style.backgroundColor == '' || st.style.backgroundColor == this.darkLightColor){
st.style.backgroundColor = this.onMouseOverColor;
}
}
// action if a row of the Table is clicked
// @head int: "Color Control" can't action the first "head" rows (COUNT) of the table.
// @tail int: "Color Control" can't action the last "tail" rows (COUNT) of the table.
this.actionOnclick =
function actionOnclick(head,tail){
var obj = window.event.srcElement.parentElement;
if(event.ctrlKey && window.event.keyCode == 0){
obj.style.backgroundColor = this.heightLightColor; //heightLight Color
}else{
var tableObj = obj.parentElement;
for(var i=head;i<(tableObj.rows.length - tail);i++){
tableObj.rows[i].style.backgroundColor = this.darkLightColor; //darkLight Color.
}
obj.style.backgroundColor = this.heightLightColor; //heightLight Color
}
}
this.setBackColor =
function setBackColor(e){
//if ( tableObj!==null && tableObj.rows!=null && tableObj.rows.length != null ){
if ( window.event.srcElement.parentElement == e )
{
var obj = window.event.srcElement.parentElement;
var tableObj = obj.parentElement;
for(var i=2;i<tableObj.rows.length;i++){
tableObj.rows[i].style.backgroundColor = this.darkLightColor; //darkLight Color.
}
obj.style.backgroundColor = this.heightLightColor; //heightLight Color
return true;
}
return false;
}
}
/**
* 当radio按钮被选中后:视觉效果改变
* @param obj - Object - the checkBox object
* @param darkLightColor - the checkBox isn't checked
* @param hightLightColor - the checkBox is checked
* */
function checkColorAction(obj,hightLightColor,darkLightColor) {
if(obj.parentElement.parentElement.style.backgroundColor==hightLightColor){
obj.parentElement.parentElement.style.backgroundColor=darkLightColor ;
}else{
obj.parentElement.parentElement.style.backgroundColor=hightLightColor;
}
}
/**函数组:----------------------------------------------------------------------------------------------
* -- 翻页工具栏控制函数
* @param formName:“翻页工具栏”所在的表单(form)
* @param actionUrl: “翻页工具栏”所在的页面 url地址
* */
function gotoHead(formName,actionUrl){ /*首页*/
var objForm = document.all(formName);
var vCurrentPage = objForm.currentPage.value;
if((parseInt(vCurrentPage)) > 1 ){
objForm.NextPage.value="1";
objForm.action= actionUrl + "?flag=1";
objForm.submit();
}
}
function gotoPre(formName,actionUrl){/*前一页*/
var objForm = document.all(formName);
var vCurrentPage = objForm.currentPage.value;
var vTotalPage = objForm.totalPage.value;
if((parseInt(vCurrentPage)) > 1){
objForm.NextPage.value=parseInt(vCurrentPage)-1;
objForm.action= actionUrl + "?flag=1";
objForm.submit();
}
}
function gotoNext(formName,actionUrl){/*下一页*/
var objForm = document.all(formName);
var vCurrentPage = objForm.currentPage.value;
var vTotalPage = objForm.totalPage.value;
if((parseInt(vCurrentPage)) < (parseInt(vTotalPage))){
objForm.NextPage.value=parseInt(vCurrentPage)+1;
objForm.action= actionUrl + "?flag=1";
objForm.submit();
}
}
function gotoTail(formName,actionUrl){/*尾页*/
var objForm = document.all(formName);
var vCurrentPage = objForm.currentPage.value;
var vTotalPage = objForm.totalPage.value;
if((parseInt(vCurrentPage)) < (parseInt(vTotalPage))){
objForm.NextPage.value=vTotalPage;
objForm.action= actionUrl + "?flag=1";
objForm.submit();
}
}
/*------翻页工具栏结束-------------------------------------------------------------------------------*/
/**
* Make the form's all elementes writable or diswritable
* @param theForm - the form Object you want to deal with
* @param isWritable - false: make the form's elementes diswritable,else writable.
* */
function isTheFormWritable(theForm,isWritable){
var elArr = theForm.elements; //elArr数组获得全部表单元素
for(var i = 0; i < elArr.length; i++)
with(elArr[i]){
try{
if (elArr[i].type=="text" || elArr[i].type=="file" || elArr[i].type =="password"){
if(isWritable == true){
elArr[i].readOnly = false;
}else{
elArr[i].readOnly = true;
}
}else if(elArr[i].type=="select-one"){
if(isWritable == true){
elArr[i].disabled = false;
}else{
elArr[i].disabled = true;
}
}
} catch(e) {}
}
}
function goto(formName,actionUrl){/*下一页*/
//var toPage = "2";
var toPage = document.getElementById('gotoPage').value;
if (!(toPage.match(/[0-9]/)))
{
alert("页数必须为数字");
}
else{
var objForm = document.all(formName);
var vCurrentPage = objForm.currentPage.value;
var vTotalPage = objForm.totalPage.value;
if((parseInt(toPage)) < (parseInt(vTotalPage)+1) && (parseInt(toPage)) > 0){
objForm.NextPage.value=toPage;
objForm.action= actionUrl + "?flag=1";
objForm.submit();
}
}
}
//删除总按钮行为
function checkAll(totalCheck,checkName){
var selectAll = document.getElementsByName(totalCheck);
var o = document.getElementsByName(checkName);
if(selectAll[0].checked==true){
for (var i=0; i<o.length; i++){
if(!o[i].disabled){
o[i].checked=true;
}
}
}else{
for (var i=0; i<o.length; i++){
o[i].checked=false;
}
}
}
//各个删除按钮行为
function checkOne(totalCheck,checkName){
var selectAll = document.getElementsByName(totalCheck);
var o = document.getElementsByName(checkName);
var cbs = true;
for (var i=0;i<o.length;i++){
if(!o[i].disabled){
if (o[i].checked==false){
cbs=false;
}
}
}
if(cbs){
selectAll[0].checked=true;
}else{
selectAll[0].checked=false;
}
} | tzou24/BPS | BPS/WebRoot/sysmanager/user/common.js | JavaScript | apache-2.0 | 8,006 |
(function() {
window.WallTime || (window.WallTime = {});
window.WallTime.data = {
rules: {"CR":[{"name":"CR","_from":"1979","_to":"1980","type":"-","in":"Feb","on":"lastSun","at":"0:00","_save":"1:00","letter":"D"},{"name":"CR","_from":"1979","_to":"1980","type":"-","in":"Jun","on":"Sun>=1","at":"0:00","_save":"0","letter":"S"},{"name":"CR","_from":"1991","_to":"1992","type":"-","in":"Jan","on":"Sat>=15","at":"0:00","_save":"1:00","letter":"D"},{"name":"CR","_from":"1991","_to":"only","type":"-","in":"Jul","on":"1","at":"0:00","_save":"0","letter":"S"},{"name":"CR","_from":"1992","_to":"only","type":"-","in":"Mar","on":"15","at":"0:00","_save":"0","letter":"S"}]},
zones: {"America/Costa_Rica":[{"name":"America/Costa_Rica","_offset":"-5:36:20","_rule":"-","format":"LMT","_until":"1890"},{"name":"America/Costa_Rica","_offset":"-5:36:20","_rule":"-","format":"SJMT","_until":"1921 Jan 15"},{"name":"America/Costa_Rica","_offset":"-6:00","_rule":"CR","format":"C%sT","_until":""}]}
};
window.WallTime.autoinit = true;
}).call(this); | DebalinaDey/AuraDevelopDeb | aura-resources/src/main/resources/aura/resources/walltime-js/olson/walltime-data_America-Costa_Rica.js | JavaScript | apache-2.0 | 1,072 |
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule writeRelayQueryPayload
*
* @typechecks
*/
/**
* @internal
*
* Traverses a query and payload in parallel, writing the results into the
* store.
*/
'use strict';
var RelayNodeInterface = require('./RelayNodeInterface');
var RelayProfiler = require('./RelayProfiler');
var RelayQueryPath = require('./RelayQueryPath');
function writeRelayQueryPayload(writer, query, payload) {
var store = writer.getRecordStore();
var path = new RelayQueryPath(query);
RelayNodeInterface.getResultsFromPayload(store, query, payload).forEach(function (_ref) {
var dataID = _ref.dataID;
var result = _ref.result;
writer.writePayload(query, dataID, result, path);
});
}
module.exports = RelayProfiler.instrument('writeRelayQueryPayload', writeRelayQueryPayload); | chandu0101/sri-relay | relay-mobile-examples/lib/writeRelayQueryPayload.js | JavaScript | apache-2.0 | 1,094 |
var MenuBuilder;
var builder = require("menu-builder");
module.exports = MenuBuilder = builder.extend({
buildDOM: function() {
this.on("new:node", this.buildNode);
this.on("new:button", this.buildButton);
this.on("new:menu", this.buildMenu);
return builder.prototype.buildDOM.call(this);
},
buildNode: function(li) {
if ((this.g != null)) {
return li.style.lineHeight = this.g.menuconfig.get("menuItemLineHeight");
}
},
buildButton: function(btn) {
if ((this.g != null)) {
btn.style.fontSize = this.g.menuconfig.get("menuFontsize");
btn.style.marginLeft = this.g.menuconfig.get("menuMarginLeft");
return btn.style.padding = this.g.menuconfig.get("menuPadding");
}
},
buildMenu: function(menu) {
if ((this.g != null)) {
return menu.style.fontSize = this.g.menuconfig.get("menuItemFontsize");
}
}
});
| maovt/p3_web | public/js/msa/src/menu/menubuilder.js | JavaScript | mit | 936 |
/**
* (c) 2010-2017 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
import H from './Globals.js';
import './Utilities.js';
import './Series.js';
import './SvgRenderer.js';
import onSeriesMixin from '../mixins/on-series.js';
var addEvent = H.addEvent,
each = H.each,
merge = H.merge,
noop = H.noop,
Renderer = H.Renderer,
Series = H.Series,
seriesType = H.seriesType,
SVGRenderer = H.SVGRenderer,
TrackerMixin = H.TrackerMixin,
VMLRenderer = H.VMLRenderer,
symbols = SVGRenderer.prototype.symbols;
/**
* The Flags series.
*
* @constructor seriesTypes.flags
* @augments seriesTypes.column
*/
/**
* Flags are used to mark events in stock charts. They can be added on the
* timeline, or attached to a specific series.
*
* @sample stock/demo/flags-general/ Flags on a line series
* @extends {plotOptions.column}
* @excluding animation,borderColor,borderRadius,borderWidth,colorByPoint,
* dataGrouping,pointPadding,pointWidth,turboThreshold
* @product highstock
* @optionparent plotOptions.flags
*/
seriesType('flags', 'column', {
/**
* In case the flag is placed on a series, on what point key to place
* it. Line and columns have one key, `y`. In range or OHLC-type series,
* however, the flag can optionally be placed on the `open`, `high`,
* `low` or `close` key.
*
* @validvalue ["y", "open", "high", "low", "close"]
* @type {String}
* @sample {highstock} stock/plotoptions/flags-onkey/
* Range series, flag on high
* @default y
* @since 4.2.2
* @product highstock
* @apioption plotOptions.flags.onKey
*/
/**
* The id of the series that the flags should be drawn on. If no id
* is given, the flags are drawn on the x axis.
*
* @type {String}
* @sample {highstock} stock/plotoptions/flags/
* Flags on series and on x axis
* @default undefined
* @product highstock
* @apioption plotOptions.flags.onSeries
*/
pointRange: 0, // #673
/**
* Whether the flags are allowed to overlap sideways. If `false`, the flags
* are moved sideways using an algorithm that seeks to place every flag as
* close as possible to its original position.
*
* @sample {highstock} stock/plotoptions/flags-allowoverlapx
* Allow sideways overlap
* @since 6.0.4
*/
allowOverlapX: false,
/**
* The shape of the marker. Can be one of "flag", "circlepin", "squarepin",
* or an image of the format `url(/path-to-image.jpg)`. Individual
* shapes can also be set for each point.
*
* @validvalue ["flag", "circlepin", "squarepin"]
* @sample {highstock} stock/plotoptions/flags/ Different shapes
* @product highstock
*/
shape: 'flag',
/**
* When multiple flags in the same series fall on the same value, this
* number determines the vertical offset between them.
*
* @sample {highstock} stock/plotoptions/flags-stackdistance/
* A greater stack distance
* @product highstock
*/
stackDistance: 12,
/**
* Text alignment for the text inside the flag.
*
* @validvalue ["left", "center", "right"]
* @since 5.0.0
* @product highstock
*/
textAlign: 'center',
/**
* Specific tooltip options for flag series. Flag series tooltips are
* different from most other types in that a flag doesn't have a data
* value, so the tooltip rather displays the `text` option for each
* point.
*
* @type {Object}
* @extends plotOptions.series.tooltip
* @excluding changeDecimals,valueDecimals,valuePrefix,valueSuffix
* @product highstock
*/
tooltip: {
pointFormat: '{point.text}<br/>'
},
threshold: null,
/**
* The text to display on each flag. This can be defined on series level,
* or individually for each point. Defaults to `"A"`.
*
* @type {String}
* @default A
* @product highstock
* @apioption plotOptions.flags.title
*/
/**
* The y position of the top left corner of the flag relative to either
* the series (if onSeries is defined), or the x axis. Defaults to
* `-30`.
*
* @product highstock
*/
y: -30,
/**
* Whether to use HTML to render the flag texts. Using HTML allows for
* advanced formatting, images and reliable bi-directional text rendering.
* Note that exported images won't respect the HTML, and that HTML
* won't respect Z-index settings.
*
* @type {Boolean}
* @default false
* @since 1.3
* @product highstock
* @apioption plotOptions.flags.useHTML
*/
/**
* Fixed width of the flag's shape. By default, width is autocalculated
* according to the flag's title.
*
* @type {Number}
* @default undefined
* @product highstock
* @sample {highstock} stock/demo/flags-shapes/ Flags with fixed width
* @apioption plotOptions.flags.width
*/
/**
* Fixed height of the flag's shape. By default, height is autocalculated
* according to the flag's title.
*
* @type {Number}
* @default undefined
* @product highstock
* @apioption plotOptions.flags.height
*/
/**
* The fill color for the flags.
*
* @type {Color}
* @default #ffffff
* @product highstock
*/
fillColor: '#ffffff',
/**
* The color of the line/border of the flag.
*
* In styled mode, the stroke is set in the
* `.highcharts-flag-series.highcharts-point` rule.
*
* @type {Color}
* @default #000000
* @product highstock
* @apioption plotOptions.flags.lineColor
*/
/**
* The pixel width of the flag's line/border.
*
* @product highstock
*/
lineWidth: 1,
states: {
/**
* @extends plotOptions.column.states.hover
* @product highstock
*/
hover: {
/**
* The color of the line/border of the flag.
*
* @type {Color}
* @default #000000
* @product highstock
*/
lineColor: '#000000',
/**
* The fill or background color of the flag.
*
* @type {Color}
* @default #ccd6eb
* @product highstock
*/
fillColor: '#ccd6eb'
}
},
/**
* The text styles of the flag.
*
* In styled mode, the styles are set in the
* `.highcharts-flag-series .highcharts-point` rule.
*
* @type {CSSObject}
* @default { "fontSize": "11px", "fontWeight": "bold" }
* @product highstock
*/
style: {
fontSize: '11px',
fontWeight: 'bold'
}
}, /** @lends seriesTypes.flags.prototype */ {
sorted: false,
noSharedTooltip: true,
allowDG: false,
takeOrdinalPosition: false, // #1074
trackerGroups: ['markerGroup'],
forceCrop: true,
/**
* Inherit the initialization from base Series.
*/
init: Series.prototype.init,
/**
* Get presentational attributes
*/
pointAttribs: function (point, state) {
var options = this.options,
color = (point && point.color) || this.color,
lineColor = options.lineColor,
lineWidth = (point && point.lineWidth),
fill = (point && point.fillColor) || options.fillColor;
if (state) {
fill = options.states[state].fillColor;
lineColor = options.states[state].lineColor;
lineWidth = options.states[state].lineWidth;
}
return {
'fill': fill || color,
'stroke': lineColor || color,
'stroke-width': lineWidth || options.lineWidth || 0
};
},
translate: onSeriesMixin.translate,
getPlotBox: onSeriesMixin.getPlotBox,
/**
* Draw the markers
*/
drawPoints: function () {
var series = this,
points = series.points,
chart = series.chart,
renderer = chart.renderer,
plotX,
plotY,
inverted = chart.inverted,
options = series.options,
optionsY = options.y,
shape,
i,
point,
graphic,
stackIndex,
anchorY,
attribs,
outsideRight,
yAxis = series.yAxis,
boxesMap = {},
boxes = [];
i = points.length;
while (i--) {
point = points[i];
outsideRight =
(inverted ? point.plotY : point.plotX) > series.xAxis.len;
plotX = point.plotX;
stackIndex = point.stackIndex;
shape = point.options.shape || options.shape;
plotY = point.plotY;
if (plotY !== undefined) {
plotY = point.plotY + optionsY -
(
stackIndex !== undefined &&
stackIndex * options.stackDistance
);
}
// skip connectors for higher level stacked points
point.anchorX = stackIndex ? undefined : point.plotX;
anchorY = stackIndex ? undefined : point.plotY;
graphic = point.graphic;
// Only draw the point if y is defined and the flag is within
// the visible area
if (plotY !== undefined && plotX >= 0 && !outsideRight) {
// Create the flag
if (!graphic) {
graphic = point.graphic = renderer.label(
'',
null,
null,
shape,
null,
null,
options.useHTML
)
.attr(series.pointAttribs(point))
.css(merge(options.style, point.style))
.attr({
align: shape === 'flag' ? 'left' : 'center',
width: options.width,
height: options.height,
'text-align': options.textAlign
})
.addClass('highcharts-point')
.add(series.markerGroup);
// Add reference to the point for tracker (#6303)
if (point.graphic.div) {
point.graphic.div.point = point;
}
graphic.shadow(options.shadow);
graphic.isNew = true;
}
if (plotX > 0) { // #3119
plotX -= graphic.strokeWidth() % 2; // #4285
}
// Plant the flag
attribs = {
y: plotY,
anchorY: anchorY
};
if (options.allowOverlapX) {
attribs.x = plotX;
attribs.anchorX = point.anchorX;
}
graphic.attr({
text: point.options.title || options.title || 'A'
})[graphic.isNew ? 'attr' : 'animate'](attribs);
// Rig for the distribute function
if (!options.allowOverlapX) {
if (!boxesMap[point.plotX]) {
boxesMap[point.plotX] = {
align: 0,
size: graphic.width,
target: plotX,
anchorX: plotX
};
} else {
boxesMap[point.plotX].size = Math.max(
boxesMap[point.plotX].size,
graphic.width
);
}
}
// Set the tooltip anchor position
point.tooltipPos = [
plotX,
plotY + yAxis.pos - chart.plotTop
]; // #6327
} else if (graphic) {
point.graphic = graphic.destroy();
}
}
// Handle X-dimension overlapping
if (!options.allowOverlapX) {
H.objectEach(boxesMap, function (box) {
box.plotX = box.anchorX;
boxes.push(box);
});
H.distribute(boxes, inverted ? yAxis.len : this.xAxis.len, 100);
each(points, function (point) {
var box = point.graphic && boxesMap[point.plotX];
if (box) {
point.graphic[point.graphic.isNew ? 'attr' : 'animate']({
x: box.pos,
anchorX: point.anchorX
});
// Hide flag when its box position is not specified (#8573)
if (!box.pos) {
point.graphic.attr({
x: -9999,
anchorX: -9999
});
point.graphic.isNew = true;
} else {
point.graphic.isNew = false;
}
}
});
}
// Might be a mix of SVG and HTML and we need events for both (#6303)
if (options.useHTML) {
H.wrap(series.markerGroup, 'on', function (proceed) {
return H.SVGElement.prototype.on.apply(
// for HTML
proceed.apply(this, [].slice.call(arguments, 1)),
// and for SVG
[].slice.call(arguments, 1));
});
}
},
/**
* Extend the column trackers with listeners to expand and contract stacks
*/
drawTracker: function () {
var series = this,
points = series.points;
TrackerMixin.drawTrackerPoint.apply(this);
/**
* Bring each stacked flag up on mouse over, this allows readability
* of vertically stacked elements as well as tight points on
* the x axis. #1924.
*/
each(points, function (point) {
var graphic = point.graphic;
if (graphic) {
addEvent(graphic.element, 'mouseover', function () {
// Raise this point
if (point.stackIndex > 0 && !point.raised) {
point._y = graphic.y;
graphic.attr({
y: point._y - 8
});
point.raised = true;
}
// Revert other raised points
each(points, function (otherPoint) {
if (
otherPoint !== point &&
otherPoint.raised &&
otherPoint.graphic
) {
otherPoint.graphic.attr({
y: otherPoint._y
});
otherPoint.raised = false;
}
});
});
}
});
},
// Disable animation, but keep clipping (#8546):
animate: function (init) {
if (init) {
this.setClip();
} else {
this.animate = null;
}
},
setClip: function () {
Series.prototype.setClip.apply(this, arguments);
if (this.options.clip !== false && this.sharedClipKey) {
this.markerGroup.clip(this.chart[this.sharedClipKey]);
}
},
buildKDTree: noop,
/**
* Don't invert the flag marker group (#4960)
*/
invertGroups: noop
});
// create the flag icon with anchor
symbols.flag = function (x, y, w, h, options) {
var anchorX = (options && options.anchorX) || x,
anchorY = (options && options.anchorY) || y;
return symbols.circle(anchorX - 1, anchorY - 1, 2, 2).concat(
[
'M', anchorX, anchorY,
'L', x, y + h,
x, y,
x + w, y,
x + w, y + h,
x, y + h,
'Z'
]
);
};
/*
* Create the circlepin and squarepin icons with anchor
*/
function createPinSymbol(shape) {
symbols[shape + 'pin'] = function (x, y, w, h, options) {
var anchorX = options && options.anchorX,
anchorY = options && options.anchorY,
path,
labelTopOrBottomY;
// For single-letter flags, make sure circular flags are not taller
// than their width
if (shape === 'circle' && h > w) {
x -= Math.round((h - w) / 2);
w = h;
}
path = symbols[shape](x, y, w, h);
if (anchorX && anchorY) {
/**
* If the label is below the anchor, draw the connecting line
* from the top edge of the label
* otherwise start drawing from the bottom edge
*/
labelTopOrBottomY = (y > anchorY) ? y : y + h;
path.push(
'M',
shape === 'circle' ? path[1] - path[4] : path[1] + path[4] / 2,
labelTopOrBottomY,
'L',
anchorX,
anchorY
);
path = path.concat(
symbols.circle(anchorX - 1, anchorY - 1, 2, 2)
);
}
return path;
};
}
createPinSymbol('circle');
createPinSymbol('square');
/**
* The symbol callbacks are generated on the SVGRenderer object in all browsers.
* Even VML browsers need this in order to generate shapes in export. Now share
* them with the VMLRenderer.
*/
if (Renderer === VMLRenderer) {
each(['flag', 'circlepin', 'squarepin'], function (shape) {
VMLRenderer.prototype.symbols[shape] = symbols[shape];
});
}
/**
* A `flags` series. If the [type](#series.flags.type) option is not
* specified, it is inherited from [chart.type](#chart.type).
*
* @type {Object}
* @extends series,plotOptions.flags
* @excluding dataParser,dataURL
* @product highstock
* @apioption series.flags
*/
/**
* An array of data points for the series. For the `flags` series type,
* points can be given in the following ways:
*
* 1. An array of objects with named values. The following snippet shows only a
* few settings, see the complete options set below. If the total number of data
* points exceeds the series' [turboThreshold](#series.flags.turboThreshold),
* this option is not available.
*
* ```js
* data: [{
* x: 1,
* title: "A",
* text: "First event"
* }, {
* x: 1,
* title: "B",
* text: "Second event"
* }]</pre>
*
* @type {Array<Object>}
* @extends series.line.data
* @excluding y,dataLabels,marker,name
* @product highstock
* @apioption series.flags.data
*/
/**
* The fill color of an individual flag. By default it inherits from
* the series color.
*
* @type {Color}
* @product highstock
* @apioption series.flags.data.fillColor
*/
/**
* The longer text to be shown in the flag's tooltip.
*
* @type {String}
* @product highstock
* @apioption series.flags.data.text
*/
/**
* The short text to be shown on the flag.
*
* @type {String}
* @product highstock
* @apioption series.flags.data.title
*/
| seogi1004/cdnjs | ajax/libs/highcharts/6.1.4/es-modules/parts/FlagsSeries.js | JavaScript | mit | 19,942 |
/*
Language: JSON
Description: JSON (JavaScript Object Notation) is a lightweight data-interchange format.
Author: Ivan Sagalaev <maniac@softwaremaniacs.org>
Website: http://www.json.org
Category: common, protocols
*/
function json(hljs) {
const LITERALS = {
literal: 'true false null'
};
const ALLOWED_COMMENTS = [
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE
];
const TYPES = [
hljs.QUOTE_STRING_MODE,
hljs.C_NUMBER_MODE
];
const VALUE_CONTAINER = {
end: ',',
endsWithParent: true,
excludeEnd: true,
contains: TYPES,
keywords: LITERALS
};
const OBJECT = {
begin: /\{/,
end: /\}/,
contains: [
{
className: 'attr',
begin: /"/,
end: /"/,
contains: [hljs.BACKSLASH_ESCAPE],
illegal: '\\n'
},
hljs.inherit(VALUE_CONTAINER, {
begin: /:/
})
].concat(ALLOWED_COMMENTS),
illegal: '\\S'
};
const ARRAY = {
begin: '\\[',
end: '\\]',
contains: [hljs.inherit(VALUE_CONTAINER)], // inherit is a workaround for a bug that makes shared modes with endsWithParent compile only the ending of one of the parents
illegal: '\\S'
};
TYPES.push(OBJECT, ARRAY);
ALLOWED_COMMENTS.forEach(function(rule) {
TYPES.push(rule);
});
return {
name: 'JSON',
contains: TYPES,
keywords: LITERALS,
illegal: '\\S'
};
}
module.exports = json;
| ealbertos/dotfiles | vscode.symlink/extensions/bierner.markdown-preview-github-styles-0.2.0/node_modules/highlight.js/lib/languages/json.js | JavaScript | mit | 1,417 |
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
/**
* The copyright in this software is being made available under the BSD License,
* included below. This software may be subject to other third party and contributor
* rights, including patent rights, and no such rights are granted under this license.
*
* Copyright (c) 2013, Dash Industry Forum.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
* * Neither the name of Dash Industry Forum nor the names of its
* contributors may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @class
* @ignore
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var EventsBase = (function () {
function EventsBase() {
_classCallCheck(this, EventsBase);
}
_createClass(EventsBase, [{
key: 'extend',
value: function extend(events, config) {
if (!events) return;
var override = config ? config.override : false;
var publicOnly = config ? config.publicOnly : false;
for (var evt in events) {
if (!events.hasOwnProperty(evt) || this[evt] && !override) continue;
if (publicOnly && events[evt].indexOf('public_') === -1) continue;
this[evt] = events[evt];
}
}
}]);
return EventsBase;
})();
exports['default'] = EventsBase;
module.exports = exports['default'];
},{}],2:[function(_dereq_,module,exports){
/**
* The copyright in this software is being made available under the BSD License,
* included below. This software may be subject to other third party and contributor
* rights, including patent rights, and no such rights are granted under this license.
*
* Copyright (c) 2013, Dash Industry Forum.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
* * Neither the name of Dash Industry Forum nor the names of its
* contributors may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _coreEventsEventsBase = _dereq_(1);
var _coreEventsEventsBase2 = _interopRequireDefault(_coreEventsEventsBase);
var MssEvents = (function (_EventsBase) {
_inherits(MssEvents, _EventsBase);
function MssEvents() {
_classCallCheck(this, MssEvents);
_get(Object.getPrototypeOf(MssEvents.prototype), 'constructor', this).call(this);
this.FRAGMENT_INFO_LOADING_COMPLETED = 'fragmentInfoLoadingCompleted';
}
return MssEvents;
})(_coreEventsEventsBase2['default']);
var mssEvents = new MssEvents();
exports['default'] = mssEvents;
module.exports = exports['default'];
},{"1":1}],3:[function(_dereq_,module,exports){
/**
* The copyright in this software is being made available under the BSD License,
* included below. This software may be subject to other third party and contributor
* rights, including patent rights, and no such rights are granted under this license.
*
* Copyright (c) 2013, Dash Industry Forum.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
* * Neither the name of Dash Industry Forum nor the names of its
* contributors may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _MssEvents = _dereq_(2);
var _MssEvents2 = _interopRequireDefault(_MssEvents);
var _MssFragmentMoofProcessor = _dereq_(4);
var _MssFragmentMoofProcessor2 = _interopRequireDefault(_MssFragmentMoofProcessor);
function MssFragmentInfoController(config) {
config = config || {};
var context = this.context;
var instance = undefined;
var fragmentModel = undefined;
var indexHandler = undefined;
var started = undefined;
var type = undefined;
var bufferTimeout = undefined;
var _fragmentInfoTime = undefined;
var startFragmentInfoDate = undefined;
var startTimeStampValue = undefined;
var deltaTime = undefined;
var segmentDuration = undefined;
var streamProcessor = config.streamProcessor;
var eventBus = config.eventBus;
var metricsModel = config.metricsModel;
var playbackController = config.playbackController;
var ISOBoxer = config.ISOBoxer;
var log = config.log;
var controllerType = 'MssFragmentInfoController';
function setup() {}
function initialize() {
started = false;
startFragmentInfoDate = null;
startTimeStampValue = null;
deltaTime = 0;
segmentDuration = NaN;
// register to stream processor as external controller
streamProcessor.registerExternalController(instance);
type = streamProcessor.getType();
fragmentModel = streamProcessor.getFragmentModel();
indexHandler = streamProcessor.getIndexHandler();
}
function getCurrentRepresentation() {
var representationController = streamProcessor.getRepresentationController();
var representation = representationController.getCurrentRepresentation();
return representation;
}
function sendRequest(request) {
fragmentModel.executeRequest(request);
}
function asFragmentInfoRequest(request) {
if (request && request.url) {
request.url = request.url.replace('Fragments', 'FragmentInfo');
request.type = 'FragmentInfoSegment';
}
return request;
}
function onFragmentRequest(request) {
// Check if current request signals end of stream
if (request !== null && request.action === request.ACTION_COMPLETE) {
doStop();
return;
}
if (request !== null) {
_fragmentInfoTime = request.startTime + request.duration;
request = asFragmentInfoRequest(request);
if (streamProcessor.getFragmentModel().isFragmentLoadedOrPending(request)) {
request = indexHandler.getNextSegmentRequest(getCurrentRepresentation());
onFragmentRequest(request);
return;
}
log('[FragmentInfoController][' + type + '] onFragmentRequest ' + request.url);
// Download the fragment info segment
sendRequest(request);
} else {
// No more fragment in current list
log('[FragmentInfoController][' + type + '] bufferFragmentInfo failed');
}
}
function bufferFragmentInfo() {
var segmentTime;
// Check if running state
if (!started) {
return;
}
log('[FragmentInfoController][' + type + '] Start buffering process...');
// Get next segment time
segmentTime = _fragmentInfoTime;
log('[FragmentInfoController][' + type + '] loadNextFragment for time: ' + segmentTime);
var representation = getCurrentRepresentation();
var request = indexHandler.getSegmentRequestForTime(representation, segmentTime);
onFragmentRequest(request);
}
function delayLoadNextFragmentInfo(delay) {
var delayMs = Math.round(Math.min(delay * 1000, 2000));
log('[FragmentInfoController][' + type + '] Check buffer delta = ' + delayMs + ' ms');
clearTimeout(bufferTimeout);
bufferTimeout = setTimeout(function () {
bufferTimeout = null;
bufferFragmentInfo();
}, delayMs);
}
function onFragmentInfoLoadedCompleted(e) {
if (e.streamProcessor !== streamProcessor) {
return;
}
var request = e.fragmentInfo.request;
var deltaDate = undefined,
deltaTimeStamp = undefined;
if (!e.fragmentInfo.response) {
log('[FragmentInfoController][' + type + '] ERROR loading ', request.url);
return;
}
segmentDuration = request.duration;
log('[FragmentInfoController][' + type + '] FragmentInfo loaded ', request.url);
try {
// update segment list
var mssFragmentMoofProcessor = (0, _MssFragmentMoofProcessor2['default'])(context).create({
metricsModel: metricsModel,
playbackController: playbackController,
ISOBoxer: ISOBoxer,
log: log
});
mssFragmentMoofProcessor.updateSegmentList(e.fragmentInfo, streamProcessor);
deltaDate = (new Date().getTime() - startFragmentInfoDate) / 1000;
deltaTimeStamp = _fragmentInfoTime + segmentDuration - startTimeStampValue;
deltaTime = deltaTimeStamp - deltaDate > 0 ? deltaTimeStamp - deltaDate : 0;
delayLoadNextFragmentInfo(deltaTime);
} catch (e) {
log('[FragmentInfoController][' + type + '] ERROR - Internal error while processing fragment info segment ');
}
}
function startPlayback() {
if (!started) {
return;
}
startFragmentInfoDate = new Date().getTime();
startTimeStampValue = _fragmentInfoTime;
log('[FragmentInfoController][' + type + '] startPlayback');
// Start buffering process
bufferFragmentInfo.call(this);
}
function doStart() {
var segments = undefined;
if (started === true) {
return;
}
eventBus.on(_MssEvents2['default'].FRAGMENT_INFO_LOADING_COMPLETED, onFragmentInfoLoadedCompleted, instance);
started = true;
log('[FragmentInfoController][' + type + '] START');
var representation = getCurrentRepresentation();
segments = representation.segments;
if (segments && segments.length > 0) {
_fragmentInfoTime = segments[segments.length - 1].presentationStartTime - segments[segments.length - 1].duration;
startPlayback();
} else {
indexHandler.updateSegmentList(representation);
segments = representation.segments;
if (segments && segments.length > 0) {
_fragmentInfoTime = segments[segments.length - 1].presentationStartTime - segments[segments.length - 1].duration;
}
startPlayback();
}
}
function doStop() {
if (!started) {
return;
}
log('[FragmentInfoController][' + type + '] STOP');
eventBus.off(_MssEvents2['default'].FRAGMENT_INFO_LOADING_COMPLETED, onFragmentInfoLoadedCompleted, instance);
// Stop buffering process
clearTimeout(bufferTimeout);
started = false;
startFragmentInfoDate = null;
startTimeStampValue = null;
}
function reset() {
doStop();
streamProcessor.unregisterExternalController(instance);
}
instance = {
initialize: initialize,
controllerType: controllerType,
start: doStart,
reset: reset
};
setup();
return instance;
}
MssFragmentInfoController.__dashjs_factory_name = 'MssFragmentInfoController';
exports['default'] = dashjs.FactoryMaker.getClassFactory(MssFragmentInfoController);
/* jshint ignore:line */
module.exports = exports['default'];
},{"2":2,"4":4}],4:[function(_dereq_,module,exports){
/**
* The copyright in this software is being made available under the BSD License,
* included below. This software may be subject to other third party and contributor
* rights, including patent rights, and no such rights are granted under this license.
*
* Copyright (c) 2013, Dash Industry Forum.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
* * Neither the name of Dash Industry Forum nor the names of its
* contributors may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @module MssFragmentMoovProcessor
* @param {Object} config object
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function MssFragmentMoofProcessor(config) {
config = config || {};
var instance = undefined;
var metricsModel = config.metricsModel;
var playbackController = config.playbackController;
var errorHandler = config.errHandler;
var ISOBoxer = config.ISOBoxer;
var log = config.log;
function setup() {}
function processTfrf(request, tfrf, tfdt, streamProcessor) {
var representationController = streamProcessor.getRepresentationController();
var representation = representationController.getCurrentRepresentation();
var indexHandler = streamProcessor.getIndexHandler();
var manifest = representation.adaptation.period.mpd.manifest;
var adaptation = manifest.Period_asArray[representation.adaptation.period.index].AdaptationSet_asArray[representation.adaptation.index];
var timescale = adaptation.SegmentTemplate.timescale;
if (manifest.type !== 'dynamic') {
return;
}
if (!tfrf) {
errorHandler.mssError('MSS_NO_TFRF : Missing tfrf in live media segment');
return;
}
// Get adaptation's segment timeline (always a SegmentTimeline in Smooth Streaming use case)
var segments = adaptation.SegmentTemplate.SegmentTimeline.S;
var entries = tfrf.entry;
var entry = undefined,
segmentTime = undefined;
var segment = null;
var type = adaptation.contentType;
var t = 0;
var availabilityStartTime = null;
var range = undefined;
if (entries.length === 0) {
return;
}
// Consider only first tfrf entry (to avoid pre-condition failure on fragment info requests)
entry = entries[0];
// Get last segment time
segmentTime = segments[segments.length - 1].tManifest ? parseFloat(segments[segments.length - 1].tManifest) : segments[segments.length - 1].t;
// Check if we have to append new segment to timeline
if (entry.fragment_absolute_time <= segmentTime) {
// Update DVR window range
// => set range end to end time of current segment
range = {
start: segments[0].t / adaptation.SegmentTemplate.timescale,
end: tfdt.baseMediaDecodeTime / adaptation.SegmentTemplate.timescale + request.duration
};
updateDVR(request.mediaType, range, streamProcessor.getStreamInfo().manifestInfo);
return;
}
log('[MssFragmentMoofProcessor][', type, '] Add new segment - t = ', entry.fragment_absolute_time / timescale);
segment = {};
segment.t = entry.fragment_absolute_time;
segment.d = entry.fragment_duration;
segments.push(segment);
//
if (manifest.timeShiftBufferDepth && manifest.timeShiftBufferDepth > 0) {
// Get timestamp of the last segment
segment = segments[segments.length - 1];
t = segment.t;
// Determine the segments' availability start time
availabilityStartTime = t - manifest.timeShiftBufferDepth * timescale;
// Remove segments prior to availability start time
segment = segments[0];
while (segment.t < availabilityStartTime) {
log('[MssFragmentMoofProcessor]Remove segment - t = ' + segment.t / timescale);
segments.splice(0, 1);
segment = segments[0];
}
// Update DVR window range
// => set range end to end time of current segment
range = {
start: segments[0].t / adaptation.SegmentTemplate.timescale,
end: tfdt.baseMediaDecodeTime / adaptation.SegmentTemplate.timescale + request.duration
};
updateDVR(request.mediaType, range, streamProcessor.getStreamInfo().manifestInfo);
}
indexHandler.updateSegmentList(representation);
}
function updateDVR(type, range, manifestInfo) {
var dvrInfos = metricsModel.getMetricsFor(type).DVRInfo;
if (dvrInfos) {
if (dvrInfos.length === 0 || dvrInfos.length > 0 && range.end > dvrInfos[dvrInfos.length - 1].range.end) {
log('[MssFragmentMoofProcessor][', type, '] Update DVR Infos [' + range.start + ' - ' + range.end + ']');
metricsModel.addDVRInfo(type, playbackController.getTime(), manifestInfo, range);
}
}
}
// This function returns the offset of the 1st byte of a child box within a container box
function getBoxOffset(parent, type) {
var offset = 8;
var i = 0;
for (i = 0; i < parent.boxes.length; i++) {
if (parent.boxes[i].type === type) {
return offset;
}
offset += parent.boxes[i].size;
}
return offset;
}
function convertFragment(e, sp) {
var i = undefined;
// e.request contains request description object
// e.response contains fragment bytes
var isoFile = ISOBoxer.parseBuffer(e.response);
// Update track_Id in tfhd box
var tfhd = isoFile.fetch('tfhd');
tfhd.track_ID = e.request.mediaInfo.index + 1;
// Add tfdt box
var tfdt = isoFile.fetch('tfdt');
var traf = isoFile.fetch('traf');
if (tfdt === null) {
tfdt = ISOBoxer.createFullBox('tfdt', traf, tfhd);
tfdt.version = 1;
tfdt.flags = 0;
tfdt.baseMediaDecodeTime = Math.floor(e.request.startTime * e.request.timescale);
}
var trun = isoFile.fetch('trun');
// Process tfxd boxes
// This box provide absolute timestamp but we take the segment start time for tfdt
var tfxd = isoFile.fetch('tfxd');
if (tfxd) {
tfxd._parent.boxes.splice(tfxd._parent.boxes.indexOf(tfxd), 1);
tfxd = null;
}
var tfrf = isoFile.fetch('tfrf');
processTfrf(e.request, tfrf, tfdt, sp);
if (tfrf) {
tfrf._parent.boxes.splice(tfrf._parent.boxes.indexOf(tfrf), 1);
tfrf = null;
}
// If protected content in PIFF1.1 format (sepiff box = Sample Encryption PIFF)
// => convert sepiff box it into a senc box
// => create saio and saiz boxes (if not already present)
var sepiff = isoFile.fetch('sepiff');
if (sepiff !== null) {
sepiff.type = 'senc';
sepiff.usertype = undefined;
var _saio = isoFile.fetch('saio');
if (_saio === null) {
// Create Sample Auxiliary Information Offsets Box box (saio)
_saio = ISOBoxer.createFullBox('saio', traf);
_saio.version = 0;
_saio.flags = 0;
_saio.entry_count = 1;
_saio.offset = [0];
var saiz = ISOBoxer.createFullBox('saiz', traf);
saiz.version = 0;
saiz.flags = 0;
saiz.sample_count = sepiff.sample_count;
saiz.default_sample_info_size = 0;
saiz.sample_info_size = [];
if (sepiff.flags & 0x02) {
// Sub-sample encryption => set sample_info_size for each sample
for (i = 0; i < sepiff.sample_count; i += 1) {
// 10 = 8 (InitializationVector field size) + 2 (subsample_count field size)
// 6 = 2 (BytesOfClearData field size) + 4 (BytesOfEncryptedData field size)
saiz.sample_info_size[i] = 10 + 6 * sepiff.entry[i].NumberOfEntries;
}
} else {
// No sub-sample encryption => set default sample_info_size = InitializationVector field size (8)
saiz.default_sample_info_size = 8;
}
}
}
tfhd.flags &= 0xFFFFFE; // set tfhd.base-data-offset-present to false
tfhd.flags |= 0x020000; // set tfhd.default-base-is-moof to true
trun.flags |= 0x000001; // set trun.data-offset-present to true
// Update trun.data_offset field that corresponds to first data byte (inside mdat box)
var moof = isoFile.fetch('moof');
var length = moof.getLength();
trun.data_offset = length + 8;
// Update saio box offset field according to new senc box offset
var saio = isoFile.fetch('saio');
if (saio !== null) {
var trafPosInMoof = getBoxOffset(moof, 'traf');
var sencPosInTraf = getBoxOffset(traf, 'senc');
// Set offset from begin fragment to the first IV field in senc box
saio.offset[0] = trafPosInMoof + sencPosInTraf + 16; // 16 = box header (12) + sample_count field size (4)
}
// Write transformed/processed fragment into request reponse data
e.response = isoFile.write();
}
function updateSegmentList(e, sp) {
// e.request contains request description object
// e.response contains fragment bytes
if (!e.response) {
throw new Error('e.response parameter is missing');
}
var isoFile = ISOBoxer.parseBuffer(e.response);
// Update track_Id in tfhd box
var tfhd = isoFile.fetch('tfhd');
tfhd.track_ID = e.request.mediaInfo.index + 1;
// Add tfdt box
var tfdt = isoFile.fetch('tfdt');
var traf = isoFile.fetch('traf');
if (tfdt === null) {
tfdt = ISOBoxer.createFullBox('tfdt', traf, tfhd);
tfdt.version = 1;
tfdt.flags = 0;
tfdt.baseMediaDecodeTime = Math.floor(e.request.startTime * e.request.timescale);
}
var tfrf = isoFile.fetch('tfrf');
processTfrf(e.request, tfrf, tfdt, sp);
if (tfrf) {
tfrf._parent.boxes.splice(tfrf._parent.boxes.indexOf(tfrf), 1);
tfrf = null;
}
}
instance = {
convertFragment: convertFragment,
updateSegmentList: updateSegmentList
};
setup();
return instance;
}
MssFragmentMoofProcessor.__dashjs_factory_name = 'MssFragmentMoofProcessor';
exports['default'] = dashjs.FactoryMaker.getClassFactory(MssFragmentMoofProcessor);
/* jshint ignore:line */
module.exports = exports['default'];
},{}],5:[function(_dereq_,module,exports){
/**
* The copyright in this software is being made available under the BSD License,
* included below. This software may be subject to other third party and contributor
* rights, including patent rights, and no such rights are granted under this license.
*
* Copyright (c) 2013, Dash Industry Forum.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
* * Neither the name of Dash Industry Forum nor the names of its
* contributors may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @module MssFragmentMoovProcessor
* @param {Object} config object
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function MssFragmentMoovProcessor(config) {
config = config || {};
var NALUTYPE_SPS = 7;
var NALUTYPE_PPS = 8;
var constants = config.constants;
var ISOBoxer = config.ISOBoxer;
var protectionController = config.protectionController;
var instance = undefined,
period = undefined,
adaptationSet = undefined,
representation = undefined,
contentProtection = undefined,
timescale = undefined,
trackId = undefined;
function createFtypBox(isoFile) {
var ftyp = ISOBoxer.createBox('ftyp', isoFile);
ftyp.major_brand = 'iso6';
ftyp.minor_version = 1; // is an informative integer for the minor version of the major brand
ftyp.compatible_brands = []; //is a list, to the end of the box, of brands isom, iso6 and msdh
ftyp.compatible_brands[0] = 'isom'; // => decimal ASCII value for isom
ftyp.compatible_brands[1] = 'iso6'; // => decimal ASCII value for iso6
ftyp.compatible_brands[2] = 'msdh'; // => decimal ASCII value for msdh
return ftyp;
}
function createMoovBox(isoFile) {
// moov box
var moov = ISOBoxer.createBox('moov', isoFile);
// moov/mvhd
createMvhdBox(moov);
// moov/trak
var trak = ISOBoxer.createBox('trak', moov);
// moov/trak/tkhd
createTkhdBox(trak);
// moov/trak/mdia
var mdia = ISOBoxer.createBox('mdia', trak);
// moov/trak/mdia/mdhd
createMdhdBox(mdia);
// moov/trak/mdia/hdlr
createHdlrBox(mdia);
// moov/trak/mdia/minf
var minf = ISOBoxer.createBox('minf', mdia);
switch (adaptationSet.type) {
case constants.VIDEO:
// moov/trak/mdia/minf/vmhd
createVmhdBox(minf);
break;
case constants.AUDIO:
// moov/trak/mdia/minf/smhd
createSmhdBox(minf);
break;
default:
break;
}
// moov/trak/mdia/minf/dinf
var dinf = ISOBoxer.createBox('dinf', minf);
// moov/trak/mdia/minf/dinf/dref
createDrefBox(dinf);
// moov/trak/mdia/minf/stbl
var stbl = ISOBoxer.createBox('stbl', minf);
// Create empty stts, stsc, stco and stsz boxes
// Use data field as for codem-isoboxer unknown boxes for setting fields value
// moov/trak/mdia/minf/stbl/stts
var stts = ISOBoxer.createFullBox('stts', stbl);
stts._data = [0, 0, 0, 0, 0, 0, 0, 0]; // version = 0, flags = 0, entry_count = 0
// moov/trak/mdia/minf/stbl/stsc
var stsc = ISOBoxer.createFullBox('stsc', stbl);
stsc._data = [0, 0, 0, 0, 0, 0, 0, 0]; // version = 0, flags = 0, entry_count = 0
// moov/trak/mdia/minf/stbl/stco
var stco = ISOBoxer.createFullBox('stco', stbl);
stco._data = [0, 0, 0, 0, 0, 0, 0, 0]; // version = 0, flags = 0, entry_count = 0
// moov/trak/mdia/minf/stbl/stsz
var stsz = ISOBoxer.createFullBox('stsz', stbl);
stsz._data = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; // version = 0, flags = 0, sample_size = 0, sample_count = 0
// moov/trak/mdia/minf/stbl/stsd
createStsdBox(stbl);
// moov/mvex
var mvex = ISOBoxer.createBox('mvex', moov);
// moov/mvex/trex
createTrexBox(mvex);
if (contentProtection && protectionController) {
var supportedKS = protectionController.getSupportedKeySystemsFromContentProtection(contentProtection);
createProtectionSystemSpecificHeaderBox(moov, supportedKS);
}
}
function createMvhdBox(moov) {
var mvhd = ISOBoxer.createFullBox('mvhd', moov);
mvhd.version = 1; // version = 1 in order to have 64bits duration value
mvhd.creation_time = 0; // the creation time of the presentation => ignore (set to 0)
mvhd.modification_time = 0; // the most recent time the presentation was modified => ignore (set to 0)
mvhd.timescale = timescale; // the time-scale for the entire presentation => 10000000 for MSS
mvhd.duration = Math.round(period.duration * timescale); // the length of the presentation (in the indicated timescale) => take duration of period
mvhd.rate = 1.0; // 16.16 number, '1.0' = normal playback
mvhd.volume = 1.0; // 8.8 number, '1.0' = full volume
mvhd.reserved1 = 0;
mvhd.reserved2 = [0x0, 0x0];
mvhd.matrix = [1, 0, 0, // provides a transformation matrix for the video;
0, 1, 0, // (u,v,w) are restricted here to (0,0,1)
0, 0, 16384];
mvhd.pre_defined = [0, 0, 0, 0, 0, 0];
mvhd.next_track_ID = trackId + 1; // indicates a value to use for the track ID of the next track to be added to this presentation
return mvhd;
}
function createTkhdBox(trak) {
var tkhd = ISOBoxer.createFullBox('tkhd', trak);
tkhd.version = 1; // version = 1 in order to have 64bits duration value
tkhd.flags = 0x1 | // Track_enabled (0x000001): Indicates that the track is enabled
0x2 | // Track_in_movie (0x000002): Indicates that the track is used in the presentation
0x4; // Track_in_preview (0x000004): Indicates that the track is used when previewing the presentation
tkhd.creation_time = 0; // the creation time of the presentation => ignore (set to 0)
tkhd.modification_time = 0; // the most recent time the presentation was modified => ignore (set to 0)
tkhd.track_ID = trackId; // uniquely identifies this track over the entire life-time of this presentation
tkhd.reserved1 = 0;
tkhd.duration = Math.round(period.duration * timescale); // the duration of this track (in the timescale indicated in the Movie Header Box) => take duration of period
tkhd.reserved2 = [0x0, 0x0];
tkhd.layer = 0; // specifies the front-to-back ordering of video tracks; tracks with lower numbers are closer to the viewer => 0 since only one video track
tkhd.alternate_group = 0; // specifies a group or collection of tracks => ignore
tkhd.volume = 1.0; // '1.0' = full volume
tkhd.reserved3 = 0;
tkhd.matrix = [1, 0, 0, // provides a transformation matrix for the video;
0, 1, 0, // (u,v,w) are restricted here to (0,0,1)
0, 0, 16384];
tkhd.width = representation.width; // visual presentation width
tkhd.height = representation.height; // visual presentation height
return tkhd;
}
function createMdhdBox(mdia) {
var mdhd = ISOBoxer.createFullBox('mdhd', mdia);
mdhd.version = 1; // version = 1 in order to have 64bits duration value
mdhd.creation_time = 0; // the creation time of the presentation => ignore (set to 0)
mdhd.modification_time = 0; // the most recent time the presentation was modified => ignore (set to 0)
mdhd.timescale = timescale; // the time-scale for the entire presentation
mdhd.duration = Math.round(period.duration * timescale); // the duration of this media (in the scale of the timescale). If the duration cannot be determined then duration is set to all 1s.
mdhd.language = adaptationSet.lang || 'und'; // declares the language code for this media (see getLanguageCode())
mdhd.pre_defined = 0;
return mdhd;
}
function createHdlrBox(mdia) {
var hdlr = ISOBoxer.createFullBox('hdlr', mdia);
hdlr.pre_defined = 0;
switch (adaptationSet.type) {
case constants.VIDEO:
hdlr.handler_type = 'vide';
break;
case constants.AUDIO:
hdlr.handler_type = 'soun';
break;
default:
hdlr.handler_type = 'meta';
break;
}
hdlr.name = representation.id;
hdlr.reserved = [0, 0, 0];
return hdlr;
}
function createVmhdBox(minf) {
var vmhd = ISOBoxer.createFullBox('vmhd', minf);
vmhd.flags = 1;
vmhd.graphicsmode = 0; // specifies a composition mode for this video track, from the following enumerated set, which may be extended by derived specifications: copy = 0 copy over the existing image
vmhd.opcolor = [0, 0, 0]; // is a set of 3 colour values (red, green, blue) available for use by graphics modes
return vmhd;
}
function createSmhdBox(minf) {
var smhd = ISOBoxer.createFullBox('smhd', minf);
smhd.flags = 1;
smhd.balance = 0; // is a fixed-point 8.8 number that places mono audio tracks in a stereo space; 0 is centre (the normal value); full left is -1.0 and full right is 1.0.
smhd.reserved = 0;
return smhd;
}
function createDrefBox(dinf) {
var dref = ISOBoxer.createFullBox('dref', dinf);
dref.entry_count = 1;
dref.entries = [];
var url = ISOBoxer.createFullBox('url ', dref, false);
url.location = '';
url.flags = 1;
dref.entries.push(url);
return dref;
}
function createStsdBox(stbl) {
var stsd = ISOBoxer.createFullBox('stsd', stbl);
stsd.entries = [];
switch (adaptationSet.type) {
case constants.VIDEO:
case constants.AUDIO:
stsd.entries.push(createSampleEntry(stsd));
break;
default:
break;
}
stsd.entry_count = stsd.entries.length; // is an integer that counts the actual entries
return stsd;
}
function createSampleEntry(stsd) {
var codec = representation.codecs.substring(0, representation.codecs.indexOf('.'));
switch (codec) {
case 'avc1':
return createAVCVisualSampleEntry(stsd, codec);
case 'mp4a':
return createMP4AudioSampleEntry(stsd, codec);
default:
throw {
name: 'Unsupported codec',
message: 'Unsupported codec',
data: {
codec: codec
}
};
}
}
function createAVCVisualSampleEntry(stsd, codec) {
var avc1 = undefined;
if (contentProtection) {
avc1 = ISOBoxer.createBox('encv', stsd, false);
} else {
avc1 = ISOBoxer.createBox('avc1', stsd, false);
}
// SampleEntry fields
avc1.reserved1 = [0x0, 0x0, 0x0, 0x0, 0x0, 0x0];
avc1.data_reference_index = 1;
// VisualSampleEntry fields
avc1.pre_defined1 = 0;
avc1.reserved2 = 0;
avc1.pre_defined2 = [0, 0, 0];
avc1.height = representation.height;
avc1.width = representation.width;
avc1.horizresolution = 72; // 72 dpi
avc1.vertresolution = 72; // 72 dpi
avc1.reserved3 = 0;
avc1.frame_count = 1; // 1 compressed video frame per sample
avc1.compressorname = [0x0A, 0x41, 0x56, 0x43, 0x20, 0x43, 0x6F, 0x64, // = 'AVC Coding';
0x69, 0x6E, 0x67, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
avc1.depth = 0x0018; // 0x0018 – images are in colour with no alpha.
avc1.pre_defined3 = 65535;
avc1.config = createAVC1ConfigurationRecord();
if (contentProtection) {
// Create and add Protection Scheme Info Box
var sinf = ISOBoxer.createBox('sinf', avc1);
// Create and add Original Format Box => indicate codec type of the encrypted content
createOriginalFormatBox(sinf, codec);
// Create and add Scheme Type box
createSchemeTypeBox(sinf);
// Create and add Scheme Information Box
createSchemeInformationBox(sinf);
}
return avc1;
}
function createAVC1ConfigurationRecord() {
var avcC = null;
var avcCLength = 15; // length = 15 by default (0 SPS and 0 PPS)
// First get all SPS and PPS from codecPrivateData
var sps = [];
var pps = [];
var AVCProfileIndication = 0;
var AVCLevelIndication = 0;
var profile_compatibility = 0;
var nalus = representation.codecPrivateData.split('00000001').slice(1);
var naluBytes = undefined,
naluType = undefined;
for (var _i = 0; _i < nalus.length; _i++) {
naluBytes = hexStringtoBuffer(nalus[_i]);
naluType = naluBytes[0] & 0x1F;
switch (naluType) {
case NALUTYPE_SPS:
sps.push(naluBytes);
avcCLength += naluBytes.length + 2; // 2 = sequenceParameterSetLength field length
break;
case NALUTYPE_PPS:
pps.push(naluBytes);
avcCLength += naluBytes.length + 2; // 2 = pictureParameterSetLength field length
break;
default:
break;
}
}
// Get profile and level from SPS
if (sps.length > 0) {
AVCProfileIndication = sps[0][1];
profile_compatibility = sps[0][2];
AVCLevelIndication = sps[0][3];
}
// Generate avcC buffer
avcC = new Uint8Array(avcCLength);
var i = 0;
// length
avcC[i++] = (avcCLength & 0xFF000000) >> 24;
avcC[i++] = (avcCLength & 0x00FF0000) >> 16;
avcC[i++] = (avcCLength & 0x0000FF00) >> 8;
avcC[i++] = avcCLength & 0x000000FF;
avcC.set([0x61, 0x76, 0x63, 0x43], i); // type = 'avcC'
i += 4;
avcC[i++] = 1; // configurationVersion = 1
avcC[i++] = AVCProfileIndication;
avcC[i++] = profile_compatibility;
avcC[i++] = AVCLevelIndication;
avcC[i++] = 0xFF; // '11111' + lengthSizeMinusOne = 3
avcC[i++] = 0xE0 | sps.length; // '111' + numOfSequenceParameterSets
for (var n = 0; n < sps.length; n++) {
avcC[i++] = (sps[n].length & 0xFF00) >> 8;
avcC[i++] = sps[n].length & 0x00FF;
avcC.set(sps[n], i);
i += sps[n].length;
}
avcC[i++] = pps.length; // numOfPictureParameterSets
for (var n = 0; n < pps.length; n++) {
avcC[i++] = (pps[n].length & 0xFF00) >> 8;
avcC[i++] = pps[n].length & 0x00FF;
avcC.set(pps[n], i);
i += pps[n].length;
}
return avcC;
}
function createMP4AudioSampleEntry(stsd, codec) {
var mp4a = undefined;
if (contentProtection) {
mp4a = ISOBoxer.createBox('enca', stsd, false);
} else {
mp4a = ISOBoxer.createBox('mp4a', stsd, false);
}
// SampleEntry fields
mp4a.reserved1 = [0x0, 0x0, 0x0, 0x0, 0x0, 0x0];
mp4a.data_reference_index = 1;
// AudioSampleEntry fields
mp4a.reserved2 = [0x0, 0x0];
mp4a.channelcount = representation.audioChannels;
mp4a.samplesize = 16;
mp4a.pre_defined = 0;
mp4a.reserved_3 = 0;
mp4a.samplerate = representation.audioSamplingRate << 16;
mp4a.esds = createMPEG4AACESDescriptor();
if (contentProtection) {
// Create and add Protection Scheme Info Box
var sinf = ISOBoxer.createBox('sinf', mp4a);
// Create and add Original Format Box => indicate codec type of the encrypted content
createOriginalFormatBox(sinf, codec);
// Create and add Scheme Type box
createSchemeTypeBox(sinf);
// Create and add Scheme Information Box
createSchemeInformationBox(sinf);
}
return mp4a;
}
function createMPEG4AACESDescriptor() {
// AudioSpecificConfig (see ISO/IEC 14496-3, subpart 1) => corresponds to hex bytes contained in 'codecPrivateData' field
var audioSpecificConfig = hexStringtoBuffer(representation.codecPrivateData);
// ESDS length = esds box header length (= 12) +
// ES_Descriptor header length (= 5) +
// DecoderConfigDescriptor header length (= 15) +
// decoderSpecificInfo header length (= 2) +
// AudioSpecificConfig length (= codecPrivateData length)
var esdsLength = 34 + audioSpecificConfig.length;
var esds = new Uint8Array(esdsLength);
var i = 0;
// esds box
esds[i++] = (esdsLength & 0xFF000000) >> 24; // esds box length
esds[i++] = (esdsLength & 0x00FF0000) >> 16; // ''
esds[i++] = (esdsLength & 0x0000FF00) >> 8; // ''
esds[i++] = esdsLength & 0x000000FF; // ''
esds.set([0x65, 0x73, 0x64, 0x73], i); // type = 'esds'
i += 4;
esds.set([0, 0, 0, 0], i); // version = 0, flags = 0
i += 4;
// ES_Descriptor (see ISO/IEC 14496-1 (Systems))
esds[i++] = 0x03; // tag = 0x03 (ES_DescrTag)
esds[i++] = 20 + audioSpecificConfig.length; // size
esds[i++] = (trackId & 0xFF00) >> 8; // ES_ID = track_id
esds[i++] = trackId & 0x00FF; // ''
esds[i++] = 0; // flags and streamPriority
// DecoderConfigDescriptor (see ISO/IEC 14496-1 (Systems))
esds[i++] = 0x04; // tag = 0x04 (DecoderConfigDescrTag)
esds[i++] = 15 + audioSpecificConfig.length; // size
esds[i++] = 0x40; // objectTypeIndication = 0x40 (MPEG-4 AAC)
esds[i] = 0x05 << 2; // streamType = 0x05 (Audiostream)
esds[i] |= 0 << 1; // upStream = 0
esds[i++] |= 1; // reserved = 1
esds[i++] = 0xFF; // buffersizeDB = undefined
esds[i++] = 0xFF; // ''
esds[i++] = 0xFF; // ''
esds[i++] = (representation.bandwidth & 0xFF000000) >> 24; // maxBitrate
esds[i++] = (representation.bandwidth & 0x00FF0000) >> 16; // ''
esds[i++] = (representation.bandwidth & 0x0000FF00) >> 8; // ''
esds[i++] = representation.bandwidth & 0x000000FF; // ''
esds[i++] = (representation.bandwidth & 0xFF000000) >> 24; // avgbitrate
esds[i++] = (representation.bandwidth & 0x00FF0000) >> 16; // ''
esds[i++] = (representation.bandwidth & 0x0000FF00) >> 8; // ''
esds[i++] = representation.bandwidth & 0x000000FF; // ''
// DecoderSpecificInfo (see ISO/IEC 14496-1 (Systems))
esds[i++] = 0x05; // tag = 0x05 (DecSpecificInfoTag)
esds[i++] = audioSpecificConfig.length; // size
esds.set(audioSpecificConfig, i); // AudioSpecificConfig bytes
return esds;
}
function createOriginalFormatBox(sinf, codec) {
var frma = ISOBoxer.createBox('frma', sinf);
frma.data_format = stringToCharCode(codec);
}
function createSchemeTypeBox(sinf) {
var schm = ISOBoxer.createFullBox('schm', sinf);
schm.flags = 0;
schm.version = 0;
schm.scheme_type = 0x63656E63; // 'cenc' => common encryption
schm.scheme_version = 0x00010000; // version set to 0x00010000 (Major version 1, Minor version 0)
}
function createSchemeInformationBox(sinf) {
var schi = ISOBoxer.createBox('schi', sinf);
// Create and add Track Encryption Box
createTrackEncryptionBox(schi);
}
function createProtectionSystemSpecificHeaderBox(moov, keySystems) {
var pssh_bytes = undefined;
var pssh = undefined;
var i = undefined;
var parsedBuffer = undefined;
for (i = 0; i < keySystems.length; i += 1) {
pssh_bytes = keySystems[i].initData;
parsedBuffer = ISOBoxer.parseBuffer(pssh_bytes);
pssh = parsedBuffer.fetch('pssh');
if (pssh) {
ISOBoxer.Utils.appendBox(moov, pssh);
}
}
}
function createTrackEncryptionBox(schi) {
var tenc = ISOBoxer.createFullBox('tenc', schi);
tenc.flags = 0;
tenc.version = 0;
tenc.default_IsEncrypted = 0x1;
tenc.default_IV_size = 8;
tenc.default_KID = contentProtection && contentProtection.length > 0 && contentProtection[0]['cenc:default_KID'] ? contentProtection[0]['cenc:default_KID'] : [0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0];
}
function createTrexBox(moov) {
var trex = ISOBoxer.createFullBox('trex', moov);
trex.track_ID = trackId;
trex.default_sample_description_index = 1;
trex.default_sample_duration = 0;
trex.default_sample_size = 0;
trex.default_sample_flags = 0;
return trex;
}
function hexStringtoBuffer(str) {
var buf = new Uint8Array(str.length / 2);
var i = undefined;
for (i = 0; i < str.length / 2; i += 1) {
buf[i] = parseInt('' + str[i * 2] + str[i * 2 + 1], 16);
}
return buf;
}
function stringToCharCode(str) {
var code = 0;
var i = undefined;
for (i = 0; i < str.length; i += 1) {
code |= str.charCodeAt(i) << (str.length - i - 1) * 8;
}
return code;
}
function generateMoov(rep) {
if (!rep || !rep.adaptation) {
return;
}
var isoFile = undefined,
arrayBuffer = undefined;
representation = rep;
adaptationSet = representation.adaptation;
period = adaptationSet.period;
trackId = adaptationSet.index + 1;
contentProtection = period.mpd.manifest.Period_asArray[period.index].AdaptationSet_asArray[adaptationSet.index].ContentProtection;
timescale = period.mpd.manifest.Period_asArray[period.index].AdaptationSet_asArray[adaptationSet.index].SegmentTemplate.timescale;
isoFile = ISOBoxer.createFile();
createFtypBox(isoFile);
createMoovBox(isoFile);
arrayBuffer = isoFile.write();
return arrayBuffer;
}
instance = {
generateMoov: generateMoov
};
return instance;
}
MssFragmentMoovProcessor.__dashjs_factory_name = 'MssFragmentMoovProcessor';
exports['default'] = dashjs.FactoryMaker.getClassFactory(MssFragmentMoovProcessor);
/* jshint ignore:line */
module.exports = exports['default'];
},{}],6:[function(_dereq_,module,exports){
/**
* The copyright in this software is being made available under the BSD License,
* included below. This software may be subject to other third party and contributor
* rights, including patent rights, and no such rights are granted under this license.
*
* Copyright (c) 2013, Dash Industry Forum.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
* * Neither the name of Dash Industry Forum nor the names of its
* contributors may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _MssFragmentMoofProcessor = _dereq_(4);
var _MssFragmentMoofProcessor2 = _interopRequireDefault(_MssFragmentMoofProcessor);
var _MssFragmentMoovProcessor = _dereq_(5);
var _MssFragmentMoovProcessor2 = _interopRequireDefault(_MssFragmentMoovProcessor);
var _MssEvents = _dereq_(2);
var _MssEvents2 = _interopRequireDefault(_MssEvents);
// Add specific box processors not provided by codem-isoboxer library
function arrayEqual(arr1, arr2) {
return arr1.length === arr2.length && arr1.every(function (element, index) {
return element === arr2[index];
});
}
function saioProcessor() {
this._procFullBox();
if (this.flags & 1) {
this._procField('aux_info_type', 'uint', 32);
this._procField('aux_info_type_parameter', 'uint', 32);
}
this._procField('entry_count', 'uint', 32);
this._procFieldArray('offset', this.entry_count, 'uint', this.version === 1 ? 64 : 32);
}
function saizProcessor() {
this._procFullBox();
if (this.flags & 1) {
this._procField('aux_info_type', 'uint', 32);
this._procField('aux_info_type_parameter', 'uint', 32);
}
this._procField('default_sample_info_size', 'uint', 8);
this._procField('sample_count', 'uint', 32);
if (this.default_sample_info_size === 0) {
this._procFieldArray('sample_info_size', this.sample_count, 'uint', 8);
}
}
function sencProcessor() {
this._procFullBox();
this._procField('sample_count', 'uint', 32);
if (this.flags & 1) {
this._procField('IV_size', 'uint', 8);
}
this._procEntries('entry', this.sample_count, function (entry) {
this._procEntryField(entry, 'InitializationVector', 'data', 8);
if (this.flags & 2) {
this._procEntryField(entry, 'NumberOfEntries', 'uint', 16);
this._procSubEntries(entry, 'clearAndCryptedData', entry.NumberOfEntries, function (clearAndCryptedData) {
this._procEntryField(clearAndCryptedData, 'BytesOfClearData', 'uint', 16);
this._procEntryField(clearAndCryptedData, 'BytesOfEncryptedData', 'uint', 32);
});
}
});
}
function uuidProcessor() {
var tfxdUserType = [0x6D, 0x1D, 0x9B, 0x05, 0x42, 0xD5, 0x44, 0xE6, 0x80, 0xE2, 0x14, 0x1D, 0xAF, 0xF7, 0x57, 0xB2];
var tfrfUserType = [0xD4, 0x80, 0x7E, 0xF2, 0xCA, 0x39, 0x46, 0x95, 0x8E, 0x54, 0x26, 0xCB, 0x9E, 0x46, 0xA7, 0x9F];
var sepiffUserType = [0xA2, 0x39, 0x4F, 0x52, 0x5A, 0x9B, 0x4f, 0x14, 0xA2, 0x44, 0x6C, 0x42, 0x7C, 0x64, 0x8D, 0xF4];
if (arrayEqual(this.usertype, tfxdUserType)) {
this._procFullBox();
if (this._parsing) {
this.type = 'tfxd';
}
this._procField('fragment_absolute_time', 'uint', this.version === 1 ? 64 : 32);
this._procField('fragment_duration', 'uint', this.version === 1 ? 64 : 32);
}
if (arrayEqual(this.usertype, tfrfUserType)) {
this._procFullBox();
if (this._parsing) {
this.type = 'tfrf';
}
this._procField('fragment_count', 'uint', 8);
this._procEntries('entry', this.fragment_count, function (entry) {
this._procEntryField(entry, 'fragment_absolute_time', 'uint', this.version === 1 ? 64 : 32);
this._procEntryField(entry, 'fragment_duration', 'uint', this.version === 1 ? 64 : 32);
});
}
if (arrayEqual(this.usertype, sepiffUserType)) {
if (this._parsing) {
this.type = 'sepiff';
}
sencProcessor.call(this);
}
}
function MssFragmentProcessor(config) {
config = config || {};
var context = this.context;
var metricsModel = config.metricsModel;
var playbackController = config.playbackController;
var eventBus = config.eventBus;
var protectionController = config.protectionController;
var ISOBoxer = config.ISOBoxer;
var log = config.log;
var instance = undefined;
function setup() {
ISOBoxer.addBoxProcessor('uuid', uuidProcessor);
ISOBoxer.addBoxProcessor('saio', saioProcessor);
ISOBoxer.addBoxProcessor('saiz', saizProcessor);
ISOBoxer.addBoxProcessor('senc', sencProcessor);
}
function generateMoov(rep) {
var mssFragmentMoovProcessor = (0, _MssFragmentMoovProcessor2['default'])(context).create({ protectionController: protectionController, constants: config.constants, ISOBoxer: config.ISOBoxer });
return mssFragmentMoovProcessor.generateMoov(rep);
}
function processFragment(e, sp) {
if (!e || !e.request || !e.response) {
throw new Error('e parameter is missing or malformed');
}
var request = e.request;
if (request.type === 'MediaSegment') {
// it's a MediaSegment, let's convert fragment
var mssFragmentMoofProcessor = (0, _MssFragmentMoofProcessor2['default'])(context).create({
metricsModel: metricsModel,
playbackController: playbackController,
ISOBoxer: ISOBoxer,
log: log,
errHandler: config.errHandler
});
mssFragmentMoofProcessor.convertFragment(e, sp);
} else if (request.type === 'FragmentInfoSegment') {
// it's a FragmentInfo, ask relative fragment info controller to handle it
eventBus.trigger(_MssEvents2['default'].FRAGMENT_INFO_LOADING_COMPLETED, {
fragmentInfo: e,
streamProcessor: sp
});
// Change the sender value to stop event to be propagated (fragment info must not be added to buffer)
e.sender = null;
}
}
instance = {
generateMoov: generateMoov,
processFragment: processFragment
};
setup();
return instance;
}
MssFragmentProcessor.__dashjs_factory_name = 'MssFragmentProcessor';
exports['default'] = dashjs.FactoryMaker.getClassFactory(MssFragmentProcessor);
/* jshint ignore:line */
module.exports = exports['default'];
},{"2":2,"4":4,"5":5}],7:[function(_dereq_,module,exports){
/**
* The copyright in this software is being made available under the BSD License,
* included below. This software may be subject to other third party and contributor
* rights, including patent rights, and no such rights are granted under this license.
*
* Copyright (c) 2013, Dash Industry Forum.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
* * Neither the name of Dash Industry Forum nor the names of its
* contributors may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _streamingVoDataChunk = _dereq_(10);
var _streamingVoDataChunk2 = _interopRequireDefault(_streamingVoDataChunk);
var _streamingVoFragmentRequest = _dereq_(11);
var _streamingVoFragmentRequest2 = _interopRequireDefault(_streamingVoFragmentRequest);
var _MssFragmentInfoController = _dereq_(3);
var _MssFragmentInfoController2 = _interopRequireDefault(_MssFragmentInfoController);
var _MssFragmentProcessor = _dereq_(6);
var _MssFragmentProcessor2 = _interopRequireDefault(_MssFragmentProcessor);
var _parserMssParser = _dereq_(9);
var _parserMssParser2 = _interopRequireDefault(_parserMssParser);
function MssHandler(config) {
config = config || {};
var context = this.context;
var eventBus = config.eventBus;
var events = config.events;
var constants = config.constants;
var initSegmentType = config.initSegmentType;
var metricsModel = config.metricsModel;
var playbackController = config.playbackController;
var protectionController = config.protectionController;
var mssFragmentProcessor = (0, _MssFragmentProcessor2['default'])(context).create({
metricsModel: metricsModel,
playbackController: playbackController,
protectionController: protectionController,
eventBus: eventBus,
constants: constants,
ISOBoxer: config.ISOBoxer,
log: config.log,
errHandler: config.errHandler
});
var mssParser = undefined;
var instance = undefined;
function setup() {}
function onInitializationRequested(e) {
var streamProcessor = e.sender.getStreamProcessor();
var request = new _streamingVoFragmentRequest2['default']();
var representationController = streamProcessor.getRepresentationController();
var representation = representationController.getCurrentRepresentation();
var period = undefined,
presentationStartTime = undefined;
period = representation.adaptation.period;
request.mediaType = representation.adaptation.type;
request.type = initSegmentType;
request.range = representation.range;
presentationStartTime = period.start;
//request.availabilityStartTime = timelineConverter.calcAvailabilityStartTimeFromPresentationTime(presentationStartTime, representation.adaptation.period.mpd, isDynamic);
//request.availabilityEndTime = timelineConverter.calcAvailabilityEndTimeFromPresentationTime(presentationStartTime + period.duration, period.mpd, isDynamic);
request.quality = representation.index;
request.mediaInfo = streamProcessor.getMediaInfo();
request.representationId = representation.id;
var chunk = createDataChunk(request, streamProcessor.getStreamInfo().id, e.type !== events.FRAGMENT_LOADING_PROGRESS);
// Generate initialization segment (moov)
chunk.bytes = mssFragmentProcessor.generateMoov(representation);
eventBus.trigger(events.INIT_FRAGMENT_LOADED, {
chunk: chunk,
fragmentModel: streamProcessor.getFragmentModel()
});
// Change the sender value to stop event to be propagated
e.sender = null;
}
function createDataChunk(request, streamId, endFragment) {
var chunk = new _streamingVoDataChunk2['default']();
chunk.streamId = streamId;
chunk.mediaInfo = request.mediaInfo;
chunk.segmentType = request.type;
chunk.start = request.startTime;
chunk.duration = request.duration;
chunk.end = chunk.start + chunk.duration;
chunk.index = request.index;
chunk.quality = request.quality;
chunk.representationId = request.representationId;
chunk.endFragment = endFragment;
return chunk;
}
function onSegmentMediaLoaded(e) {
if (e.error) {
return;
}
// Process moof to transcode it from MSS to DASH
var streamProcessor = e.sender.getStreamProcessor();
mssFragmentProcessor.processFragment(e, streamProcessor);
}
function onPlaybackSeekAsked() {
if (playbackController.getIsDynamic() && playbackController.getTime() !== 0) {
//create fragment info controllers for each stream processors of active stream (only for audio, video or fragmentedText)
var streamController = playbackController.getStreamController();
if (streamController) {
var processors = streamController.getActiveStreamProcessors();
processors.forEach(function (processor) {
if (processor.getType() === constants.VIDEO || processor.getType() === constants.AUDIO || processor.getType() === constants.FRAGMENTED_TEXT) {
// check that there is no fragment info controller registered to processor
var i = undefined;
var alreadyRegistered = false;
var externalControllers = processor.getExternalControllers();
for (i = 0; i < externalControllers.length; i++) {
if (externalControllers[i].controllerType && externalControllers[i].controllerType === 'MssFragmentInfoController') {
alreadyRegistered = true;
}
}
if (!alreadyRegistered) {
var fragmentInfoController = (0, _MssFragmentInfoController2['default'])(context).create({
streamProcessor: processor,
eventBus: eventBus,
metricsModel: metricsModel,
playbackController: playbackController,
ISOBoxer: config.ISOBoxer,
log: config.log
});
fragmentInfoController.initialize();
fragmentInfoController.start();
}
}
});
}
}
}
function onTTMLPreProcess(ttmlSubtitles) {
if (!ttmlSubtitles || !ttmlSubtitles.data) {
return;
}
while (ttmlSubtitles.data.indexOf('http://www.w3.org/2006/10/ttaf1') !== -1) {
ttmlSubtitles.data = ttmlSubtitles.data.replace('http://www.w3.org/2006/10/ttaf1', 'http://www.w3.org/ns/ttml');
}
}
function registerEvents() {
eventBus.on(events.INIT_REQUESTED, onInitializationRequested, instance, dashjs.FactoryMaker.getSingletonFactoryByName(eventBus.getClassName()).EVENT_PRIORITY_HIGH); /* jshint ignore:line */
eventBus.on(events.PLAYBACK_SEEK_ASKED, onPlaybackSeekAsked, instance, dashjs.FactoryMaker.getSingletonFactoryByName(eventBus.getClassName()).EVENT_PRIORITY_HIGH); /* jshint ignore:line */
eventBus.on(events.FRAGMENT_LOADING_COMPLETED, onSegmentMediaLoaded, instance, dashjs.FactoryMaker.getSingletonFactoryByName(eventBus.getClassName()).EVENT_PRIORITY_HIGH); /* jshint ignore:line */
eventBus.on(events.TTML_TO_PARSE, onTTMLPreProcess, instance);
}
function reset() {
eventBus.off(events.INIT_REQUESTED, onInitializationRequested, this);
eventBus.off(events.PLAYBACK_SEEK_ASKED, onPlaybackSeekAsked, this);
eventBus.off(events.FRAGMENT_LOADING_COMPLETED, onSegmentMediaLoaded, this);
eventBus.off(events.TTML_TO_PARSE, onTTMLPreProcess, this);
}
function createMssParser() {
mssParser = (0, _parserMssParser2['default'])(context).create(config);
return mssParser;
}
instance = {
reset: reset,
createMssParser: createMssParser,
registerEvents: registerEvents
};
setup();
return instance;
}
MssHandler.__dashjs_factory_name = 'MssHandler';
exports['default'] = dashjs.FactoryMaker.getClassFactory(MssHandler);
/* jshint ignore:line */
module.exports = exports['default'];
},{"10":10,"11":11,"3":3,"6":6,"9":9}],8:[function(_dereq_,module,exports){
(function (global){
/**
* The copyright in this software is being made available under the BSD License,
* included below. This software may be subject to other third party and contributor
* rights, including patent rights, and no such rights are granted under this license.
*
* Copyright (c) 2013, Dash Industry Forum.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
* * Neither the name of Dash Industry Forum nor the names of its
* contributors may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _MssHandler = _dereq_(7);
var _MssHandler2 = _interopRequireDefault(_MssHandler);
// Shove both of these into the global scope
var context = typeof window !== 'undefined' && window || global;
var dashjs = context.dashjs;
if (!dashjs) {
dashjs = context.dashjs = {};
}
dashjs.MssHandler = _MssHandler2['default'];
exports['default'] = dashjs;
exports.MssHandler = _MssHandler2['default'];
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"7":7}],9:[function(_dereq_,module,exports){
/**
* The copyright in this software is being made available under the BSD License,
* included below. This software may be subject to other third party and contributor
* rights, including patent rights, and no such rights are granted under this license.
*
* Copyright (c) 2013, Dash Industry Forum.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
* * Neither the name of Dash Industry Forum nor the names of its
* contributors may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @module MssParser
* @param {Object} config object
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function MssParser(config) {
config = config || {};
var BASE64 = config.BASE64;
var log = config.log;
var errorHandler = config.errHandler;
var constants = config.constants;
var DEFAULT_TIME_SCALE = 10000000.0;
var SUPPORTED_CODECS = ['AAC', 'AACL', 'AVC1', 'H264', 'TTML', 'DFXP'];
// MPEG-DASH Role and accessibility mapping according to ETSI TS 103 285 v1.1.1 (section 7.1.2)
var ROLE = {
'SUBT': 'alternate',
'CAPT': 'alternate', // 'CAPT' is commonly equivalent to 'SUBT'
'DESC': 'main'
};
var ACCESSIBILITY = {
'DESC': '2'
};
var samplingFrequencyIndex = {
96000: 0x0,
88200: 0x1,
64000: 0x2,
48000: 0x3,
44100: 0x4,
32000: 0x5,
24000: 0x6,
22050: 0x7,
16000: 0x8,
12000: 0x9,
11025: 0xA,
8000: 0xB,
7350: 0xC
};
var mimeTypeMap = {
'video': 'video/mp4',
'audio': 'audio/mp4',
'text': 'application/mp4'
};
var instance = undefined,
mediaPlayerModel = undefined;
function setup() {
mediaPlayerModel = config.mediaPlayerModel;
}
function mapPeriod(smoothStreamingMedia, timescale) {
var period = {};
var streams = undefined,
adaptation = undefined;
// For each StreamIndex node, create an AdaptationSet element
period.AdaptationSet_asArray = [];
streams = smoothStreamingMedia.getElementsByTagName('StreamIndex');
for (var i = 0; i < streams.length; i++) {
adaptation = mapAdaptationSet(streams[i], timescale);
if (adaptation !== null) {
period.AdaptationSet_asArray.push(adaptation);
}
}
if (period.AdaptationSet_asArray.length > 0) {
period.AdaptationSet = period.AdaptationSet_asArray.length > 1 ? period.AdaptationSet_asArray : period.AdaptationSet_asArray[0];
}
return period;
}
function mapAdaptationSet(streamIndex, timescale) {
var adaptationSet = {};
var representations = [];
var segmentTemplate = {};
var qualityLevels = undefined,
representation = undefined,
segments = undefined,
i = undefined;
adaptationSet.id = streamIndex.getAttribute('Name') ? streamIndex.getAttribute('Name') : streamIndex.getAttribute('Type');
adaptationSet.contentType = streamIndex.getAttribute('Type');
adaptationSet.lang = streamIndex.getAttribute('Language') || 'und';
adaptationSet.mimeType = mimeTypeMap[adaptationSet.contentType];
adaptationSet.subType = streamIndex.getAttribute('Subtype');
adaptationSet.maxWidth = streamIndex.getAttribute('MaxWidth');
adaptationSet.maxHeight = streamIndex.getAttribute('MaxHeight');
// Map subTypes to MPEG-DASH AdaptationSet role and accessibility (see ETSI TS 103 285 v1.1.1, section 7.1.2)
if (adaptationSet.subType) {
if (ROLE[adaptationSet.subType]) {
var role = {
schemeIdUri: 'urn:mpeg:dash:role:2011',
value: ROLE[adaptationSet.subType]
};
adaptationSet.Role = role;
adaptationSet.Role_asArray = [role];
}
if (ACCESSIBILITY[adaptationSet.subType]) {
var accessibility = {
schemeIdUri: 'urn:tva:metadata:cs:AudioPurposeCS:2007',
value: ACCESSIBILITY[adaptationSet.subType]
};
adaptationSet.Accessibility = accessibility;
adaptationSet.Accessibility_asArray = [accessibility];
}
}
// Create a SegmentTemplate with a SegmentTimeline
segmentTemplate = mapSegmentTemplate(streamIndex, timescale);
qualityLevels = streamIndex.getElementsByTagName('QualityLevel');
// For each QualityLevel node, create a Representation element
for (i = 0; i < qualityLevels.length; i++) {
// Propagate BaseURL and mimeType
qualityLevels[i].BaseURL = adaptationSet.BaseURL;
qualityLevels[i].mimeType = adaptationSet.mimeType;
// Set quality level id
qualityLevels[i].Id = adaptationSet.id + '_' + qualityLevels[i].getAttribute('Index');
// Map Representation to QualityLevel
representation = mapRepresentation(qualityLevels[i], streamIndex);
if (representation !== null) {
// Copy SegmentTemplate into Representation
representation.SegmentTemplate = segmentTemplate;
representations.push(representation);
}
}
if (representations.length === 0) {
return null;
}
adaptationSet.Representation = representations.length > 1 ? representations : representations[0];
adaptationSet.Representation_asArray = representations;
// Set SegmentTemplate
adaptationSet.SegmentTemplate = segmentTemplate;
segments = segmentTemplate.SegmentTimeline.S_asArray;
return adaptationSet;
}
function mapRepresentation(qualityLevel, streamIndex) {
var representation = {};
var fourCCValue = null;
var type = streamIndex.getAttribute('Type');
representation.id = qualityLevel.Id;
representation.bandwidth = parseInt(qualityLevel.getAttribute('Bitrate'), 10);
representation.mimeType = qualityLevel.mimeType;
representation.width = parseInt(qualityLevel.getAttribute('MaxWidth'), 10);
representation.height = parseInt(qualityLevel.getAttribute('MaxHeight'), 10);
fourCCValue = qualityLevel.getAttribute('FourCC');
// If FourCC not defined at QualityLevel level, then get it from StreamIndex level
if (fourCCValue === null || fourCCValue === '') {
fourCCValue = streamIndex.getAttribute('FourCC');
}
// If still not defined (optionnal for audio stream, see https://msdn.microsoft.com/en-us/library/ff728116%28v=vs.95%29.aspx),
// then we consider the stream is an audio AAC stream
if (fourCCValue === null || fourCCValue === '') {
if (type === 'audio') {
fourCCValue = 'AAC';
} else if (type === 'video') {
log('[MssParser] FourCC is not defined whereas it is required for a QualityLevel element for a StreamIndex of type "video"');
return null;
}
}
// Check if codec is supported
if (SUPPORTED_CODECS.indexOf(fourCCValue.toUpperCase()) === -1) {
// Do not send warning
//this.errHandler.sendWarning(MediaPlayer.dependencies.ErrorHandler.prototype.MEDIA_ERR_CODEC_UNSUPPORTED, 'Codec not supported', {codec: fourCCValue});
log('[MssParser] Codec not supported: ' + fourCCValue);
return null;
}
// Get codecs value according to FourCC field
if (fourCCValue === 'H264' || fourCCValue === 'AVC1') {
representation.codecs = getH264Codec(qualityLevel);
} else if (fourCCValue.indexOf('AAC') >= 0) {
representation.codecs = getAACCodec(qualityLevel, fourCCValue);
representation.audioSamplingRate = parseInt(qualityLevel.getAttribute('SamplingRate'), 10);
representation.audioChannels = parseInt(qualityLevel.getAttribute('Channels'), 10);
} else if (fourCCValue.indexOf('TTML') || fourCCValue.indexOf('DFXP')) {
representation.codecs = constants.STPP;
}
representation.codecPrivateData = '' + qualityLevel.getAttribute('CodecPrivateData');
representation.BaseURL = qualityLevel.BaseURL;
return representation;
}
function getH264Codec(qualityLevel) {
var codecPrivateData = qualityLevel.getAttribute('CodecPrivateData').toString();
var nalHeader = undefined,
avcoti = undefined;
// Extract from the CodecPrivateData field the hexadecimal representation of the following
// three bytes in the sequence parameter set NAL unit.
// => Find the SPS nal header
nalHeader = /00000001[0-9]7/.exec(codecPrivateData);
// => Find the 6 characters after the SPS nalHeader (if it exists)
avcoti = nalHeader && nalHeader[0] ? codecPrivateData.substr(codecPrivateData.indexOf(nalHeader[0]) + 10, 6) : undefined;
return 'avc1.' + avcoti;
}
function getAACCodec(qualityLevel, fourCCValue) {
var objectType = 0;
var codecPrivateData = qualityLevel.getAttribute('CodecPrivateData').toString();
var samplingRate = parseInt(qualityLevel.getAttribute('SamplingRate'), 10);
var codecPrivateDataHex = undefined,
arr16 = undefined,
indexFreq = undefined,
extensionSamplingFrequencyIndex = undefined;
//chrome problem, in implicit AAC HE definition, so when AACH is detected in FourCC
//set objectType to 5 => strange, it should be 2
if (fourCCValue === 'AACH') {
objectType = 0x05;
}
//if codecPrivateData is empty, build it :
if (codecPrivateData === undefined || codecPrivateData === '') {
objectType = 0x02; //AAC Main Low Complexity => object Type = 2
indexFreq = samplingFrequencyIndex[samplingRate];
if (fourCCValue === 'AACH') {
// 4 bytes : XXXXX XXXX XXXX XXXX XXXXX XXX XXXXXXX
// ' ObjectType' 'Freq Index' 'Channels value' 'Extens Sampl Freq' 'ObjectType' 'GAS' 'alignment = 0'
objectType = 0x05; // High Efficiency AAC Profile = object Type = 5 SBR
codecPrivateData = new Uint8Array(4);
extensionSamplingFrequencyIndex = samplingFrequencyIndex[samplingRate * 2]; // in HE AAC Extension Sampling frequence
// equals to SamplingRate*2
//Freq Index is present for 3 bits in the first byte, last bit is in the second
codecPrivateData[0] = objectType << 3 | indexFreq >> 1;
codecPrivateData[1] = indexFreq << 7 | qualityLevel.Channels << 3 | extensionSamplingFrequencyIndex >> 1;
codecPrivateData[2] = extensionSamplingFrequencyIndex << 7 | 0x02 << 2; // origin object type equals to 2 => AAC Main Low Complexity
codecPrivateData[3] = 0x0; //alignment bits
arr16 = new Uint16Array(2);
arr16[0] = (codecPrivateData[0] << 8) + codecPrivateData[1];
arr16[1] = (codecPrivateData[2] << 8) + codecPrivateData[3];
//convert decimal to hex value
codecPrivateDataHex = arr16[0].toString(16);
codecPrivateDataHex = arr16[0].toString(16) + arr16[1].toString(16);
} else {
// 2 bytes : XXXXX XXXX XXXX XXX
// ' ObjectType' 'Freq Index' 'Channels value' 'GAS = 000'
codecPrivateData = new Uint8Array(2);
//Freq Index is present for 3 bits in the first byte, last bit is in the second
codecPrivateData[0] = objectType << 3 | indexFreq >> 1;
codecPrivateData[1] = indexFreq << 7 | parseInt(qualityLevel.getAttribute('Channels'), 10) << 3;
// put the 2 bytes in an 16 bits array
arr16 = new Uint16Array(1);
arr16[0] = (codecPrivateData[0] << 8) + codecPrivateData[1];
//convert decimal to hex value
codecPrivateDataHex = arr16[0].toString(16);
}
codecPrivateData = '' + codecPrivateDataHex;
codecPrivateData = codecPrivateData.toUpperCase();
qualityLevel.setAttribute('CodecPrivateData', codecPrivateData);
} else if (objectType === 0) {
objectType = (parseInt(codecPrivateData.substr(0, 2), 16) & 0xF8) >> 3;
}
return 'mp4a.40.' + objectType;
}
function mapSegmentTemplate(streamIndex, timescale) {
var segmentTemplate = {};
var mediaUrl = undefined,
streamIndexTimeScale = undefined;
mediaUrl = streamIndex.getAttribute('Url').replace('{bitrate}', '$Bandwidth$');
mediaUrl = mediaUrl.replace('{start time}', '$Time$');
streamIndexTimeScale = streamIndex.getAttribute('TimeScale');
streamIndexTimeScale = streamIndexTimeScale ? parseFloat(streamIndexTimeScale) : timescale;
segmentTemplate.media = mediaUrl;
segmentTemplate.timescale = streamIndexTimeScale;
segmentTemplate.SegmentTimeline = mapSegmentTimeline(streamIndex, segmentTemplate.timescale);
return segmentTemplate;
}
function mapSegmentTimeline(streamIndex, timescale) {
var segmentTimeline = {};
var chunks = streamIndex.getElementsByTagName('c');
var segments = [];
var segment = undefined;
var prevSegment = undefined;
var tManifest = undefined;
var i = undefined,
j = undefined,
r = undefined;
var duration = 0;
for (i = 0; i < chunks.length; i++) {
segment = {};
// Get time 't' attribute value
tManifest = chunks[i].getAttribute('t');
// => segment.tManifest = original timestamp value as a string (for constructing the fragment request url, see DashHandler)
// => segment.t = number value of timestamp (maybe rounded value, but only for 0.1 microsecond)
segment.tManifest = parseFloat(tManifest);
segment.t = parseFloat(tManifest);
// Get duration 'd' attribute value
segment.d = parseFloat(chunks[i].getAttribute('d'));
// If 't' not defined for first segment then t=0
if (i === 0 && !segment.t) {
segment.t = 0;
}
if (i > 0) {
prevSegment = segments[segments.length - 1];
// Update previous segment duration if not defined
if (!prevSegment.d) {
if (prevSegment.tManifest) {
prevSegment.d = parseFloat(tManifest) - parseFloat(prevSegment.tManifest);
} else {
prevSegment.d = segment.t - prevSegment.t;
}
}
// Set segment absolute timestamp if not set in manifest
if (!segment.t) {
if (prevSegment.tManifest) {
segment.tManifest = parseFloat(prevSegment.tManifest) + prevSegment.d;
segment.t = parseFloat(segment.tManifest);
} else {
segment.t = prevSegment.t + prevSegment.d;
}
}
}
duration += segment.d;
// Create new segment
segments.push(segment);
// Support for 'r' attribute (i.e. "repeat" as in MPEG-DASH)
r = parseFloat(chunks[i].getAttribute('r'));
if (r) {
for (j = 0; j < r - 1; j++) {
prevSegment = segments[segments.length - 1];
segment = {};
segment.t = prevSegment.t + prevSegment.d;
segment.d = prevSegment.d;
if (prevSegment.tManifest) {
segment.tManifest = parseFloat(prevSegment.tManifest) + prevSegment.d;
}
duration += segment.d;
segments.push(segment);
}
}
}
segmentTimeline.S = segments;
segmentTimeline.S_asArray = segments;
segmentTimeline.duration = duration / timescale;
return segmentTimeline;
}
function getKIDFromProtectionHeader(protectionHeader) {
var prHeader = undefined,
wrmHeader = undefined,
xmlReader = undefined,
KID = undefined;
// Get PlayReady header as byte array (base64 decoded)
prHeader = BASE64.decodeArray(protectionHeader.firstChild.data);
// Get Right Management header (WRMHEADER) from PlayReady header
wrmHeader = getWRMHeaderFromPRHeader(prHeader);
// Convert from multi-byte to unicode
wrmHeader = new Uint16Array(wrmHeader.buffer);
// Convert to string
wrmHeader = String.fromCharCode.apply(null, wrmHeader);
// Parse <WRMHeader> to get KID field value
xmlReader = new DOMParser().parseFromString(wrmHeader, 'application/xml');
KID = xmlReader.querySelector('KID').textContent;
// Get KID (base64 decoded) as byte array
KID = BASE64.decodeArray(KID);
// Convert UUID from little-endian to big-endian
convertUuidEndianness(KID);
return KID;
}
function getWRMHeaderFromPRHeader(prHeader) {
var length = undefined,
recordCount = undefined,
recordType = undefined,
recordLength = undefined,
recordValue = undefined;
var i = 0;
// Parse PlayReady header
// Length - 32 bits (LE format)
length = (prHeader[i + 3] << 24) + (prHeader[i + 2] << 16) + (prHeader[i + 1] << 8) + prHeader[i];
i += 4;
// Record count - 16 bits (LE format)
recordCount = (prHeader[i + 1] << 8) + prHeader[i];
i += 2;
// Parse records
while (i < prHeader.length) {
// Record type - 16 bits (LE format)
recordType = (prHeader[i + 1] << 8) + prHeader[i];
i += 2;
// Check if Rights Management header (record type = 0x01)
if (recordType === 0x01) {
// Record length - 16 bits (LE format)
recordLength = (prHeader[i + 1] << 8) + prHeader[i];
i += 2;
// Record value => contains <WRMHEADER>
recordValue = new Uint8Array(recordLength);
recordValue.set(prHeader.subarray(i, i + recordLength));
return recordValue;
}
}
return null;
}
function convertUuidEndianness(uuid) {
swapBytes(uuid, 0, 3);
swapBytes(uuid, 1, 2);
swapBytes(uuid, 4, 5);
swapBytes(uuid, 6, 7);
}
function swapBytes(bytes, pos1, pos2) {
var temp = bytes[pos1];
bytes[pos1] = bytes[pos2];
bytes[pos2] = temp;
}
function createPRContentProtection(protectionHeader) {
var pro = {
__text: protectionHeader.firstChild.data,
__prefix: 'mspr'
};
return {
schemeIdUri: 'urn:uuid:9a04f079-9840-4286-ab92-e65be0885f95',
value: 'com.microsoft.playready',
pro: pro,
pro_asArray: pro
};
}
function createWidevineContentProtection(protectionHeader, KID) {
// Create Widevine CENC header (Protocol Buffer) with KID value
var wvCencHeader = new Uint8Array(2 + KID.length);
wvCencHeader[0] = 0x12;
wvCencHeader[1] = 0x10;
wvCencHeader.set(KID, 2);
// Create a pssh box
var length = 12 /* box length, type, version and flags */ + 16 /* SystemID */ + 4 /* data length */ + wvCencHeader.length;
var pssh = new Uint8Array(length);
var i = 0;
// Set box length value
pssh[i++] = (length & 0xFF000000) >> 24;
pssh[i++] = (length & 0x00FF0000) >> 16;
pssh[i++] = (length & 0x0000FF00) >> 8;
pssh[i++] = length & 0x000000FF;
// Set type ('pssh'), version (0) and flags (0)
pssh.set([0x70, 0x73, 0x73, 0x68, 0x00, 0x00, 0x00, 0x00], i);
i += 8;
// Set SystemID ('edef8ba9-79d6-4ace-a3c8-27dcd51d21ed')
pssh.set([0xed, 0xef, 0x8b, 0xa9, 0x79, 0xd6, 0x4a, 0xce, 0xa3, 0xc8, 0x27, 0xdc, 0xd5, 0x1d, 0x21, 0xed], i);
i += 16;
// Set data length value
pssh[i++] = (wvCencHeader.length & 0xFF000000) >> 24;
pssh[i++] = (wvCencHeader.length & 0x00FF0000) >> 16;
pssh[i++] = (wvCencHeader.length & 0x0000FF00) >> 8;
pssh[i++] = wvCencHeader.length & 0x000000FF;
// Copy Widevine CENC header
pssh.set(wvCencHeader, i);
// Convert to BASE64 string
pssh = String.fromCharCode.apply(null, pssh);
pssh = BASE64.encodeASCII(pssh);
return {
schemeIdUri: 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed',
value: 'com.widevine.alpha',
pssh: {
__text: pssh
}
};
}
function processManifest(xmlDoc, manifestLoadedTime) {
var manifest = {};
var contentProtections = [];
var smoothStreamingMedia = xmlDoc.getElementsByTagName('SmoothStreamingMedia')[0];
var protection = xmlDoc.getElementsByTagName('Protection')[0];
var protectionHeader = null;
var period = undefined,
adaptations = undefined,
contentProtection = undefined,
KID = undefined,
timestampOffset = undefined,
startTime = undefined,
segments = undefined,
timescale = undefined,
i = undefined,
j = undefined;
// Set manifest node properties
manifest.protocol = 'MSS';
manifest.profiles = 'urn:mpeg:dash:profile:isoff-live:2011';
manifest.type = smoothStreamingMedia.getAttribute('IsLive') === 'TRUE' ? 'dynamic' : 'static';
timescale = smoothStreamingMedia.getAttribute('TimeScale');
manifest.timescale = timescale ? parseFloat(timescale) : DEFAULT_TIME_SCALE;
manifest.timeShiftBufferDepth = parseFloat(smoothStreamingMedia.getAttribute('DVRWindowLength')) / manifest.timescale;
manifest.mediaPresentationDuration = parseFloat(smoothStreamingMedia.getAttribute('Duration')) === 0 ? Infinity : parseFloat(smoothStreamingMedia.getAttribute('Duration')) / manifest.timescale;
manifest.minBufferTime = mediaPlayerModel.getStableBufferTime();
manifest.ttmlTimeIsRelative = true;
// In case of live streams, set availabilityStartTime property according to DVRWindowLength
if (manifest.type === 'dynamic') {
manifest.availabilityStartTime = new Date(manifestLoadedTime.getTime() - manifest.timeShiftBufferDepth * 1000);
manifest.refreshManifestOnSwitchTrack = true;
manifest.doNotUpdateDVRWindowOnBufferUpdated = true; // done by Mss fragment processor
manifest.ignorePostponeTimePeriod = true; // in Mss, manifest is never updated
}
// Map period node to manifest root node
manifest.Period = mapPeriod(smoothStreamingMedia, manifest.timescale);
manifest.Period_asArray = [manifest.Period];
// Initialize period start time
period = manifest.Period;
period.start = 0;
// ContentProtection node
if (protection !== undefined) {
protectionHeader = xmlDoc.getElementsByTagName('ProtectionHeader')[0];
// Some packagers put newlines into the ProtectionHeader base64 string, which is not good
// because this cannot be correctly parsed. Let's just filter out any newlines found in there.
protectionHeader.firstChild.data = protectionHeader.firstChild.data.replace(/\n|\r/g, '');
// Get KID (in CENC format) from protection header
KID = getKIDFromProtectionHeader(protectionHeader);
// Create ContentProtection for PlayReady
contentProtection = createPRContentProtection(protectionHeader);
contentProtection['cenc:default_KID'] = KID;
contentProtections.push(contentProtection);
// Create ContentProtection for Widevine (as a CENC protection)
contentProtection = createWidevineContentProtection(protectionHeader, KID);
contentProtection['cenc:default_KID'] = KID;
contentProtections.push(contentProtection);
manifest.ContentProtection = contentProtections;
manifest.ContentProtection_asArray = contentProtections;
}
adaptations = period.AdaptationSet_asArray;
for (i = 0; i < adaptations.length; i += 1) {
adaptations[i].SegmentTemplate.initialization = '$Bandwidth$';
// Propagate content protection information into each adaptation
if (manifest.ContentProtection !== undefined) {
adaptations[i].ContentProtection = manifest.ContentProtection;
adaptations[i].ContentProtection_asArray = manifest.ContentProtection_asArray;
}
if (manifest.type === 'dynamic') {
// Match timeShiftBufferDepth to video segment timeline duration
if (manifest.timeShiftBufferDepth > 0 && adaptations[i].contentType === 'video' && manifest.timeShiftBufferDepth > adaptations[i].SegmentTemplate.SegmentTimeline.duration) {
manifest.timeShiftBufferDepth = adaptations[i].SegmentTemplate.SegmentTimeline.duration;
}
}
}
if (manifest.timeShiftBufferDepth < manifest.minBufferTime) {
manifest.minBufferTime = manifest.timeShiftBufferDepth;
}
// Delete Content Protection under root manifest node
delete manifest.ContentProtection;
delete manifest.ContentProtection_asArray;
// In case of VOD streams, check if start time is greater than 0
// Then determine timestamp offset according to higher audio/video start time
// (use case = live stream delinearization)
if (manifest.type === 'static') {
for (i = 0; i < adaptations.length; i++) {
if (adaptations[i].contentType === 'audio' || adaptations[i].contentType === 'video') {
segments = adaptations[i].SegmentTemplate.SegmentTimeline.S_asArray;
startTime = segments[0].t / adaptations[i].SegmentTemplate.timescale;
if (timestampOffset === undefined) {
timestampOffset = startTime;
}
timestampOffset = Math.min(timestampOffset, startTime);
// Correct content duration according to minimum adaptation's segments duration
// in order to force <video> element sending 'ended' event
manifest.mediaPresentationDuration = Math.min(manifest.mediaPresentationDuration, adaptations[i].SegmentTemplate.SegmentTimeline.duration);
}
}
// Patch segment templates timestamps and determine period start time (since audio/video should not be aligned to 0)
if (timestampOffset > 0) {
for (i = 0; i < adaptations.length; i++) {
segments = adaptations[i].SegmentTemplate.SegmentTimeline.S_asArray;
for (j = 0; j < segments.length; j++) {
if (!segments[j].tManifest) {
segments[j].tManifest = segments[j].t;
}
segments[j].t -= timestampOffset * adaptations[i].SegmentTemplate.timescale;
}
if (adaptations[i].contentType === 'audio' || adaptations[i].contentType === 'video') {
period.start = Math.max(segments[0].t, period.start);
adaptations[i].SegmentTemplate.presentationTimeOffset = period.start;
}
}
period.start /= manifest.timescale;
}
}
manifest.mediaPresentationDuration = Math.floor(manifest.mediaPresentationDuration * 1000) / 1000;
period.duration = manifest.mediaPresentationDuration;
return manifest;
}
function parseDOM(data) {
var xmlDoc = null;
if (window.DOMParser) {
try {
var parser = new window.DOMParser();
xmlDoc = parser.parseFromString(data, 'text/xml');
if (xmlDoc.getElementsByTagName('parsererror').length > 0) {
throw new Error('Error parsing XML');
}
} catch (e) {
errorHandler.manifestError('parsing the manifest failed', 'parse', data, e);
xmlDoc = null;
}
}
return xmlDoc;
}
function getMatchers() {
return null;
}
function getIron() {
return null;
}
function internalParse(data) {
var xmlDoc = null;
var manifest = null;
var startTime = window.performance.now();
// Parse the MSS XML manifest
xmlDoc = parseDOM(data);
var xmlParseTime = window.performance.now();
if (xmlDoc === null) {
return null;
}
// Convert MSS manifest into DASH manifest
manifest = processManifest(xmlDoc, new Date());
var mss2dashTime = window.performance.now();
log('Parsing complete: (xmlParsing: ' + (xmlParseTime - startTime).toPrecision(3) + 'ms, mss2dash: ' + (mss2dashTime - xmlParseTime).toPrecision(3) + 'ms, total: ' + ((mss2dashTime - startTime) / 1000).toPrecision(3) + 's)');
return manifest;
}
instance = {
parse: internalParse,
getMatchers: getMatchers,
getIron: getIron
};
setup();
return instance;
}
MssParser.__dashjs_factory_name = 'MssParser';
exports['default'] = dashjs.FactoryMaker.getClassFactory(MssParser);
/* jshint ignore:line */
module.exports = exports['default'];
},{}],10:[function(_dereq_,module,exports){
/**
* The copyright in this software is being made available under the BSD License,
* included below. This software may be subject to other third party and contributor
* rights, including patent rights, and no such rights are granted under this license.
*
* Copyright (c) 2013, Dash Industry Forum.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
* * Neither the name of Dash Industry Forum nor the names of its
* contributors may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @class
* @ignore
*/
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var DataChunk =
//Represents a data structure that keep all the necessary info about a single init/media segment
function DataChunk() {
_classCallCheck(this, DataChunk);
this.streamId = null;
this.mediaInfo = null;
this.segmentType = null;
this.quality = NaN;
this.index = NaN;
this.bytes = null;
this.start = NaN;
this.end = NaN;
this.duration = NaN;
this.representationId = null;
this.endFragment = null;
};
exports["default"] = DataChunk;
module.exports = exports["default"];
},{}],11:[function(_dereq_,module,exports){
/**
* The copyright in this software is being made available under the BSD License,
* included below. This software may be subject to other third party and contributor
* rights, including patent rights, and no such rights are granted under this license.
*
* Copyright (c) 2013, Dash Industry Forum.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
* * Neither the name of Dash Industry Forum nor the names of its
* contributors may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @class
* @ignore
*/
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var FragmentRequest = function FragmentRequest() {
_classCallCheck(this, FragmentRequest);
this.action = FragmentRequest.ACTION_DOWNLOAD;
this.startTime = NaN;
this.mediaType = null;
this.mediaInfo = null;
this.type = null;
this.duration = NaN;
this.timescale = NaN;
this.range = null;
this.url = null;
this.serviceLocation = null;
this.requestStartDate = null;
this.firstByteDate = null;
this.requestEndDate = null;
this.quality = NaN;
this.index = NaN;
this.availabilityStartTime = null;
this.availabilityEndTime = null;
this.wallStartTime = null;
this.bytesLoaded = NaN;
this.bytesTotal = NaN;
this.delayLoadingTime = NaN;
this.responseType = 'arraybuffer';
this.representationId = null;
};
FragmentRequest.ACTION_DOWNLOAD = 'download';
FragmentRequest.ACTION_COMPLETE = 'complete';
exports['default'] = FragmentRequest;
module.exports = exports['default'];
},{}]},{},[8])
//# sourceMappingURL=dash.mss.debug.js.map
| extend1994/cdnjs | ajax/libs/dashjs/2.6.8/dash.mss.debug.js | JavaScript | mit | 113,217 |
/* global it, describe, maxTimeout*/
define(["tests/Core", "chai", "Tone/component/CrossFade", "Tone/core/Master", "Tone/signal/Signal",
"Recorder", "Tone/component/Panner", "Tone/component/LFO", "Tone/component/Gate",
"Tone/component/Follower", "Tone/component/Envelope", "Tone/component/Filter", "Tone/component/EQ3",
"Tone/component/Merge", "Tone/component/Split", "tests/Common", "Tone/component/AmplitudeEnvelope",
"Tone/component/LowpassCombFilter", "Tone/component/FeedbackCombFilter", "Tone/component/Mono",
"Tone/component/MultibandSplit", "Tone/component/Compressor", "Tone/component/PanVol",
"Tone/component/MultibandCompressor", "Tone/component/ScaledEnvelope", "Tone/component/Limiter",
"Tone/core/Transport", "Tone/component/Volume", "Tone/component/MidSideSplit",
"Tone/component/MidSideMerge", "Tone/component/MidSideCompressor"],
function(coreTest, chai, CrossFade, Master, Signal, Recorder, Panner, LFO, Gate, Follower, Envelope,
Filter, EQ3, Merge, Split, Test, AmplitudeEnvelope, LowpassCombFilter, FeedbackCombFilter,
Mono, MultibandSplit, Compressor, PanVol, MultibandCompressor, ScaledEnvelope, Limiter, Transport,
Volume, MidSideSplit, MidSideMerge, MidSideCompressor){
var expect = chai.expect;
Master.mute = true;
describe("Tone.CrossFade", function(){
this.timeout(maxTimeout);
var crossFade, drySignal, wetSignal, recorder;
it("can be created and disposed", function(){
var dw = new CrossFade();
dw.dispose();
Test.wasDisposed(dw);
});
it("handles input and output connections", function(){
Test.onlineContext();
var crossFade = new CrossFade();
Test.acceptsInput(crossFade, 0);
Test.acceptsInput(crossFade, 1);
Test.acceptsOutput(crossFade);
crossFade.dispose();
});
it("pass 100% dry signal", function(done){
Test.offlineTest(0.1, function(dest){
crossFade = new CrossFade();
drySignal = new Signal(10);
wetSignal = new Signal(20);
drySignal.connect(crossFade, 0, 0);
wetSignal.connect(crossFade, 0, 1);
recorder = new Recorder();
crossFade.fade.value = 0;
crossFade.connect(dest);
}, function(sample){
expect(sample).to.closeTo(10, 0.01);
}, function(){
crossFade.dispose();
drySignal.dispose();
wetSignal.dispose();
done();
});
});
it("pass 100% wet signal", function(done){
Test.offlineTest(0.1, function(dest){
crossFade = new CrossFade();
drySignal = new Signal(10);
wetSignal = new Signal(20);
drySignal.connect(crossFade, 0, 0);
wetSignal.connect(crossFade, 0, 1);
recorder = new Recorder();
crossFade.fade.value = 1;
crossFade.connect(dest);
}, function(sample){
expect(sample).to.closeTo(20, 0.01);
}, function(){
crossFade.dispose();
drySignal.dispose();
wetSignal.dispose();
done();
});
});
it("can mix two signals", function(done){
Test.offlineTest(0.1, function(dest){
crossFade = new CrossFade();
drySignal = new Signal(0.5);
wetSignal = new Signal(0.5);
drySignal.connect(crossFade, 0, 0);
wetSignal.connect(crossFade, 0, 1);
recorder = new Recorder();
crossFade.fade.value = 0.5;
crossFade.connect(dest);
}, function(sample){
expect(sample).to.closeTo(0.707, 0.01);
}, function(){
crossFade.dispose();
drySignal.dispose();
wetSignal.dispose();
done();
});
});
});
describe("Tone.Panner", function(){
this.timeout(maxTimeout);
it("can be created and disposed", function(){
var panner = new Panner();
panner.dispose();
Test.wasDisposed(panner);
});
it("handles input and output connections", function(){
Test.onlineContext();
var panner = new Panner();
Test.acceptsInputAndOutput(panner);
panner.dispose();
});
it("passes the incoming signal through", function(done){
var panner;
Test.passesAudio(function(input, output){
panner = new Panner();
input.connect(panner);
panner.connect(output);
}, function(){
panner.dispose();
done();
});
});
it("can pan an incoming signal", function(done){
//pan hard right
var signal, panner;
Test.offlineStereoTest(0.1, function(dest){
panner = new Panner();
signal = new Signal(1);
signal.connect(panner);
panner.pan.value = 1;
panner.connect(dest);
}, function(L, R){
expect(L).to.be.closeTo(0, 0.01);
expect(R).to.be.closeTo(1, 0.01);
}, function(){
panner.dispose();
signal.dispose();
done();
});
});
});
describe("Tone.LFO", function(){
this.timeout(maxTimeout);
it("can be created and disposed", function(){
var l = new LFO();
l.dispose();
Test.wasDisposed(l);
});
it("can be started and stopped", function(){
Test.onlineContext();
var lfo = new LFO();
lfo.start();
lfo.stop();
lfo.dispose();
});
it("handles output connections", function(){
Test.onlineContext();
var lfo = new LFO();
Test.acceptsOutput(lfo);
lfo.dispose();
});
it("can sync to Transport", function(done){
var lfo;
Test.offlineTest(0.1, function(dest){
Transport.bpm.value = 120;
lfo = new LFO(2);
lfo.frequency.connect(dest);
lfo.sync();
Transport.bpm.value = 240;
}, function(freq){
expect(freq).to.be.closeTo(4, 0.001);
}, function(){
lfo.dispose();
done();
});
});
it("can unsync to Transport", function(done){
var lfo;
Test.offlineTest(0.1, function(dest){
Transport.bpm.value = 120;
lfo = new LFO(2);
lfo.frequency.connect(dest);
lfo.sync();
Transport.bpm.value = 240;
lfo.unsync();
}, function(freq){
expect(freq).to.be.closeTo(2, 0.001);
}, function(){
lfo.dispose();
done();
});
});
it("can be creates an oscillation in a specific range", function(done){
var lfo;
Test.offlineTest(0.1, function(dest){
lfo = new LFO(100, 10, 20);
lfo.connect(dest);
lfo.start();
}, function(sample){
expect(sample).to.be.within(10, 20);
}, function(){
lfo.dispose();
done();
});
});
it("can change the oscillation range", function(done){
var lfo;
Test.offlineTest(0.1, function(dest){
lfo = new LFO(100, 10, 20);
lfo.connect(dest);
lfo.start();
lfo.min = 15;
lfo.max = 18;
}, function(sample){
expect(sample).to.be.within(15, 18);
}, function(){
lfo.dispose();
done();
});
});
it("handles getters/setters as objects", function(){
var lfo = new LFO();
var values = {
"type" : "square",
"min" : -1,
"max" : 2,
"phase" : 180,
"frequency" : "8n",
};
lfo.set(values);
expect(lfo.get()).to.contain.keys(Object.keys(values));
expect(lfo.type).to.equal(values.type);
expect(lfo.min).to.equal(values.min);
expect(lfo.max).to.equal(values.max);
expect(lfo.phase).to.equal(values.phase);
lfo.dispose();
});
});
describe("Tone.Gate", function(){
this.timeout(maxTimeout);
it("can be created and disposed", function(){
var g = new Gate();
g.dispose();
Test.wasDisposed(g);
});
it("handles input and output connections", function(){
Test.onlineContext();
var gate = new Gate();
Test.acceptsInputAndOutput(gate);
gate.dispose();
});
it("handles getter/setters", function(){
Test.onlineContext();
var gate = new Gate();
var values = {
"attack" : "4n",
"release" : "8n",
"threshold" : -25,
};
gate.set(values);
expect(gate.get()).to.have.keys(["attack", "release", "threshold"]);
expect(gate.attack).to.equal(values.attack);
expect(gate.decay).to.equal(values.decay);
expect(gate.threshold).to.be.closeTo(values.threshold, 0.1);
gate.dispose();
});
it("won't let signals below a db thresh through", function(done){
var gate, sig;
Test.offlineTest(0.5, function(dest){
gate = new Gate(-10, 0.01);
sig = new Signal(gate.dbToGain(-11));
sig.connect(gate);
gate.connect(dest);
}, function(sample){
expect(sample).to.equal(0);
}, function(){
gate.dispose();
sig.dispose();
done();
});
});
it("lets signals above the db thresh through", function(done){
var gate, sig, level;
Test.offlineTest(0.5, function(dest){
gate = new Gate(-8, 0.01);
level = gate.dbToGain(-6);
sig = new Signal(level);
sig.connect(gate);
gate.connect(dest);
}, function(sample, time){
if (time >= 0.1){
expect(sample).to.be.closeTo(level, 0.001);
}
}, function(){
gate.dispose();
sig.dispose();
done();
});
});
});
describe("Tone.Follower", function(){
this.timeout(maxTimeout);
it("can be created and disposed", function(){
var f = new Follower();
f.dispose();
Test.wasDisposed(f);
});
it("handles input and output connections", function(){
Test.onlineContext();
var foll = new Follower(0.1, 0.5);
Test.acceptsInputAndOutput(foll);
foll.dispose();
});
it("smoothes the incoming signal", function(done){
var foll, sig;
Test.offlineTest(0.1, function(dest){
foll = new Follower(0.1, 0.5);
sig = new Signal(0);
sig.connect(foll);
foll.connect(dest);
sig.setValueAtTime(1, "+0.1");
}, function(sample){
expect(sample).to.lessThan(1);
}, function(){
foll.dispose();
sig.dispose();
done();
});
});
it("handles getter/setter as Object", function(){
var foll = new Follower();
var values = {
"attack" : "8n",
"release" : "4n"
};
foll.set(values);
expect(foll.get()).to.have.keys(["attack", "release"]);
expect(foll.get()).to.deep.equal(values);
foll.dispose();
});
});
describe("Tone.Envelope", function(){
this.timeout(maxTimeout);
it("can be created and disposed", function(){
var e = new Envelope();
e.dispose();
Test.wasDisposed(e);
});
it("handles output connections", function(){
Test.onlineContext();
var e = new Envelope();
Test.acceptsOutput(e);
e.dispose();
});
it ("can take parameters as both an object and as arguments", function(){
var e0 = new Envelope({
"attack" : 0,
"decay" : 0.5,
"sustain" : 1
});
expect(e0.attack).to.equal(0);
expect(e0.decay).to.equal(0.5);
expect(e0.sustain).to.equal(1);
e0.dispose();
var e1 = new Envelope(0.1, 0.2, 0.3);
expect(e1.attack).to.equal(0.1);
expect(e1.decay).to.equal(0.2);
expect(e1.sustain).to.equal(0.3);
e1.dispose();
});
it ("can schedule an ADSR envelope", function(done){
var env;
Test.offlineTest(0.7, function(dest){
env = new Envelope(0.1, 0.2, 0.5, 0.1);
env.connect(dest);
env.triggerAttack(0);
env.triggerRelease(0.4);
}, function(sample, time){
if (time < 0.1){
expect(sample).to.be.within(0, 1);
} else if (time < 0.3){
expect(sample).to.be.within(0.5, 1);
} else if (time < 0.4){
expect(sample).to.be.within(0.499, 0.51);
} else if (time < 0.5){
expect(sample).to.be.within(0, 0.51);
} else {
expect(sample).to.be.below(0.1);
}
}, function(){
env.dispose();
done();
});
});
it ("can get and set values an Objects", function(){
var env = new Envelope();
var values = {
"attack" : 0,
"decay" : 0.5,
"sustain" : 1,
"release" : "4n"
};
env.set(values);
expect(env.get()).to.contain.keys(Object.keys(values));
env.dispose();
});
it ("can schedule an attackRelease", function(done){
var env;
Test.offlineTest(0.7, function(dest){
env = new Envelope(0.1, 0.2, 0.5, 0.1);
env.connect(dest);
env.triggerAttackRelease(0.4, 0);
}, function(sample, time){
if (time < 0.1){
expect(sample).to.be.within(0, 1);
} else if (time < 0.3){
expect(sample).to.be.within(0.5, 1);
} else if (time < 0.4){
expect(sample).to.be.within(0.499, 0.51);
} else if (time < 0.5){
expect(sample).to.be.within(0, 0.51);
} else {
expect(sample).to.be.below(0.1);
}
}, function(){
env.dispose();
done();
});
});
});
describe("Tone.Filter", function(){
this.timeout(maxTimeout);
it("can be created and disposed", function(){
var f = new Filter();
f.dispose();
Test.wasDisposed(f);
});
it("handles input and output connections", function(){
Test.onlineContext();
var f = new Filter();
Test.acceptsInputAndOutput(f);
f.dispose();
});
it("can set/get values as an Object", function(){
var f = new Filter();
var values = {
"type" : "highpass",
"frequency" : 440,
"rolloff" : -24,
"Q" : 2,
"gain" : -6,
};
f.set(values);
expect(f.get()).to.have.keys(["type", "frequency", "rolloff", "Q", "gain"]);
expect(f.type).to.equal(values.type);
expect(f.frequency.value).to.equal(values.frequency);
expect(f.rolloff).to.equal(values.rolloff);
expect(f.Q.value).to.equal(values.Q);
expect(f.gain.value).to.be.closeTo(values.gain, 0.04);
f.dispose();
});
it("passes the incoming signal through", function(done){
var filter;
Test.passesAudio(function(input, output){
filter = new Filter();
input.connect(filter);
filter.connect(output);
}, function(){
filter.dispose();
done();
});
});
it ("can take parameters as both an object and as arguments", function(){
Test.onlineContext();
var f0 = new Filter({
"frequency" : 1000,
"type" : "highpass"
});
expect(f0.frequency.value).to.equal(1000);
expect(f0.type).to.equal("highpass");
f0.dispose();
var f1 = new Filter(200, "bandpass");
expect(f1.frequency.value).to.equal(200);
expect(f1.type).to.equal("bandpass");
f1.dispose();
});
});
describe("Tone.EQ33", function(){
this.timeout(maxTimeout);
it("can be created and disposed", function(){
var eq = new EQ3();
eq.dispose();
Test.wasDisposed(eq);
});
it("handles input and output connections", function(){
Test.onlineContext();
var eq = new EQ3();
Test.acceptsInputAndOutput(eq);
eq.dispose();
});
it("passes the incoming signal through", function(done){
var eq;
Test.passesAudio(function(input, output){
eq = new EQ3();
input.connect(eq);
eq.connect(output);
}, function(){
eq.dispose();
done();
});
});
it("can set/get values as an Object", function(){
Test.onlineContext();
var eq = new EQ3();
var values = {
"high" : -12,
"mid" : -24,
"low" : -1
};
eq.set(values);
expect(eq.high.value).to.be.closeTo(values.high, 0.1);
expect(eq.mid.value).to.be.closeTo(values.mid, 0.1);
expect(eq.low.value).to.be.closeTo(values.low, 0.1);
eq.dispose();
});
});
//MERGE
describe("Tone.Merge", function(){
this.timeout(maxTimeout);
it("can be created and disposed", function(){
var mer = new Merge();
mer.dispose();
Test.wasDisposed(mer);
});
it("handles input and output connections", function(){
Test.onlineContext();
var mer = new Merge();
Test.acceptsInput(mer.left);
Test.acceptsInput(mer.right);
Test.acceptsOutput(mer);
mer.dispose();
});
it("merge two signal into one stereo signal", function(done){
//make an oscillator to drive the signal
var sigL, sigR, merger;
Test.offlineStereoTest(0.1, function(dest){
sigL = new Signal(1);
sigR = new Signal(2);
merger = new Merge();
sigL.connect(merger.left);
sigR.connect(merger.right);
merger.connect(dest);
}, function(L, R){
expect(L).to.equal(1);
expect(R).to.equal(2);
}, function(){
sigL.dispose();
sigR.dispose();
merger.dispose();
done();
});
});
});
describe("Tone.Split", function(){
this.timeout(maxTimeout);
it("can be created and disposed", function(){
var split = new Split();
split.dispose();
Test.wasDisposed(split);
});
it("handles input and output connections", function(){
Test.onlineContext();
var split = new Split();
Test.acceptsInput(split);
Test.acceptsOutput(split.left);
Test.acceptsOutput(split.right);
split.dispose();
});
it("merges two signal into one stereo signal and then split them back into two signals on left side", function(done){
var sigL, sigR, merger, split;
Test.offlineTest(0.1, function(dest){
sigL = new Signal(1);
sigR = new Signal(2);
merger = new Merge();
split = new Split();
sigL.connect(merger.left);
sigR.connect(merger.right);
merger.connect(split);
split.connect(dest, 0, 0);
}, function(sample){
expect(sample).to.equal(1);
}, function(){
sigL.dispose();
sigR.dispose();
merger.dispose();
split.dispose();
done();
});
});
it("merges two signal into one stereo signal and then split them back into two signals on right side", function(done){
var sigL, sigR, merger, split;
Test.offlineTest(0.1, function(dest){
sigL = new Signal(1);
sigR = new Signal(2);
merger = new Merge();
split = new Split();
sigL.connect(merger.left);
sigR.connect(merger.right);
merger.connect(split);
split.connect(dest, 1, 0);
}, function(sample){
expect(sample).to.equal(2);
}, function(){
sigL.dispose();
sigR.dispose();
merger.dispose();
split.dispose();
done();
});
});
});
describe("Tone.AmplitudeEnvelope", function(){
this.timeout(maxTimeout);
it("can be created and disposed", function(){
var ampEnv = new AmplitudeEnvelope();
ampEnv.dispose();
Test.wasDisposed(ampEnv);
});
it("handles input and output connections", function(){
Test.onlineContext();
var ampEnv = new AmplitudeEnvelope();
Test.acceptsInputAndOutput(ampEnv);
ampEnv.dispose();
});
it("inherits all methods from Envelope", function(){
var ampEnv = new AmplitudeEnvelope();
expect(ampEnv).to.be.instanceOf(Envelope);
ampEnv.dispose();
});
});
describe("Tone.LowpassCombFilter", function(){
this.timeout(maxTimeout);
it("can be created and disposed", function(){
var lfcf = new LowpassCombFilter();
lfcf.dispose();
Test.wasDisposed(lfcf);
});
it("handles input and output connections", function(){
Test.onlineContext();
var lfcf = new LowpassCombFilter();
Test.acceptsInputAndOutput(lfcf);
lfcf.dispose();
});
it("passes the incoming signal through", function(done){
var lfcf;
Test.passesAudio(function(input, output){
lfcf = new LowpassCombFilter();
input.connect(lfcf);
lfcf.connect(output);
}, function(){
lfcf.dispose();
done();
});
});
it("handles getters/setters", function(){
Test.onlineContext();
var lfcf = new LowpassCombFilter();
var values = {
"resonance" : 0.4,
"dampening" : 4000,
"delayTime" : "4n"
};
lfcf.set(values);
expect(lfcf.get()).to.have.keys(["resonance", "dampening", "delayTime"]);
lfcf.dispose();
});
});
describe("Tone.FeedbackCombFilter", function(){
this.timeout(maxTimeout);
it("can be created and disposed", function(){
var fbcf = new FeedbackCombFilter();
fbcf.dispose();
Test.wasDisposed(fbcf);
});
it("handles input and output connections", function(){
Test.onlineContext();
var fbcf = new FeedbackCombFilter();
Test.acceptsInputAndOutput(fbcf);
fbcf.dispose();
});
it("can set delayTime", function(){
Test.onlineContext();
var fbcf = new FeedbackCombFilter();
fbcf.delayTime.value = "4n";
var quarterSeconds = fbcf.toSeconds("4n");
expect(fbcf.delayTime.value).to.equal(quarterSeconds);
fbcf.dispose();
});
it("passes the incoming signal through", function(done){
var fbcf;
Test.passesAudio(function(input, output){
fbcf = new FeedbackCombFilter();
input.connect(fbcf);
fbcf.connect(output);
}, function(){
fbcf.dispose();
done();
});
});
});
describe("Tone.Mono", function(){
this.timeout(maxTimeout);
it("can be created and disposed", function(){
var mono = new Mono();
mono.dispose();
Test.wasDisposed(mono);
});
it("handles input and output connections", function(){
Test.onlineContext();
var mono = new Mono();
Test.acceptsInputAndOutput(mono);
mono.dispose();
});
it("passes the incoming signal through", function(done){
var mono;
Test.passesAudio(function(input, output){
mono = new FeedbackCombFilter();
input.connect(mono);
mono.connect(output);
}, function(){
mono.dispose();
done();
});
});
});
describe("Tone.MultibandSplit", function(){
this.timeout(maxTimeout);
it("can be created and disposed", function(){
var mband = new MultibandSplit();
mband.dispose();
Test.wasDisposed(mband);
});
it("handles input and output connections", function(){
Test.onlineContext();
var mband = new MultibandSplit();
Test.acceptsInput(mband);
Test.acceptsOutput(mband.low);
Test.acceptsOutput(mband, 1);
Test.acceptsOutput(mband, 2);
mband.dispose();
});
});
describe("Tone.Compressor", function(){
this.timeout(maxTimeout);
it("can be created and disposed", function(){
var comp = new Compressor();
comp.dispose();
Test.wasDisposed(comp);
});
it("handles input and output connections", function(){
Test.onlineContext();
var comp = new Compressor();
Test.acceptsInputAndOutput(comp);
comp.dispose();
});
it("passes the incoming signal through", function(done){
var comp;
Test.passesAudio(function(input, output){
comp = new Compressor();
input.connect(comp);
comp.connect(output);
}, function(){
comp.dispose();
done();
});
});
it("can be get and set through object", function(){
var comp = new Compressor();
var values = {
"ratio" : 22,
"threshold" : -30,
"release" : 0.5,
"attack" : 0.03,
"knee" : 20
};
comp.set(values);
expect(comp.get()).to.have.keys(["ratio", "threshold", "release", "attack", "ratio"]);
comp.dispose();
});
it("can get/set all interfaces", function(){
var comp = new Compressor();
var values = {
"ratio" : 22,
"threshold" : -30,
"release" : 0.5,
"attack" : 0.03,
"knee" : 20
};
comp.ratio.value = values.ratio;
comp.threshold.value = values.threshold;
comp.release.value = values.release;
comp.attack.value = values.attack;
comp.knee.value = values.knee;
expect(comp.ratio.value).to.equal(values.ratio);
expect(comp.threshold.value).to.equal(values.threshold);
expect(comp.release.value).to.equal(values.release);
expect(comp.attack.value).to.be.closeTo(values.attack, 0.01);
expect(comp.knee.value).to.equal(values.knee);
comp.dispose();
});
});
describe("Tone.PanVol", function(){
this.timeout(maxTimeout);
it("can be created and disposed", function(){
var panvol = new PanVol();
panvol.dispose();
Test.wasDisposed(panvol);
});
it("handles input and output connections", function(){
Test.onlineContext();
var panvol = new PanVol();
Test.acceptsInputAndOutput(panvol);
panvol.dispose();
});
it("passes the incoming signal through", function(done){
var panvol;
Test.passesAudio(function(input, output){
panvol = new PanVol();
input.connect(panvol);
panvol.connect(output);
}, function(){
panvol.dispose();
done();
});
});
it("can set the pan and volume", function(){
var panvol = new PanVol();
panvol.volume.value = -12;
panvol.pan.value = 0;
expect(panvol.volume.value).to.be.closeTo(-12, 0.1);
expect(panvol.pan.value).to.be.equal(0);
});
});
describe("Tone.MultibandCompressor", function(){
this.timeout(maxTimeout);
it("can be created and disposed", function(){
var comp = new MultibandCompressor();
comp.dispose();
Test.wasDisposed(comp);
});
it("handles input and output connections", function(){
Test.onlineContext();
var comp = new MultibandCompressor();
Test.acceptsInputAndOutput(comp);
comp.dispose();
});
it("passes the incoming signal through", function(done){
var comp;
Test.passesAudio(function(input, output){
comp = new MultibandCompressor();
input.connect(comp);
comp.connect(output);
}, function(){
comp.dispose();
done();
});
});
it("handles getters/setters", function(){
Test.onlineContext();
var comp = new MultibandCompressor();
var values = {
"low" : {
"attack" : 0.3
},
"mid" : {
"threshold" : -12
}
};
comp.set(values);
expect(comp.get()).to.have.deep.property("low.attack");
expect(comp.get()).to.have.deep.property("mid.threshold");
expect(comp.low.attack.value).to.be.closeTo(0.3, 0.05);
expect(comp.mid.threshold.value).to.be.closeTo(-12, 0.05);
comp.dispose();
});
});
describe("Tone.ScaledEnvelope", function(){
this.timeout(maxTimeout);
it("can be created and disposed", function(){
var e = new ScaledEnvelope();
e.dispose();
Test.wasDisposed(e);
});
it("handles output connections", function(){
Test.onlineContext();
var e = new ScaledEnvelope();
Test.acceptsOutput(e);
e.dispose();
});
it ("can take parameters as an object", function(){
var e0 = new ScaledEnvelope({
"attack" : 0,
"decay" : 0.5,
"sustain" : 1,
"min" : 10,
"max": 5
});
expect(e0.attack).to.equal(0);
expect(e0.decay).to.equal(0.5);
expect(e0.sustain).to.equal(1);
e0.dispose();
});
it ("can schedule an ADSR envelope", function(done){
var env;
Test.offlineTest(0.7, function(dest){
env = new ScaledEnvelope({
"attack" : 0.1,
"decay" : 0.2,
"sustain" : 0.5,
"release" : 0.1,
"min" : 0,
"max": 100
});
env.connect(dest);
env.triggerAttack(0);
env.triggerRelease(0.4);
}, function(sample, time){
if (time < 0.1){
expect(sample).to.be.within(0, 100);
} else if (time < 0.3){
expect(sample).to.be.within(0.5, 100);
} else if (time < 0.4){
expect(sample).to.be.within(0.5, 51);
} else if (time < 0.5){
expect(sample).to.be.within(0, 51);
} else {
expect(sample).to.be.below(1);
}
}, function(){
env.dispose();
done();
});
});
it ("can scale the range", function(done){
var env;
Test.offlineTest(0.7, function(dest){
env = new ScaledEnvelope(0.1, 0.2, 0.5, 0.1);
env.connect(dest);
env.min = 5;
env.max = 10;
env.triggerAttack(0.1);
}, function(sample, time){
if (time < 0.1){
expect(sample).to.be.closeTo(5, 0.1);
} else if (time < 0.2){
expect(sample).to.be.within(5, 10);
}
}, function(){
env.dispose();
done();
});
});
});
describe("Tone.Limiter", function(){
this.timeout(maxTimeout);
it("can be created and disposed", function(){
var lim = new Limiter();
lim.dispose();
Test.wasDisposed(lim);
});
it("handles input and output connections", function(){
Test.onlineContext();
var lim = new Limiter();
Test.acceptsInputAndOutput(lim);
lim.dispose();
});
it("can get and set values", function(){
Test.onlineContext();
var lim = new Limiter();
lim.threshold.value = -12;
expect(lim.threshold.value).to.be.closeTo(-12, 0.05);
lim.dispose();
});
it("passes the incoming signal through", function(done){
var lim;
Test.passesAudio(function(input, output){
lim = new Limiter();
input.connect(lim);
lim.connect(output);
}, function(){
lim.dispose();
done();
});
});
});
describe("Tone.Volume", function(){
this.timeout(maxTimeout);
it("can be created and disposed", function(){
var vol = new Volume();
vol.dispose();
Test.wasDisposed(vol);
});
it("handles input and output connections", function(){
Test.onlineContext();
var vol = new Volume();
Test.acceptsInputAndOutput(vol);
vol.dispose();
});
it("can get and set values", function(){
Test.onlineContext();
var vol = new Volume();
vol.volume.value = -12;
expect(vol.volume.value).to.be.closeTo(-12, 0.05);
vol.dispose();
});
it("passes the incoming signal through", function(done){
var vol;
Test.passesAudio(function(input, output){
vol = new Volume();
input.connect(vol);
vol.connect(output);
}, function(){
vol.dispose();
done();
});
});
});
describe("Tone.MidSideSplit", function(){
this.timeout(maxTimeout);
it("can be created and disposed", function(){
var split = new MidSideSplit();
split.dispose();
Test.wasDisposed(split);
});
it("handles input and output connections", function(){
Test.onlineContext();
var split = new MidSideSplit();
Test.acceptsInput(split);
Test.acceptsOutput(split.mid);
Test.acceptsOutput(split.side);
split.dispose();
});
});
describe("Tone.MidSideMerge", function(){
this.timeout(maxTimeout);
it("can be created and disposed", function(){
var merge = new MidSideMerge();
merge.dispose();
Test.wasDisposed(merge);
});
it("handles input and output connections", function(){
Test.onlineContext();
var merge = new MidSideMerge();
Test.acceptsInput(merge.side);
Test.acceptsInput(merge.mid);
Test.acceptsOutput(merge);
merge.dispose();
});
it("passes the mid signal through", function(done){
var merge;
Test.passesAudio(function(input, output){
merge = new MidSideMerge();
input.connect(merge.mid);
merge.connect(output);
}, function(){
merge.dispose();
done();
});
});
it("passes the side signal through", function(done){
var merge;
Test.passesAudio(function(input, output){
merge = new MidSideMerge();
input.connect(merge.side);
merge.connect(output);
}, function(){
merge.dispose();
done();
});
});
});
describe("Tone.MidSideCompressor", function(){
this.timeout(maxTimeout);
it("can be created and disposed", function(){
var comp = new MidSideCompressor();
comp.dispose();
Test.wasDisposed(comp);
});
it("handles input and output connections", function(){
Test.onlineContext();
var comp = new MidSideCompressor();
Test.acceptsInput(comp);
Test.acceptsOutput(comp);
comp.dispose();
});
it("passes signal through", function(done){
var comp;
Test.passesAudio(function(input, output){
comp = new MidSideCompressor();
input.connect(comp);
comp.connect(output);
}, function(){
comp.dispose();
done();
});
});
});
}); | nickells/Tone.js | test/tests/Components.js | JavaScript | mit | 30,333 |
/* eslint max-statements: 0 */
// Support for functions returning promise
"use strict";
var objectMap = require("es5-ext/object/map")
, primitiveSet = require("es5-ext/object/primitive-set")
, ensureString = require("es5-ext/object/validate-stringifiable-value")
, toShortString = require("es5-ext/to-short-string-representation")
, isPromise = require("is-promise")
, nextTick = require("next-tick");
var create = Object.create
, supportedModes = primitiveSet("then", "then:finally", "done", "done:finally");
require("../lib/registered-extensions").promise = function (mode, conf) {
var waiting = create(null), cache = create(null), promises = create(null);
if (mode === true) {
mode = null;
} else {
mode = ensureString(mode);
if (!supportedModes[mode]) {
throw new TypeError("'" + toShortString(mode) + "' is not valid promise mode");
}
}
// After not from cache call
conf.on("set", function (id, ignore, promise) {
var isFailed = false;
if (!isPromise(promise)) {
// Non promise result
cache[id] = promise;
conf.emit("setasync", id, 1);
return;
}
waiting[id] = 1;
promises[id] = promise;
var onSuccess = function (result) {
var count = waiting[id];
if (isFailed) {
throw new Error(
"Memoizee error: Detected unordered then|done & finally resolution, which " +
"in turn makes proper detection of success/failure impossible (when in " +
"'done:finally' mode)\n" +
"Consider to rely on 'then' or 'done' mode instead."
);
}
if (!count) return; // Deleted from cache before resolved
delete waiting[id];
cache[id] = result;
conf.emit("setasync", id, count);
};
var onFailure = function () {
isFailed = true;
if (!waiting[id]) return; // Deleted from cache (or succeed in case of finally)
delete waiting[id];
delete promises[id];
conf.delete(id);
};
var resolvedMode = mode;
if (!resolvedMode) resolvedMode = "then";
if (resolvedMode === "then") {
var nextTickFailure = function () { nextTick(onFailure); };
// Eventual finally needs to be attached to non rejected promise
// (so we not force propagation of unhandled rejection)
promise = promise.then(function (result) {
nextTick(onSuccess.bind(this, result));
}, nextTickFailure);
// If `finally` is a function we attach to it to remove cancelled promises.
if (typeof promise.finally === "function") {
promise.finally(nextTickFailure);
}
} else if (resolvedMode === "done") {
// Not recommended, as it may mute any eventual "Unhandled error" events
if (typeof promise.done !== "function") {
throw new Error(
"Memoizee error: Retrieved promise does not implement 'done' " +
"in 'done' mode"
);
}
promise.done(onSuccess, onFailure);
} else if (resolvedMode === "done:finally") {
// The only mode with no side effects assuming library does not throw unconditionally
// for rejected promises.
if (typeof promise.done !== "function") {
throw new Error(
"Memoizee error: Retrieved promise does not implement 'done' " +
"in 'done:finally' mode"
);
}
if (typeof promise.finally !== "function") {
throw new Error(
"Memoizee error: Retrieved promise does not implement 'finally' " +
"in 'done:finally' mode"
);
}
promise.done(onSuccess);
promise.finally(onFailure);
}
});
// From cache (sync)
conf.on("get", function (id, args, context) {
var promise;
if (waiting[id]) {
++waiting[id]; // Still waiting
return;
}
promise = promises[id];
var emit = function () { conf.emit("getasync", id, args, context); };
if (isPromise(promise)) {
if (typeof promise.done === "function") promise.done(emit);
else {
promise.then(function () { nextTick(emit); });
}
} else {
emit();
}
});
// On delete
conf.on("delete", function (id) {
delete promises[id];
if (waiting[id]) {
delete waiting[id];
return; // Not yet resolved
}
if (!hasOwnProperty.call(cache, id)) return;
var result = cache[id];
delete cache[id];
conf.emit("deleteasync", id, [result]);
});
// On clear
conf.on("clear", function () {
var oldCache = cache;
cache = create(null);
waiting = create(null);
promises = create(null);
conf.emit("clearasync", objectMap(oldCache, function (data) { return [data]; }));
});
};
| evilz/evilz.github.io | node_modules/memoizee/ext/promise.js | JavaScript | mit | 4,373 |
if(true) {
console.log(true);
}
| jimenglish81/ember-suave | tests/fixtures/rules/require-space-after-keywords/bad/if.js | JavaScript | mit | 34 |
'use strict';
module.exports = {
'GET /api/example': function (req, res) {
setTimeout(function () {
res.json({
success: true,
data: ['foo', 'bar'],
});
}, 500);
},
};
| iWantMoneyMore/ykj | ykj-web/mock/example.js | JavaScript | gpl-2.0 | 210 |
//= testdir! | AlexanderDolgan/juliawp | wp-content/themes/node_modules/gulp-rigger/node_modules/rigger/test/input-aliases/local-includedir.js | JavaScript | gpl-2.0 | 12 |
module.exports = function( grunt ) {
'use strict';
var banner = '/**\n * <%= pkg.homepage %>\n * Copyright (c) <%= grunt.template.today("yyyy") %>\n * This file is generated automatically. Do not edit.\n */\n';
require('phplint').gruntPlugin(grunt);
// Project configuration
grunt.initConfig( {
pkg: grunt.file.readJSON( 'package.json' ),
phpcs: {
plugin: {
src: './'
},
options: {
bin: "vendor/bin/phpcs --extensions=php --ignore=\"*/vendor/*,*/node_modules/*\"",
standard: "phpcs.ruleset.xml"
}
},
phplint: {
options: {
limit: 10,
stdout: true,
stderr: true
},
files: ['lib/**/*.php', 'tests/*.php', '*.php']
},
phpunit: {
'default': {
cmd: 'phpunit',
args: ['-c', 'phpunit.xml.dist']
},
},
} );
grunt.loadNpmTasks( 'grunt-phpcs' );
// Testing tasks.
grunt.registerMultiTask('phpunit', 'Runs PHPUnit tests, including the ajax, external-http, and multisite tests.', function() {
grunt.util.spawn({
cmd: this.data.cmd,
args: this.data.args,
opts: {stdio: 'inherit'}
}, this.async());
});
grunt.registerTask( 'test', [ 'phpcs', 'phplint', 'phpunit' ] );
grunt.util.linefeed = '\n';
};
| ntamvl/an001 | wp-content/plugins/WP-API-develop/Gruntfile.js | JavaScript | gpl-2.0 | 1,194 |
/*
* Copyright (C) eZ Systems AS. All rights reserved.
* For full copyright and license information view LICENSE file distributed with this source code.
*/
YUI.add('ez-textline-editview-tests', function (Y) {
var viewTest, registerTest, getFieldTest;
viewTest = new Y.Test.Case({
name: "eZ Text Line View test",
_getFieldDefinition: function (required, minLength, maxLength) {
return {
isRequired: required,
validatorConfiguration: {
StringLengthValidator: {
minStringLength: minLength,
maxStringLength: maxLength
}
}
};
},
setUp: function () {
this.field = {};
this.jsonContent = {};
this.jsonContentType = {};
this.jsonVersion = {};
this.content = new Y.Mock();
this.version = new Y.Mock();
this.contentType = new Y.Mock();
Y.Mock.expect(this.content, {
method: 'toJSON',
returns: this.jsonContent
});
Y.Mock.expect(this.version, {
method: 'toJSON',
returns: this.jsonVersion
});
Y.Mock.expect(this.contentType, {
method: 'toJSON',
returns: this.jsonContentType
});
this.view = new Y.eZ.TextLineEditView({
container: '.container',
field: this.field,
content: this.content,
version: this.version,
contentType: this.contentType
});
},
tearDown: function () {
this.view.destroy();
},
_testAvailableVariables: function (required, minLength, maxLength, expectRequired, expectMinLength, expectMinLengthPattern, expectMaxLength) {
var fieldDefinition = this._getFieldDefinition(required, minLength, maxLength),
that = this;
this.view.set('fieldDefinition', fieldDefinition);
this.view.template = function (variables) {
Y.Assert.isObject(variables, "The template should receive some variables");
Y.Assert.areEqual(9, Y.Object.keys(variables).length, "The template should receive 9 variables");
Y.Assert.areSame(
that.jsonContent, variables.content,
"The content should be available in the field edit view template"
);
Y.Assert.areSame(
that.jsonVersion, variables.version,
"The version should be available in the field edit view template"
);
Y.Assert.areSame(
that.jsonContentType, variables.contentType,
"The contentType should be available in the field edit view template"
);
Y.Assert.areSame(
fieldDefinition, variables.fieldDefinition,
"The fieldDefinition should be available in the field edit view template"
);
Y.Assert.areSame(
that.field, variables.field,
"The field should be available in the field edit view template"
);
Y.Assert.areSame(expectRequired, variables.isRequired);
Y.Assert.areSame(expectMinLength, variables.minLength);
Y.Assert.areSame(expectMinLengthPattern, variables.minLengthPattern);
Y.Assert.areSame(expectMaxLength, variables.maxLength);
return '';
};
this.view.render();
},
"Test not required field no constraints": function () {
this._testAvailableVariables(false, false, false, false, false, false, false);
},
"Test required field no constraints": function () {
this._testAvailableVariables(true, false, false, true, false, false, false);
},
"Test not required field with min length constraint": function () {
this._testAvailableVariables(false, 10, false, true, 10, '.{10,}', false);
},
"Test required field with constraints": function () {
this._testAvailableVariables(true, 10, 50, true, 10, '.{10,}', 50);
},
"Test not required field with constraints": function () {
this._testAvailableVariables(false, 10, 50, true, 10, '.{10,}', 50);
},
"Test validate no constraints": function () {
var fieldDefinition = this._getFieldDefinition(false, false, false),
input;
this.view.set('fieldDefinition', fieldDefinition);
this.view.render();
this.view.validate();
Y.Assert.isTrue(
this.view.isValid(),
"An empty input is valid"
);
input = Y.one('.container input');
input.set('value', 'foobar');
Y.Assert.isTrue(
this.view.isValid(),
"A non empty input is valid"
);
},
"Test validate required": function () {
var fieldDefinition = this._getFieldDefinition(true, false, false),
input;
this.view.set('fieldDefinition', fieldDefinition);
this.view.render();
input = Y.one('.container input');
input.set('value', 'foobar');
this.view.validate();
Y.Assert.isTrue(
this.view.isValid(),
"A non empty input is valid"
);
input.set('value', '');
this.view.validate();
Y.Assert.isFalse(
this.view.isValid(),
"An empty input is invalid"
);
},
"Test validate min length": function () {
var fieldDefinition = this._getFieldDefinition(false, 5, false),
input;
this.view.set('fieldDefinition', fieldDefinition);
this.view.render();
input = Y.one('.container input');
input.set('value', 'foobar');
this.view.validate();
Y.Assert.isTrue(
this.view.isValid(),
"'foobar' is valid"
);
input.set('value', 'foo');
this.view.validate();
Y.Assert.isFalse(
this.view.isValid(),
"'foo' is invalid"
);
input.set('value', '');
this.view.validate();
Y.Assert.isFalse(
this.view.isValid(),
"An empty string is invalid"
);
},
"Test validate required && min length": function () {
var fieldDefinition = this._getFieldDefinition(true, 5, false),
input;
this.view.set('fieldDefinition', fieldDefinition);
this.view.render();
input = Y.one('.container input');
input.set('value', 'foobar');
this.view.validate();
Y.Assert.isTrue(
this.view.isValid(),
"'foobar' is valid"
);
input.set('value', 'foo');
this.view.validate();
Y.Assert.isFalse(
this.view.isValid(),
"'foo' is invalid"
);
input.set('value', '');
this.view.validate();
Y.Assert.isFalse(
this.view.isValid(),
"An empty string is invalid"
);
}
});
Y.Test.Runner.setName("eZ Text Line Edit View tests");
Y.Test.Runner.add(viewTest);
getFieldTest = new Y.Test.Case(
Y.merge(Y.eZ.Test.GetFieldTests, {
fieldDefinition: {isRequired: false, validatorConfiguration: {StringLengthValidator: {}}},
ViewConstructor: Y.eZ.TextLineEditView,
newValue: 'Led Zeppelin',
})
);
Y.Test.Runner.add(getFieldTest);
registerTest = new Y.Test.Case(Y.eZ.EditViewRegisterTest);
registerTest.name = "Text Line Edit View registration test";
registerTest.viewType = Y.eZ.TextLineEditView;
registerTest.viewKey = "ezstring";
Y.Test.Runner.add(registerTest);
}, '', {requires: ['test', 'getfield-tests', 'editviewregister-tests', 'ez-textline-editview']});
| flovntp/BikeTutorialWebsite | vendor/ezsystems/platform-ui-bundle/Tests/js/views/fields/assets/ez-textline-editview-tests.js | JavaScript | gpl-2.0 | 8,506 |
/**
* @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
/**
* @fileOverview
*/
/**#@+
@type String
@example
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKEDITOR.lang[ 'sv' ] = {
// ARIA description.
editor: 'Rich Text Editor',
editorPanel: 'Rich Text Editor panel',
// Common messages and labels.
common: {
// Screenreader titles. Please note that screenreaders are not always capable
// of reading non-English words. So be careful while translating it.
editorHelp: 'Tryck ALT 0 för hjälp',
browseServer: 'Bläddra på server',
url: 'URL',
protocol: 'Protokoll',
upload: 'Ladda upp',
uploadSubmit: 'Skicka till server',
image: 'Bild',
flash: 'Flash',
form: 'Formulär',
checkbox: 'Kryssruta',
radio: 'Alternativknapp',
textField: 'Textfält',
textarea: 'Textruta',
hiddenField: 'Dolt fält',
button: 'Knapp',
select: 'Flervalslista',
imageButton: 'Bildknapp',
notSet: '<ej angivet>',
id: 'Id',
name: 'Namn',
langDir: 'Språkriktning',
langDirLtr: 'Vänster till Höger (VTH)',
langDirRtl: 'Höger till Vänster (HTV)',
langCode: 'Språkkod',
longDescr: 'URL-beskrivning',
cssClass: 'Stilmall',
advisoryTitle: 'Titel',
cssStyle: 'Stilmall',
ok: 'OK',
cancel: 'Avbryt',
close: 'Stäng',
preview: 'Förhandsgranska',
resize: 'Dra för att ändra storlek',
generalTab: 'Allmänt',
advancedTab: 'Avancerad',
validateNumberFailed: 'Värdet är inte ett nummer.',
confirmNewPage: 'Alla ändringar i innehållet kommer att förloras. Är du säker på att du vill ladda en ny sida?',
confirmCancel: 'Några av alternativen har ändrats. Är du säker på att du vill stänga dialogrutan?',
options: 'Alternativ',
target: 'Mål',
targetNew: 'Nytt fönster (_blank)',
targetTop: 'Översta fönstret (_top)',
targetSelf: 'Samma fönster (_self)',
targetParent: 'Föregående fönster (_parent)',
langDirLTR: 'Vänster till höger (LTR)',
langDirRTL: 'Höger till vänster (RTL)',
styles: 'Stil',
cssClasses: 'Stilmallar',
width: 'Bredd',
height: 'Höjd',
align: 'Justering',
alignLeft: 'Vänster',
alignRight: 'Höger',
alignCenter: 'Centrerad',
alignJustify: 'Justera till marginaler',
alignTop: 'Överkant',
alignMiddle: 'Mitten',
alignBottom: 'Nederkant',
alignNone: 'Ingen',
invalidValue : 'Felaktigt värde.',
invalidHeight: 'Höjd måste vara ett nummer.',
invalidWidth: 'Bredd måste vara ett nummer.',
invalidCssLength: 'Värdet för fältet "%1" måste vara ett positivt nummer med eller utan CSS-mätenheter (px, %, in, cm, mm, em, ex, pt, eller pc).',
invalidHtmlLength: 'Värdet för fältet "%1" måste vara ett positivt nummer med eller utan godkända HTML-mätenheter (px eller %).',
invalidInlineStyle: 'Det angivna värdet för style måste innehålla en eller flera tupler separerade med semikolon i följande format: "name : value"',
cssLengthTooltip: 'Ange ett nummer i pixlar eller ett nummer men godkänd CSS-mätenhet (px, %, in, cm, mm, em, ex, pt, eller pc).',
// Put the voice-only part of the label in the span.
unavailable: '%1<span class="cke_accessibility">, Ej tillgänglig</span>'
}
};
| SeeyaSia/www | web/libraries/ckeditor/lang/sv.js | JavaScript | gpl-2.0 | 3,300 |
// Copyright 2014 Runtime.JS project authors
//
// 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.
// NOTE: This script is executed in every context automatically
var console = (function(undef) {
var stdout = null;
var stderr = null;
var times = {};
function getStdout() {
if (null === stdout) {
stdout = isolate.env.stdout;
}
return stdout;
}
return {
log: function() {
var s = Array.prototype.join.call(arguments, ' ');
getStdout()(s + '\n');
},
error: function() {
if (null === stderr) {
stderr = isolate.env.stderr;
}
var s = Array.prototype.join.call(arguments, ' ');
stderr(s + '\n');
},
time: function(label) {
times['l' + label] = Date.now();
},
timeEnd: function(label) {
var time = times['l' + label];
if ('undefined' === typeof time) {
return;
}
var d = Date.now() - time;
getStdout()(label + ': ' + d/1000 + 'ms' + '\n');
times['l' + label] = undef;
},
};
})();
(function(__native) {
"use strict";
/**
* Helper function to support IPC function calls
*/
function RPC_CALL(fn, threadPtr, argsArray, promiseid) {
if (null === fn) {
// Invalid function call
__native.callResult(false, threadPtr, promiseid, null);
return;
}
var ret;
try {
ret = fn.apply(this, argsArray);
} catch (err) {
__native.callResult(false, threadPtr, promiseid, err);
throw err;
}
if (ret instanceof Promise) {
if (!ret.then) return;
ret.then(function(result) {
__native.callResult(true, threadPtr, promiseid, result);
}, function(err) {
__native.callResult(false, threadPtr, promiseid, err);
}).catch(function(err) {
__native.callResult(false, threadPtr, promiseid, err);
});
return;
}
if (ret instanceof Error) {
__native.callResult(false, threadPtr, promiseid, ret);
} else {
__native.callResult(true, threadPtr, promiseid, ret);
}
};
__native.installInternals({
callWrapper: RPC_CALL,
});
});
// No more code here
| dawangjiaowolaixunshan/runtime | initrd/system/init.js | JavaScript | apache-2.0 | 2,651 |
/*
MediaCenterJS - A NodeJS based mediacenter solution
Copyright (C) 2014 - Jan Smolders
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* Global Imports */
var fs = require('fs.extra')
, file_utils = require('../../lib/utils/file-utils')
, app_cache_handler = require('../../lib/handlers/app-cache-handler')
, colors = require('colors')
, os = require('os')
, metafetcher = require('../../lib/utils/metadata-fetcher')
, config = require('../../lib/handlers/configuration-handler').getConfiguration();
var dblite = require('dblite')
if(os.platform() === 'win32'){
dblite.bin = "./bin/sqlite3/sqlite3";
}
var db = dblite('./lib/database/mcjs.sqlite');
db.on('info', function (text) { console.log(text) });
db.on('error', function (err) { console.error('Database error: ' + err) });
exports.loadItems = function (req, res, serveToFrontEnd){
var metaType = "movie";
if(serveToFrontEnd === false){
fetchMovieData(req, res, metaType, serveToFrontEnd);
} else if(serveToFrontEnd === undefined || serveToFrontEnd === null){
var serveToFrontEnd = true;
getMovies(req, res, metaType, serveToFrontEnd);
} else{
serveToFrontEnd = true;
getMovies(req, res, metaType, serveToFrontEnd);
}
};
exports.backdrops = function (req, res){
db.query('SELECT * FROM movies',{
original_name : String,
title : String,
poster_path : String,
backdrop_path : String,
imdb_id : String,
rating : String,
certification : String,
genre : String,
runtime : String,
overview : String,
cd_number : String,
adult : String
}, function(rows) {
if (typeof rows !== 'undefined' && rows.length > 0){
var backdropArray = [];
rows.forEach(function(item){
var backdrop = item.backdrop_path;
backdropArray.push(backdrop)
});
res.json(backdropArray);
} else {
console.log('Could not index any movies, please check given movie collection path');
}
});
};
exports.playMovie = function (req, res, movieTitle){
file_utils.getLocalFile(config.moviepath, movieTitle, function(err, file) {
if (err) console.log(err .red);
if (file) {
var movieUrl = file.href
, movie_playback_handler = require('./movie-playback-handler');
var subtitleUrl = movieUrl;
subtitleUrl = subtitleUrl.split(".");
subtitleUrl = subtitleUrl[0]+".srt";
var subtitleTitle = movieTitle;
subtitleTitle = subtitleTitle.split(".");
subtitleTitle = subtitleTitle[0]+".srt";
movie_playback_handler.startPlayback(res, movieUrl, movieTitle, subtitleUrl, subtitleTitle);
} else {
console.log("File " + movieTitle + " could not be found!" .red);
}
});
};
exports.getGenres = function (req, res){
db.query('SELECT genre FROM movies', function(rows) {
if (typeof rows !== 'undefined' && rows.length > 0){
var allGenres = rows[0][0].replace(/\r\n|\r|\n| /g,","),
genreArray = allGenres.split(',');
res.json(genreArray);
}
});
};
exports.filter = function (req, res, movieRequest){
db.query('SELECT * FROM movies WHERE genre =?', [movieRequest], { local_name: String }, function(rows) {
if (typeof rows !== 'undefined' && rows.length > 0) {
res.json(rows);
}
});
};
exports.sendState = function (req, res){
db.query("CREATE TABLE IF NOT EXISTS progressionmarker (movietitle TEXT PRIMARY KEY, progression TEXT, transcodingstatus TEXT)");
var incommingData = req.body
, movieTitle = incommingData.movieTitle
, progression = incommingData.currentTime
, transcodingstatus = 'pending';
if(movieTitle !== undefined && progression !== undefined){
var progressionData = [movieTitle, progression, transcodingstatus];
db.query('INSERT OR REPLACE INTO progressionmarker VALUES(?,?,?)', progressionData);
}
}
/** Private functions **/
fetchMovieData = function(req, res, metaType, serveToFrontEnd) {
metafetcher.fetch(req, res, metaType, function(type){
if(type === metaType){
getMovies(req, res, metaType, serveToFrontEnd);
}
});
}
getMovies = function(req, res, metaType, serveToFrontEnd){
db.query('SELECT * FROM movies',{
original_name : String,
title : String,
poster_path : String,
backdrop_path : String,
imdb_id : String,
rating : String,
certification : String,
genre : String,
runtime : String,
overview : String,
cd_number : String,
adult : String
},
function(err, rows) {
if(err){
console.log("DB error",err);
serveToFrontEnd = true;
fetchMovieData(req, res, metaType, serveToFrontEnd);
}
if (typeof rows !== 'undefined' && rows.length > 0){
if(serveToFrontEnd !== false){
res.json(rows);
}
} else {
serveToFrontEnd = true;
fetchMovieData(req, res, metaType, serveToFrontEnd);
}
});
} | qhanam/Pangor | js/test/input/special_type_handling/movie-functions_old.js | JavaScript | apache-2.0 | 5,868 |
/**
* 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.
*/
/* Queued ajax handling for Horizon.
*
* Note: The number of concurrent AJAX connections hanlded in the queue
* can be configured by setting an "ajax_queue_limit" key in
* HORIZON_CONFIG to the desired number (or None to disable queue
* limiting).
*/
horizon.ajax = {
// This will be our jQuery queue container.
_queue: [],
_active: [],
get_messages: function (request) {
return request.getResponseHeader("X-Horizon-Messages");
},
// Function to add a new call to the queue.
queue: function(opts) {
var def = $.Deferred();
horizon.ajax._queue.push({opts: opts, deferred: def});
// Start up the queue handler in case it's stopped.
horizon.ajax.next();
return def.promise();
},
next: function () {
var queue = horizon.ajax._queue;
var limit = horizon.conf.ajax.queue_limit;
function process_queue(request) {
return function() {
// TODO(sambetts) Add some processing for error cases
// such as unauthorised etc.
var active = horizon.ajax._active;
var index = $.inArray(request, active);
if (index > -1) {
active.splice(index, 1);
}
horizon.ajax.next();
};
}
if (queue.length && (!limit || horizon.ajax._active.length < limit)) {
var item = queue.shift();
var request = $.ajax(item.opts);
horizon.ajax._active.push(request);
// Add an always callback that processes the next part of the queue,
// as well as success and fail callbacks that resolved/rejects
// the deferred.
request.always(process_queue(request));
request.then(item.deferred.resolve, item.deferred.reject);
}
}
};
| kogotko/carburetor | static/horizon/js/horizon.communication.js | JavaScript | apache-2.0 | 2,242 |
(function () {
'use strict';
/* App Module */
var openmrs = angular.module('openmrs', ['motech-dashboard', 'openmrs.services', 'openmrs.controllers',
'ngCookies', 'uiServices']);
openmrs.config(['$stateProvider', function ($stateProvider) {
$stateProvider
.state('openmrs', {
url: "/openmrs",
abstract: true,
views: {
"moduleToLoad": {
templateUrl: "../openmrs/resources/index.html"
}
}
})
.state('openmrs.settings', {
url: "/settings",
parent:'openmrs',
views: {
"openmrsView": {
templateUrl: "../openmrs/resources/partials/settings.html",
controller: 'OpenMRSSettingsCtrl'
}
}
});
}]);
}());
| martokarski/modules | openmrs/src/main/resources/webapp/js/app.js | JavaScript | bsd-3-clause | 976 |
// 'catch' - Promise extension
//
// promise.catch(cb)
//
// Same as `then` but accepts only onFail callback
'use strict';
var isCallable = require('es5-ext/lib/Object/is-callable')
, validValue = require('es5-ext/lib/Object/valid-value')
, deferred = require('../../deferred')
, isPromise = require('../../is-promise');
deferred.extend('catch', function (cb) {
var def;
validValue(cb);
if (!this.pending) this.pending = [];
def = deferred();
this.pending.push('catch', [cb, def.resolve]);
return def.promise;
}, function (cb, resolve) {
var value;
if (!this.failed) {
resolve(this.value);
return;
}
if (isCallable(cb)) {
if (isPromise(cb)) {
if (cb.resolved) resolve(cb.value);
else cb.done(resolve, resolve);
return;
}
try { value = cb(this.value); } catch (e) { value = e; }
resolve(value);
return;
}
resolve(cb);
}, function (cb) {
var value;
validValue(cb);
if (!this.failed) return this;
if (isCallable(cb)) {
if (isPromise(cb)) return cb;
try { value = cb(this.value); } catch (e) { value = e; }
return deferred(value);
}
return deferred(cb);
});
| nateyang/grunt-build_js | tasks/libs/deferred/lib/ext/promise/catch.js | JavaScript | mit | 1,113 |
tinyMCE.addI18n('zh-cn.locomotive_media',{"image_desc": "插入媒体"}); | thirus/engine | app/assets/javascripts/tinymce/plugins/locomotive_media/langs/zh-cn.js | JavaScript | mit | 73 |
/* */
'use strict';
var keyMirror = require("./keyMirror");
var ReactMultiChildUpdateTypes = keyMirror({
INSERT_MARKUP: null,
MOVE_EXISTING: null,
REMOVE_NODE: null,
TEXT_CONTENT: null
});
module.exports = ReactMultiChildUpdateTypes;
| thomjoy/turftest | src/jspm_packages/npm/react@0.13.0/lib/ReactMultiChildUpdateTypes.js | JavaScript | mit | 243 |
'use strict';
require('../common');
const assert = require('assert');
function range(n) {
return 'x'.repeat(n + 1).split('').map(function(_, i) { return i; });
}
function timeout(nargs) {
const args = range(nargs);
setTimeout.apply(null, [callback, 1].concat(args));
function callback() {
assert.deepStrictEqual([].slice.call(arguments), args);
if (nargs < 128) timeout(nargs + 1);
}
}
function interval(nargs) {
const args = range(nargs);
const timer = setTimeout.apply(null, [callback, 1].concat(args));
function callback() {
clearInterval(timer);
assert.deepStrictEqual([].slice.call(arguments), args);
if (nargs < 128) interval(nargs + 1);
}
}
timeout(0);
interval(0);
| MTASZTAKI/ApertusVR | plugins/languageAPI/jsAPI/3rdParty/nodejs/10.1.0/source/test/parallel/test-timers-args.js | JavaScript | mit | 717 |
var tests = {
'postcss-nesting': {
'basic': {
message: 'supports basic usage'
},
'ignore': {
message: 'ignores invalid syntax'
}
}
};
var debug = true;
var dir = './test/fixtures/';
var fs = require('fs');
var path = require('path');
var plugin = require('../');
var test = require('tape');
Object.keys(tests).forEach(function (name) {
var parts = tests[name];
test(name, function (t) {
var fixtures = Object.keys(parts);
t.plan(fixtures.length * 2);
fixtures.forEach(function (fixture) {
var message = parts[fixture].message;
var options = parts[fixture].options;
var warning = parts[fixture].warning || 0;
var warningMsg = message + ' (# of warnings)';
var baseName = fixture.split(':')[0];
var testName = fixture.split(':').join('.');
var inputPath = path.resolve(dir + baseName + '.css');
var expectPath = path.resolve(dir + testName + '.expect.css');
var actualPath = path.resolve(dir + testName + '.actual.css');
var inputCSS = fs.readFileSync(inputPath, 'utf8');
var expectCSS = fs.readFileSync(expectPath, 'utf8');
plugin.process(inputCSS, options).then(function (result) {
var actualCSS = result.css;
if (debug) fs.writeFileSync(actualPath, actualCSS);
t.equal(actualCSS, expectCSS, message);
t.equal(result.warnings().length, warning, warningMsg);
});
});
});
});
| edsrupp/eds-mess | node_modules/precss/node_modules/postcss-nesting/test/index.js | JavaScript | mit | 1,399 |
define(['./_createAssigner', './allKeys'], function (_createAssigner, allKeys) {
// Fill in a given object with default properties.
var defaults = _createAssigner(allKeys, true);
return defaults;
});
| ealbertos/dotfiles | vscode.symlink/extensions/ms-mssql.mssql-1.11.1/node_modules/underscore/amd/defaults.js | JavaScript | mit | 206 |
Modernizr.addTest("bgpositionxy",function(){return Modernizr.testStyles("#modernizr {background-position: 3px 5px;}",function(o){var n=window.getComputedStyle?getComputedStyle(o,null):o.currentStyle,t="3px"==n.backgroundPositionX||"3px"==n["background-position-x"],i="5px"==n.backgroundPositionY||"5px"==n["background-position-y"];return t&&i})}); | topshelfdesign/Wordpress | wp-content/themes/tsd_master/bower_components/modernizr/feature-detects/min/css-backgroundposition-xy-min.js | JavaScript | gpl-2.0 | 347 |
# underscore name translator dynalink linker example
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// This script assumes you've built jdk9 or using latest
// jdk9 image and put the 'bin' directory in the PATH
$EXEC.throwOnError=true
// compile UnderscoreNameLinkerExporter
`javac -cp ../../dist/nashorn.jar UnderscoreNameLinkerExporter.java`
// make a jar file out of pluggable linker
`jar cvf underscore_linker.jar UnderscoreNameLinkerExporter*.class META-INF/`
// run a sample script that uses pluggable linker
// but make sure classpath points to the pluggable linker jar!
`jjs -cp underscore_linker.jar underscore.js`
print($ERR)
print($OUT)
| dmlloyd/openjdk-modules | nashorn/samples/dynalink/underscore_linker.js | JavaScript | gpl-2.0 | 2,204 |
var Stream = require('stream').Stream,
util = require('util'),
driver = require('websocket-driver'),
API = require('./websocket/api'),
EventTarget = require('./websocket/api/event_target'),
Event = require('./websocket/api/event');
var EventSource = function(request, response, options) {
this.writable = true;
options = options || {};
this._stream = response.socket;
this._ping = options.ping || this.DEFAULT_PING;
this._retry = options.retry || this.DEFAULT_RETRY;
var scheme = driver.isSecureRequest(request) ? 'https:' : 'http:';
this.url = scheme + '//' + request.headers.host + request.url;
this.lastEventId = request.headers['last-event-id'] || '';
this.readyState = API.CONNECTING;
var self = this;
if (!this._stream || !this._stream.writable) return;
process.nextTick(function() { self._open() });
this._stream.setTimeout(0);
this._stream.setNoDelay(true);
var handshake = 'HTTP/1.1 200 OK\r\n' +
'Content-Type: text/event-stream\r\n' +
'Cache-Control: no-cache, no-store\r\n' +
'Connection: close\r\n' +
'\r\n\r\n' +
'retry: ' + Math.floor(this._retry * 1000) + '\r\n\r\n';
this._write(handshake);
this._stream.on('drain', function() { self.emit('drain') });
if (this._ping)
this._pingTimer = setInterval(function() { self.ping() }, this._ping * 1000);
['error', 'end'].forEach(function(event) {
self._stream.on(event, function() { self.close() });
});
};
util.inherits(EventSource, Stream);
EventSource.isEventSource = function(request) {
if (request.method !== 'GET') return false;
var accept = (request.headers.accept || '').split(/\s*,\s*/);
return accept.indexOf('text/event-stream') >= 0;
};
var instance = {
DEFAULT_PING: 10,
DEFAULT_RETRY: 5,
_write: function(chunk) {
if (!this.writable) return false;
try {
return this._stream.write(chunk, 'utf8');
} catch (e) {
return false;
}
},
_open: function() {
if (this.readyState !== API.CONNECTING) return;
this.readyState = API.OPEN;
var event = new Event('open');
event.initEvent('open', false, false);
this.dispatchEvent(event);
},
write: function(message) {
return this.send(message);
},
end: function(message) {
if (message !== undefined) this.write(message);
this.close();
},
send: function(message, options) {
if (this.readyState > API.OPEN) return false;
message = String(message).replace(/(\r\n|\r|\n)/g, '$1data: ');
options = options || {};
var frame = '';
if (options.event) frame += 'event: ' + options.event + '\r\n';
if (options.id) frame += 'id: ' + options.id + '\r\n';
frame += 'data: ' + message + '\r\n\r\n';
return this._write(frame);
},
ping: function() {
return this._write(':\r\n\r\n');
},
close: function() {
if (this.readyState > API.OPEN) return false;
this.readyState = API.CLOSED;
this.writable = false;
if (this._pingTimer) clearInterval(this._pingTimer);
if (this._stream) this._stream.end();
var event = new Event('close');
event.initEvent('close', false, false);
this.dispatchEvent(event);
return true;
}
};
for (var method in instance) EventSource.prototype[method] = instance[method];
for (var key in EventTarget) EventSource.prototype[key] = EventTarget[key];
module.exports = EventSource;
| hackathon-3d/twilson63-repo | node_modules/firebase/node_modules/faye-websocket/lib/faye/eventsource.js | JavaScript | gpl-2.0 | 3,510 |
this.__proto__ = [];
gczeal(2);
gc();
var box = evalcx('lazy');
| michath/ConMonkey | js/src/jit-test/tests/basic/bug642326.js | JavaScript | mpl-2.0 | 65 |
/**
* jQuery plugin for code highlighting based on the ace editor.
*
* Call as $("selector").highlight({mode: "xquery"}). The highlighting mode
* may also be specified by adding a data-language="xquery" to the element
* on which highlight is called.
*
* @author Wolfgang Meier
*/
(function($) {
var methods = {
init: function(options) {
// check if we have to use ace.require or just require
// depends on the ace package loaded
var _require;
if (ace && ace.require)
_require = ace.require;
else
_require = require;
var EditSession = _require("ace/edit_session").EditSession;
var TextLayer = _require("ace/layer/text").Text;
var JavaScriptMode = _require("ace/mode/javascript").Mode;
var XQueryMode = _require("ace/mode/xquery").Mode;
var baseStyles = _require("ace/requirejs/text!./static.css");
// for better performance, create one session for all elements
var session = new EditSession("");
session.setUseWorker(false);
session.setWrapLimitRange(60, 60);
session.setUseWrapMode(true);
return this.each(function() {
var plugin = $(this);
var settings = {
mode: "text",
theme: "tomorrow_night"
};
if (options) {
$.extend(settings, options);
}
var lang = plugin.data("language");
if (lang) {
settings.mode = lang;
}
function getMode() {
var req = _require("ace/mode/" + settings.mode);
if (req) {
return new (req.Mode)();
}
return null;
}
function render(data, theme, mode, disableGutter) {
session.setMode(mode);
session.setValue(data);
var textLayer = new TextLayer(document.createElement("div"));
textLayer.config = {
};
textLayer.setSession(session);
var stringBuilder = [];
var length = session.getLength();
for(var ix = 0; ix < length; ix++) {
if (!disableGutter)
stringBuilder.push("<span class='ace_gutter ace_gutter-cell' unselectable='on'>" + (ix) + "</span>");
textLayer.$renderLine(stringBuilder, ix, false, false);
}
// let's prepare the whole html
var html = "<div class=':cssClass'>\
<div class='ace_text-layer'>\
:code\
</div>\
</div>".replace(/:cssClass/, theme.cssClass).replace(/:code/, stringBuilder.join(""));
textLayer.destroy();
return {
css: baseStyles + theme.cssText,
html: html
};
}
var theme = _require("ace/theme/" + settings.theme);
var dom = _require("ace/lib/dom");
var data = $(this).text();
var mode = getMode();
if (!mode) {
mode = new (_require("ace/mode/text").Mode)();
}
var highlighted = render(data, theme, mode, true);
dom.importCssString(highlighted.css, "ace_highlight");
$(this).html(highlighted.html);
$(this).data("text", data);
});
},
getText: function() {
return $(this).data("text");
}
};
$.fn.highlight = function (method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
alert('Method "' + method + '" not found!');
}
};
})(jQuery); | ebeshero/mitford | eXist-db/db-2020-07-18/db/apps/shared-resources/resources/scripts/highlight.js | JavaScript | agpl-3.0 | 4,596 |
define([
"TerraMA2WebApp/countries/services/index",
"TerraMA2WebApp/countries/directives/countries-list"
], function(countriesServiceModule, countriesList) {
var moduleName = "terrama2.countries.directive";
angular.module(moduleName, [countriesServiceModule])
.directive("terrama2CountriesList", countriesList);
return moduleName;
}) | ViniciusCampanha/terrama2 | webapp/public/javascripts/angular/countries/directives/index.js | JavaScript | lgpl-3.0 | 349 |