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 |
|---|---|---|---|---|---|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionFeedback = (props) => (
<SvgIcon {...props}>
<path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-7 12h-2v-2h2v2zm0-4h-2V6h2v4z"/>
</SvgIcon>
);
ActionFeedback = pure(ActionFeedback);
ActionFeedback.displayName = 'ActionFeedback';
export default ActionFeedback;
| rhaedes/material-ui | src/svg-icons/action/feedback.js | JavaScript | mit | 412 |
/*
* Note that this control will most likely remain as an example, and not as a core Ext form
* control. However, the API will be changing in a future release and so should not yet be
* treated as a final, stable API at this time.
*/
/**
* A control that allows selection of between two Ext.ux.form.MultiSelect controls.
*/
Ext.define('Ext.ux.form.ItemSelector', {
extend: 'Ext.ux.form.MultiSelect',
alias: ['widget.itemselectorfield', 'widget.itemselector'],
alternateClassName: ['Ext.ux.ItemSelector'],
requires: [
'Ext.button.Button',
'Ext.ux.form.MultiSelect'
],
/**
* @cfg {Boolean} [hideNavIcons=false] True to hide the navigation icons
*/
hideNavIcons:false,
/**
* @cfg {Array} buttons Defines the set of buttons that should be displayed in between the ItemSelector
* fields. Defaults to <tt>['top', 'up', 'add', 'remove', 'down', 'bottom']</tt>. These names are used
* to build the button CSS class names, and to look up the button text labels in {@link #buttonsText}.
* This can be overridden with a custom Array to change which buttons are displayed or their order.
*/
buttons: ['top', 'up', 'add', 'remove', 'down', 'bottom'],
/**
* @cfg {Object} buttonsText The tooltips for the {@link #buttons}.
* Labels for buttons.
*/
buttonsText: {
top: "Move to Top",
up: "Move Up",
add: "Add to Selected",
remove: "Remove from Selected",
down: "Move Down",
bottom: "Move to Bottom"
},
layout: {
type: 'hbox',
align: 'stretch'
},
initComponent: function() {
var me = this;
me.ddGroup = me.id + '-dd';
me.callParent();
// bindStore must be called after the fromField has been created because
// it copies records from our configured Store into the fromField's Store
me.bindStore(me.store);
},
createList: function(title){
var me = this,
storeCfg = {
data: []
};
if (me.store.model) {
storeCfg.model = me.store.model;
} else {
storeCfg.fields = [];
}
return Ext.create('Ext.ux.form.MultiSelect', {
// We don't want the multiselects themselves to act like fields,
// so override these methods to prevent them from including
// any of their values
submitValue: false,
getSubmitData: function(){
return null;
},
getModelData: function(){
return null;
},
flex: 1,
dragGroup: me.ddGroup,
dropGroup: me.ddGroup,
title: title,
store: storeCfg,
displayField: me.displayField,
valueField: me.valueField,
disabled: me.disabled,
listeners: {
boundList: {
scope: me,
itemdblclick: me.onItemDblClick,
drop: me.syncValue
}
}
});
},
setupItems: function() {
var me = this;
me.fromField = me.createList(me.fromTitle);
me.toField = me.createList(me.toTitle);
return [
me.fromField,
{
xtype: 'container',
margin: '0 4',
layout: {
type: 'vbox',
pack: 'center'
},
items: me.createButtons()
},
me.toField
];
},
createButtons: function() {
var me = this,
buttons = [];
if (!me.hideNavIcons) {
Ext.Array.forEach(me.buttons, function(name) {
buttons.push({
xtype: 'button',
tooltip: me.buttonsText[name],
handler: me['on' + Ext.String.capitalize(name) + 'BtnClick'],
cls: Ext.baseCSSPrefix + 'form-itemselector-btn',
iconCls: Ext.baseCSSPrefix + 'form-itemselector-' + name,
navBtn: true,
scope: me,
margin: '4 0 0 0'
});
});
}
return buttons;
},
/**
* Get the selected records from the specified list.
*
* Records will be returned *in store order*, not in order of selection.
* @param {Ext.view.BoundList} list The list to read selections from.
* @return {Ext.data.Model[]} The selected records in store order.
*
*/
getSelections: function(list) {
var store = list.getStore();
return Ext.Array.sort(list.getSelectionModel().getSelection(), function(a, b) {
a = store.indexOf(a);
b = store.indexOf(b);
if (a < b) {
return -1;
} else if (a > b) {
return 1;
}
return 0;
});
},
onTopBtnClick : function() {
var list = this.toField.boundList,
store = list.getStore(),
selected = this.getSelections(list);
store.suspendEvents();
store.remove(selected, true);
store.insert(0, selected);
store.resumeEvents();
list.refresh();
this.syncValue();
list.getSelectionModel().select(selected);
},
onBottomBtnClick : function() {
var list = this.toField.boundList,
store = list.getStore(),
selected = this.getSelections(list);
store.suspendEvents();
store.remove(selected, true);
store.add(selected);
store.resumeEvents();
list.refresh();
this.syncValue();
list.getSelectionModel().select(selected);
},
onUpBtnClick : function() {
var list = this.toField.boundList,
store = list.getStore(),
selected = this.getSelections(list),
rec,
i = 0,
len = selected.length,
index = 0;
// Move each selection up by one place if possible
store.suspendEvents();
for (; i < len; ++i, index++) {
rec = selected[i];
index = Math.max(index, store.indexOf(rec) - 1);
store.remove(rec, true);
store.insert(index, rec);
}
store.resumeEvents();
list.refresh();
this.syncValue();
list.getSelectionModel().select(selected);
},
onDownBtnClick : function() {
var list = this.toField.boundList,
store = list.getStore(),
selected = this.getSelections(list),
rec,
i = selected.length - 1,
index = store.getCount() - 1;
// Move each selection down by one place if possible
store.suspendEvents();
for (; i > -1; --i, index--) {
rec = selected[i];
index = Math.min(index, store.indexOf(rec) + 1);
store.remove(rec, true);
store.insert(index, rec);
}
store.resumeEvents();
list.refresh();
this.syncValue();
list.getSelectionModel().select(selected);
},
onAddBtnClick : function() {
var me = this,
selected = me.getSelections(me.fromField.boundList);
me.moveRec(true, selected);
me.toField.boundList.getSelectionModel().select(selected);
},
onRemoveBtnClick : function() {
var me = this,
selected = me.getSelections(me.toField.boundList);
me.moveRec(false, selected);
me.fromField.boundList.getSelectionModel().select(selected);
},
moveRec: function(add, recs) {
var me = this,
fromField = me.fromField,
toField = me.toField,
fromStore = add ? fromField.store : toField.store,
toStore = add ? toField.store : fromField.store;
fromStore.suspendEvents();
toStore.suspendEvents();
fromStore.remove(recs);
toStore.add(recs);
fromStore.resumeEvents();
toStore.resumeEvents();
fromField.boundList.refresh();
toField.boundList.refresh();
me.syncValue();
},
// Synchronizes the submit value with the current state of the toStore
syncValue: function() {
var me = this;
me.mixins.field.setValue.call(me, me.setupValue(me.toField.store.getRange()));
},
onItemDblClick: function(view, rec) {
this.moveRec(view === this.fromField.boundList, rec);
},
setValue: function(value) {
var me = this,
fromField = me.fromField,
toField = me.toField,
fromStore = fromField.store,
toStore = toField.store,
selected;
// Wait for from store to be loaded
if (!me.fromStorePopulated) {
me.fromField.store.on({
load: Ext.Function.bind(me.setValue, me, [value]),
single: true
});
return;
}
value = me.setupValue(value);
me.mixins.field.setValue.call(me, value);
selected = me.getRecordsForValue(value);
// Clear both left and right Stores.
// Both stores must not fire events during this process.
fromStore.suspendEvents();
toStore.suspendEvents();
fromStore.removeAll();
toStore.removeAll();
// Reset fromStore
me.populateFromStore(me.store);
// Copy selection across to toStore
Ext.Array.forEach(selected, function(rec){
// In the from store, move it over
if (fromStore.indexOf(rec) > -1) {
fromStore.remove(rec);
}
toStore.add(rec);
});
// Stores may now fire events
fromStore.resumeEvents();
toStore.resumeEvents();
// Refresh both sides and then update the app layout
Ext.suspendLayouts();
fromField.boundList.refresh();
toField.boundList.refresh();
Ext.resumeLayouts(true);
},
onBindStore: function(store, initial) {
var me = this,
fromField = me.fromField,
toField = me.toField;
if (fromField) {
fromField.store.removeAll();
toField.store.removeAll();
if (store.autoCreated) {
fromField.resolveDisplayField();
toField.resolveDisplayField();
me.resolveDisplayField();
}
if (!Ext.isDefined(me.valueField)) {
me.valueField = me.displayField;
}
// Add everything to the from field as soon as the Store is loaded
if (store.getCount()) {
me.populateFromStore(store);
} else {
me.store.on('load', me.populateFromStore, me);
}
}
},
populateFromStore: function(store) {
var fromStore = this.fromField.store;
// Flag set when the fromStore has been loaded
this.fromStorePopulated = true;
fromStore.add(store.getRange());
// setValue waits for the from Store to be loaded
fromStore.fireEvent('load', fromStore);
},
onEnable: function(){
var me = this;
me.callParent();
me.fromField.enable();
me.toField.enable();
Ext.Array.forEach(me.query('[navBtn]'), function(btn){
btn.enable();
});
},
onDisable: function(){
var me = this;
me.callParent();
me.fromField.disable();
me.toField.disable();
Ext.Array.forEach(me.query('[navBtn]'), function(btn){
btn.disable();
});
},
onDestroy: function(){
this.bindStore(null);
this.callParent();
}
});
| devmaster-terian/hwt-backend | gestion/recurso/framework/ext-5.1.3/examples/ux/form/ItemSelector.js | JavaScript | mit | 11,926 |
/*
YUI 3.8.0pr2 (build 154)
Copyright 2012 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add("lang/datatype-date-format_es-VE",function(e){e.Intl.add("datatype-date-format","es-VE",{a:["dom","lun","mar","mi\u00e9","jue","vie","s\u00e1b"],A:["domingo","lunes","martes","mi\u00e9rcoles","jueves","viernes","s\u00e1bado"],b:["ene","feb","mar","abr","may","jun","jul","ago","sep","oct","nov","dic"],B:["enero","febrero","marzo","abril","mayo","junio","julio","agosto","septiembre","octubre","noviembre","diciembre"],c:"%a, %d %b %Y %H:%M:%S %Z",p:["A.M.","P.M."],P:["a.m.","p.m."],x:"%d/%m/%y",X:"%H:%M:%S"})},"3.8.0pr2");
| SHMEDIALIMITED/tallest-tower | node_modules/grunt-contrib/node_modules/grunt-contrib-yuidoc/node_modules/yuidocjs/node_modules/yui/datatype-date-format/lang/datatype-date-format_es-VE.js | JavaScript | mit | 676 |
module.exports = function () {
var module = {
t: function () {
console.log('a');
}
};
return module;
}(); | phillipgreenii/deamdify | test/data/module-with-contained-variabled-named-module.expect.js | JavaScript | mit | 145 |
app.PageNav = React.createClass({
handleWelcome:function(){
//dispatch a navigate to welcome on click
app.PageActions.navigate({
dest: 'welcome'
});
},
render:function(){
return (
<header className="pure-g" ref="body">
<div className="pure-u-1-2">
<button className="pure-button" ref="welcome" onClick={this.handleWelcome}>Home</button>
</div>
<div className="login pure-u-1-2">
<app.User />
</div>
</header>
);
}
});
| drabinowitz/Brainstorm | client/react/PageNav.js | JavaScript | mit | 519 |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
(function () {
"use strict";
var ClaimedLineDisplay = Windows.Devices.PointOfService.ClaimedLineDisplay;
var LineDisplayTextAttribute = Windows.Devices.PointOfService.LineDisplayTextAttribute;
var LineDisplayTextAttributeGranularity = Windows.Devices.PointOfService.LineDisplayTextAttributeGranularity;
var blinkRateSlider;
var blinkIntervalSpan;
var brightnessSlider;
var brightnessSpan;
var screenSizeInCharactersSelect;
var characterSetMappingEnabledCheckbox;
var lineDisplay;
var page = WinJS.UI.Pages.define("/html/scenario4-updatingLineDisplayAttributes.html", {
ready: async function (element, options) {
WinJS.UI.processAll();
blinkRateSlider = document.getElementById("blinkRateSlider");
blinkIntervalSpan = document.getElementById("blinkIntervalSpan");
brightnessSlider = document.getElementById("brightnessSlider");
brightnessSpan = document.getElementById("brightnessSpan");
screenSizeInCharactersSelect = document.getElementById("screenSizeInCharactersSelect");
characterSetMappingEnabledCheckbox = document.getElementById("characterSetMappingEnabledCheckbox");
blinkRateSlider.addEventListener("input", updateBlinkRateSliderValue);
brightnessSlider.addEventListener("input", updateBrightnessSliderValue);
updateButton.addEventListener("click", updateButton_click);
await initializeAsync();
setValuesFromLineDisplay();
},
unload: function () {
lineDisplay && lineDisplay.close();
lineDisplay = null;
}
});
async function initializeAsync() {
lineDisplay = await SdkSample.claimScenarioLineDisplayAsync();
blinkRateSlider.disabled = !lineDisplay || !lineDisplay.capabilities.canChangeBlinkRate;
brightnessSlider.disabled = !lineDisplay || !lineDisplay.capabilities.isBrightnessSupported;
screenSizeInCharactersSelect.disabled = !lineDisplay || !lineDisplay.capabilities.canChangeScreenSize;
if (!screenSizeInCharactersSelect.disabled) {
lineDisplay.supportedScreenSizesInCharacters.forEach(screenSize => {
SdkSample.addOption(screenSizeInCharactersSelect, `${screenSize.width} x ${screenSize.height}`);
});
screenSizeInCharactersSelect.selectedIndex = 0;
}
characterSetMappingEnabledCheckbox.disabled = !lineDisplay || !lineDisplay.capabilities.canMapCharacterSets;
updateButton.disabled = !lineDisplay;
if (!updateButton.disabled) {
if (lineDisplay.capabilities.canBlink === LineDisplayTextAttributeGranularity.notSupported) {
await lineDisplay.defaultWindow.tryDisplayTextAsync("Regular Text");
} else {
await lineDisplay.defaultWindow.tryDisplayTextAsync("Blinking Text", LineDisplayTextAttribute.blink);
}
}
}
function setValuesFromLineDisplay() {
if (lineDisplay) {
var attributes = lineDisplay.getAttributes();
blinkRateSlider.value = attributes.blinkRate;
brightnessSlider.value = attributes.brightness;
characterSetMappingEnabledCheckbox.checked = attributes.isCharacterSetMappingEnabled;
}
updateBlinkRateSliderValue();
updateBrightnessSliderValue();
}
function updateBlinkRateSliderValue() {
blinkIntervalSpan.innerHTML = blinkRateSlider.value;
}
function updateBrightnessSliderValue() {
brightnessSpan.innerHTML = brightnessSlider.value;
}
async function updateButton_click() {
var attributes = lineDisplay.getAttributes();
if (lineDisplay.capabilities.canChangeBlinkRate) {
attributes.blinkRate = blinkRateSlider.value;
}
if (lineDisplay.capabilities.isBrightnessSupported) {
attributes.brightness = brightnessSlider.value;
}
if (lineDisplay.capabilities.canChangeScreenSize) {
attributes.screenSizeInCharacters = lineDisplay.supportedScreenSizesInCharacters[screenSizeInCharactersSelect.selectedIndex];
}
if (lineDisplay.capabilities.canMapCharacterSets) {
attributes.isCharacterSetMappingEnabled = characterSetMappingEnabledCheckbox.checked;
}
if (await lineDisplay.tryUpdateAttributesAsync(attributes)) {
WinJS.log("Attributes updated successfully.", "sample", "status");
// The resulting attributes may not match our request.
// For example, the Line Display will choose the closest available blink rate.
// Update the controls to show what the Line Display actually used.
setValuesFromLineDisplay();
} else {
// We probably lost our claim.
WinJS.log("Failed to update attributes.", "sample", "error");
}
}
}) (); | Microsoft/Windows-universal-samples | archived/LineDisplay/js/js/scenario4-updatingLineDisplayAttributes.js | JavaScript | mit | 5,422 |
/**
*
* Created by aleckim on 2015. 10. 18..
*/
"use strict";
var Logger = require('../lib/log');
global.log = new Logger(__dirname + "/debug.log");
var assert = require('assert');
var config = require('../config/config');
var LifeIndexKmaRequester = require('../lib/lifeIndexKmaRequester');
describe('unit test - requester of kma index service class', function() {
var reqLifeIndex;
it('create Controller Kma Index Service', function() {
reqLifeIndex = new LifeIndexKmaRequester();
reqLifeIndex._areaList.push({
town: {first: "서울특별시", second: "", third: ""},
mCoord: {mx: 0, my: 0},
gCoord: {lat: 37.5636, lon: 126.98},
areaNo: "1100000000"
});
reqLifeIndex._areaList.push({
town: {first: "부산광역시", second: "", third: ""},
mCoord: {mx: 0, my: 0},
gCoord: {lat: 35.177, lon: 129.077},
areaNo: "2600000000"
});
reqLifeIndex._areaList.push({
town: {first: "대구광역시", second: "", third: ""},
mCoord: {mx: 0, my: 0},
gCoord: {lat: 35.8685, lon: 128.6036},
areaNo: "2700000000"
});
assert.equal(reqLifeIndex.fsn.nextTime, null, 'check object created');
});
it('set time to get fsn life list', function() {
var time = new Date();
reqLifeIndex.setNextGetTime('fsn', time);
assert.equal(reqLifeIndex.fsn.nextTime, time, 'check next get fsn list list time');
});
it('set next time to get fsn life list', function() {
var time = new Date(2015, 10, 18, 9);
reqLifeIndex.setNextGetTime('fsn', time);
time.setHours(10);
time.setMinutes(10);
assert.equal(reqLifeIndex.fsn.nextTime, time, 'check next get fsn list list time');
time = new Date(2015, 10, 18, 10, 20);
reqLifeIndex.setNextGetTime('fsn', time);
time.setHours(22);
time.setMinutes(10);
assert.equal(reqLifeIndex.fsn.nextTime, time, 'check next get fsn list list time');
time = new Date(2015, 10, 18, 22, 20);
reqLifeIndex.setNextGetTime('fsn', time);
time.setDate(time.getDate()+1);
time.setHours(10);
time.setMinutes(10);
assert.equal(reqLifeIndex.fsn.nextTime, time, 'check next get fsn list list time');
});
it('get url to get fsn life list', function () {
reqLifeIndex.setServiceKey(config.keyString.test_cert);
var url = reqLifeIndex.getUrl('fsn', 1111051500);
assert.equal(url, url, 'check next get fsn list list time');
});
var fsn;
it('parse fsn life data', function() {
var data1 = {"Response":{"header":{"successYN":"Y","returnCode":"00","errMsg":""},"body":{"@xsi.type":"idxBody",
"indexModel":{"code":"A01_2","areaNo":1100000000,"date":2015102018,"today":48,"tomorrow":51,
"theDayAfterTomorrow":51}}}};
var result1 = reqLifeIndex.parseLifeIndex('fsn', data1);
//console.log(result1.data.fsn);
assert.equal(result1.data.fsn.data[0].value, data1.Response.body.indexModel.today, 'compare parsed data1 of fsn');
var data2 = {"Response":{"header":{"successYN":"Y","returnCode":"00","errMsg":""},"body":{"@xsi.type":"idxBody",
"indexModel":{"code":"A01_2","areaNo":2700000000,"date":2015102018,"today":"","tomorrow":50,
"theDayAfterTomorrow":48}}}};
var result2 = reqLifeIndex.parseLifeIndex('fsn', data2);
fsn = result2.data.fsn;
assert.equal(result2.data.fsn.data[0].value, data2.Response.body.indexModel.tomorrow, 'compare parsed data2 of fsn');
});
it('make new life index kma', function () {
var LifeIndexKma = require('../models/lifeIndexKma');
var kmaIndex = new LifeIndexKma({town: {first: 'a', second: 'b', third: 'c'}, mCoord: {mx:125, my:77},
areaNo: '2700000000',
fsn: fsn});
assert.equal(kmaIndex.fsn.lastUpdateDate, fsn.lastUpdateDate, 'compare fsn');
});
it('update or add fsn data ', function () {
var newFsn = fsn;
newFsn.data[1].value = 51;
newFsn.data.push({date: '20151023', value: 66});
reqLifeIndex.updateOrAddLifeIndex(fsn, newFsn);
//console.log(fsn);
assert.equal(fsn.data[2].value, newFsn.data[2].value, 'compare new value of data');
});
it('set get time at first', function () {
var date = new Date();
reqLifeIndex.setNextGetTime('ultrv', date);
assert.equal(reqLifeIndex['ultrv'].nextTime, date, '');
});
it('set next get time', function () {
reqLifeIndex.setNextGetTime('ultrv');
});
it('check time of all', function () {
var isGo = reqLifeIndex.checkGetTime('ultrv', new Date());
assert.equal(isGo, false, '');
});
it ('get url', function() {
var url = reqLifeIndex.getUrl('ultrv', '1100000000');
var result = 'http://203.247.66.146/iros/RetrieveLifeIndexService/getUltrvLifeList?serviceKey='+
config.keyString.test_cert+'&AreaNo=1100000000&_type=json';
assert.equal(url, result, '');
url = reqLifeIndex.getUrl('fsn', '1100000000');
result = 'http://203.247.66.146/iros/RetrieveLifeIndexService/getFsnLifeList?serviceKey='+
config.keyString.test_cert+'&AreaNo=1100000000&_type=json';
assert.equal(url, result, '');
});
//it ('get fsn life index', function (done) {
// co.getLifeIndex('fsn', '1100000000', function (err, body) {
// assert.equal(body.Response.header.successYN, 'Y', '');
// done();
// });
//});
//
//it ('get ultrv life index', function (done) {
// co.getLifeIndex('ultrv', '1100000000', function (err, body) {
// assert.equal(body.Response.header.successYN, 'Y', '');
// done();
// });
//});
it ('parse hourly life index', function () {
var data = {"Response":{"header":{"successYN":"Y","returnCode":"00","errMsg":""},"body":{"@xsi.type":"idxBody",
"indexModel":{"code":"A02","areaNo":5013062000,"date":2015103018,
"h3":0,"h6":0,"h9":0,"h12":0,"h15":0,"h18":0,"h21":0,"h24":0,"h27":0,"h30":0,"h33":0,"h36":0,"h39":0,"h42":0,
"h45":0,"h48":1,"h51":3,"h54":3,"h57":"","h60":"","h63":"","h66":""}}}};
var result = reqLifeIndex.parseLifeIndex('rot', data);
assert.equal(result.data.rot.data[0].time, '2100', '');
});
it ('parse daily life index', function () {
var data = {"Response":{"header":{"successYN":"Y","returnCode":"00",
"errMsg":""},"body":{"@xsi.type":"idxBody",
"indexModel":{"code":"A07","areaNo":1100000000,"date":2015102819,
"today":"","tomorrow":2,"theDayAfterTomorrow":3}}}};
var result = reqLifeIndex.parseLifeIndex('ultrv', data);
assert.equal(result.data.ultrv.data[0].date, '20151029', '');
});
it ('parse daily life index 2', function () {
var data = {"Response": {
"header": {"successYN":"Y","returnCode":"00","errMsg":""},
"body":{
"indexModels":[
{"code":"A01_2","areaNo":"1100000000","date":"2018020106",
"today":"56","tomorrow":"53","theDayAfterTomorrow":"55"},
{"code":"A01_2","areaNo":"1111000000","date":"2018020106",
"today":"56","tomorrow":"53","theDayAfterTomorrow":"55"},
{"code":"A01_2","areaNo":"1111051500","date":"2018020106",
"today":"56","tomorrow":"53","theDayAfterTomorrow":"55"},
{"code":"A01_2","areaNo":"5019099000","date":"2018020106",
"today":"58","tomorrow":"57","theDayAfterTomorrow":"55"}]}}};
var results = reqLifeIndex.parseLifeIndex2('fsn', data);
console.log(JSON.stringify(results));
});
it ('update or add life index', function () {
var ultraIndex = { lastUpdateDate: '2015102819', data: []};
var data = { data: [{ date: '20151029', value: 2}, { date: '20151030', value: 3}],
lastUpdateDate: '2015102819' };
var result = reqLifeIndex.updateOrAddLifeIndex(ultraIndex, data);
ultraIndex.data = data.data;
assert.equal(result, ultraIndex, '');
});
//it('update Life Index Db From Towns', function (done) {
// this.timeout(30*1000);
// var mongoose = require('mongoose');
// mongoose.connect('localhost/todayweather', function(err) {
// if (err) {
// console.error('Could not connect to MongoDB!');
// console.log(err);
// done();
// }
// });
// mongoose.connection.on('error', function(err) {
// console.error('MongoDB connection error: ' + err);
// });
//
// reqLifeIndex.updateLifeIndexDbFromTowns(function (err, results) {
// if (err) {
// log.error(err.toString());
// return done();
// }
// log.info(JSON.stringify(results));
// done();
// });
//});
//it ('get LifeIndex By Town', function (done) {
// this.timeout(10*1000);
// var mongoose = require('mongoose');
// mongoose.connect('localhost/todayweather', function(err) {
// if (err) {
// console.error('Could not connect to MongoDB!');
// console.log(err);
// done();
// }
// });
// mongoose.connection.on('error', function(err) {
// console.error('MongoDB connection error: ' + err);
// });
//
// var town = {third: '구미동', second: '성남시분당구', first: '경기도'};
// reqLifeIndex.getLifeIndexByTown(town, function(err, data) {
// if (err) console.log(err);
// console.log(data);
// //console.log(data.rot.data);
// done();
// });
//});
//it ('save life index', function (done) {
// var mongoose = require('mongoose');
// mongoose.connect('localhost/todayweather', function(err) {
// if (err) {
// console.error('Could not connect to MongoDB!');
// console.log(err);
// done();
// }
// });
// mongoose.connection.on('error', function(err) {
// console.error('MongoDB connection error: ' + err);
// done();
// });
//
// var newData = { error: undefined, result: { areaNo: '1100000000',
// ultrv: { lastUpdateDate: '2015102819', data: [ { date: '20151029',
// value: 2 }, { date: '20151030', value: 3 } ] } } };
// var townObject = co._areaList[0];
//
// co.saveLifeIndex('ultrv', townObject, newData.result, function (err) {
// console.log(err);
// done();
// });
//});
//it('test db', function (done) {
// var mongoose = require('mongoose');
// mongoose.connect('localhost/todayweather', function(err) {
// if (err) {
// console.error('Could not connect to MongoDB!');
// console.log(err);
// }
// });
// mongoose.connection.on('error', function(err) {
// console.error('MongoDB connection error: ' + err);
// process.exit(-1);
// });
//
// var Town = require('../models/town');
// //Town.find({"mCoord": {"my":119, "mx":95}}, function(err, townList) {
// Town.find({"areaNo": "99"}, function(err, townList) {
// if (townList.length === 0) {
// var town = new Town({town:{first: "a", second:"b", third:"c"}, areaNo: "99"});
// town.save(function (err) {
// console.log(err);
// });
// console.log("XXXXX");
// }
// console.log(townList);
// });
//});
//it('test update lifeindex db from towns', function (done) {
// var mongoose = require('mongoose');
// mongoose.connect('localhost/todayweather', function(err) {
// if (err) {
// console.error('Could not connect to MongoDB!');
// console.log(err);
// }
// });
// mongoose.connection.on('error', function(err) {
// console.error('MongoDB connection error: ' + err);
// process.exit(-1);
// });
//
// reqLifeIndex = new LifeIndexKmaRequester();
// reqLifeIndex.updateLifeIndexDbFromTowns(function (err, results) {
// if (err) {
// log.error(err);
// }
// log.info('Finish updating life index db from towns');
// log.info(results);
// done();
// });
//});
});
| WizardFactory/TodayWeather | server/test/testLifeIndexKmaRequester.js | JavaScript | mit | 13,097 |
// Copyright: Hiroshi Ichikawa <http://gimite.net/en/>
// License: New BSD License
// Reference: http://dev.w3.org/html5/websockets/
// Reference: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol
(function() {
if (window.WebSocket) return;
var console = window.console;
if (!console) console = {log: function(){ }, error: function(){ }};
if (!swfobject.hasFlashPlayerVersion("9.0.0")) {
console.error("Flash Player is not installed.");
return;
}
if (location.protocol == "file:") {
console.error(
"WARNING: web-socket-js doesn't work in file:///... URL " +
"unless you set Flash Security Settings properly. " +
"Open the page via Web server i.e. http://...");
}
WebSocket = function(url, protocol, proxyHost, proxyPort, headers) {
var self = this;
self.readyState = WebSocket.CONNECTING;
self.bufferedAmount = 0;
// Uses setTimeout() to make sure __createFlash() runs after the caller sets ws.onopen etc.
// Otherwise, when onopen fires immediately, onopen is called before it is set.
setTimeout(function() {
WebSocket.__addTask(function() {
self.__createFlash(url, protocol, proxyHost, proxyPort, headers);
});
}, 1);
}
WebSocket.prototype.__createFlash = function(url, protocol, proxyHost, proxyPort, headers) {
var self = this;
self.__flash =
WebSocket.__flash.create(url, protocol, proxyHost || null, proxyPort || 0, headers || null);
self.__flash.addEventListener("open", function(fe) {
try {
self.readyState = self.__flash.getReadyState();
if (self.__timer) clearInterval(self.__timer);
if (window.opera) {
// Workaround for weird behavior of Opera which sometimes drops events.
self.__timer = setInterval(function () {
self.__handleMessages();
}, 500);
}
if (self.onopen) self.onopen();
} catch (e) {
console.error(e.toString());
}
});
self.__flash.addEventListener("close", function(fe) {
try {
self.readyState = self.__flash.getReadyState();
if (self.__timer) clearInterval(self.__timer);
if (self.onclose) self.onclose();
} catch (e) {
console.error(e.toString());
}
});
self.__flash.addEventListener("message", function() {
try {
self.__handleMessages();
} catch (e) {
console.error(e.toString());
}
});
self.__flash.addEventListener("error", function(fe) {
try {
if (self.__timer) clearInterval(self.__timer);
if (self.onerror) self.onerror();
} catch (e) {
console.error(e.toString());
}
});
self.__flash.addEventListener("stateChange", function(fe) {
try {
self.readyState = self.__flash.getReadyState();
self.bufferedAmount = fe.getBufferedAmount();
} catch (e) {
console.error(e.toString());
}
});
//console.log("[WebSocket] Flash object is ready");
};
WebSocket.prototype.send = function(data) {
if (this.__flash) {
this.readyState = this.__flash.getReadyState();
}
if (!this.__flash || this.readyState == WebSocket.CONNECTING) {
throw "INVALID_STATE_ERR: Web Socket connection has not been established";
}
// We use encodeURIComponent() here, because FABridge doesn't work if
// the argument includes some characters. We don't use escape() here
// because of this:
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#escape_and_unescape_Functions
// But it looks decodeURIComponent(encodeURIComponent(s)) doesn't
// preserve all Unicode characters either e.g. "\uffff" in Firefox.
var result = this.__flash.send(encodeURIComponent(data));
if (result < 0) { // success
return true;
} else {
this.bufferedAmount = result;
return false;
}
};
WebSocket.prototype.close = function() {
if (!this.__flash) return;
this.readyState = this.__flash.getReadyState();
if (this.readyState != WebSocket.OPEN) return;
this.__flash.close();
// Sets/calls them manually here because Flash WebSocketConnection.close cannot fire events
// which causes weird error:
// > You are trying to call recursively into the Flash Player which is not allowed.
this.readyState = WebSocket.CLOSED;
if (this.__timer) clearInterval(this.__timer);
if (this.onclose) this.onclose();
};
/**
* Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
*
* @param {string} type
* @param {function} listener
* @param {boolean} useCapture !NB Not implemented yet
* @return void
*/
WebSocket.prototype.addEventListener = function(type, listener, useCapture) {
if (!('__events' in this)) {
this.__events = {};
}
if (!(type in this.__events)) {
this.__events[type] = [];
if ('function' == typeof this['on' + type]) {
this.__events[type].defaultHandler = this['on' + type];
this['on' + type] = this.__createEventHandler(this, type);
}
}
this.__events[type].push(listener);
};
/**
* Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
*
* @param {string} type
* @param {function} listener
* @param {boolean} useCapture NB! Not implemented yet
* @return void
*/
WebSocket.prototype.removeEventListener = function(type, listener, useCapture) {
if (!('__events' in this)) {
this.__events = {};
}
if (!(type in this.__events)) return;
for (var i = this.__events.length; i > -1; --i) {
if (listener === this.__events[type][i]) {
this.__events[type].splice(i, 1);
break;
}
}
};
/**
* Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
*
* @param {WebSocketEvent} event
* @return void
*/
WebSocket.prototype.dispatchEvent = function(event) {
if (!('__events' in this)) throw 'UNSPECIFIED_EVENT_TYPE_ERR';
if (!(event.type in this.__events)) throw 'UNSPECIFIED_EVENT_TYPE_ERR';
for (var i = 0, l = this.__events[event.type].length; i < l; ++ i) {
this.__events[event.type][i](event);
if (event.cancelBubble) break;
}
if (false !== event.returnValue &&
'function' == typeof this.__events[event.type].defaultHandler)
{
this.__events[event.type].defaultHandler(event);
}
};
WebSocket.prototype.__handleMessages = function() {
// Gets data using readSocketData() instead of getting it from event object
// of Flash event. This is to make sure to keep message order.
// It seems sometimes Flash events don't arrive in the same order as they are sent.
var arr = this.__flash.readSocketData();
for (var i = 0; i < arr.length; i++) {
var data = decodeURIComponent(arr[i]);
try {
if (this.onmessage) {
var e;
if (window.MessageEvent) {
e = document.createEvent("MessageEvent");
e.initMessageEvent("message", false, false, data, null, null, window, null);
} else { // IE
e = {data: data};
}
this.onmessage(e);
}
} catch (e) {
console.error(e.toString());
}
}
};
/**
* @param {object} object
* @param {string} type
*/
WebSocket.prototype.__createEventHandler = function(object, type) {
return function(data) {
var event = new WebSocketEvent();
event.initEvent(type, true, true);
event.target = event.currentTarget = object;
for (var key in data) {
event[key] = data[key];
}
object.dispatchEvent(event, arguments);
};
}
/**
* Basic implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-interface">DOM 2 EventInterface</a>}
*
* @class
* @constructor
*/
function WebSocketEvent(){}
/**
*
* @type boolean
*/
WebSocketEvent.prototype.cancelable = true;
/**
*
* @type boolean
*/
WebSocketEvent.prototype.cancelBubble = false;
/**
*
* @return void
*/
WebSocketEvent.prototype.preventDefault = function() {
if (this.cancelable) {
this.returnValue = false;
}
};
/**
*
* @return void
*/
WebSocketEvent.prototype.stopPropagation = function() {
this.cancelBubble = true;
};
/**
*
* @param {string} eventTypeArg
* @param {boolean} canBubbleArg
* @param {boolean} cancelableArg
* @return void
*/
WebSocketEvent.prototype.initEvent = function(eventTypeArg, canBubbleArg, cancelableArg) {
this.type = eventTypeArg;
this.cancelable = cancelableArg;
this.timeStamp = new Date();
};
WebSocket.CONNECTING = 0;
WebSocket.OPEN = 1;
WebSocket.CLOSING = 2;
WebSocket.CLOSED = 3;
WebSocket.__tasks = [];
WebSocket.__initialize = function() {
if (WebSocket.__swfLocation) {
// For backword compatibility.
window.WEB_SOCKET_SWF_LOCATION = WebSocket.__swfLocation;
}
if (!window.WEB_SOCKET_SWF_LOCATION) {
console.error("[WebSocket] set WEB_SOCKET_SWF_LOCATION to location of WebSocketMain.swf");
return;
}
var container = document.createElement("div");
container.id = "webSocketContainer";
// Hides Flash box. We cannot use display: none or visibility: hidden because it prevents
// Flash from loading at least in IE. So we move it out of the screen at (-100, -100).
// But this even doesn't work with Flash Lite (e.g. in Droid Incredible). So with Flash
// Lite, we put it at (0, 0). This shows 1x1 box visible at left-top corner but this is
// the best we can do as far as we know now.
container.style.position = "absolute";
if (WebSocket.__isFlashLite()) {
container.style.left = "0px";
container.style.top = "0px";
} else {
container.style.left = "-100px";
container.style.top = "-100px";
}
var holder = document.createElement("div");
holder.id = "webSocketFlash";
container.appendChild(holder);
document.body.appendChild(container);
// See this article for hasPriority:
// http://help.adobe.com/en_US/as3/mobile/WS4bebcd66a74275c36cfb8137124318eebc6-7ffd.html
swfobject.embedSWF(
WEB_SOCKET_SWF_LOCATION, "webSocketFlash",
"1" /* width */, "1" /* height */, "9.0.0" /* SWF version */,
null, {bridgeName: "webSocket"}, {hasPriority: true}, null,
function(e) {
if (!e.success) console.error("[WebSocket] swfobject.embedSWF failed");
}
);
FABridge.addInitializationCallback("webSocket", function() {
try {
//console.log("[WebSocket] FABridge initializad");
WebSocket.__flash = FABridge.webSocket.root();
WebSocket.__flash.setCallerUrl(location.href);
WebSocket.__flash.setDebug(!!window.WEB_SOCKET_DEBUG);
for (var i = 0; i < WebSocket.__tasks.length; ++i) {
WebSocket.__tasks[i]();
}
WebSocket.__tasks = [];
} catch (e) {
console.error("[WebSocket] " + e.toString());
}
});
};
WebSocket.__addTask = function(task) {
if (WebSocket.__flash) {
task();
} else {
WebSocket.__tasks.push(task);
}
};
WebSocket.__isFlashLite = function() {
if (!window.navigator || !window.navigator.mimeTypes) return false;
var mimeType = window.navigator.mimeTypes["application/x-shockwave-flash"];
if (!mimeType || !mimeType.enabledPlugin || !mimeType.enabledPlugin.filename) return false;
return mimeType.enabledPlugin.filename.match(/flashlite/i) ? true : false;
};
// called from Flash
window.webSocketLog = function(message) {
console.log(decodeURIComponent(message));
};
// called from Flash
window.webSocketError = function(message) {
console.error(decodeURIComponent(message));
};
if (!window.WEB_SOCKET_DISABLE_AUTO_INITIALIZATION) {
if (window.addEventListener) {
window.addEventListener("load", WebSocket.__initialize, false);
} else {
window.attachEvent("onload", WebSocket.__initialize);
}
}
})();
| ruby-hammer/hammer-app-base | public/websocket/web_socket.js | JavaScript | mit | 12,347 |
/**
* Very simple implementation of a popup window. Any DOM element can be marked up as a popup,
* usage is:
*
* $("selector").popup(); // initializes it as a popup, and hides it
*
* // later...
*
* $("selector").popup("show"); // to show it
* $("selector").popup("hide"); // to hide it
*
* Copyright (c) 2012 by Dean Harding (dean@codeka.com.au)
*/
(function($) {
$.extend({
popup: {
defaults: {
width: "50%",
height: "500px",
background: "#fff",
popupId: "popup-H7dGS"
},
init: function(dom, options) {
options = $.extend({}, this.defaults, options);
dom.data("popup-options", options);
var popupDom = $("#"+options.popupId);
if (popupDom.size() == 0) {
popupDom = $("<div id=\""+options.popupId+"\"></div>");
popupDom.css("display", "none")
.css("position", "absolute")
.css("background", options.background)
.css("box-shadow", "0 0 5px 5px #888");
$(document.body).append(popupDom);
}
dom.each(function() {
$(this).hide();
});
},
show: function(dom, options) {
options = $.extend({}, dom.data("popup-options"), options);
console.log("Showing popup: "+options.popupId);
var popupDom = $("#"+options.popupId);
popupDom.empty();
dom.each(function() {
var me = $(this);
popupDom.append(me.clone().show());
});
popupDom.css("width", options.width)
.css("height", options.height)
.css("top", parseInt(($(document).height() / 2) - (popupDom.height() / 2)) + "px")
.css("left", parseInt(($(document).width() / 2) - (popupDom.width() / 2)) + "px")
.fadeIn("fast");
},
hide: function(dom, options) {
options = $.extend({}, dom.data("popup-options"), options);
console.log("Hiding popup: "+options.popupId);
var popupDom = $("#"+options.popupId);
popupDom.fadeOut("fast");
}
}
});
$.fn.popup = function(method, options) {
if (!options && typeof method != "string") {
options = method;
method = "init";
}
return $.popup[method].call($.popup, this, options);
}
})(jQuery);
| jife94/wwmmo | website/static/js/popup.js | JavaScript | mit | 2,340 |
/* *
*
* (c) 2010-2020 Torstein Honsi
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from './Globals.js';
/**
* Define the time span for the button
*
* @typedef {"all"|"day"|"hour"|"millisecond"|"minute"|"month"|"second"|"week"|"year"|"ytd"} Highcharts.RangeSelectorButtonTypeValue
*/
/**
* Callback function to react on button clicks.
*
* @callback Highcharts.RangeSelectorClickCallbackFunction
*
* @param {global.Event} e
* Event arguments.
*
* @param {boolean|undefined}
* Return false to cancel the default button event.
*/
/**
* Callback function to parse values entered in the input boxes and return a
* valid JavaScript time as milliseconds since 1970.
*
* @callback Highcharts.RangeSelectorParseCallbackFunction
*
* @param {string} value
* Input value to parse.
*
* @return {number}
* Parsed JavaScript time value.
*/
import U from './Utilities.js';
var addEvent = U.addEvent, createElement = U.createElement, css = U.css, defined = U.defined, destroyObjectProperties = U.destroyObjectProperties, discardElement = U.discardElement, extend = U.extend, fireEvent = U.fireEvent, isNumber = U.isNumber, merge = U.merge, objectEach = U.objectEach, pick = U.pick, pInt = U.pInt, splat = U.splat;
import './Axis.js';
import './Chart.js';
var Axis = H.Axis, Chart = H.Chart, defaultOptions = H.defaultOptions;
/* ************************************************************************** *
* Start Range Selector code *
* ************************************************************************** */
extend(defaultOptions, {
/**
* The range selector is a tool for selecting ranges to display within
* the chart. It provides buttons to select preconfigured ranges in
* the chart, like 1 day, 1 week, 1 month etc. It also provides input
* boxes where min and max dates can be manually input.
*
* @product highstock gantt
* @optionparent rangeSelector
*/
rangeSelector: {
/**
* Whether to enable all buttons from the start. By default buttons are
* only enabled if the corresponding time range exists on the X axis,
* but enabling all buttons allows for dynamically loading different
* time ranges.
*
* @sample {highstock} stock/rangeselector/allbuttonsenabled-true/
* All buttons enabled
*
* @type {boolean}
* @default false
* @since 2.0.3
* @apioption rangeSelector.allButtonsEnabled
*/
/**
* An array of configuration objects for the buttons.
*
* Defaults to:
* ```js
* buttons: [{
* type: 'month',
* count: 1,
* text: '1m'
* }, {
* type: 'month',
* count: 3,
* text: '3m'
* }, {
* type: 'month',
* count: 6,
* text: '6m'
* }, {
* type: 'ytd',
* text: 'YTD'
* }, {
* type: 'year',
* count: 1,
* text: '1y'
* }, {
* type: 'all',
* text: 'All'
* }]
* ```
*
* @sample {highstock} stock/rangeselector/datagrouping/
* Data grouping by buttons
*
* @type {Array<*>}
* @apioption rangeSelector.buttons
*/
/**
* How many units of the defined type the button should span. If `type`
* is "month" and `count` is 3, the button spans three months.
*
* @type {number}
* @default 1
* @apioption rangeSelector.buttons.count
*/
/**
* Fires when clicking on the rangeSelector button. One parameter,
* event, is passed to the function, containing common event
* information.
*
* ```js
* click: function(e) {
* console.log(this);
* }
* ```
*
* Return false to stop default button's click action.
*
* @sample {highstock} stock/rangeselector/button-click/
* Click event on the button
*
* @type {Highcharts.RangeSelectorClickCallbackFunction}
* @apioption rangeSelector.buttons.events.click
*/
/**
* Additional range (in milliseconds) added to the end of the calculated
* time span.
*
* @sample {highstock} stock/rangeselector/min-max-offsets/
* Button offsets
*
* @type {number}
* @default 0
* @since 6.0.0
* @apioption rangeSelector.buttons.offsetMax
*/
/**
* Additional range (in milliseconds) added to the start of the
* calculated time span.
*
* @sample {highstock} stock/rangeselector/min-max-offsets/
* Button offsets
*
* @type {number}
* @default 0
* @since 6.0.0
* @apioption rangeSelector.buttons.offsetMin
*/
/**
* When buttons apply dataGrouping on a series, by default zooming
* in/out will deselect buttons and unset dataGrouping. Enable this
* option to keep buttons selected when extremes change.
*
* @sample {highstock} stock/rangeselector/preserve-datagrouping/
* Different preserveDataGrouping settings
*
* @type {boolean}
* @default false
* @since 6.1.2
* @apioption rangeSelector.buttons.preserveDataGrouping
*/
/**
* A custom data grouping object for each button.
*
* @see [series.dataGrouping](#plotOptions.series.dataGrouping)
*
* @sample {highstock} stock/rangeselector/datagrouping/
* Data grouping by range selector buttons
*
* @type {*}
* @extends plotOptions.series.dataGrouping
* @apioption rangeSelector.buttons.dataGrouping
*/
/**
* The text for the button itself.
*
* @type {string}
* @apioption rangeSelector.buttons.text
*/
/**
* Defined the time span for the button. Can be one of `millisecond`,
* `second`, `minute`, `hour`, `day`, `week`, `month`, `year`, `ytd`,
* and `all`.
*
* @type {Highcharts.RangeSelectorButtonTypeValue}
* @apioption rangeSelector.buttons.type
*/
/**
* The space in pixels between the buttons in the range selector.
*
* @type {number}
* @default 0
* @apioption rangeSelector.buttonSpacing
*/
/**
* Enable or disable the range selector.
*
* @sample {highstock} stock/rangeselector/enabled/
* Disable the range selector
*
* @type {boolean}
* @default true
* @apioption rangeSelector.enabled
*/
/**
* The vertical alignment of the rangeselector box. Allowed properties
* are `top`, `middle`, `bottom`.
*
* @sample {highstock} stock/rangeselector/vertical-align-middle/
* Middle
* @sample {highstock} stock/rangeselector/vertical-align-bottom/
* Bottom
*
* @type {Highcharts.VerticalAlignValue}
* @since 6.0.0
*/
verticalAlign: 'top',
/**
* A collection of attributes for the buttons. The object takes SVG
* attributes like `fill`, `stroke`, `stroke-width`, as well as `style`,
* a collection of CSS properties for the text.
*
* The object can also be extended with states, so you can set
* presentational options for `hover`, `select` or `disabled` button
* states.
*
* CSS styles for the text label.
*
* In styled mode, the buttons are styled by the
* `.highcharts-range-selector-buttons .highcharts-button` rule with its
* different states.
*
* @sample {highstock} stock/rangeselector/styling/
* Styling the buttons and inputs
*
* @type {Highcharts.SVGAttributes}
*/
buttonTheme: {
/** @ignore */
width: 28,
/** @ignore */
height: 18,
/** @ignore */
padding: 2,
/** @ignore */
zIndex: 7 // #484, #852
},
/**
* When the rangeselector is floating, the plot area does not reserve
* space for it. This opens for positioning anywhere on the chart.
*
* @sample {highstock} stock/rangeselector/floating/
* Placing the range selector between the plot area and the
* navigator
*
* @since 6.0.0
*/
floating: false,
/**
* The x offset of the range selector relative to its horizontal
* alignment within `chart.spacingLeft` and `chart.spacingRight`.
*
* @since 6.0.0
*/
x: 0,
/**
* The y offset of the range selector relative to its horizontal
* alignment within `chart.spacingLeft` and `chart.spacingRight`.
*
* @since 6.0.0
*/
y: 0,
/**
* Deprecated. The height of the range selector. Currently it is
* calculated dynamically.
*
* @deprecated
* @type {number|undefined}
* @since 2.1.9
*/
height: void 0,
/**
* The border color of the date input boxes.
*
* @sample {highstock} stock/rangeselector/styling/
* Styling the buttons and inputs
*
* @type {Highcharts.ColorString}
* @default #cccccc
* @since 1.3.7
* @apioption rangeSelector.inputBoxBorderColor
*/
/**
* The pixel height of the date input boxes.
*
* @sample {highstock} stock/rangeselector/styling/
* Styling the buttons and inputs
*
* @type {number}
* @default 17
* @since 1.3.7
* @apioption rangeSelector.inputBoxHeight
*/
/**
* CSS for the container DIV holding the input boxes. Deprecated as
* of 1.2.5\. Use [inputPosition](#rangeSelector.inputPosition) instead.
*
* @sample {highstock} stock/rangeselector/styling/
* Styling the buttons and inputs
*
* @deprecated
* @type {Highcharts.CSSObject}
* @apioption rangeSelector.inputBoxStyle
*/
/**
* The pixel width of the date input boxes.
*
* @sample {highstock} stock/rangeselector/styling/
* Styling the buttons and inputs
*
* @type {number}
* @default 90
* @since 1.3.7
* @apioption rangeSelector.inputBoxWidth
*/
/**
* The date format in the input boxes when not selected for editing.
* Defaults to `%b %e, %Y`.
*
* @sample {highstock} stock/rangeselector/input-format/
* Milliseconds in the range selector
*
* @type {string}
* @default %b %e, %Y
* @apioption rangeSelector.inputDateFormat
*/
/**
* A custom callback function to parse values entered in the input boxes
* and return a valid JavaScript time as milliseconds since 1970.
*
* @sample {highstock} stock/rangeselector/input-format/
* Milliseconds in the range selector
*
* @type {Highcharts.RangeSelectorParseCallbackFunction}
* @since 1.3.3
* @apioption rangeSelector.inputDateParser
*/
/**
* The date format in the input boxes when they are selected for
* editing. This must be a format that is recognized by JavaScript
* Date.parse.
*
* @sample {highstock} stock/rangeselector/input-format/
* Milliseconds in the range selector
*
* @type {string}
* @default %Y-%m-%d
* @apioption rangeSelector.inputEditDateFormat
*/
/**
* Enable or disable the date input boxes. Defaults to enabled when
* there is enough space, disabled if not (typically mobile).
*
* @sample {highstock} stock/rangeselector/input-datepicker/
* Extending the input with a jQuery UI datepicker
*
* @type {boolean}
* @default true
* @apioption rangeSelector.inputEnabled
*/
/**
* Positioning for the input boxes. Allowed properties are `align`,
* `x` and `y`.
*
* @since 1.2.4
*/
inputPosition: {
/**
* The alignment of the input box. Allowed properties are `left`,
* `center`, `right`.
*
* @sample {highstock} stock/rangeselector/input-button-position/
* Alignment
*
* @type {Highcharts.AlignValue}
* @since 6.0.0
*/
align: 'right',
/**
* X offset of the input row.
*/
x: 0,
/**
* Y offset of the input row.
*/
y: 0
},
/**
* The index of the button to appear pre-selected.
*
* @type {number}
* @apioption rangeSelector.selected
*/
/**
* Positioning for the button row.
*
* @since 1.2.4
*/
buttonPosition: {
/**
* The alignment of the input box. Allowed properties are `left`,
* `center`, `right`.
*
* @sample {highstock} stock/rangeselector/input-button-position/
* Alignment
*
* @type {Highcharts.AlignValue}
* @since 6.0.0
*/
align: 'left',
/**
* X offset of the button row.
*/
x: 0,
/**
* Y offset of the button row.
*/
y: 0
},
/**
* CSS for the HTML inputs in the range selector.
*
* In styled mode, the inputs are styled by the
* `.highcharts-range-input text` rule in SVG mode, and
* `input.highcharts-range-selector` when active.
*
* @sample {highstock} stock/rangeselector/styling/
* Styling the buttons and inputs
*
* @type {Highcharts.CSSObject}
* @apioption rangeSelector.inputStyle
*/
/**
* CSS styles for the labels - the Zoom, From and To texts.
*
* In styled mode, the labels are styled by the
* `.highcharts-range-label` class.
*
* @sample {highstock} stock/rangeselector/styling/
* Styling the buttons and inputs
*
* @type {Highcharts.CSSObject}
*/
labelStyle: {
/** @ignore */
color: '#666666'
}
}
});
defaultOptions.lang = merge(defaultOptions.lang,
/**
* Language object. The language object is global and it can't be set
* on each chart initialization. Instead, use `Highcharts.setOptions` to
* set it before any chart is initialized.
*
* ```js
* Highcharts.setOptions({
* lang: {
* months: [
* 'Janvier', 'Février', 'Mars', 'Avril',
* 'Mai', 'Juin', 'Juillet', 'Août',
* 'Septembre', 'Octobre', 'Novembre', 'Décembre'
* ],
* weekdays: [
* 'Dimanche', 'Lundi', 'Mardi', 'Mercredi',
* 'Jeudi', 'Vendredi', 'Samedi'
* ]
* }
* });
* ```
*
* @optionparent lang
*/
{
/**
* The text for the label for the range selector buttons.
*
* @product highstock gantt
*/
rangeSelectorZoom: 'Zoom',
/**
* The text for the label for the "from" input box in the range
* selector.
*
* @product highstock gantt
*/
rangeSelectorFrom: 'From',
/**
* The text for the label for the "to" input box in the range selector.
*
* @product highstock gantt
*/
rangeSelectorTo: 'To'
});
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* The range selector.
*
* @private
* @class
* @name Highcharts.RangeSelector
* @param {Highcharts.Chart} chart
*/
function RangeSelector(chart) {
// Run RangeSelector
this.init(chart);
}
RangeSelector.prototype = {
/**
* The method to run when one of the buttons in the range selectors is
* clicked
*
* @private
* @function Highcharts.RangeSelector#clickButton
* @param {number} i
* The index of the button
* @param {boolean} [redraw]
* @return {void}
*/
clickButton: function (i, redraw) {
var rangeSelector = this, chart = rangeSelector.chart, rangeOptions = rangeSelector.buttonOptions[i], baseAxis = chart.xAxis[0], unionExtremes = (chart.scroller && chart.scroller.getUnionExtremes()) || baseAxis || {}, dataMin = unionExtremes.dataMin, dataMax = unionExtremes.dataMax, newMin, newMax = baseAxis && Math.round(Math.min(baseAxis.max, pick(dataMax, baseAxis.max))), // #1568
type = rangeOptions.type, baseXAxisOptions, range = rangeOptions._range, rangeMin, minSetting, rangeSetting, ctx, ytdExtremes, dataGrouping = rangeOptions.dataGrouping;
// chart has no data, base series is removed
if (dataMin === null || dataMax === null) {
return;
}
// Set the fixed range before range is altered
chart.fixedRange = range;
// Apply dataGrouping associated to button
if (dataGrouping) {
this.forcedDataGrouping = true;
Axis.prototype.setDataGrouping.call(baseAxis || { chart: this.chart }, dataGrouping, false);
this.frozenStates = rangeOptions.preserveDataGrouping;
}
// Apply range
if (type === 'month' || type === 'year') {
if (!baseAxis) {
// This is set to the user options and picked up later when the
// axis is instantiated so that we know the min and max.
range = rangeOptions;
}
else {
ctx = {
range: rangeOptions,
max: newMax,
chart: chart,
dataMin: dataMin,
dataMax: dataMax
};
newMin = baseAxis.minFromRange.call(ctx);
if (isNumber(ctx.newMax)) {
newMax = ctx.newMax;
}
}
// Fixed times like minutes, hours, days
}
else if (range) {
newMin = Math.max(newMax - range, dataMin);
newMax = Math.min(newMin + range, dataMax);
}
else if (type === 'ytd') {
// On user clicks on the buttons, or a delayed action running from
// the beforeRender event (below), the baseAxis is defined.
if (baseAxis) {
// When "ytd" is the pre-selected button for the initial view,
// its calculation is delayed and rerun in the beforeRender
// event (below). When the series are initialized, but before
// the chart is rendered, we have access to the xData array
// (#942).
if (typeof dataMax === 'undefined') {
dataMin = Number.MAX_VALUE;
dataMax = Number.MIN_VALUE;
chart.series.forEach(function (series) {
// reassign it to the last item
var xData = series.xData;
dataMin = Math.min(xData[0], dataMin);
dataMax = Math.max(xData[xData.length - 1], dataMax);
});
redraw = false;
}
ytdExtremes = rangeSelector.getYTDExtremes(dataMax, dataMin, chart.time.useUTC);
newMin = rangeMin = ytdExtremes.min;
newMax = ytdExtremes.max;
// "ytd" is pre-selected. We don't yet have access to processed
// point and extremes data (things like pointStart and pointInterval
// are missing), so we delay the process (#942)
}
else {
rangeSelector.deferredYTDClick = i;
return;
}
}
else if (type === 'all' && baseAxis) {
newMin = dataMin;
newMax = dataMax;
}
newMin += rangeOptions._offsetMin;
newMax += rangeOptions._offsetMax;
rangeSelector.setSelected(i);
// Update the chart
if (!baseAxis) {
// Axis not yet instanciated. Temporarily set min and range
// options and remove them on chart load (#4317).
baseXAxisOptions = splat(chart.options.xAxis)[0];
rangeSetting = baseXAxisOptions.range;
baseXAxisOptions.range = range;
minSetting = baseXAxisOptions.min;
baseXAxisOptions.min = rangeMin;
addEvent(chart, 'load', function resetMinAndRange() {
baseXAxisOptions.range = rangeSetting;
baseXAxisOptions.min = minSetting;
});
}
else {
// Existing axis object. Set extremes after render time.
baseAxis.setExtremes(newMin, newMax, pick(redraw, 1), null, // auto animation
{
trigger: 'rangeSelectorButton',
rangeSelectorButton: rangeOptions
});
}
},
/**
* Set the selected option. This method only sets the internal flag, it
* doesn't update the buttons or the actual zoomed range.
*
* @private
* @function Highcharts.RangeSelector#setSelected
* @param {number} [selected]
* @return {void}
*/
setSelected: function (selected) {
this.selected = this.options.selected = selected;
},
/**
* The default buttons for pre-selecting time frames
*/
defaultButtons: [{
type: 'month',
count: 1,
text: '1m'
}, {
type: 'month',
count: 3,
text: '3m'
}, {
type: 'month',
count: 6,
text: '6m'
}, {
type: 'ytd',
text: 'YTD'
}, {
type: 'year',
count: 1,
text: '1y'
}, {
type: 'all',
text: 'All'
}],
/**
* Initialize the range selector
*
* @private
* @function Highcharts.RangeSelector#init
* @param {Highcharts.Chart} chart
* @return {void}
*/
init: function (chart) {
var rangeSelector = this, options = chart.options.rangeSelector, buttonOptions = options.buttons ||
[].concat(rangeSelector.defaultButtons), selectedOption = options.selected, blurInputs = function () {
var minInput = rangeSelector.minInput, maxInput = rangeSelector.maxInput;
// #3274 in some case blur is not defined
if (minInput && minInput.blur) {
fireEvent(minInput, 'blur');
}
if (maxInput && maxInput.blur) {
fireEvent(maxInput, 'blur');
}
};
rangeSelector.chart = chart;
rangeSelector.options = options;
rangeSelector.buttons = [];
rangeSelector.buttonOptions = buttonOptions;
this.unMouseDown = addEvent(chart.container, 'mousedown', blurInputs);
this.unResize = addEvent(chart, 'resize', blurInputs);
// Extend the buttonOptions with actual range
buttonOptions.forEach(rangeSelector.computeButtonRange);
// zoomed range based on a pre-selected button index
if (typeof selectedOption !== 'undefined' &&
buttonOptions[selectedOption]) {
this.clickButton(selectedOption, false);
}
addEvent(chart, 'load', function () {
// If a data grouping is applied to the current button, release it
// when extremes change
if (chart.xAxis && chart.xAxis[0]) {
addEvent(chart.xAxis[0], 'setExtremes', function (e) {
if (this.max - this.min !==
chart.fixedRange &&
e.trigger !== 'rangeSelectorButton' &&
e.trigger !== 'updatedData' &&
rangeSelector.forcedDataGrouping &&
!rangeSelector.frozenStates) {
this.setDataGrouping(false, false);
}
});
}
});
},
/**
* Dynamically update the range selector buttons after a new range has been
* set
*
* @private
* @function Highcharts.RangeSelector#updateButtonStates
* @return {void}
*/
updateButtonStates: function () {
var rangeSelector = this, chart = this.chart, baseAxis = chart.xAxis[0], actualRange = Math.round(baseAxis.max - baseAxis.min), hasNoData = !baseAxis.hasVisibleSeries, day = 24 * 36e5, // A single day in milliseconds
unionExtremes = (chart.scroller &&
chart.scroller.getUnionExtremes()) || baseAxis, dataMin = unionExtremes.dataMin, dataMax = unionExtremes.dataMax, ytdExtremes = rangeSelector.getYTDExtremes(dataMax, dataMin, chart.time.useUTC), ytdMin = ytdExtremes.min, ytdMax = ytdExtremes.max, selected = rangeSelector.selected, selectedExists = isNumber(selected), allButtonsEnabled = rangeSelector.options.allButtonsEnabled, buttons = rangeSelector.buttons;
rangeSelector.buttonOptions.forEach(function (rangeOptions, i) {
var range = rangeOptions._range, type = rangeOptions.type, count = rangeOptions.count || 1, button = buttons[i], state = 0, disable, select, offsetRange = rangeOptions._offsetMax -
rangeOptions._offsetMin, isSelected = i === selected,
// Disable buttons where the range exceeds what is allowed in
// the current view
isTooGreatRange = range >
dataMax - dataMin,
// Disable buttons where the range is smaller than the minimum
// range
isTooSmallRange = range < baseAxis.minRange,
// Do not select the YTD button if not explicitly told so
isYTDButNotSelected = false,
// Disable the All button if we're already showing all
isAllButAlreadyShowingAll = false, isSameRange = range === actualRange;
// Months and years have a variable range so we check the extremes
if ((type === 'month' || type === 'year') &&
(actualRange + 36e5 >=
{ month: 28, year: 365 }[type] * day * count - offsetRange) &&
(actualRange - 36e5 <=
{ month: 31, year: 366 }[type] * day * count + offsetRange)) {
isSameRange = true;
}
else if (type === 'ytd') {
isSameRange = (ytdMax - ytdMin + offsetRange) === actualRange;
isYTDButNotSelected = !isSelected;
}
else if (type === 'all') {
isSameRange = (baseAxis.max - baseAxis.min >=
dataMax - dataMin);
isAllButAlreadyShowingAll = (!isSelected &&
selectedExists &&
isSameRange);
}
// The new zoom area happens to match the range for a button - mark
// it selected. This happens when scrolling across an ordinal gap.
// It can be seen in the intraday demos when selecting 1h and scroll
// across the night gap.
disable = (!allButtonsEnabled &&
(isTooGreatRange ||
isTooSmallRange ||
isAllButAlreadyShowingAll ||
hasNoData));
select = ((isSelected && isSameRange) ||
(isSameRange && !selectedExists && !isYTDButNotSelected) ||
(isSelected && rangeSelector.frozenStates));
if (disable) {
state = 3;
}
else if (select) {
selectedExists = true; // Only one button can be selected
state = 2;
}
// If state has changed, update the button
if (button.state !== state) {
button.setState(state);
// Reset (#9209)
if (state === 0 && selected === i) {
rangeSelector.setSelected(null);
}
}
});
},
/**
* Compute and cache the range for an individual button
*
* @private
* @function Highcharts.RangeSelector#computeButtonRange
* @param {Highcharts.RangeSelectorButtonsOptions} rangeOptions
* @return {void}
*/
computeButtonRange: function (rangeOptions) {
var type = rangeOptions.type, count = rangeOptions.count || 1,
// these time intervals have a fixed number of milliseconds, as
// opposed to month, ytd and year
fixedTimes = {
millisecond: 1,
second: 1000,
minute: 60 * 1000,
hour: 3600 * 1000,
day: 24 * 3600 * 1000,
week: 7 * 24 * 3600 * 1000
};
// Store the range on the button object
if (fixedTimes[type]) {
rangeOptions._range = fixedTimes[type] * count;
}
else if (type === 'month' || type === 'year') {
rangeOptions._range = {
month: 30,
year: 365
}[type] * 24 * 36e5 * count;
}
rangeOptions._offsetMin = pick(rangeOptions.offsetMin, 0);
rangeOptions._offsetMax = pick(rangeOptions.offsetMax, 0);
rangeOptions._range +=
rangeOptions._offsetMax - rangeOptions._offsetMin;
},
/**
* Set the internal and displayed value of a HTML input for the dates
*
* @private
* @function Highcharts.RangeSelector#setInputValue
* @param {string} name
* @param {number} [inputTime]
* @return {void}
*/
setInputValue: function (name, inputTime) {
var options = this.chart.options.rangeSelector, time = this.chart.time, input = this[name + 'Input'];
if (defined(inputTime)) {
input.previousValue = input.HCTime;
input.HCTime = inputTime;
}
input.value = time.dateFormat(options.inputEditDateFormat || '%Y-%m-%d', input.HCTime);
this[name + 'DateBox'].attr({
text: time.dateFormat(options.inputDateFormat || '%b %e, %Y', input.HCTime)
});
},
/**
* @private
* @function Highcharts.RangeSelector#showInput
* @param {string} name
* @return {void}
*/
showInput: function (name) {
var inputGroup = this.inputGroup, dateBox = this[name + 'DateBox'];
css(this[name + 'Input'], {
left: (inputGroup.translateX + dateBox.x) + 'px',
top: inputGroup.translateY + 'px',
width: (dateBox.width - 2) + 'px',
height: (dateBox.height - 2) + 'px',
border: '2px solid silver'
});
},
/**
* @private
* @function Highcharts.RangeSelector#hideInput
* @param {string} name
* @return {void}
*/
hideInput: function (name) {
css(this[name + 'Input'], {
border: 0,
width: '1px',
height: '1px'
});
this.setInputValue(name);
},
/**
* Draw either the 'from' or the 'to' HTML input box of the range selector
*
* @private
* @function Highcharts.RangeSelector#drawInput
* @param {string} name
* @return {void}
*/
drawInput: function (name) {
var rangeSelector = this, chart = rangeSelector.chart, chartStyle = chart.renderer.style || {}, renderer = chart.renderer, options = chart.options.rangeSelector, lang = defaultOptions.lang, div = rangeSelector.div, isMin = name === 'min', input, label, dateBox, inputGroup = this.inputGroup;
/**
* @private
*/
function updateExtremes() {
var inputValue = input.value, value = (options.inputDateParser || Date.parse)(inputValue), chartAxis = chart.xAxis[0], dataAxis = chart.scroller && chart.scroller.xAxis ?
chart.scroller.xAxis :
chartAxis, dataMin = dataAxis.dataMin, dataMax = dataAxis.dataMax;
if (value !== input.previousValue) {
input.previousValue = value;
// If the value isn't parsed directly to a value by the
// browser's Date.parse method, like YYYY-MM-DD in IE, try
// parsing it a different way
if (!isNumber(value)) {
value = inputValue.split('-');
value = Date.UTC(pInt(value[0]), pInt(value[1]) - 1, pInt(value[2]));
}
if (isNumber(value)) {
// Correct for timezone offset (#433)
if (!chart.time.useUTC) {
value =
value + new Date().getTimezoneOffset() * 60 * 1000;
}
// Validate the extremes. If it goes beyound the data min or
// max, use the actual data extreme (#2438).
if (isMin) {
if (value > rangeSelector.maxInput.HCTime) {
value = void 0;
}
else if (value < dataMin) {
value = dataMin;
}
}
else {
if (value < rangeSelector.minInput.HCTime) {
value = void 0;
}
else if (value > dataMax) {
value = dataMax;
}
}
// Set the extremes
if (typeof value !== 'undefined') { // @todo typof undefined
chartAxis.setExtremes(isMin ? value : chartAxis.min, isMin ? chartAxis.max : value, void 0, void 0, { trigger: 'rangeSelectorInput' });
}
}
}
}
// Create the text label
this[name + 'Label'] = label = renderer
.label(lang[isMin ? 'rangeSelectorFrom' : 'rangeSelectorTo'], this.inputGroup.offset)
.addClass('highcharts-range-label')
.attr({
padding: 2
})
.add(inputGroup);
inputGroup.offset += label.width + 5;
// Create an SVG label that shows updated date ranges and and records
// click events that bring in the HTML input.
this[name + 'DateBox'] = dateBox = renderer
.label('', inputGroup.offset)
.addClass('highcharts-range-input')
.attr({
padding: 2,
width: options.inputBoxWidth || 90,
height: options.inputBoxHeight || 17,
'text-align': 'center'
})
.on('click', function () {
// If it is already focused, the onfocus event doesn't fire
// (#3713)
rangeSelector.showInput(name);
rangeSelector[name + 'Input'].focus();
});
if (!chart.styledMode) {
dateBox.attr({
stroke: options.inputBoxBorderColor || '#cccccc',
'stroke-width': 1
});
}
dateBox.add(inputGroup);
inputGroup.offset += dateBox.width + (isMin ? 10 : 0);
// Create the HTML input element. This is rendered as 1x1 pixel then set
// to the right size when focused.
this[name + 'Input'] = input = createElement('input', {
name: name,
className: 'highcharts-range-selector',
type: 'text'
}, {
top: chart.plotTop + 'px' // prevent jump on focus in Firefox
}, div);
if (!chart.styledMode) {
// Styles
label.css(merge(chartStyle, options.labelStyle));
dateBox.css(merge({
color: '#333333'
}, chartStyle, options.inputStyle));
css(input, extend({
position: 'absolute',
border: 0,
width: '1px',
height: '1px',
padding: 0,
textAlign: 'center',
fontSize: chartStyle.fontSize,
fontFamily: chartStyle.fontFamily,
top: '-9999em' // #4798
}, options.inputStyle));
}
// Blow up the input box
input.onfocus = function () {
rangeSelector.showInput(name);
};
// Hide away the input box
input.onblur = function () {
// update extermes only when inputs are active
if (input === H.doc.activeElement) { // Only when focused
// Update also when no `change` event is triggered, like when
// clicking inside the SVG (#4710)
updateExtremes();
}
// #10404 - move hide and blur outside focus
rangeSelector.hideInput(name);
input.blur(); // #4606
};
// handle changes in the input boxes
input.onchange = updateExtremes;
input.onkeypress = function (event) {
// IE does not fire onchange on enter
if (event.keyCode === 13) {
updateExtremes();
}
};
},
/**
* Get the position of the range selector buttons and inputs. This can be
* overridden from outside for custom positioning.
*
* @private
* @function Highcharts.RangeSelector#getPosition
*
* @return {Highcharts.Dictionary<number>}
*/
getPosition: function () {
var chart = this.chart, options = chart.options.rangeSelector, top = options.verticalAlign === 'top' ?
chart.plotTop - chart.axisOffset[0] :
0; // set offset only for varticalAlign top
return {
buttonTop: top + options.buttonPosition.y,
inputTop: top + options.inputPosition.y - 10
};
},
/**
* Get the extremes of YTD. Will choose dataMax if its value is lower than
* the current timestamp. Will choose dataMin if its value is higher than
* the timestamp for the start of current year.
*
* @private
* @function Highcharts.RangeSelector#getYTDExtremes
*
* @param {number} dataMax
*
* @param {number} dataMin
*
* @return {*}
* Returns min and max for the YTD
*/
getYTDExtremes: function (dataMax, dataMin, useUTC) {
var time = this.chart.time, min, now = new time.Date(dataMax), year = time.get('FullYear', now), startOfYear = useUTC ?
time.Date.UTC(year, 0, 1) : // eslint-disable-line new-cap
+new time.Date(year, 0, 1);
min = Math.max(dataMin || 0, startOfYear);
now = now.getTime();
return {
max: Math.min(dataMax || now, now),
min: min
};
},
/**
* Render the range selector including the buttons and the inputs. The first
* time render is called, the elements are created and positioned. On
* subsequent calls, they are moved and updated.
*
* @private
* @function Highcharts.RangeSelector#render
* @param {number} [min]
* X axis minimum
* @param {number} [max]
* X axis maximum
* @return {void}
*/
render: function (min, max) {
var rangeSelector = this, chart = rangeSelector.chart, renderer = chart.renderer, container = chart.container, chartOptions = chart.options, navButtonOptions = (chartOptions.exporting &&
chartOptions.exporting.enabled !== false &&
chartOptions.navigation &&
chartOptions.navigation.buttonOptions), lang = defaultOptions.lang, div = rangeSelector.div, options = chartOptions.rangeSelector,
// Place inputs above the container
inputsZIndex = pick(chartOptions.chart.style &&
chartOptions.chart.style.zIndex, 0) + 1, floating = options.floating, buttons = rangeSelector.buttons, inputGroup = rangeSelector.inputGroup, buttonTheme = options.buttonTheme, buttonPosition = options.buttonPosition, inputPosition = options.inputPosition, inputEnabled = options.inputEnabled, states = buttonTheme && buttonTheme.states, plotLeft = chart.plotLeft, buttonLeft, buttonGroup = rangeSelector.buttonGroup, group, groupHeight, rendered = rangeSelector.rendered, verticalAlign = rangeSelector.options.verticalAlign, legend = chart.legend, legendOptions = legend && legend.options, buttonPositionY = buttonPosition.y, inputPositionY = inputPosition.y, animate = chart.hasLoaded, verb = animate ? 'animate' : 'attr', exportingX = 0, alignTranslateY, legendHeight, minPosition, translateY = 0, translateX;
if (options.enabled === false) {
return;
}
// create the elements
if (!rendered) {
rangeSelector.group = group = renderer.g('range-selector-group')
.attr({
zIndex: 7
})
.add();
rangeSelector.buttonGroup = buttonGroup =
renderer.g('range-selector-buttons').add(group);
rangeSelector.zoomText = renderer
.text(lang.rangeSelectorZoom, 0, 15)
.add(buttonGroup);
if (!chart.styledMode) {
rangeSelector.zoomText.css(options.labelStyle);
buttonTheme['stroke-width'] =
pick(buttonTheme['stroke-width'], 0);
}
rangeSelector.buttonOptions.forEach(function (rangeOptions, i) {
buttons[i] = renderer
.button(rangeOptions.text, 0, 0, function (e) {
// extract events from button object and call
var buttonEvents = (rangeOptions.events &&
rangeOptions.events.click), callDefaultEvent;
if (buttonEvents) {
callDefaultEvent =
buttonEvents.call(rangeOptions, e);
}
if (callDefaultEvent !== false) {
rangeSelector.clickButton(i);
}
rangeSelector.isActive = true;
}, buttonTheme, states && states.hover, states && states.select, states && states.disabled)
.attr({
'text-align': 'center'
})
.add(buttonGroup);
});
// first create a wrapper outside the container in order to make
// the inputs work and make export correct
if (inputEnabled !== false) {
rangeSelector.div = div = createElement('div', null, {
position: 'relative',
height: 0,
zIndex: inputsZIndex
});
container.parentNode.insertBefore(div, container);
// Create the group to keep the inputs
rangeSelector.inputGroup = inputGroup =
renderer.g('input-group').add(group);
inputGroup.offset = 0;
rangeSelector.drawInput('min');
rangeSelector.drawInput('max');
}
}
// #8769, allow dynamically updating margins
rangeSelector.zoomText[verb]({
x: pick(plotLeft + buttonPosition.x, plotLeft)
});
// button start position
buttonLeft = pick(plotLeft + buttonPosition.x, plotLeft) +
rangeSelector.zoomText.getBBox().width + 5;
rangeSelector.buttonOptions.forEach(function (rangeOptions, i) {
buttons[i][verb]({ x: buttonLeft });
// increase button position for the next button
buttonLeft += buttons[i].width + pick(options.buttonSpacing, 5);
});
plotLeft = chart.plotLeft - chart.spacing[3];
rangeSelector.updateButtonStates();
// detect collisiton with exporting
if (navButtonOptions &&
this.titleCollision(chart) &&
verticalAlign === 'top' &&
buttonPosition.align === 'right' && ((buttonPosition.y +
buttonGroup.getBBox().height - 12) <
((navButtonOptions.y || 0) +
navButtonOptions.height))) {
exportingX = -40;
}
if (buttonPosition.align === 'left') {
translateX = buttonPosition.x - chart.spacing[3];
}
else if (buttonPosition.align === 'right') {
translateX =
buttonPosition.x + exportingX - chart.spacing[1];
}
// align button group
buttonGroup.align({
y: buttonPosition.y,
width: buttonGroup.getBBox().width,
align: buttonPosition.align,
x: translateX
}, true, chart.spacingBox);
// skip animation
rangeSelector.group.placed = animate;
rangeSelector.buttonGroup.placed = animate;
if (inputEnabled !== false) {
var inputGroupX, inputGroupWidth, buttonGroupX, buttonGroupWidth;
// detect collision with exporting
if (navButtonOptions &&
this.titleCollision(chart) &&
verticalAlign === 'top' &&
inputPosition.align === 'right' && ((inputPosition.y -
inputGroup.getBBox().height - 12) <
((navButtonOptions.y || 0) +
navButtonOptions.height +
chart.spacing[0]))) {
exportingX = -40;
}
else {
exportingX = 0;
}
if (inputPosition.align === 'left') {
translateX = plotLeft;
}
else if (inputPosition.align === 'right') {
translateX = -Math.max(chart.axisOffset[1], -exportingX);
}
// Update the alignment to the updated spacing box
inputGroup.align({
y: inputPosition.y,
width: inputGroup.getBBox().width,
align: inputPosition.align,
// fix wrong getBBox() value on right align
x: inputPosition.x + translateX - 2
}, true, chart.spacingBox);
// detect collision
inputGroupX = (inputGroup.alignAttr.translateX +
inputGroup.alignOptions.x -
exportingX +
// getBBox for detecing left margin
inputGroup.getBBox().x +
// 2px padding to not overlap input and label
2);
inputGroupWidth = inputGroup.alignOptions.width;
buttonGroupX = buttonGroup.alignAttr.translateX +
buttonGroup.getBBox().x;
// 20 is minimal spacing between elements
buttonGroupWidth = buttonGroup.getBBox().width + 20;
if ((inputPosition.align ===
buttonPosition.align) || ((buttonGroupX + buttonGroupWidth > inputGroupX) &&
(inputGroupX + inputGroupWidth > buttonGroupX) &&
(buttonPositionY <
(inputPositionY +
inputGroup.getBBox().height)))) {
inputGroup.attr({
translateX: inputGroup.alignAttr.translateX +
(chart.axisOffset[1] >= -exportingX ? 0 : -exportingX),
translateY: inputGroup.alignAttr.translateY +
buttonGroup.getBBox().height + 10
});
}
// Set or reset the input values
rangeSelector.setInputValue('min', min);
rangeSelector.setInputValue('max', max);
// skip animation
rangeSelector.inputGroup.placed = animate;
}
// vertical align
rangeSelector.group.align({
verticalAlign: verticalAlign
}, true, chart.spacingBox);
// set position
groupHeight =
rangeSelector.group.getBBox().height + 20; // # 20 padding
alignTranslateY =
rangeSelector.group.alignAttr.translateY;
// calculate bottom position
if (verticalAlign === 'bottom') {
legendHeight = (legendOptions &&
legendOptions.verticalAlign === 'bottom' &&
legendOptions.enabled &&
!legendOptions.floating ?
legend.legendHeight + pick(legendOptions.margin, 10) :
0);
groupHeight = groupHeight + legendHeight - 20;
translateY = (alignTranslateY -
groupHeight -
(floating ? 0 : options.y) -
(chart.titleOffset ? chart.titleOffset[2] : 0) -
10 // 10 spacing
);
}
if (verticalAlign === 'top') {
if (floating) {
translateY = 0;
}
if (chart.titleOffset && chart.titleOffset[0]) {
translateY = chart.titleOffset[0];
}
translateY += ((chart.margin[0] - chart.spacing[0]) || 0);
}
else if (verticalAlign === 'middle') {
if (inputPositionY === buttonPositionY) {
if (inputPositionY < 0) {
translateY = alignTranslateY + minPosition;
}
else {
translateY = alignTranslateY;
}
}
else if (inputPositionY || buttonPositionY) {
if (inputPositionY < 0 ||
buttonPositionY < 0) {
translateY -= Math.min(inputPositionY, buttonPositionY);
}
else {
translateY =
alignTranslateY - groupHeight + minPosition;
}
}
}
rangeSelector.group.translate(options.x, options.y + Math.floor(translateY));
// translate HTML inputs
if (inputEnabled !== false) {
rangeSelector.minInput.style.marginTop =
rangeSelector.group.translateY + 'px';
rangeSelector.maxInput.style.marginTop =
rangeSelector.group.translateY + 'px';
}
rangeSelector.rendered = true;
},
/**
* Extracts height of range selector
*
* @private
* @function Highcharts.RangeSelector#getHeight
* @return {number}
* Returns rangeSelector height
*/
getHeight: function () {
var rangeSelector = this, options = rangeSelector.options, rangeSelectorGroup = rangeSelector.group, inputPosition = options.inputPosition, buttonPosition = options.buttonPosition, yPosition = options.y, buttonPositionY = buttonPosition.y, inputPositionY = inputPosition.y, rangeSelectorHeight = 0, minPosition;
if (options.height) {
return options.height;
}
rangeSelectorHeight = rangeSelectorGroup ?
// 13px to keep back compatibility
(rangeSelectorGroup.getBBox(true).height) + 13 +
yPosition :
0;
minPosition = Math.min(inputPositionY, buttonPositionY);
if ((inputPositionY < 0 && buttonPositionY < 0) ||
(inputPositionY > 0 && buttonPositionY > 0)) {
rangeSelectorHeight += Math.abs(minPosition);
}
return rangeSelectorHeight;
},
/**
* Detect collision with title or subtitle
*
* @private
* @function Highcharts.RangeSelector#titleCollision
*
* @param {Highcharts.Chart} chart
*
* @return {boolean}
* Returns collision status
*/
titleCollision: function (chart) {
return !(chart.options.title.text ||
chart.options.subtitle.text);
},
/**
* Update the range selector with new options
*
* @private
* @function Highcharts.RangeSelector#update
* @param {Highcharts.RangeSelectorOptions} options
* @return {void}
*/
update: function (options) {
var chart = this.chart;
merge(true, chart.options.rangeSelector, options);
this.destroy();
this.init(chart);
chart.rangeSelector.render();
},
/**
* Destroys allocated elements.
*
* @private
* @function Highcharts.RangeSelector#destroy
*/
destroy: function () {
var rSelector = this, minInput = rSelector.minInput, maxInput = rSelector.maxInput;
rSelector.unMouseDown();
rSelector.unResize();
// Destroy elements in collections
destroyObjectProperties(rSelector.buttons);
// Clear input element events
if (minInput) {
minInput.onfocus = minInput.onblur = minInput.onchange = null;
}
if (maxInput) {
maxInput.onfocus = maxInput.onblur = maxInput.onchange = null;
}
// Destroy HTML and SVG elements
objectEach(rSelector, function (val, key) {
if (val && key !== 'chart') {
if (val.destroy) {
// SVGElement
val.destroy();
}
else if (val.nodeType) {
// HTML element
discardElement(this[key]);
}
}
if (val !== RangeSelector.prototype[key]) {
rSelector[key] = null;
}
}, this);
}
};
/**
* Get the axis min value based on the range option and the current max. For
* stock charts this is extended via the {@link RangeSelector} so that if the
* selected range is a multiple of months or years, it is compensated for
* various month lengths.
*
* @private
* @function Highcharts.Axis#minFromRange
* @return {number|undefined}
* The new minimum value.
*/
Axis.prototype.minFromRange = function () {
var rangeOptions = this.range, type = rangeOptions.type, min, max = this.max, dataMin, range, time = this.chart.time,
// Get the true range from a start date
getTrueRange = function (base, count) {
var timeName = type === 'year' ? 'FullYear' : 'Month';
var date = new time.Date(base);
var basePeriod = time.get(timeName, date);
time.set(timeName, date, basePeriod + count);
if (basePeriod === time.get(timeName, date)) {
time.set('Date', date, 0); // #6537
}
return date.getTime() - base;
};
if (isNumber(rangeOptions)) {
min = max - rangeOptions;
range = rangeOptions;
}
else {
min = max + getTrueRange(max, -rangeOptions.count);
// Let the fixedRange reflect initial settings (#5930)
if (this.chart) {
this.chart.fixedRange = max - min;
}
}
dataMin = pick(this.dataMin, Number.MIN_VALUE);
if (!isNumber(min)) {
min = dataMin;
}
if (min <= dataMin) {
min = dataMin;
if (typeof range === 'undefined') { // #4501
range = getTrueRange(min, rangeOptions.count);
}
this.newMax = Math.min(min + range, this.dataMax);
}
if (!isNumber(max)) {
min = void 0;
}
return min;
};
if (!H.RangeSelector) {
// Initialize rangeselector for stock charts
addEvent(Chart, 'afterGetContainer', function () {
if (this.options.rangeSelector.enabled) {
this.rangeSelector = new RangeSelector(this);
}
});
addEvent(Chart, 'beforeRender', function () {
var chart = this, axes = chart.axes, rangeSelector = chart.rangeSelector, verticalAlign;
if (rangeSelector) {
if (isNumber(rangeSelector.deferredYTDClick)) {
rangeSelector.clickButton(rangeSelector.deferredYTDClick);
delete rangeSelector.deferredYTDClick;
}
axes.forEach(function (axis) {
axis.updateNames();
axis.setScale();
});
chart.getAxisMargins();
rangeSelector.render();
verticalAlign = rangeSelector.options.verticalAlign;
if (!rangeSelector.options.floating) {
if (verticalAlign === 'bottom') {
this.extraBottomMargin = true;
}
else if (verticalAlign !== 'middle') {
this.extraTopMargin = true;
}
}
}
});
addEvent(Chart, 'update', function (e) {
var chart = this, options = e.options, optionsRangeSelector = options.rangeSelector, rangeSelector = chart.rangeSelector, verticalAlign, extraBottomMarginWas = this.extraBottomMargin, extraTopMarginWas = this.extraTopMargin;
if (optionsRangeSelector &&
optionsRangeSelector.enabled &&
!defined(rangeSelector)) {
this.options.rangeSelector.enabled = true;
this.rangeSelector = new RangeSelector(this);
}
this.extraBottomMargin = false;
this.extraTopMargin = false;
if (rangeSelector) {
rangeSelector.render();
verticalAlign = (optionsRangeSelector &&
optionsRangeSelector.verticalAlign) || (rangeSelector.options && rangeSelector.options.verticalAlign);
if (!rangeSelector.options.floating) {
if (verticalAlign === 'bottom') {
this.extraBottomMargin = true;
}
else if (verticalAlign !== 'middle') {
this.extraTopMargin = true;
}
}
if (this.extraBottomMargin !== extraBottomMarginWas ||
this.extraTopMargin !== extraTopMarginWas) {
this.isDirtyBox = true;
}
}
});
addEvent(Chart, 'render', function () {
var chart = this, rangeSelector = chart.rangeSelector, verticalAlign;
if (rangeSelector && !rangeSelector.options.floating) {
rangeSelector.render();
verticalAlign = rangeSelector.options.verticalAlign;
if (verticalAlign === 'bottom') {
this.extraBottomMargin = true;
}
else if (verticalAlign !== 'middle') {
this.extraTopMargin = true;
}
}
});
addEvent(Chart, 'getMargins', function () {
var rangeSelector = this.rangeSelector, rangeSelectorHeight;
if (rangeSelector) {
rangeSelectorHeight = rangeSelector.getHeight();
if (this.extraTopMargin) {
this.plotTop += rangeSelectorHeight;
}
if (this.extraBottomMargin) {
this.marginBottom += rangeSelectorHeight;
}
}
});
Chart.prototype.callbacks.push(function (chart) {
var extremes, rangeSelector = chart.rangeSelector, unbindRender, unbindSetExtremes;
/**
* @private
*/
function renderRangeSelector() {
extremes = chart.xAxis[0].getExtremes();
if (isNumber(extremes.min)) {
rangeSelector.render(extremes.min, extremes.max);
}
}
if (rangeSelector) {
// redraw the scroller on setExtremes
unbindSetExtremes = addEvent(chart.xAxis[0], 'afterSetExtremes', function (e) {
rangeSelector.render(e.min, e.max);
});
// redraw the scroller chart resize
unbindRender = addEvent(chart, 'redraw', renderRangeSelector);
// do it now
renderRangeSelector();
}
// Remove resize/afterSetExtremes at chart destroy
addEvent(chart, 'destroy', function destroyEvents() {
if (rangeSelector) {
unbindRender();
unbindSetExtremes();
}
});
});
H.RangeSelector = RangeSelector;
}
| generalludd/expenses | js/highcharts/es-modules/parts/RangeSelector.js | JavaScript | mit | 61,256 |
'use strict';
var cfenv = require('cfenv'),
appEnv = cfenv.getAppEnv(),
cfMongoUrl = appEnv.getService('mean-mongo') ?
appEnv.getService('mean-mongo').credentials.uri : undefined;
var getCred = function (serviceName, credProp) {
return appEnv.getService(serviceName) ?
appEnv.getService(serviceName).credentials[credProp] : undefined;
};
module.exports = {
port: appEnv.port,
db: {
uri: cfMongoUrl,
options: {
user: '',
pass: ''
}
},
log: {
// Can specify one of 'combined', 'common', 'dev', 'short', 'tiny'
format: 'combined',
// Stream defaults to process.stdout
// By default we want logs to go to process.out so the Cloud Foundry Loggregator will collect them
options: {}
},
facebook: {
clientID: getCred('mean-facebook', 'id') || 'APP_ID',
clientSecret: getCred('mean-facebook', 'secret') || 'APP_SECRET',
callbackURL: '/api/auth/facebook/callback'
},
twitter: {
clientID: getCred('mean-twitter', 'key') || 'CONSUMER_KEY',
clientSecret: getCred('mean-twitter', 'secret') || 'CONSUMER_SECRET',
callbackURL: '/api/auth/twitter/callback'
},
google: {
clientID: getCred('mean-google', 'id') || 'APP_ID',
clientSecret: getCred('mean-google', 'secret') || 'APP_SECRET',
callbackURL: '/api/auth/google/callback'
},
linkedin: {
clientID: getCred('mean-linkedin', 'id') || 'APP_ID',
clientSecret: getCred('mean-linkedin', 'secret') || 'APP_SECRET',
callbackURL: '/api/auth/linkedin/callback'
},
github: {
clientID: getCred('mean-github', 'id') || 'APP_ID',
clientSecret: getCred('mean-github', 'secret') || 'APP_SECRET',
callbackURL: '/api/auth/github/callback'
},
paypal: {
clientID: getCred('mean-paypal', 'id') || 'CLIENT_ID',
clientSecret: getCred('mean-paypal', 'secret') || 'CLIENT_SECRET',
callbackURL: '/api/auth/paypal/callback',
sandbox: false
},
mailer: {
from: getCred('mean-mail', 'from') || 'MAILER_FROM',
options: {
service: getCred('mean-mail', 'service') || 'MAILER_SERVICE_PROVIDER',
auth: {
user: getCred('mean-mail', 'username') || 'MAILER_EMAIL_ID',
pass: getCred('mean-mail', 'password') || 'MAILER_PASSWORD'
}
}
},
seedDB: {
seed: process.env.MONGO_SEED === 'true' ? true : false,
options: {
logResults: process.env.MONGO_SEED_LOG_RESULTS === 'false' ? false : true,
seedUser: {
username: process.env.MONGO_SEED_USER_USERNAME || 'user',
provider: 'local',
email: process.env.MONGO_SEED_USER_EMAIL || 'user@localhost.com',
firstName: 'User',
lastName: 'Local',
displayName: 'User Local',
roles: ['user']
},
seedAdmin: {
username: process.env.MONGO_SEED_ADMIN_USERNAME || 'admin',
provider: 'local',
email: process.env.MONGO_SEED_ADMIN_EMAIL || 'admin@localhost.com',
firstName: 'Admin',
lastName: 'Local',
displayName: 'Admin Local',
roles: ['user', 'admin']
}
}
}
};
| NicolasKovalsky/mean | config/env/cloud-foundry.js | JavaScript | mit | 3,063 |
/*
Highcharts JS v7.1.0 (2019-04-01)
Force directed graph module
(c) 2010-2019 Torstein Honsi
License: www.highcharts.com/license
*/
(function(h){"object"===typeof module&&module.exports?(h["default"]=h,module.exports=h):"function"===typeof define&&define.amd?define("highcharts/modules/networkgraph",["highcharts"],function(m){h(m);h.Highcharts=m;return h}):h("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(h){function m(f,c,d,b){f.hasOwnProperty(c)||(f[c]=b.apply(null,d))}h=h?h._modules:{};m(h,"mixins/nodes.js",[h["parts/Globals.js"]],function(f){var c=f.pick,d=f.defined,b=f.Point;f.NodesMixin={createNode:function(b){function a(a,
e){return f.find(a,function(a){return a.id===e})}var e=a(this.nodes,b),g=this.pointClass,d;e||(d=this.options.nodes&&a(this.options.nodes,b),e=(new g).init(this,f.extend({className:"highcharts-node",isNode:!0,id:b,y:1},d)),e.linksTo=[],e.linksFrom=[],e.formatPrefix="node",e.name=e.name||e.options.id,e.mass=c(e.options.mass,e.options.marker&&e.options.marker.radius,this.options.marker&&this.options.marker.radius,4),e.getSum=function(){var a=0,b=0;e.linksTo.forEach(function(e){a+=e.weight});e.linksFrom.forEach(function(a){b+=
a.weight});return Math.max(a,b)},e.offset=function(a,b){for(var g=0,c=0;c<e[b].length;c++){if(e[b][c]===a)return g;g+=e[b][c].weight}},e.hasShape=function(){var a=0;e.linksTo.forEach(function(e){e.outgoing&&a++});return!e.linksTo.length||a!==e.linksTo.length},this.nodes.push(e));return e},generatePoints:function(){var b={},a=this.chart;f.Series.prototype.generatePoints.call(this);this.nodes||(this.nodes=[]);this.colorCounter=0;this.nodes.forEach(function(a){a.linksFrom.length=0;a.linksTo.length=0;
a.level=void 0});this.points.forEach(function(e){d(e.from)&&(b[e.from]||(b[e.from]=this.createNode(e.from)),b[e.from].linksFrom.push(e),e.fromNode=b[e.from],a.styledMode?e.colorIndex=c(e.options.colorIndex,b[e.from].colorIndex):e.color=e.options.color||b[e.from].color);d(e.to)&&(b[e.to]||(b[e.to]=this.createNode(e.to)),b[e.to].linksTo.push(e),e.toNode=b[e.to]);e.name=e.name||e.id},this);this.nodeLookup=b},setData:function(){this.nodes&&(this.nodes.forEach(function(b){b.destroy()}),this.nodes.length=
0);f.Series.prototype.setData.apply(this,arguments)},destroy:function(){this.data=[].concat(this.points||[],this.nodes);return f.Series.prototype.destroy.apply(this,arguments)},setNodeState:function(){var c=arguments;(this.isNode?this.linksTo.concat(this.linksFrom):[this.fromNode,this.toNode]).forEach(function(a){b.prototype.setState.apply(a,c);a.isNode||(a.fromNode.graphic&&b.prototype.setState.apply(a.fromNode,c),a.toNode.graphic&&b.prototype.setState.apply(a.toNode,c))});b.prototype.setState.apply(this,
c)}}});m(h,"modules/networkgraph/integrations.js",[h["parts/Globals.js"]],function(f){f.networkgraphIntegrations={verlet:{attractiveForceFunction:function(c,d){return(d-c)/c},repulsiveForceFunction:function(c,d){return(d-c)/c*(d>c?1:0)},barycenter:function(){var c=this.options.gravitationalConstant,d=this.barycenter.xFactor,b=this.barycenter.yFactor,d=(d-(this.box.left+this.box.width)/2)*c,b=(b-(this.box.top+this.box.height)/2)*c;this.nodes.forEach(function(c){c.fixedPosition||(c.plotX-=d/c.mass/
c.degree,c.plotY-=b/c.mass/c.degree)})},repulsive:function(c,d,b){d=d*this.diffTemperature/c.mass/c.degree;c.fixedPosition||(c.plotX+=b.x*d,c.plotY+=b.y*d)},attractive:function(c,d,b){var g=c.getMass(),a=-b.x*d*this.diffTemperature;d=-b.y*d*this.diffTemperature;c.fromNode.fixedPosition||(c.fromNode.plotX-=a*g.fromNode/c.fromNode.degree,c.fromNode.plotY-=d*g.fromNode/c.fromNode.degree);c.toNode.fixedPosition||(c.toNode.plotX+=a*g.toNode/c.toNode.degree,c.toNode.plotY+=d*g.toNode/c.toNode.degree)},
integrate:function(c,d){var b=-c.options.friction,g=c.options.maxSpeed,a=(d.plotX+d.dispX-d.prevX)*b,b=(d.plotY+d.dispY-d.prevY)*b,e=Math.abs,p=e(a)/(a||1),e=e(b)/(b||1),a=p*Math.min(g,Math.abs(a)),b=e*Math.min(g,Math.abs(b));d.prevX=d.plotX+d.dispX;d.prevY=d.plotY+d.dispY;d.plotX+=a;d.plotY+=b;d.temperature=c.vectorLength({x:a,y:b})},getK:function(c){return Math.pow(c.box.width*c.box.height/c.nodes.length,.5)}},euler:{attractiveForceFunction:function(c,d){return c*c/d},repulsiveForceFunction:function(c,
d){return d*d/c},barycenter:function(){var c=this.options.gravitationalConstant,d=this.barycenter.xFactor,b=this.barycenter.yFactor;this.nodes.forEach(function(g){if(!g.fixedPosition){var a=g.getDegree(),a=a*(1+a/2);g.dispX+=(d-g.plotX)*c*a/g.degree;g.dispY+=(b-g.plotY)*c*a/g.degree}})},repulsive:function(c,d,b,g){c.dispX+=b.x/g*d/c.degree;c.dispY+=b.y/g*d/c.degree},attractive:function(c,d,b,g){var a=c.getMass(),e=b.x/g*d;d*=b.y/g;c.fromNode.fixedPosition||(c.fromNode.dispX-=e*a.fromNode/c.fromNode.degree,
c.fromNode.dispY-=d*a.fromNode/c.fromNode.degree);c.toNode.fixedPosition||(c.toNode.dispX+=e*a.toNode/c.toNode.degree,c.toNode.dispY+=d*a.toNode/c.toNode.degree)},integrate:function(c,d){var b;d.dispX+=d.dispX*c.options.friction;d.dispY+=d.dispY*c.options.friction;b=d.temperature=c.vectorLength({x:d.dispX,y:d.dispY});0!==b&&(d.plotX+=d.dispX/b*Math.min(Math.abs(d.dispX),c.temperature),d.plotY+=d.dispY/b*Math.min(Math.abs(d.dispY),c.temperature))},getK:function(c){return Math.pow(c.box.width*c.box.height/
c.nodes.length,.3)}}}});m(h,"modules/networkgraph/QuadTree.js",[h["parts/Globals.js"]],function(f){var c=f.QuadTreeNode=function(b){this.box=b;this.boxSize=Math.min(b.width,b.height);this.nodes=[];this.body=this.isInternal=!1;this.isEmpty=!0};f.extend(c.prototype,{insert:function(b,c){this.isInternal?this.nodes[this.getBoxPosition(b)].insert(b,c-1):(this.isEmpty=!1,this.body?c?(this.isInternal=!0,this.divideBox(),!0!==this.body&&(this.nodes[this.getBoxPosition(this.body)].insert(this.body,c-1),this.body=
!0),this.nodes[this.getBoxPosition(b)].insert(b,c-1)):this.nodes.push(b):(this.isInternal=!1,this.body=b))},updateMassAndCenter:function(){var b=0,c=0,a=0;this.isInternal?(this.nodes.forEach(function(e){e.isEmpty||(b+=e.mass,c+=e.plotX*e.mass,a+=e.plotY*e.mass)}),c/=b,a/=b):this.body&&(b=this.body.mass,c=this.body.plotX,a=this.body.plotY);this.mass=b;this.plotX=c;this.plotY=a},divideBox:function(){var b=this.box.width/2,d=this.box.height/2;this.nodes[0]=new c({left:this.box.left,top:this.box.top,
width:b,height:d});this.nodes[1]=new c({left:this.box.left+b,top:this.box.top,width:b,height:d});this.nodes[2]=new c({left:this.box.left+b,top:this.box.top+d,width:b,height:d});this.nodes[3]=new c({left:this.box.left,top:this.box.top+d,width:b,height:d})},getBoxPosition:function(b){var c=b.plotY<this.box.top+this.box.height/2;return b.plotX<this.box.left+this.box.width/2?c?0:3:c?1:2}});var d=f.QuadTree=function(b,d,a,e){this.box={left:b,top:d,width:a,height:e};this.maxDepth=25;this.root=new c(this.box,
"0");this.root.isInternal=!0;this.root.isRoot=!0;this.root.divideBox()};f.extend(d.prototype,{insertNodes:function(b){b.forEach(function(b){this.root.insert(b,this.maxDepth)},this)},visitNodeRecursive:function(b,c,a,e,d){var l;b||(b=this.root);b===this.root&&c&&(l=c(b));!1!==l&&(b.nodes.forEach(function(b){if(b.isInternal){c&&(l=c(b));if(!1===l)return;this.visitNodeRecursive(b,c,a,e,d)}else b.body&&c&&c(b.body);a&&a(b)},this),b===this.root&&a&&a(b))},calculateMassAndCenter:function(){this.visitNodeRecursive(null,
null,function(b){b.updateMassAndCenter()})},render:function(b,c){this.visitNodeRecursive(this.root,null,null,b,c)},clear:function(b){this.render(b,!0)},renderBox:function(b,c,a){b.graphic||a?a&&(b.graphic&&(b.graphic=b.graphic.destroy()),b.graphic2&&(b.graphic2=b.graphic2.destroy()),b.label&&(b.label=b.label.destroy())):(b.graphic=c.renderer.rect(b.box.left+c.plotLeft,b.box.top+c.plotTop,b.box.width,b.box.height).attr({stroke:"rgba(100, 100, 100, 0.5)","stroke-width":2}).add(),isNaN(b.plotX)||(b.graphic2=
c.renderer.circle(b.plotX,b.plotY,b.mass/10).attr({fill:"red",translateY:c.plotTop,translateX:c.plotLeft}).add()))}})});m(h,"modules/networkgraph/layouts.js",[h["parts/Globals.js"]],function(f){var c=f.pick,d=f.defined,b=f.addEvent,g=f.Chart;f.layouts={"reingold-fruchterman":function(){}};f.extend(f.layouts["reingold-fruchterman"].prototype,{init:function(a){this.options=a;this.nodes=[];this.links=[];this.series=[];this.box={x:0,y:0,width:0,height:0};this.setInitialRendering(!0);this.integration=
f.networkgraphIntegrations[a.integration];this.attractiveForce=c(a.attractiveForce,this.integration.attractiveForceFunction);this.repulsiveForce=c(a.repulsiveForce,this.integration.repulsiveForceFunction);this.approximation=a.approximation},start:function(){var a=this.series,b=this.options;this.currentStep=0;this.forces=a[0]&&a[0].forces||[];this.initialRendering&&(this.initPositions(),a.forEach(function(a){a.render()}));this.setK();this.resetSimulation(b);b.enableSimulation&&this.step()},step:function(){var a=
this,b=this.series,c=this.options;a.currentStep++;"barnes-hut"===a.approximation&&(a.createQuadTree(),a.quadTree.calculateMassAndCenter());a.forces.forEach(function(b){a[b+"Forces"](a.temperature)});a.applyLimits(a.temperature);a.temperature=a.coolDown(a.startTemperature,a.diffTemperature,a.currentStep);a.prevSystemTemperature=a.systemTemperature;a.systemTemperature=a.getSystemTemperature();c.enableSimulation&&(b.forEach(function(a){a.chart&&a.render()}),a.maxIterations--&&isFinite(a.temperature)&&
!a.isStable()?(a.simulation&&f.win.cancelAnimationFrame(a.simulation),a.simulation=f.win.requestAnimationFrame(function(){a.step()})):a.simulation=!1)},stop:function(){this.simulation&&f.win.cancelAnimationFrame(this.simulation)},setArea:function(a,b,c,d){this.box={left:a,top:b,width:c,height:d}},setK:function(){this.k=this.options.linkLength||this.integration.getK(this)},addNodes:function(a){a.forEach(function(a){-1===this.nodes.indexOf(a)&&this.nodes.push(a)},this)},removeNode:function(a){a=this.nodes.indexOf(a);
-1!==a&&this.nodes.splice(a,1)},removeLink:function(a){a=this.links.indexOf(a);-1!==a&&this.links.splice(a,1)},addLinks:function(a){a.forEach(function(a){-1===this.links.indexOf(a)&&this.links.push(a)},this)},addSeries:function(a){-1===this.series.indexOf(a)&&this.series.push(a)},clear:function(){this.nodes.length=0;this.links.length=0;this.series.length=0;this.resetSimulation()},resetSimulation:function(){this.forcedStop=!1;this.systemTemperature=0;this.setMaxIterations();this.setTemperature();this.setDiffTemperature()},
setMaxIterations:function(a){this.maxIterations=c(a,this.options.maxIterations)},setTemperature:function(){this.temperature=this.startTemperature=Math.sqrt(this.nodes.length)},setDiffTemperature:function(){this.diffTemperature=this.startTemperature/(this.options.maxIterations+1)},setInitialRendering:function(a){this.initialRendering=a},createQuadTree:function(){this.quadTree=new f.QuadTree(this.box.left,this.box.top,this.box.width,this.box.height);this.quadTree.insertNodes(this.nodes)},initPositions:function(){var a=
this.options.initialPositions;f.isFunction(a)?(a.call(this),this.nodes.forEach(function(a){d(a.prevX)||(a.prevX=a.plotX);d(a.prevY)||(a.prevY=a.plotY);a.dispX=0;a.dispY=0})):"circle"===a?this.setCircularPositions():this.setRandomPositions()},setCircularPositions:function(){function a(b){b.linksFrom.forEach(function(b){f[b.toNode.id]||(f[b.toNode.id]=!0,k.push(b.toNode),a(b.toNode))})}var b=this.box,d=this.nodes,l=2*Math.PI/(d.length+1),n=d.filter(function(a){return 0===a.linksTo.length}),k=[],f={},
g=this.options.initialPositionRadius;n.forEach(function(b){k.push(b);a(b)});k.length?d.forEach(function(a){-1===k.indexOf(a)&&k.push(a)}):k=d;k.forEach(function(a,e){a.plotX=a.prevX=c(a.plotX,b.width/2+g*Math.cos(e*l));a.plotY=a.prevY=c(a.plotY,b.height/2+g*Math.sin(e*l));a.dispX=0;a.dispY=0})},setRandomPositions:function(){function a(a){a=a*a/Math.PI;return a-=Math.floor(a)}var b=this.box,d=this.nodes,l=d.length+1;d.forEach(function(e,d){e.plotX=e.prevX=c(e.plotX,b.width*a(d));e.plotY=e.prevY=c(e.plotY,
b.height*a(l+d));e.dispX=0;e.dispY=0})},force:function(a){this.integration[a].apply(this,Array.prototype.slice.call(arguments,1))},barycenterForces:function(){this.getBarycenter();this.force("barycenter")},getBarycenter:function(){var a=0,b=0,c=0;this.nodes.forEach(function(e){b+=e.plotX*e.mass;c+=e.plotY*e.mass;a+=e.mass});return this.barycenter={x:b,y:c,xFactor:b/a,yFactor:c/a}},barnesHutApproximation:function(a,b){var c=this.getDistXY(a,b),e=this.vectorLength(c),d,k;a!==b&&0!==e&&(b.isInternal?
b.boxSize/e<this.options.theta&&0!==e?(k=this.repulsiveForce(e,this.k),this.force("repulsive",a,k*b.mass,c,e),d=!1):d=!0:(k=this.repulsiveForce(e,this.k),this.force("repulsive",a,k*b.mass,c,e)));return d},repulsiveForces:function(){var a=this;"barnes-hut"===a.approximation?a.nodes.forEach(function(b){a.quadTree.visitNodeRecursive(null,function(c){return a.barnesHutApproximation(b,c)})}):a.nodes.forEach(function(b){a.nodes.forEach(function(c){var e,d,k;b===c||b.fixedPosition||(k=a.getDistXY(b,c),d=
a.vectorLength(k),e=a.repulsiveForce(d,a.k),a.force("repulsive",b,e*c.mass,k,d))})})},attractiveForces:function(){var a=this,b,c,d;a.links.forEach(function(e){e.fromNode&&e.toNode&&(b=a.getDistXY(e.fromNode,e.toNode),c=a.vectorLength(b),0!==c&&(d=a.attractiveForce(c,a.k),a.force("attractive",e,d,b,c)))})},applyLimits:function(){var a=this;a.nodes.forEach(function(b){b.fixedPosition||(a.integration.integrate(a,b),a.applyLimitBox(b,a.box),b.dispX=0,b.dispY=0)})},applyLimitBox:function(a,b){var c=a.marker&&
a.marker.radius||0;a.plotX=Math.max(Math.min(a.plotX,b.width-c),b.left+c);a.plotY=Math.max(Math.min(a.plotY,b.height-c),b.top+c)},coolDown:function(a,b,c){return a-b*c},isStable:function(){return.00001>Math.abs(this.systemTemperature-this.prevSystemTemperature)||0>=this.temperature},getSystemTemperature:function(){return this.nodes.reduce(function(a,b){return a+b.temperature},0)},vectorLength:function(a){return Math.sqrt(a.x*a.x+a.y*a.y)},getDistR:function(a,b){a=this.getDistXY(a,b);return this.vectorLength(a)},
getDistXY:function(a,b){var c=a.plotX-b.plotX;a=a.plotY-b.plotY;return{x:c,y:a,absX:Math.abs(c),absY:Math.abs(a)}}});b(g,"predraw",function(){this.graphLayoutsLookup&&this.graphLayoutsLookup.forEach(function(a){a.stop()})});b(g,"render",function(){function a(a){a.maxIterations--&&isFinite(a.temperature)&&!a.isStable()&&!a.options.enableSimulation&&(a.beforeStep&&a.beforeStep(),a.step(),b=!1,c=!0)}var b,c=!1;if(this.graphLayoutsLookup){f.setAnimation(!1,this);for(this.graphLayoutsLookup.forEach(function(a){a.start()});!b;)b=
!0,this.graphLayoutsLookup.forEach(a);c&&this.series.forEach(function(a){a&&a.layout&&a.render()})}})});m(h,"modules/networkgraph/draggable-nodes.js",[h["parts/Globals.js"]],function(f){var c=f.Chart,d=f.addEvent;f.dragNodesMixin={onMouseDown:function(b,c){c=this.chart.pointer.normalize(c);b.fixedPosition={chartX:c.chartX,chartY:c.chartY,plotX:b.plotX,plotY:b.plotY};b.inDragMode=!0},onMouseMove:function(b,c){if(b.fixedPosition&&b.inDragMode){var a=this.chart,d=a.pointer.normalize(c);c=b.fixedPosition.chartX-
d.chartX;d=b.fixedPosition.chartY-d.chartY;if(5<Math.abs(c)||5<Math.abs(d))c=b.fixedPosition.plotX-c,d=b.fixedPosition.plotY-d,a.isInsidePlot(c,d)&&(b.plotX=c,b.plotY=d,this.redrawHalo(b),this.layout.simulation?this.layout.resetSimulation():(this.layout.setInitialRendering(!1),this.layout.enableSimulation?this.layout.start():this.layout.setMaxIterations(1),this.chart.redraw(),this.layout.setInitialRendering(!0)))}},onMouseUp:function(b){b.fixedPosition&&(this.layout.enableSimulation?this.layout.start():
this.chart.redraw(),b.inDragMode=!1,this.options.fixedDraggable||delete b.fixedPosition)},redrawHalo:function(b){b&&this.halo&&this.halo.attr({d:b.haloPath(this.options.states.hover.halo.size)})}};d(c,"load",function(){var b=this,c,a,e;b.container&&(c=d(b.container,"mousedown",function(c){var f=b.hoverPoint;f&&f.series&&f.series.hasDraggableNodes&&f.series.options.draggable&&(f.series.onMouseDown(f,c),a=d(b.container,"mousemove",function(a){return f&&f.series&&f.series.onMouseMove(f,a)}),e=d(b.container.ownerDocument,
"mouseup",function(b){a();e();return f&&f.series&&f.series.onMouseUp(f,b)}))}));d(b,"destroy",function(){c()})})});m(h,"modules/networkgraph/networkgraph.src.js",[h["parts/Globals.js"]],function(f){var c=f.addEvent,d=f.defined,b=f.seriesType,g=f.seriesTypes,a=f.pick,e=f.Point,h=f.Series,l=f.dragNodesMixin;b("networkgraph","line",{stickyTracking:!1,inactiveOtherPoints:!0,marker:{enabled:!0,states:{inactive:{opacity:.3,animation:{duration:50}}}},states:{inactive:{linkOpacity:.3,animation:{duration:50}}},
dataLabels:{formatter:function(){return this.key},linkFormatter:function(){return this.point.fromNode.name+"\x3cbr\x3e"+this.point.toNode.name},linkTextPath:{enabled:!0},textPath:{enabled:!1}},link:{color:"rgba(100, 100, 100, 0.5)",width:1},draggable:!0,layoutAlgorithm:{initialPositions:"circle",initialPositionRadius:1,enableSimulation:!1,theta:.5,maxSpeed:10,approximation:"none",type:"reingold-fruchterman",integration:"euler",maxIterations:1E3,gravitationalConstant:.0625,friction:-.981},showInLegend:!1},
{forces:["barycenter","repulsive","attractive"],hasDraggableNodes:!0,drawGraph:null,isCartesian:!1,requireSorting:!1,directTouch:!0,noSharedTooltip:!0,trackerGroups:["group","markerGroup","dataLabelsGroup"],drawTracker:f.TrackerMixin.drawTrackerPoint,animate:null,buildKDTree:f.noop,createNode:f.NodesMixin.createNode,setData:f.NodesMixin.setData,destroy:f.NodesMixin.destroy,init:function(){h.prototype.init.apply(this,arguments);c(this,"updatedData",function(){this.layout&&this.layout.stop()});return this},
generatePoints:function(){f.NodesMixin.generatePoints.apply(this,arguments);this.options.nodes&&this.options.nodes.forEach(function(a){this.nodeLookup[a.id]||(this.nodeLookup[a.id]=this.createNode(a.id))},this);this.nodes.forEach(function(a){a.degree=a.getDegree()});this.data.forEach(function(a){a.formatPrefix="link"})},markerAttribs:function(a,b){b=h.prototype.markerAttribs.call(this,a,b);b.x=a.plotX-(b.width/2||0);return b},translate:function(){this.processedXData||this.processData();this.generatePoints();
this.deferLayout();this.nodes.forEach(function(a){a.isInside=!0;a.linksFrom.forEach(function(a){a.shapeType="path";a.y=1})})},deferLayout:function(){var a=this.options.layoutAlgorithm,b=this.chart.graphLayoutsStorage,c=this.chart.graphLayoutsLookup,e=this.chart.options.chart,g;this.visible&&(b||(this.chart.graphLayoutsStorage=b={},this.chart.graphLayoutsLookup=c=[]),g=b[a.type],g||(a.enableSimulation=d(e.forExport)?!e.forExport:a.enableSimulation,b[a.type]=g=new f.layouts[a.type],g.init(a),c.splice(g.index,
0,g)),this.layout=g,g.setArea(0,0,this.chart.plotWidth,this.chart.plotHeight),g.addSeries(this),g.addNodes(this.nodes),g.addLinks(this.points))},render:function(){var a=this.points,b=this.chart.hoverPoint,c=[];this.points=this.nodes;g.line.prototype.render.call(this);this.points=a;a.forEach(function(a){a.fromNode&&a.toNode&&(a.renderLink(),a.redrawLink())});b&&b.series===this&&this.redrawHalo(b);this.chart.hasRendered&&!this.options.dataLabels.allowOverlap&&(this.nodes.concat(this.points).forEach(function(a){a.dataLabel&&
c.push(a.dataLabel)}),this.chart.hideOverlappingLabels(c))},drawDataLabels:function(){var a=this.options.dataLabels.textPath;h.prototype.drawDataLabels.apply(this,arguments);this.points=this.data;this.options.dataLabels.textPath=this.options.dataLabels.linkTextPath;h.prototype.drawDataLabels.apply(this,arguments);this.points=this.nodes;this.options.dataLabels.textPath=a},pointAttribs:function(b,c){var d=c||b.state||"normal";c=h.prototype.pointAttribs.call(this,b,d);d=this.options.states[d];b.isNode||
(c=b.getLinkAttributes(),d&&(c={stroke:d.linkColor||c.stroke,dashstyle:d.linkDashStyle||c.dashstyle,opacity:a(d.linkOpacity,c.opacity),"stroke-width":d.linkColor||c["stroke-width"]}));return c},redrawHalo:l.redrawHalo,onMouseDown:l.onMouseDown,onMouseMove:l.onMouseMove,onMouseUp:l.onMouseUp,setState:function(a,b){b?(this.points=this.nodes.concat(this.data),h.prototype.setState.apply(this,arguments),this.points=this.data):h.prototype.setState.apply(this,arguments);this.layout.simulation||a||this.render()}},
{setState:f.NodesMixin.setNodeState,init:function(){e.prototype.init.apply(this,arguments);this.series.options.draggable&&!this.series.chart.styledMode&&(c(this,"mouseOver",function(){f.css(this.series.chart.container,{cursor:"move"})}),c(this,"mouseOut",function(){f.css(this.series.chart.container,{cursor:"default"})}));return this},getDegree:function(){var a=this.isNode?this.linksFrom.length+this.linksTo.length:0;return 0===a?1:a},getLinkAttributes:function(){var b=this.series.options.link,c=this.options;
return{"stroke-width":a(c.width,b.width),stroke:c.color||b.color,dashstyle:c.dashStyle||b.dashStyle,opacity:a(c.opacity,b.opacity,1)}},renderLink:function(){var a;this.graphic||(this.graphic=this.series.chart.renderer.path(this.getLinkPath()).add(this.series.group),this.series.chart.styledMode||(a=this.series.pointAttribs(this),this.graphic.attr(a),(this.dataLabels||[]).forEach(function(b){b&&b.attr({opacity:a.opacity})})))},redrawLink:function(){var a=this.getLinkPath(),b;this.graphic&&(this.shapeArgs=
{d:a},this.series.chart.styledMode||(b=this.series.pointAttribs(this),this.graphic.attr(b),(this.dataLabels||[]).forEach(function(a){a&&a.attr({opacity:b.opacity})})),this.graphic.animate(this.shapeArgs),this.plotX=(a[1]+a[4])/2,this.plotY=(a[2]+a[5])/2)},getMass:function(){var a=this.fromNode.mass,b=this.toNode.mass,c=a+b;return{fromNode:1-a/c,toNode:1-b/c}},getLinkPath:function(){var a=this.fromNode,b=this.toNode;a.plotX>b.plotX&&(a=this.toNode,b=this.fromNode);return["M",a.plotX,a.plotY,"L",b.plotX,
b.plotY]},isValid:function(){return!this.isNode||d(this.id)},destroy:function(){this.isNode?(this.linksFrom.forEach(function(a){a.destroyElements()}),this.series.layout.removeNode(this)):this.series.layout.removeLink(this);return e.prototype.destroy.apply(this,arguments)}})});m(h,"masters/modules/networkgraph.src.js",[],function(){})});
//# sourceMappingURL=networkgraph.js.map | extend1994/cdnjs | ajax/libs/highcharts/7.1.0/modules/networkgraph.js | JavaScript | mit | 22,028 |
/* jshint globalstrict: true */
'use strict';
function setupModuleLoader(window) {
var ensure = function(obj, name, factory) {
return obj[name] || (obj[name] = factory());
};
var angular = ensure(window, 'angular', Object);
var createModule = function(name, requires, modules, configFn) {
if (name === 'hasOwnProperty') {
throw 'hasOwnProperty is not a valid module name';
}
var invokeQueue = [];
var configBlocks = [];
var invokeLater = function(service, method, arrayMethod, queue) {
return function() {
queue = queue || invokeQueue;
queue[arrayMethod || 'push']([service, method, arguments]);
return moduleInstance;
};
};
var moduleInstance = {
name: name,
requires: requires,
constant: invokeLater('$provide', 'constant', 'unshift'),
provider: invokeLater('$provide', 'provider'),
factory: invokeLater('$provide', 'factory'),
value: invokeLater('$provide', 'value'),
service: invokeLater('$provide', 'service'),
decorator: invokeLater('$provide', 'decorator'),
filter: invokeLater('$filterProvider', 'register'),
directive: invokeLater('$compileProvider', 'directive'),
controller: invokeLater('$controllerProvider', 'register'),
config: invokeLater('$injector', 'invoke', 'push', configBlocks),
run: function(fn) {
moduleInstance._runBlocks.push(fn);
return moduleInstance;
},
_invokeQueue: invokeQueue,
_configBlocks: configBlocks,
_runBlocks: []
};
if (configFn) {
moduleInstance.config(configFn);
}
modules[name] = moduleInstance;
return moduleInstance;
};
var getModule = function(name, modules) {
if (modules.hasOwnProperty(name)) {
return modules[name];
} else {
throw 'Module '+name+' is not available!';
}
};
ensure(angular, 'module', function() {
var modules = {};
return function(name, requires, configFn) {
if (requires) {
return createModule(name, requires, modules, configFn);
} else {
return getModule(name, modules);
}
};
});
}
| resalisbury/build-your-own-angularjs | src/loader.js | JavaScript | mit | 2,172 |
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('mobx'), require('react-dom')) :
typeof define === 'function' && define.amd ? define(['exports', 'react', 'mobx', 'react-dom'], factory) :
(factory((global.mobxReact = {}),global.React,global.mobx,global.ReactDOM));
}(this, (function (exports,React,mobx,reactDom) { 'use strict';
var React__default = 'default' in React ? React['default'] : React;
function _typeof(obj) {
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function (obj) {
return typeof obj;
};
} else {
_typeof = function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a 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);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _objectSpread(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === 'function') {
ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
}));
}
ownKeys.forEach(function (key) {
_defineProperty(target, key, source[key]);
});
}
return target;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (typeof call === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
// These functions can be stubbed out in specific environments
function unwrapExports (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x.default : x;
}
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var reactIs_production_min = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports,"__esModule",{value:!0});
var b="function"===typeof Symbol&&Symbol.for,c=b?Symbol.for("react.element"):60103,d=b?Symbol.for("react.portal"):60106,e=b?Symbol.for("react.fragment"):60107,f=b?Symbol.for("react.strict_mode"):60108,g=b?Symbol.for("react.profiler"):60114,h=b?Symbol.for("react.provider"):60109,k=b?Symbol.for("react.context"):60110,l=b?Symbol.for("react.async_mode"):60111,m=b?Symbol.for("react.forward_ref"):60112,n=b?Symbol.for("react.placeholder"):60113;
function q(a){if("object"===typeof a&&null!==a){var p=a.$$typeof;switch(p){case c:switch(a=a.type,a){case l:case e:case g:case f:return a;default:switch(a=a&&a.$$typeof,a){case k:case m:case h:return a;default:return p}}case d:return p}}}exports.typeOf=q;exports.AsyncMode=l;exports.ContextConsumer=k;exports.ContextProvider=h;exports.Element=c;exports.ForwardRef=m;exports.Fragment=e;exports.Profiler=g;exports.Portal=d;exports.StrictMode=f;
exports.isValidElementType=function(a){return "string"===typeof a||"function"===typeof a||a===e||a===l||a===g||a===f||a===n||"object"===typeof a&&null!==a&&("function"===typeof a.then||a.$$typeof===h||a.$$typeof===k||a.$$typeof===m)};exports.isAsyncMode=function(a){return q(a)===l};exports.isContextConsumer=function(a){return q(a)===k};exports.isContextProvider=function(a){return q(a)===h};exports.isElement=function(a){return "object"===typeof a&&null!==a&&a.$$typeof===c};
exports.isForwardRef=function(a){return q(a)===m};exports.isFragment=function(a){return q(a)===e};exports.isProfiler=function(a){return q(a)===g};exports.isPortal=function(a){return q(a)===d};exports.isStrictMode=function(a){return q(a)===f};
});
unwrapExports(reactIs_production_min);
var reactIs_production_min_1 = reactIs_production_min.typeOf;
var reactIs_production_min_2 = reactIs_production_min.AsyncMode;
var reactIs_production_min_3 = reactIs_production_min.ContextConsumer;
var reactIs_production_min_4 = reactIs_production_min.ContextProvider;
var reactIs_production_min_5 = reactIs_production_min.Element;
var reactIs_production_min_6 = reactIs_production_min.ForwardRef;
var reactIs_production_min_7 = reactIs_production_min.Fragment;
var reactIs_production_min_8 = reactIs_production_min.Profiler;
var reactIs_production_min_9 = reactIs_production_min.Portal;
var reactIs_production_min_10 = reactIs_production_min.StrictMode;
var reactIs_production_min_11 = reactIs_production_min.isValidElementType;
var reactIs_production_min_12 = reactIs_production_min.isAsyncMode;
var reactIs_production_min_13 = reactIs_production_min.isContextConsumer;
var reactIs_production_min_14 = reactIs_production_min.isContextProvider;
var reactIs_production_min_15 = reactIs_production_min.isElement;
var reactIs_production_min_16 = reactIs_production_min.isForwardRef;
var reactIs_production_min_17 = reactIs_production_min.isFragment;
var reactIs_production_min_18 = reactIs_production_min.isProfiler;
var reactIs_production_min_19 = reactIs_production_min.isPortal;
var reactIs_production_min_20 = reactIs_production_min.isStrictMode;
var reactIs = createCommonjsModule(function (module) {
{
module.exports = reactIs_production_min;
}
});
var _ReactIs$ForwardRef;
function _defineProperty$1(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
/**
* Copyright 2015, Yahoo! Inc.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var REACT_STATICS = {
childContextTypes: true,
contextTypes: true,
defaultProps: true,
displayName: true,
getDefaultProps: true,
getDerivedStateFromProps: true,
mixins: true,
propTypes: true,
type: true
};
var KNOWN_STATICS = {
name: true,
length: true,
prototype: true,
caller: true,
callee: true,
arguments: true,
arity: true
};
var TYPE_STATICS = _defineProperty$1({}, reactIs.ForwardRef, (_ReactIs$ForwardRef = {}, _defineProperty$1(_ReactIs$ForwardRef, '$$typeof', true), _defineProperty$1(_ReactIs$ForwardRef, 'render', true), _ReactIs$ForwardRef));
var defineProperty = Object.defineProperty;
var getOwnPropertyNames = Object.getOwnPropertyNames;
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
var getPrototypeOf = Object.getPrototypeOf;
var objectPrototype = Object.prototype;
function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) {
if (typeof sourceComponent !== 'string') {
// don't hoist over string (html) components
if (objectPrototype) {
var inheritedComponent = getPrototypeOf(sourceComponent);
if (inheritedComponent && inheritedComponent !== objectPrototype) {
hoistNonReactStatics(targetComponent, inheritedComponent, blacklist);
}
}
var keys = getOwnPropertyNames(sourceComponent);
if (getOwnPropertySymbols) {
keys = keys.concat(getOwnPropertySymbols(sourceComponent));
}
var targetStatics = TYPE_STATICS[targetComponent['$$typeof']] || REACT_STATICS;
var sourceStatics = TYPE_STATICS[sourceComponent['$$typeof']] || REACT_STATICS;
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) {
var descriptor = getOwnPropertyDescriptor(sourceComponent, key);
try {
// Avoid failures from read-only properties
defineProperty(targetComponent, key, descriptor);
} catch (e) {}
}
}
return targetComponent;
}
return targetComponent;
}
var hoistNonReactStatics_cjs = hoistNonReactStatics;
var EventEmitter =
/*#__PURE__*/
function () {
function EventEmitter() {
_classCallCheck(this, EventEmitter);
this.listeners = [];
}
_createClass(EventEmitter, [{
key: "on",
value: function on(cb) {
var _this = this;
this.listeners.push(cb);
return function () {
var index = _this.listeners.indexOf(cb);
if (index !== -1) _this.listeners.splice(index, 1);
};
}
}, {
key: "emit",
value: function emit(data) {
this.listeners.forEach(function (fn) {
return fn(data);
});
}
}]);
return EventEmitter;
}();
function createChainableTypeChecker(validate) {
function checkType(isRequired, props, propName, componentName, location, propFullName) {
for (var _len = arguments.length, rest = new Array(_len > 6 ? _len - 6 : 0), _key = 6; _key < _len; _key++) {
rest[_key - 6] = arguments[_key];
}
return mobx.untracked(function () {
componentName = componentName || "<<anonymous>>";
propFullName = propFullName || propName;
if (props[propName] == null) {
if (isRequired) {
var actual = props[propName] === null ? "null" : "undefined";
return new Error("The " + location + " `" + propFullName + "` is marked as required " + "in `" + componentName + "`, but its value is `" + actual + "`.");
}
return null;
} else {
return validate.apply(void 0, [props, propName, componentName, location, propFullName].concat(rest));
}
});
}
var chainedCheckType = checkType.bind(null, false);
chainedCheckType.isRequired = checkType.bind(null, true);
return chainedCheckType;
} // Copied from React.PropTypes
function isSymbol(propType, propValue) {
// Native Symbol.
if (propType === "symbol") {
return true;
} // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'
if (propValue["@@toStringTag"] === "Symbol") {
return true;
} // Fallback for non-spec compliant Symbols which are polyfilled.
if (typeof Symbol === "function" && propValue instanceof Symbol) {
return true;
}
return false;
} // Copied from React.PropTypes
function getPropType(propValue) {
var propType = _typeof(propValue);
if (Array.isArray(propValue)) {
return "array";
}
if (propValue instanceof RegExp) {
// Old webkits (at least until Android 4.0) return 'function' rather than
// 'object' for typeof a RegExp. We'll normalize this here so that /bla/
// passes PropTypes.object.
return "object";
}
if (isSymbol(propType, propValue)) {
return "symbol";
}
return propType;
} // This handles more types than `getPropType`. Only used for error messages.
// Copied from React.PropTypes
function getPreciseType(propValue) {
var propType = getPropType(propValue);
if (propType === "object") {
if (propValue instanceof Date) {
return "date";
} else if (propValue instanceof RegExp) {
return "regexp";
}
}
return propType;
}
function createObservableTypeCheckerCreator(allowNativeType, mobxType) {
return createChainableTypeChecker(function (props, propName, componentName, location, propFullName) {
return mobx.untracked(function () {
if (allowNativeType) {
if (getPropType(props[propName]) === mobxType.toLowerCase()) return null;
}
var mobxChecker;
switch (mobxType) {
case "Array":
mobxChecker = mobx.isObservableArray;
break;
case "Object":
mobxChecker = mobx.isObservableObject;
break;
case "Map":
mobxChecker = mobx.isObservableMap;
break;
default:
throw new Error("Unexpected mobxType: ".concat(mobxType));
}
var propValue = props[propName];
if (!mobxChecker(propValue)) {
var preciseType = getPreciseType(propValue);
var nativeTypeExpectationMessage = allowNativeType ? " or javascript `" + mobxType.toLowerCase() + "`" : "";
return new Error("Invalid prop `" + propFullName + "` of type `" + preciseType + "` supplied to" + " `" + componentName + "`, expected `mobx.Observable" + mobxType + "`" + nativeTypeExpectationMessage + ".");
}
return null;
});
});
}
function createObservableArrayOfTypeChecker(allowNativeType, typeChecker) {
return createChainableTypeChecker(function (props, propName, componentName, location, propFullName) {
for (var _len2 = arguments.length, rest = new Array(_len2 > 5 ? _len2 - 5 : 0), _key2 = 5; _key2 < _len2; _key2++) {
rest[_key2 - 5] = arguments[_key2];
}
return mobx.untracked(function () {
if (typeof typeChecker !== "function") {
return new Error("Property `" + propFullName + "` of component `" + componentName + "` has " + "invalid PropType notation.");
}
var error = createObservableTypeCheckerCreator(allowNativeType, "Array")(props, propName, componentName);
if (error instanceof Error) return error;
var propValue = props[propName];
for (var i = 0; i < propValue.length; i++) {
error = typeChecker.apply(void 0, [propValue, i, componentName, location, propFullName + "[" + i + "]"].concat(rest));
if (error instanceof Error) return error;
}
return null;
});
});
}
var observableArray = createObservableTypeCheckerCreator(false, "Array");
var observableArrayOf = createObservableArrayOfTypeChecker.bind(null, false);
var observableMap = createObservableTypeCheckerCreator(false, "Map");
var observableObject = createObservableTypeCheckerCreator(false, "Object");
var arrayOrObservableArray = createObservableTypeCheckerCreator(true, "Array");
var arrayOrObservableArrayOf = createObservableArrayOfTypeChecker.bind(null, true);
var objectOrObservableObject = createObservableTypeCheckerCreator(true, "Object");
var propTypes = /*#__PURE__*/Object.freeze({
observableArray: observableArray,
observableArrayOf: observableArrayOf,
observableMap: observableMap,
observableObject: observableObject,
arrayOrObservableArray: arrayOrObservableArray,
arrayOrObservableArrayOf: arrayOrObservableArrayOf,
objectOrObservableObject: objectOrObservableObject
});
function isStateless(component) {
// `function() {}` has prototype, but `() => {}` doesn't
// `() => {}` via Babel has prototype too.
return !(component.prototype && component.prototype.render);
}
var symbolId = 0;
function newSymbol(name) {
if (typeof Symbol === "function") {
return Symbol(name);
}
var symbol = "__$mobx-react ".concat(name, " (").concat(symbolId, ")");
symbolId++;
return symbol;
}
var mobxMixins = newSymbol("patchMixins");
var mobxPatchedDefinition = newSymbol("patchedDefinition");
function getMixins(target, methodName) {
var mixins = target[mobxMixins] = target[mobxMixins] || {};
var methodMixins = mixins[methodName] = mixins[methodName] || {};
methodMixins.locks = methodMixins.locks || 0;
methodMixins.methods = methodMixins.methods || [];
return methodMixins;
}
function wrapper(realMethod, mixins) {
var _this = this;
for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
args[_key - 2] = arguments[_key];
}
// locks are used to ensure that mixins are invoked only once per invocation, even on recursive calls
mixins.locks++;
try {
var retVal;
if (realMethod !== undefined && realMethod !== null) {
retVal = realMethod.apply(this, args);
}
return retVal;
} finally {
mixins.locks--;
if (mixins.locks === 0) {
mixins.methods.forEach(function (mx) {
mx.apply(_this, args);
});
}
}
}
function wrapFunction(realMethod, mixins) {
var fn = function fn() {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
wrapper.call.apply(wrapper, [this, realMethod, mixins].concat(args));
};
return fn;
}
function patch(target, methodName) {
var mixins = getMixins(target, methodName);
for (var _len3 = arguments.length, mixinMethods = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {
mixinMethods[_key3 - 2] = arguments[_key3];
}
for (var _i = 0; _i < mixinMethods.length; _i++) {
var mixinMethod = mixinMethods[_i];
if (mixins.methods.indexOf(mixinMethod) < 0) {
mixins.methods.push(mixinMethod);
}
}
var oldDefinition = Object.getOwnPropertyDescriptor(target, methodName);
if (oldDefinition && oldDefinition[mobxPatchedDefinition]) {
// already patched definition, do not repatch
return;
}
var originalMethod = target[methodName];
var newDefinition = createDefinition(target, methodName, oldDefinition ? oldDefinition.enumerable : undefined, mixins, originalMethod);
Object.defineProperty(target, methodName, newDefinition);
}
function createDefinition(target, methodName, enumerable, mixins, originalMethod) {
var _ref;
var wrappedFunc = wrapFunction(originalMethod, mixins);
return _ref = {}, _defineProperty(_ref, mobxPatchedDefinition, true), _defineProperty(_ref, "get", function get() {
return wrappedFunc;
}), _defineProperty(_ref, "set", function set(value) {
if (this === target) {
wrappedFunc = wrapFunction(value, mixins);
} else {
// when it is an instance of the prototype/a child prototype patch that particular case again separately
// since we need to store separate values depending on wether it is the actual instance, the prototype, etc
// e.g. the method for super might not be the same as the method for the prototype which might be not the same
// as the method for the instance
var newDefinition = createDefinition(this, methodName, enumerable, mixins, value);
Object.defineProperty(this, methodName, newDefinition);
}
}), _defineProperty(_ref, "configurable", true), _defineProperty(_ref, "enumerable", enumerable), _ref;
}
var injectorContextTypes = {
mobxStores: objectOrObservableObject
};
Object.seal(injectorContextTypes);
var proxiedInjectorProps = {
contextTypes: {
get: function get() {
return injectorContextTypes;
},
set: function set(_) {
console.warn("Mobx Injector: you are trying to attach `contextTypes` on an component decorated with `inject` (or `observer`) HOC. Please specify the contextTypes on the wrapped component instead. It is accessible through the `wrappedComponent`");
},
configurable: true,
enumerable: false
},
isMobxInjector: {
value: true,
writable: true,
configurable: true,
enumerable: true
}
/**
* Store Injection
*/
};
function createStoreInjector(grabStoresFn, component, injectNames) {
var displayName = "inject-" + (component.displayName || component.name || component.constructor && component.constructor.name || "Unknown");
if (injectNames) displayName += "-with-" + injectNames;
var Injector =
/*#__PURE__*/
function (_Component) {
_inherits(Injector, _Component);
function Injector() {
var _getPrototypeOf2;
var _this;
_classCallCheck(this, Injector);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(Injector)).call.apply(_getPrototypeOf2, [this].concat(args)));
_this.storeRef = function (instance) {
_this.wrappedInstance = instance;
};
return _this;
}
_createClass(Injector, [{
key: "render",
value: function render() {
// Optimization: it might be more efficient to apply the mapper function *outside* the render method
// (if the mapper is a function), that could avoid expensive(?) re-rendering of the injector component
// See this test: 'using a custom injector is not too reactive' in inject.js
var newProps = {};
for (var key in this.props) {
if (this.props.hasOwnProperty(key)) {
newProps[key] = this.props[key];
}
}
var additionalProps = grabStoresFn(this.context.mobxStores || {}, newProps, this.context) || {};
for (var _key2 in additionalProps) {
newProps[_key2] = additionalProps[_key2];
}
if (!isStateless(component)) {
newProps.ref = this.storeRef;
}
return React.createElement(component, newProps);
}
}]);
return Injector;
}(React.Component); // Static fields from component should be visible on the generated Injector
Injector.displayName = displayName;
hoistNonReactStatics_cjs(Injector, component);
Injector.wrappedComponent = component;
Object.defineProperties(Injector, proxiedInjectorProps);
return Injector;
}
function grabStoresByName(storeNames) {
return function (baseStores, nextProps) {
storeNames.forEach(function (storeName) {
if (storeName in nextProps // prefer props over stores
) return;
if (!(storeName in baseStores)) throw new Error("MobX injector: Store '" + storeName + "' is not available! Make sure it is provided by some Provider");
nextProps[storeName] = baseStores[storeName];
});
return nextProps;
};
}
/**
* higher order component that injects stores to a child.
* takes either a varargs list of strings, which are stores read from the context,
* or a function that manually maps the available stores from the context to props:
* storesToProps(mobxStores, props, context) => newProps
*/
function inject()
/* fn(stores, nextProps) or ...storeNames */
{
var grabStoresFn;
if (typeof arguments[0] === "function") {
grabStoresFn = arguments[0];
return function (componentClass) {
var injected = createStoreInjector(grabStoresFn, componentClass);
injected.isMobxInjector = false; // supress warning
// mark the Injector as observer, to make it react to expressions in `grabStoresFn`,
// see #111
injected = observer(injected);
injected.isMobxInjector = true; // restore warning
return injected;
};
} else {
var storeNames = [];
for (var i = 0; i < arguments.length; i++) {
storeNames[i] = arguments[i];
}
grabStoresFn = grabStoresByName(storeNames);
return function (componentClass) {
return createStoreInjector(grabStoresFn, componentClass, storeNames.join("-"));
};
}
}
var mobxAdminProperty = mobx.$mobx || "$mobx";
var mobxIsUnmounted = newSymbol("isUnmounted");
/**
* dev tool support
*/
var isDevtoolsEnabled = false;
var isUsingStaticRendering = false;
var warnedAboutObserverInjectDeprecation = false; // WeakMap<Node, Object>;
var componentByNodeRegistry = typeof WeakMap !== "undefined" ? new WeakMap() : undefined;
var renderReporter = new EventEmitter();
var skipRenderKey = newSymbol("skipRender");
var isForcingUpdateKey = newSymbol("isForcingUpdate"); // Using react-is had some issues (and operates on elements, not on types), see #608 / #609
var ReactForwardRefSymbol = typeof React.forwardRef === "function" && React.forwardRef(function (_props, _ref) {})["$$typeof"];
/**
* Helper to set `prop` to `this` as non-enumerable (hidden prop)
* @param target
* @param prop
* @param value
*/
function setHiddenProp(target, prop, value) {
if (!Object.hasOwnProperty.call(target, prop)) {
Object.defineProperty(target, prop, {
enumerable: false,
configurable: true,
writable: true,
value: value
});
} else {
target[prop] = value;
}
}
function findDOMNode$1(component) {
if (reactDom.findDOMNode) {
try {
return reactDom.findDOMNode(component);
} catch (e) {
// findDOMNode will throw in react-test-renderer, see:
// See https://github.com/mobxjs/mobx-react/issues/216
// Is there a better heuristic?
return null;
}
}
return null;
}
function reportRendering(component) {
var node = findDOMNode$1(component);
if (node && componentByNodeRegistry) componentByNodeRegistry.set(node, component);
renderReporter.emit({
event: "render",
renderTime: component.__$mobRenderEnd - component.__$mobRenderStart,
totalTime: Date.now() - component.__$mobRenderStart,
component: component,
node: node
});
}
function trackComponents() {
if (typeof WeakMap === "undefined") throw new Error("[mobx-react] tracking components is not supported in this browser.");
if (!isDevtoolsEnabled) isDevtoolsEnabled = true;
}
function useStaticRendering(useStaticRendering) {
isUsingStaticRendering = useStaticRendering;
}
/**
* Errors reporter
*/
var errorsReporter = new EventEmitter();
/**
* Utilities
*/
function patch$1(target, funcName) {
patch(target, funcName, reactiveMixin[funcName]);
}
function shallowEqual(objA, objB) {
//From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js
if (is(objA, objB)) return true;
if (_typeof(objA) !== "object" || objA === null || _typeof(objB) !== "object" || objB === null) {
return false;
}
var keysA = Object.keys(objA);
var keysB = Object.keys(objB);
if (keysA.length !== keysB.length) return false;
for (var i = 0; i < keysA.length; i++) {
if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
return false;
}
}
return true;
}
function is(x, y) {
// From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js
if (x === y) {
return x !== 0 || 1 / x === 1 / y;
} else {
return x !== x && y !== y;
}
}
function makeComponentReactive(render) {
var _this2 = this;
if (isUsingStaticRendering === true) return render.call(this);
function reactiveRender() {
var _this = this;
isRenderingPending = false;
var exception = undefined;
var rendering = undefined;
reaction.track(function () {
if (isDevtoolsEnabled) {
_this.__$mobRenderStart = Date.now();
}
try {
rendering = mobx._allowStateChanges(false, baseRender);
} catch (e) {
exception = e;
}
if (isDevtoolsEnabled) {
_this.__$mobRenderEnd = Date.now();
}
});
if (exception) {
errorsReporter.emit(exception);
throw exception;
}
return rendering;
} // Generate friendly name for debugging
var initialName = this.displayName || this.name || this.constructor && (this.constructor.displayName || this.constructor.name) || "<component>";
var rootNodeID = this._reactInternalInstance && this._reactInternalInstance._rootNodeID || this._reactInternalInstance && this._reactInternalInstance._debugID || this._reactInternalFiber && this._reactInternalFiber._debugID;
/**
* If props are shallowly modified, react will render anyway,
* so atom.reportChanged() should not result in yet another re-render
*/
setHiddenProp(this, skipRenderKey, false);
/**
* forceUpdate will re-assign this.props. We don't want that to cause a loop,
* so detect these changes
*/
setHiddenProp(this, isForcingUpdateKey, false); // wire up reactive render
var baseRender = render.bind(this);
var isRenderingPending = false;
var reaction = new mobx.Reaction("".concat(initialName, "#").concat(rootNodeID, ".render()"), function () {
if (!isRenderingPending) {
// N.B. Getting here *before mounting* means that a component constructor has side effects (see the relevant test in misc.js)
// This unidiomatic React usage but React will correctly warn about this so we continue as usual
// See #85 / Pull #44
isRenderingPending = true;
if (typeof _this2.componentWillReact === "function") _this2.componentWillReact(); // TODO: wrap in action?
if (_this2[mobxIsUnmounted] !== true) {
// If we are unmounted at this point, componentWillReact() had a side effect causing the component to unmounted
// TODO: remove this check? Then react will properly warn about the fact that this should not happen? See #73
// However, people also claim this might happen during unit tests..
var hasError = true;
try {
setHiddenProp(_this2, isForcingUpdateKey, true);
if (!_this2[skipRenderKey]) React.Component.prototype.forceUpdate.call(_this2);
hasError = false;
} finally {
setHiddenProp(_this2, isForcingUpdateKey, false);
if (hasError) reaction.dispose();
}
}
}
});
reaction.reactComponent = this;
reactiveRender[mobxAdminProperty] = reaction;
this.render = reactiveRender;
return reactiveRender.call(this);
}
/**
* ReactiveMixin
*/
var reactiveMixin = {
componentWillUnmount: function componentWillUnmount() {
if (isUsingStaticRendering === true) return;
this.render[mobxAdminProperty] && this.render[mobxAdminProperty].dispose();
this[mobxIsUnmounted] = true;
if (isDevtoolsEnabled) {
var node = findDOMNode$1(this);
if (node && componentByNodeRegistry) {
componentByNodeRegistry.delete(node);
}
renderReporter.emit({
event: "destroy",
component: this,
node: node
});
}
},
componentDidMount: function componentDidMount() {
if (isDevtoolsEnabled) {
reportRendering(this);
}
},
componentDidUpdate: function componentDidUpdate() {
if (isDevtoolsEnabled) {
reportRendering(this);
}
},
shouldComponentUpdate: function shouldComponentUpdate(nextProps, nextState) {
if (isUsingStaticRendering) {
console.warn("[mobx-react] It seems that a re-rendering of a React component is triggered while in static (server-side) mode. Please make sure components are rendered only once server-side.");
} // update on any state changes (as is the default)
if (this.state !== nextState) {
return true;
} // update if props are shallowly not equal, inspired by PureRenderMixin
// we could return just 'false' here, and avoid the `skipRender` checks etc
// however, it is nicer if lifecycle events are triggered like usually,
// so we return true here if props are shallowly modified.
return !shallowEqual(this.props, nextProps);
}
};
function makeObservableProp(target, propName) {
var valueHolderKey = newSymbol("reactProp_".concat(propName, "_valueHolder"));
var atomHolderKey = newSymbol("reactProp_".concat(propName, "_atomHolder"));
function getAtom() {
if (!this[atomHolderKey]) {
setHiddenProp(this, atomHolderKey, mobx.createAtom("reactive " + propName));
}
return this[atomHolderKey];
}
Object.defineProperty(target, propName, {
configurable: true,
enumerable: true,
get: function get() {
getAtom.call(this).reportObserved();
return this[valueHolderKey];
},
set: function set(v) {
if (!this[isForcingUpdateKey] && !shallowEqual(this[valueHolderKey], v)) {
setHiddenProp(this, valueHolderKey, v);
setHiddenProp(this, skipRenderKey, true);
getAtom.call(this).reportChanged();
setHiddenProp(this, skipRenderKey, false);
} else {
setHiddenProp(this, valueHolderKey, v);
}
}
});
}
/**
* Observer function / decorator
*/
function observer(arg1, arg2) {
if (typeof arg1 === "string") {
throw new Error("Store names should be provided as array");
}
if (Array.isArray(arg1)) {
// TODO: remove in next major
// component needs stores
if (!warnedAboutObserverInjectDeprecation) {
warnedAboutObserverInjectDeprecation = true;
console.warn('Mobx observer: Using observer to inject stores is deprecated since 4.0. Use `@inject("store1", "store2") @observer ComponentClass` or `inject("store1", "store2")(observer(componentClass))` instead of `@observer(["store1", "store2"]) ComponentClass`');
}
if (!arg2) {
// invoked as decorator
return function (componentClass) {
return observer(arg1, componentClass);
};
} else {
return inject.apply(null, arg1)(observer(arg2));
}
}
var componentClass = arg1;
if (componentClass.isMobxInjector === true) {
console.warn("Mobx observer: You are trying to use 'observer' on a component that already has 'inject'. Please apply 'observer' before applying 'inject'");
}
if (componentClass.__proto__ === React.PureComponent) {
console.warn("Mobx observer: You are using 'observer' on React.PureComponent. These two achieve two opposite goals and should not be used together");
} // Unwrap forward refs into `<Observer>` component
// we need to unwrap the render, because it is the inner render that needs to be tracked,
// not the ForwardRef HoC
if (ReactForwardRefSymbol && componentClass["$$typeof"] === ReactForwardRefSymbol) {
var _baseRender = componentClass.render;
if (typeof _baseRender !== "function") throw new Error("render property of ForwardRef was not a function");
return _objectSpread({}, componentClass, {
render: function render() {
var _arguments = arguments;
return React__default.createElement(Observer, null, function () {
return _baseRender.apply(undefined, _arguments);
});
}
});
} // Stateless function component:
// If it is function but doesn't seem to be a react class constructor,
// wrap it to a react class automatically
if (typeof componentClass === "function" && (!componentClass.prototype || !componentClass.prototype.render) && !componentClass.isReactClass && !React.Component.isPrototypeOf(componentClass)) {
var _class, _temp;
var observerComponent = observer((_temp = _class =
/*#__PURE__*/
function (_Component) {
_inherits(_class, _Component);
function _class() {
_classCallCheck(this, _class);
return _possibleConstructorReturn(this, _getPrototypeOf(_class).apply(this, arguments));
}
_createClass(_class, [{
key: "render",
value: function render() {
return componentClass.call(this, this.props, this.context);
}
}]);
return _class;
}(React.Component), _class.displayName = componentClass.displayName || componentClass.name, _class.contextTypes = componentClass.contextTypes, _class.propTypes = componentClass.propTypes, _class.defaultProps = componentClass.defaultProps, _temp));
hoistNonReactStatics_cjs(observerComponent, componentClass);
return observerComponent;
}
if (!componentClass) {
throw new Error("Please pass a valid component to 'observer'");
}
var target = componentClass.prototype || componentClass;
mixinLifecycleEvents(target);
componentClass.isMobXReactObserver = true;
makeObservableProp(target, "props");
makeObservableProp(target, "state");
var baseRender = target.render;
target.render = function () {
return makeComponentReactive.call(this, baseRender);
};
return componentClass;
}
function mixinLifecycleEvents(target) {
["componentDidMount", "componentWillUnmount", "componentDidUpdate"].forEach(function (funcName) {
patch$1(target, funcName);
});
if (!target.shouldComponentUpdate) {
target.shouldComponentUpdate = reactiveMixin.shouldComponentUpdate;
} else {
if (target.shouldComponentUpdate !== reactiveMixin.shouldComponentUpdate) {
// TODO: make throw in next major
console.warn("Use `shouldComponentUpdate` in an `observer` based component breaks the behavior of `observer` and might lead to unexpected results. Manually implementing `sCU` should not be needed when using mobx-react.");
}
}
}
var Observer = observer(function (_ref2) {
var children = _ref2.children,
observerInject = _ref2.inject,
render = _ref2.render;
var component = children || render;
if (typeof component === "undefined") {
return null;
}
if (!observerInject) {
return component();
} // TODO: remove in next major
console.warn("<Observer inject=.../> is no longer supported. Please use inject on the enclosing component instead");
var InjectComponent = inject(observerInject)(component);
return React__default.createElement(InjectComponent, null);
});
Observer.displayName = "Observer";
var ObserverPropsCheck = function ObserverPropsCheck(props, key, componentName, location, propFullName) {
var extraKey = key === "children" ? "render" : "children";
if (typeof props[key] === "function" && typeof props[extraKey] === "function") {
return new Error("Invalid prop,do not use children and render in the same time in`" + componentName);
}
if (typeof props[key] === "function" || typeof props[extraKey] === "function") {
return;
}
return new Error("Invalid prop `" + propFullName + "` of type `" + _typeof(props[key]) + "` supplied to" + " `" + componentName + "`, expected `function`.");
};
Observer.propTypes = {
render: ObserverPropsCheck,
children: ObserverPropsCheck
};
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function componentWillMount() {
// Call this.constructor.gDSFP to support sub-classes.
var state = this.constructor.getDerivedStateFromProps(this.props, this.state);
if (state !== null && state !== undefined) {
this.setState(state);
}
}
function componentWillReceiveProps(nextProps) {
// Call this.constructor.gDSFP to support sub-classes.
// Use the setState() updater to ensure state isn't stale in certain edge cases.
function updater(prevState) {
var state = this.constructor.getDerivedStateFromProps(nextProps, prevState);
return state !== null && state !== undefined ? state : null;
}
// Binding "this" is important for shallow renderer support.
this.setState(updater.bind(this));
}
function componentWillUpdate(nextProps, nextState) {
try {
var prevProps = this.props;
var prevState = this.state;
this.props = nextProps;
this.state = nextState;
this.__reactInternalSnapshotFlag = true;
this.__reactInternalSnapshot = this.getSnapshotBeforeUpdate(
prevProps,
prevState
);
} finally {
this.props = prevProps;
this.state = prevState;
}
}
// React may warn about cWM/cWRP/cWU methods being deprecated.
// Add a flag to suppress these warnings for this special case.
componentWillMount.__suppressDeprecationWarning = true;
componentWillReceiveProps.__suppressDeprecationWarning = true;
componentWillUpdate.__suppressDeprecationWarning = true;
function polyfill(Component) {
var prototype = Component.prototype;
if (!prototype || !prototype.isReactComponent) {
throw new Error('Can only polyfill class components');
}
if (
typeof Component.getDerivedStateFromProps !== 'function' &&
typeof prototype.getSnapshotBeforeUpdate !== 'function'
) {
return Component;
}
// If new component APIs are defined, "unsafe" lifecycles won't be called.
// Error if any of these lifecycles are present,
// Because they would work differently between older and newer (16.3+) versions of React.
var foundWillMountName = null;
var foundWillReceivePropsName = null;
var foundWillUpdateName = null;
if (typeof prototype.componentWillMount === 'function') {
foundWillMountName = 'componentWillMount';
} else if (typeof prototype.UNSAFE_componentWillMount === 'function') {
foundWillMountName = 'UNSAFE_componentWillMount';
}
if (typeof prototype.componentWillReceiveProps === 'function') {
foundWillReceivePropsName = 'componentWillReceiveProps';
} else if (typeof prototype.UNSAFE_componentWillReceiveProps === 'function') {
foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';
}
if (typeof prototype.componentWillUpdate === 'function') {
foundWillUpdateName = 'componentWillUpdate';
} else if (typeof prototype.UNSAFE_componentWillUpdate === 'function') {
foundWillUpdateName = 'UNSAFE_componentWillUpdate';
}
if (
foundWillMountName !== null ||
foundWillReceivePropsName !== null ||
foundWillUpdateName !== null
) {
var componentName = Component.displayName || Component.name;
var newApiName =
typeof Component.getDerivedStateFromProps === 'function'
? 'getDerivedStateFromProps()'
: 'getSnapshotBeforeUpdate()';
throw Error(
'Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' +
componentName +
' uses ' +
newApiName +
' but also contains the following legacy lifecycles:' +
(foundWillMountName !== null ? '\n ' + foundWillMountName : '') +
(foundWillReceivePropsName !== null
? '\n ' + foundWillReceivePropsName
: '') +
(foundWillUpdateName !== null ? '\n ' + foundWillUpdateName : '') +
'\n\nThe above lifecycles should be removed. Learn more about this warning here:\n' +
'https://fb.me/react-async-component-lifecycle-hooks'
);
}
// React <= 16.2 does not support static getDerivedStateFromProps.
// As a workaround, use cWM and cWRP to invoke the new static lifecycle.
// Newer versions of React will ignore these lifecycles if gDSFP exists.
if (typeof Component.getDerivedStateFromProps === 'function') {
prototype.componentWillMount = componentWillMount;
prototype.componentWillReceiveProps = componentWillReceiveProps;
}
// React <= 16.2 does not support getSnapshotBeforeUpdate.
// As a workaround, use cWU to invoke the new lifecycle.
// Newer versions of React will ignore that lifecycle if gSBU exists.
if (typeof prototype.getSnapshotBeforeUpdate === 'function') {
if (typeof prototype.componentDidUpdate !== 'function') {
throw new Error(
'Cannot polyfill getSnapshotBeforeUpdate() for components that do not define componentDidUpdate() on the prototype'
);
}
prototype.componentWillUpdate = componentWillUpdate;
var componentDidUpdate = prototype.componentDidUpdate;
prototype.componentDidUpdate = function componentDidUpdatePolyfill(
prevProps,
prevState,
maybeSnapshot
) {
// 16.3+ will not execute our will-update method;
// It will pass a snapshot value to did-update though.
// Older versions will require our polyfilled will-update value.
// We need to handle both cases, but can't just check for the presence of "maybeSnapshot",
// Because for <= 15.x versions this might be a "prevContext" object.
// We also can't just check "__reactInternalSnapshot",
// Because get-snapshot might return a falsy value.
// So check for the explicit __reactInternalSnapshotFlag flag to determine behavior.
var snapshot = this.__reactInternalSnapshotFlag
? this.__reactInternalSnapshot
: maybeSnapshot;
componentDidUpdate.call(this, prevProps, prevState, snapshot);
};
}
return Component;
}
var specialReactKeys = {
children: true,
key: true,
ref: true
};
var Provider =
/*#__PURE__*/
function (_Component) {
_inherits(Provider, _Component);
function Provider(props, context) {
var _this;
_classCallCheck(this, Provider);
_this = _possibleConstructorReturn(this, _getPrototypeOf(Provider).call(this, props, context));
_this.state = {};
copyStores(props, _this.state);
return _this;
}
_createClass(Provider, [{
key: "render",
value: function render() {
return React.Children.only(this.props.children);
}
}, {
key: "getChildContext",
value: function getChildContext() {
var stores = {}; // inherit stores
copyStores(this.context.mobxStores, stores); // add own stores
copyStores(this.props, stores);
return {
mobxStores: stores
};
}
}], [{
key: "getDerivedStateFromProps",
value: function getDerivedStateFromProps(nextProps, prevState) {
if (!nextProps) return null;
if (!prevState) return nextProps; // Maybe this warning is too aggressive?
if (Object.keys(nextProps).filter(validStoreName).length !== Object.keys(prevState).filter(validStoreName).length) console.warn("MobX Provider: The set of provided stores has changed. Please avoid changing stores as the change might not propagate to all children");
if (!nextProps.suppressChangedStoreWarning) for (var key in nextProps) {
if (validStoreName(key) && prevState[key] !== nextProps[key]) console.warn("MobX Provider: Provided store '" + key + "' has changed. Please avoid replacing stores as the change might not propagate to all children");
}
return nextProps;
}
}]);
return Provider;
}(React.Component);
Provider.contextTypes = {
mobxStores: objectOrObservableObject
};
Provider.childContextTypes = {
mobxStores: objectOrObservableObject.isRequired
};
function copyStores(from, to) {
if (!from) return;
for (var key in from) {
if (validStoreName(key)) to[key] = from[key];
}
}
function validStoreName(key) {
return !specialReactKeys[key] && key !== "suppressChangedStoreWarning";
} // TODO: kill in next major
polyfill(Provider);
var storeKey = newSymbol("disposeOnUnmount");
function runDisposersOnWillUnmount() {
var _this = this;
if (!this[storeKey]) {
// when disposeOnUnmount is only set to some instances of a component it will still patch the prototype
return;
}
this[storeKey].forEach(function (propKeyOrFunction) {
var prop = typeof propKeyOrFunction === "string" ? _this[propKeyOrFunction] : propKeyOrFunction;
if (prop !== undefined && prop !== null) {
if (typeof prop !== "function") {
throw new Error("[mobx-react] disposeOnUnmount only works on functions such as disposers returned by reactions, autorun, etc.");
}
prop();
}
});
this[storeKey] = [];
}
function disposeOnUnmount(target, propertyKeyOrFunction) {
if (Array.isArray(propertyKeyOrFunction)) {
return propertyKeyOrFunction.map(function (fn) {
return disposeOnUnmount(target, fn);
});
}
if (!target instanceof React.Component) {
throw new Error("[mobx-react] disposeOnUnmount only works on class based React components.");
}
if (typeof propertyKeyOrFunction !== "string" && typeof propertyKeyOrFunction !== "function") {
throw new Error("[mobx-react] disposeOnUnmount only works if the parameter is either a property key or a function.");
} // add property key / function we want run (disposed) to the store
var componentWasAlreadyModified = !!target[storeKey];
var store = target[storeKey] || (target[storeKey] = []);
store.push(propertyKeyOrFunction); // tweak the component class componentWillUnmount if not done already
if (!componentWasAlreadyModified) {
patch(target, "componentWillUnmount", runDisposersOnWillUnmount);
} // return the disposer as is if invoked as a non decorator
if (typeof propertyKeyOrFunction !== "string") {
return propertyKeyOrFunction;
}
}
if (!React.Component) throw new Error("mobx-react requires React to be available");
if (!mobx.spy) throw new Error("mobx-react requires mobx to be available");
if (typeof reactDom.unstable_batchedUpdates === "function") mobx.configure({
reactionScheduler: reactDom.unstable_batchedUpdates
});
var onError = function onError(fn) {
return errorsReporter.on(fn);
};
if ((typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__ === "undefined" ? "undefined" : _typeof(__MOBX_DEVTOOLS_GLOBAL_HOOK__)) === "object") {
var mobx$1 = {
spy: mobx.spy,
extras: {
getDebugName: mobx.getDebugName
}
};
var mobxReact = {
renderReporter: renderReporter,
componentByNodeRegistry: componentByNodeRegistry,
componentByNodeRegistery: componentByNodeRegistry,
trackComponents: trackComponents
};
__MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobxReact(mobxReact, mobx$1);
}
exports.propTypes = propTypes;
exports.PropTypes = propTypes;
exports.onError = onError;
exports.observer = observer;
exports.Observer = Observer;
exports.renderReporter = renderReporter;
exports.componentByNodeRegistery = componentByNodeRegistry;
exports.componentByNodeRegistry = componentByNodeRegistry;
exports.trackComponents = trackComponents;
exports.useStaticRendering = useStaticRendering;
exports.Provider = Provider;
exports.inject = inject;
exports.disposeOnUnmount = disposeOnUnmount;
Object.defineProperty(exports, '__esModule', { value: true });
})));
| extend1994/cdnjs | ajax/libs/mobx-react/5.4.2/index.js | JavaScript | mit | 52,938 |
'use strict';
const path = require('path');
const fs = require('fs');
const commonDir = require('commondir');
const pkgDir = require('pkg-dir');
const makeDir = require('make-dir');
const isWritable = path => {
try {
fs.accessSync(path, fs.constants.W_OK);
return true;
} catch (_) {
return false;
}
};
module.exports = (options = {}) => {
const {name} = options;
let directory = options.cwd;
if (options.files) {
directory = commonDir(directory, options.files);
} else {
directory = directory || process.cwd();
}
directory = pkgDir.sync(directory);
if (directory) {
const nodeModules = path.join(directory, 'node_modules');
if (
!isWritable(nodeModules) &&
(fs.existsSync(nodeModules) || !isWritable(path.join(directory)))
) {
return undefined;
}
directory = path.join(directory, 'node_modules', '.cache', name);
if (directory && options.create) {
makeDir.sync(directory);
}
if (options.thunk) {
return (...arguments_) => path.join(directory, ...arguments_);
}
}
return directory;
};
| jeffmcfadden/PiThermostat | node_modules/terser-webpack-plugin/node_modules/find-cache-dir/index.js | JavaScript | mit | 1,049 |
var args = arguments[0] || {};
var api = {
// initialization of our variables
callback: null,
content: null,
contentView: null,
headerPullView: null,
headerPullControl: null,
headerPullViewSize : 60,
headerPullViewArgs : [],
// ios ptr parameters
iosRefreshControl: [],
// android ptr flags
isChecking: false,
offset: 0, // The position of the scroll considering the pull action
previousOffset: 0,
pulling: false,
reloading: false, // boolean to know if it's already reload
initialize: function(parameters) {
parameters.arguments = parameters.arguments || {};
// create the controller given in argument witch we give the var api in argument
api.content = Alloy.createController(parameters.controller, { pulltorefresh: api, arguments: parameters.arguments });
api.contentView = api.content.getView();
if (OS_IOS) {
if (parameters.iosRefreshControl) {
api.iosRefreshControl.tintColor = parameters.iosRefreshControl.tintColor ? parameters.iosRefreshControl.tintColor : 'black';
api.iosRefreshControl.title = parameters.iosRefreshControl.title ? parameters.iosRefreshControl.title : null;
}
var control = Ti.UI.createRefreshControl({
tintColor: api.iosRefreshControl.tintColor,
title: api.iosRefreshControl.title
});
control.addEventListener('refreshstart', api.doRefresh);
api.contentView.refreshControl = control;
$.pulltorefresh.add(api.contentView);
}
// Our headerpullView for other devices
else {
if (parameters.headerPullView) {
api.headerPullViewArgs = parameters.headerPullView;
if (parameters.headerPullView.view) {
api.headerPullViewSize = parameters.headerPullView.view.size ? parameters.headerPullView.view.size : 60;
}
}
// create the controller headerPullView
api.headerPullControl = Widget.createController('headerPullView', { parameters: api.headerPullViewArgs });
api.headerPullView = api.headerPullControl.getView();
// add it in the ptr scrollview
$.container.add(api.headerPullView);
$.container.addEventListener('touchend', api.touchEnd);
$.container.addEventListener('scroll', api.scroll);
// add the content to the root of the ptr component
$.container.add(api.contentView);
}
},
/*
* Callback function to refresh the data
* of your ListView
*/
doRefresh: function() {
if (api.callback) {
api.callback();
} else {
api.stop();
}
},
setCallback: function(callback) {
api.callback = callback;
},
// only for Android
scroll: function(e) {
if (e.y != null) {
api.offset = e.y;
}
if (!api.isChecking) {
api.isChecking = true;
var interval = setInterval(function() {
if (api.previousOffset != api.offset) {
api.previousOffset = api.offset;
api.isChecking = true;
} else {
if (api.offset !== api.headerPullViewSize * Ti.Platform.displayCaps.logicalDensityFactor){
// the scroll has ended \o/
clearInterval(interval);
api.isChecking = false;
api.touchEnd();
}
}
}, 2000);
}
if (api.offset <= 0 && !api.pulling) {
api.pulling = true;
api.headerPullControl.pulling();
} else if (api.pulling && api.offset >= 1 && api.offset < api.headerPullViewSize * Ti.Platform.displayCaps.logicalDensityFactor) {
api.pulling = false;
api.headerPullControl.pullingStop();
}
},
/**
* contentHeight: height of the content
* hideHeight : size of the header - size of the navBar if there is a navBar
*/
stop: function(contentHeight, hideHeight) {
hideHeight = hideHeight || 0;
if (OS_ANDROID) {
api.reloading = false;
$.container.scrollTo(0, api.headerPullViewSize * Ti.Platform.displayCaps.logicalDensityFactor);
api.headerPullControl && api.headerPullControl.updateComplete();
if (contentHeight) {
$.container.contentHeight = hideHeight * Ti.Platform.displayCaps.logicalDensityFactor
+ Math.max(contentHeight * Ti.Platform.displayCaps.logicalDensityFactor, Ti.Platform.displayCaps.platformHeight);
}
} else {
if (api.contentView && api.contentView.refreshControl) {
api.contentView.refreshControl.endRefreshing();
}
}
},
/*
*
*/
touchEnd: function(e) {
if (api.offset <= 0) {
if (api.pulling && !api.reloading) {
api.reloading = true;
api.pulling = false;
api.headerPullControl.pullingComplete();
api.doRefresh();
}
} else if (api.offset < api.headerPullViewSize * Ti.Platform.displayCaps.logicalDensityFactor) {
api.pulling = false;
api.headerPullControl.pullingStop();
api.stop();
}
},
};
exports.initialize = api.initialize;
| jolicode/Alloy-PullToRefresh | controllers/widget.js | JavaScript | mit | 5,589 |
describe('setViewportSize/getViewportSize', () => {
let windowSize = {}
before(async function () {
windowSize = await this.client.windowHandleSize()
})
beforeEach(async function () {
await this.client.windowHandleSize({ width: 300, height: 300 })
})
it('should change viewport size of current window and should return the exact value', async function () {
await this.client.setViewportSize({ width: 500, height: 500 }, true)
const viewportSize = await this.client.getViewportSize()
viewportSize.width.should.be.equal(500)
viewportSize.height.should.be.equal(500)
})
it(`should set window size equal when parameter 'type' is true by default`, async function () {
await this.client.setViewportSize({ width: 500, height: 500 })
const viewportSize = await this.client.getViewportSize()
viewportSize.width.should.be.equal(500)
viewportSize.height.should.be.equal(500)
const windowSize = await this.client.windowHandleSize()
windowSize.value.width.should.be.greaterThan(499)
windowSize.value.height.should.be.greaterThan(499)
})
it('should let windowHandleSize return bigger values since it includes menu and status bar heights', async function () {
await this.client.setViewportSize({ width: 500, height: 500 }, false)
const viewportSize = await this.client.getViewportSize()
viewportSize.width.should.be.lessThan(501)
viewportSize.height.should.be.lessThan(501)
const windowSize = await this.client.windowHandleSize()
windowSize.value.width.should.be.equal(500)
windowSize.value.height.should.be.equal(500)
})
after(async function () {
await this.client.windowHandleSize(windowSize.value)
})
})
| testingbot/webdriverjs | test/spec/desktop/viewportSize.js | JavaScript | mit | 1,822 |
/* *
*
* Copyright (c) 2019-2021 Highsoft AS
*
* Boost module: stripped-down renderer for higher performance
*
* License: highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import '../../Core/Globals.js';
/**
* Options for the Boost module. The Boost module allows certain series types
* to be rendered by WebGL instead of the default SVG. This allows hundreds of
* thousands of data points to be rendered in milliseconds. In addition to the
* WebGL rendering it saves time by skipping processing and inspection of the
* data wherever possible. This introduces some limitations to what features are
* available in boost mode. See [the docs](
* https://www.highcharts.com/docs/advanced-chart-features/boost-module) for
* details.
*
* In addition to the global `boost` option, each series has a
* [boostThreshold](#plotOptions.series.boostThreshold) that defines when the
* boost should kick in.
*
* Requires the `modules/boost.js` module.
*
* @sample {highstock} highcharts/boost/line-series-heavy-stock
* Stock chart
* @sample {highstock} highcharts/boost/line-series-heavy-dynamic
* Dynamic stock chart
* @sample highcharts/boost/line
* Line chart
* @sample highcharts/boost/line-series-heavy
* Line chart with hundreds of series
* @sample highcharts/boost/scatter
* Scatter chart
* @sample highcharts/boost/area
* Area chart
* @sample highcharts/boost/arearange
* Area range chart
* @sample highcharts/boost/column
* Column chart
* @sample highcharts/boost/columnrange
* Column range chart
* @sample highcharts/boost/bubble
* Bubble chart
* @sample highcharts/boost/heatmap
* Heat map
* @sample highcharts/boost/treemap
* Tree map
*
* @product highcharts highstock
* @requires modules/boost
* @apioption boost
*/
/**
* Set the series threshold for when the boost should kick in globally.
*
* Setting to e.g. 20 will cause the whole chart to enter boost mode
* if there are 20 or more series active. When the chart is in boost mode,
* every series in it will be rendered to a common canvas. This offers
* a significant speed improvment in charts with a very high
* amount of series.
*
* @type {number}
* @default 50
* @apioption boost.seriesThreshold
*/
/**
* Enable or disable boost on a chart.
*
* @type {boolean}
* @default true
* @apioption boost.enabled
*/
/**
* Debugging options for boost.
* Useful for benchmarking, and general timing.
*
* @apioption boost.debug
*/
/**
* Time the series rendering.
*
* This outputs the time spent on actual rendering in the console when
* set to true.
*
* @type {boolean}
* @default false
* @apioption boost.debug.timeRendering
*/
/**
* Time the series processing.
*
* This outputs the time spent on transforming the series data to
* vertex buffers when set to true.
*
* @type {boolean}
* @default false
* @apioption boost.debug.timeSeriesProcessing
*/
/**
* Time the the WebGL setup.
*
* This outputs the time spent on setting up the WebGL context,
* creating shaders, and textures.
*
* @type {boolean}
* @default false
* @apioption boost.debug.timeSetup
*/
/**
* Time the building of the k-d tree.
*
* This outputs the time spent building the k-d tree used for
* markers etc.
*
* Note that the k-d tree is built async, and runs post-rendering.
* Following, it does not affect the performance of the rendering itself.
*
* @type {boolean}
* @default false
* @apioption boost.debug.timeKDTree
*/
/**
* Show the number of points skipped through culling.
*
* When set to true, the number of points skipped in series processing
* is outputted. Points are skipped if they are closer than 1 pixel from
* each other.
*
* @type {boolean}
* @default false
* @apioption boost.debug.showSkipSummary
*/
/**
* Time the WebGL to SVG buffer copy
*
* After rendering, the result is copied to an image which is injected
* into the SVG.
*
* If this property is set to true, the time it takes for the buffer copy
* to complete is outputted.
*
* @type {boolean}
* @default false
* @apioption boost.debug.timeBufferCopy
*/
/**
* Enable or disable GPU translations. GPU translations are faster than doing
* the translation in JavaScript.
*
* This option may cause rendering issues with certain datasets.
* Namely, if your dataset has large numbers with small increments (such as
* timestamps), it won't work correctly. This is due to floating point
* precission.
*
* @type {boolean}
* @default false
* @apioption boost.useGPUTranslations
*/
/**
* Enable or disable pre-allocation of vertex buffers.
*
* Enabling this will make it so that the binary data arrays required for
* storing the series data will be allocated prior to transforming the data
* to a WebGL-compatible format.
*
* This saves a copy operation on the order of O(n) and so is significantly more
* performant. However, this is currently an experimental option, and may cause
* visual artifacts with some datasets.
*
* As such, care should be taken when using this setting to make sure that
* it doesn't cause any rendering glitches with the given use-case.
*
* @type {boolean}
* @default false
* @apioption boost.usePreallocated
*/
/**
* Set the point threshold for when a series should enter boost mode.
*
* Setting it to e.g. 2000 will cause the series to enter boost mode when there
* are 2000 or more points in the series.
*
* To disable boosting on the series, set the `boostThreshold` to 0. Setting it
* to 1 will force boosting.
*
* Note that the [cropThreshold](plotOptions.series.cropThreshold) also affects
* this setting. When zooming in on a series that has fewer points than the
* `cropThreshold`, all points are rendered although outside the visible plot
* area, and the `boostThreshold` won't take effect.
*
* @type {number}
* @default 5000
* @requires modules/boost
* @apioption plotOptions.series.boostThreshold
*/
/**
* If set to true, the whole chart will be boosted if one of the series
* crosses its threshold, and all the series can be boosted.
*
* @type {boolean}
* @default true
* @apioption boost.allowForce
*/
/**
* Sets the color blending in the boost module.
*
* @type {string}
* @default undefined
* @validvalue ["add", "multiply", "darken"]
* @requires modules/boost
* @apioption plotOptions.series.boostBlending
*/
''; // adds doclets above to transpiled file
| cdnjs/cdnjs | ajax/libs/highcharts/9.3.3/es-modules/Extensions/Boost/BoostOptions.js | JavaScript | mit | 6,649 |
var classwayverb_1_1combined_1_1model_1_1material =
[
[ "material", "classwayverb_1_1combined_1_1model_1_1material.html#a583d34826add3ae50891b9fdf7d2352f", null ],
[ "get_name", "classwayverb_1_1combined_1_1model_1_1material.html#abbeec8c982d714f016f711e851a606b0", null ],
[ "get_surface", "classwayverb_1_1combined_1_1model_1_1material.html#abfa679e90c7310ec9eae90e813167e03", null ],
[ "serialize", "classwayverb_1_1combined_1_1model_1_1material.html#adcdaef089ffa7feb50a46b05a2bc6a9d", null ],
[ "set_name", "classwayverb_1_1combined_1_1model_1_1material.html#ae095b842a8fd9cedf6d37df2e667d70f", null ],
[ "set_surface", "classwayverb_1_1combined_1_1model_1_1material.html#a2fd7609a5262ce706727a1a9ec0f8bfa", null ]
]; | reuk/waveguide | docs_source/doxygen/html/classwayverb_1_1combined_1_1model_1_1material.js | JavaScript | gpl-2.0 | 746 |
jQuery(document).ready(function(){
// Index first
slideshowSlideInserterIndexSlidesOrder();
// Make list items in the sortables list sortable, exclude elements with cancel option.
jQuery('.sortable-slides-list').sortable({
revert: true,
placeholder: 'sortable-placeholder',
forcePlaceholderSize: true,
stop: function(event, ui){
slideshowSlideInserterIndexSlidesOrder();
},
cancel: 'input, select, p'
});
// Make the black background stretch all the way down the document
jQuery('#slideshow-slide-inserter-popup-background').height(jQuery(document).outerHeight(true));
// Center the popup in the window
jQuery('#slideshow-slide-inserter-popup').css({
'top': parseInt((jQuery(window).height() / 2) - (jQuery('#slideshow-slide-inserter-popup').outerHeight(true) / 2), 10),
'left': parseInt((jQuery(window).width() / 2) - (jQuery('#slideshow-slide-inserter-popup').outerWidth(true) / 2), 10)
});
// Focus on search bar
jQuery('#slideshow-slide-inserter-popup #search').focus();
// Preload attachments
slideshowSlideInserterGetSearchResults();
/**
* Close popup when clicked on cross
*/
jQuery('#slideshow-slide-inserter-popup #close').click(function(){
slideshowSlideInserterClosePopup();
});
/**
* Close popup when clicked on background
*/
jQuery('#slideshow-slide-inserter-popup-background').click(function(){
slideshowSlideInserterClosePopup();
});
/**
* Send ajax request on click of the search button
*/
jQuery('#slideshow-slide-inserter-popup #search-submit').click(function(){
slideshowSlideInserterGetSearchResults();
});
/**
* Make the 'enter' key do the same as the search button
*/
jQuery('#slideshow-slide-inserter-popup #search').keypress(function(event){
if(event.which == 13){
event.preventDefault();
slideshowSlideInserterGetSearchResults();
}
});
/**
* Open popup by click on button
*/
jQuery('#slideshow-insert-image-slide').click(function(){
jQuery('#slideshow-slide-inserter-popup, #slideshow-slide-inserter-popup-background').css({ display: 'block' });
});
/**
* Insert text slide into the sortable list when the Insert Text Slide button is clicked
*/
jQuery('#slideshow-insert-text-slide').click(function(){
slideshowSlideInserterInsertTextSlide();
});
/**
* Insert video slide into the sortable list when the Insert Video Slide button is clicked
*/
jQuery('#slideshow-insert-video-slide').click(function(){
slideshowSlideInserterInsertVideoSlide();
});
/**
* Ajax deletes a slide from the slides list and from the database
*/
jQuery('.slideshow-delete-slide').click(function(){
var confirmMessage = 'Are you sure you want to delete this slide?';
if(typeof SlideInserterTranslations !== undefined)
confirmMessage = SlideInserterTranslations.confirmMessage;
var deleteSlide = confirm(confirmMessage);
if(!deleteSlide)
return;
// Get postId from url
var postId = -1;
jQuery.each(location.search.replace('?', '').split('&'), function(key, value){
var splitValue = value.split('=');
if(splitValue[0] == 'post')
postId = splitValue[1];
});
// Get slideId
var slideId = jQuery(this).find('span').attr('class');
// Exit if no slideId is found
if(postId == -1 || slideId == 'undefined')
return;
// Remove slide from DOM
jQuery(this).parent().remove();
// Remove slide by AJAX.
jQuery.post(
ajaxurl,
{
action: 'slideshow_delete_slide',
postId: postId,
slideId: slideId
}
);
});
/**
* Loop through list items, setting slide orders
*/
function slideshowSlideInserterIndexSlidesOrder(){
// Loop through sortables
jQuery.each(jQuery('.sortable-slides-list').find('li'), function(key, value){
// Loop through all input, select and text area boxes
jQuery.each(jQuery(this).find('input, select, textarea'), function(key2, input){
// Remove brackets
var name = jQuery(input).attr('name');
// No name found, skip
if(name == undefined)
return;
// Divide name parts
name = name.replace(/[\[\]']+/g, ' ').split(' ');
// Put name with new order ID back on the page
jQuery(input).attr('name', name[0] + '[' + (key + 1) + '][' + name[2] + ']');
});
});
}
/**
* Sends an ajax post request with the search query and print
* retrieved html to the results table.
*
* If offset is set, append data to data that is already there
*
* @param offset (optional, defaults to 0)
*/
function slideshowSlideInserterGetSearchResults(offset){
if(!offset){
offset = 0;
jQuery('#slideshow-slide-inserter-popup #results').html('');
}
jQuery.post(
ajaxurl,
{
action: 'slideshow_slide_inserter_search_query',
search: jQuery('#slideshow-slide-inserter-popup #search').attr('value'),
offset: offset
},
function(response){
// Fill table
jQuery('#slideshow-slide-inserter-popup #results').append(response);
// Apply insert to slideshow script
jQuery('#slideshow-slide-inserter-popup #results .insert-attachment').click(function(){
var tr = jQuery(this).closest('tr');
slideshowSlideInserterInsertImageSlide(
jQuery(this).attr('id'),
jQuery(tr).find('.title').text(),
jQuery(tr).find('.description').text(),
jQuery(tr).find('.image img').attr('src')
);
});
// Load more results on click of the 'Load more results' button
if(jQuery('.load-more-results')){
jQuery('.load-more-results').click(function(){
// Get offset
var previousOffset = jQuery(this).attr('class').split(' ')[2];
// Load ajax results
slideshowSlideInserterGetSearchResults(previousOffset);
// Remove button row
jQuery(this).closest('tr').remove();
});
}
}
);
}
/**
* Inserts image slide into the slides list
*
* @param id
* @param title
* @param description
* @param src
*/
function slideshowSlideInserterInsertImageSlide(id, title, description, src){
// Find and clone the image slide template
var imageSlide = jQuery('.image-slide-template').find('li').clone();
// Fill slide with data
imageSlide.find('.attachment').attr('src', src);
imageSlide.find('.attachment').attr('title', title);
imageSlide.find('.attachment').attr('alt', title);
imageSlide.find('.title').attr('value', title);
imageSlide.find('.description').html(description);
imageSlide.find('.postId').attr('value', id);
// Set names to be saved to the database
imageSlide.find('.title').attr('name', 'slides[0][title]');
imageSlide.find('.description').attr('name', 'slides[0][description]');
imageSlide.find('.url').attr('name', 'slides[0][url]');
imageSlide.find('.urlTarget').attr('name', 'slides[0][urlTarget]');
imageSlide.find('.type').attr('name', 'slides[0][type]');
imageSlide.find('.postId').attr('name', 'slides[0][postId]');
imageSlide.find('.slide_order').attr('name', 'slides[0][order]');
// Register delete link (only needs to delete from DOM)
imageSlide.find('.slideshow-delete-new-slide').click(function(){
var deleteSlide = confirm('Are you sure you want to delete this slide?');
if(!deleteSlide)
return;
jQuery(this).closest('li').remove();
});
// Put slide in the sortables list.
jQuery('.sortable-slides-list').prepend(imageSlide);
// Reindex
slideshowSlideInserterIndexSlidesOrder();
}
/**
* Inserts text slide into the slides list
*/
function slideshowSlideInserterInsertTextSlide(){
// Find and clone the text slide template
var textSlide = jQuery('.text-slide-template').find('li').clone();
// Set names to be saved to the database
textSlide.find('.title').attr('name', 'slides[0][title]');
textSlide.find('.description').attr('name', 'slides[0][description]');
textSlide.find('.color').attr('name', 'slides[0][color]');
textSlide.find('.url').attr('name', 'slides[0][url]');
textSlide.find('.urlTarget').attr('name', 'slides[0][urlTarget]');
textSlide.find('.type').attr('name', 'slides[0][type]');
textSlide.find('.slide_order').attr('name', 'slides[0][order]');
// Register delete link (only needs to delete from DOM)
textSlide.find('.slideshow-delete-new-slide').click(function(){
var deleteSlide = confirm('Are you sure you want to delete this slide?');
if(!deleteSlide)
return;
jQuery(this).closest('li').remove();
});
// Put slide in the sortables list.
jQuery('.sortable-slides-list').prepend(textSlide);
// Reindex slide orders
slideshowSlideInserterIndexSlidesOrder();
}
/**
* Inserts video slide into the slides list
*/
function slideshowSlideInserterInsertVideoSlide(){
// Find and clone the video slide template
var videoSlide = jQuery('.video-slide-template').find('li').clone();
// Set names to be saved to the database
videoSlide.find('.videoId').attr('name', 'slides[0][videoId]');
videoSlide.find('.type').attr('name', 'slides[0][type]');
videoSlide.find('.slide_order').attr('name', 'slides[0][order]');
// Register delete link (only needs to delete from DOM)
videoSlide.find('.slideshow-delete-new-slide').click(function(){
var deleteSlide = confirm('Are you sure you want to delete this slide?');
if(!deleteSlide)
return;
jQuery(this).closest('li').remove();
});
// Put slide in the sortables list.
jQuery('.sortable-slides-list').prepend(videoSlide);
// Reindex slide orders
slideshowSlideInserterIndexSlidesOrder();
}
/**
* Closes popup
*/
function slideshowSlideInserterClosePopup(){
jQuery('#slideshow-slide-inserter-popup, #slideshow-slide-inserter-popup-background').css({ display: 'none' });
}
}); | Bochet/festival_lgbt | wp-content/plugins/slideshow-jquery-image-gallery/js/SlideshowPluginSlideInserter/slide-inserter.js | JavaScript | gpl-2.0 | 9,929 |
/**
* ------------------------------------------------------------------------
* T3V2 Framework
* ------------------------------------------------------------------------
* Copyright (C) 2004-20011 J.O.O.M Solutions Co., Ltd. All Rights Reserved.
* @license - GNU/GPL, http://www.gnu.org/licenses/gpl.html
* Author: J.O.O.M Solutions Co., Ltd
* Websites: http://www.joomlart.com - http://www.joomlancers.com
* ------------------------------------------------------------------------
*/
var JAT3_PAGEIDSETTINGS = new Class({
initialize: function(options) {
this.options = $extend({
param_name: null,
page_select: null,
theme_select: null,
activePopIn: 0,
obj_theme_select: null
}, options || {});
},
choosePageids: function (obj, k){
obj = $(obj)
if(!$type(k)){
k = this.options.page_select;
}
values = obj.getText().trim();
this.close_popup(this.options.param_name + '-ja-popup-profiles');
this.options.page_select = parseInt(k);
var selected = values.split(',');
for(var i=0; i<selected.length; i++){
selected[i] = selected[i].clean();
}
var selections = $(this.options.param_name + '-selections');
var all_pageids_selected = this.get_all_pageids_selected();
for (var i=0; i<selections.length; i++){
selections[i].selected = false;
selections[i].disabled = false;
if(all_pageids_selected.contains(selections[i].value.clean())){
selections[i].onclick = function(){void(0)};
selections[i].disabled = true;
}
if(selected.contains(selections[i].value.clean())){
selections[i].disabled = false;
selections[i].selected = true;
}
}
this.setPosition_for_poup($(this.options.param_name + '-ja-popup-pageids'), obj)
this.options.activePopIn = 0;return;
},
chooseProfile: function (obj, k){
obj = $(obj);
if($type(k)){
this.options.theme_select = k;
}
else{
k = this.options.theme_select;
}
this.close_popup(this.options.param_name + '-ja-popup-pageids');
this.options.obj_theme_select = obj;
var selected = obj.getText().trim().toLowerCase();
var selections = $$('#' + this.options.param_name + '-ja-popup-profiles li');
for (var i=0; i<selections.length; i++){
selections[i].removeClass('active');
if(selections[i].getText().trim().toLowerCase()==selected){
selections[i].addClass('active');
}
}
this.options.activePopIn = 0;
this.setPosition_for_poup($(this.options.param_name + '-ja-popup-profiles'), obj);
},
add_chooseProfile: function (obj, k){
obj = $(obj);
this.chooseProfile(obj, k);
obj.setOpacity('1');
},
setPosition_for_poup: function (popup_obj, position_obj){
var position = position_obj.getPosition();
var height = position_obj.offsetHeight;
popup_obj.setStyles({top: position.y + height, left: position.x, display:'block'});
$(this.options.param_name + '-ja-popup-pageids').setStyle('width', $(this.options.param_name + '-selections').offsetWidth);
},
close_popup: function (divid){
$(divid).setStyle('display', 'none');
},
select_multi_pageids: function (){
this.close_popup(this.options.param_name + '-ja-popup-pageids');
var selections = $(this.options.param_name + '-selections');
var selected = new Array();
for (var i=0; i<selections.length; i++){
if(selections[i].selected){
selected += selections[i].value + ', ';
}
}
if(selected.length>0) selected = selected.substring(0, selected.length-2);
if(parseInt(this.options.page_select)>-1 && selected!=''){
$(this.options.param_name + '-row-' + this.options.page_select).getFirst().getFirst().setText(selected);
$(this.options.param_name + '-row-' + this.options.page_select).getFirst().getFirst().removeClass('more');
this.buildData_of_param();
}
},
select_profile: function (obj){
obj = $(obj);
var value = obj.getText().trim();
this.close_popup(this.options.param_name + '-ja-popup-profiles');
if(obj.getParent().className.indexOf('active')>-1){
return;
}
this.options.obj_theme_select.removeClass('active');
if(parseInt(this.options.theme_select)>-1 && value!=''){
var new_el = this.options.obj_theme_select;
new_el.setText(value);
new_el.setStyle('display', 'inline');
new_el.removeClass('more');
this.buildData_of_param();
}
},
addrow: function (obj) {
obj = $(obj);
var table = $(this.options.param_name + '-ja-list-pageids');
var k = table.rows.length-1;
this.options.page_select = k;
this.options.theme_select = k;
var last = table.rows[k];
var li = $(last).clone();
li.injectAfter(last);
last.set({'id': this.options.param_name + '-row-'+k });
var args = new Array(last.getElement('span.pageid_text'), k);
last.getElement('span.pageid_text').addEvent('click', this.choosePageids.pass(args, this));
var args = new Array(last.getElement('span.profile_text'), k);
last.getElement('span.profile_text').addEvent('click', this.add_chooseProfile.pass(args,this));
last.getElement('span.ja_close').addEvent('click', this.removerow.bind(this, last.getElement('span.ja_close')));
if(obj==last.getFirst()){
this.choosePageids(obj.getElement('span.pageid_text'), k);
}
if(obj==last.getChildren()[1]){
this.add_chooseProfile(obj.getElement('span.profile_text'), k);
}
obj.getFirst().setOpacity(1);
obj.getNext().getFirst().setOpacity(1);
obj.getNext().getNext().getElement('img').setOpacity(1);
last.setOpacity('1');
last.getElement('span.ja_close').setStyle('display', '');
last.getFirst().onclick = function (){void(0)};
last.getChildren()[1].onclick = function (){void(0)};
if($type(jatabs)){
jatabs.resize();
}
},
removerow: function (obj){
obj = $(obj);
$(obj.parentNode.parentNode).remove();
this.buildData_of_param();
},
buildData_of_param: function (){
var params = $(this.options.param_name + '-profile');
params.value = '';
var els = $(this.options.param_name+'-ja-list-pageids').getElements ('tr.ja-item');
var length = els.length-1;
els.each(function (el, i){
if($type( $E('span.pageid_text', el) ) && $E('span.pageid_text', el).getText().trim()!='' && $E('span.profile_text', el).getText().trim()!='')
{
if(!i){
params.value += 'all';
}
else{
params.value += $E('span.pageid_text', el).getText().trim();
}
params.value += '=';
params.value += $E('span.profile_text', el).getText().trim();
if(i<length){
params.value += '\n';
}
}
});
},
deleteTheme: function (obj){
obj = $(obj);
$(obj).getPrevious().remove();
$(obj).remove();
this.buildData_of_param();
},
get_all_pageids_selected: function (){
var all_pageids_selected = new Array();
var k = 0;
var els = $$('.ja-list-pageids tr.ja-item');
els.each(function (el){
if($type( $E('span.pageid_text', el) ) && $E('span.pageid_text', el).getText().trim()!='')
{
var tem = $E('span.pageid_text', el).getText().trim().split(',');
for(var j=0; j<tem.length; j++){
all_pageids_selected[k] = tem[j].clean();
k++;
}
}
});
return all_pageids_selected;
},
clearData: function(){
if (this.options.activePopIn == 1) {
$(this.options.param_name + '-ja-popup-profiles').setStyle('display', 'none');
$(this.options.param_name + '-ja-popup-pageids').setStyle('display', 'none');
this.options.activePopIn = 0;
}
this.options.activePopIn = 1;
if(parseInt(this.options.theme_select)>-1 &&
$type($(this.options.param_name + '-row-' + this.options.theme_select)) &&
$type($(this.options.param_name + '-row-' + this.options.theme_select).getElement('span.active')))
{
$(this.options.param_name + '-row-' + this.options.theme_select).getElement('span.active').removeClass('active');
}
}
}); | heqiaoliu/Viral-Dark-Matter | tmp/install_4f209c9de9bf1/plugins/system/jat3/core/admin/assets/js/japageidsettings.js | JavaScript | gpl-2.0 | 8,087 |
var searchData=
[
['material',['material',['../classmaterial.html',1,'']]]
];
| hishamop/CROptim | search/classes_7.js | JavaScript | gpl-3.0 | 80 |
"use strict";
var nconf = require('nconf'),
path = require('path'),
winston = require('winston'),
controllers = require('../controllers'),
meta = require('../meta'),
plugins = require('../plugins'),
express = require('express'),
metaRoutes = require('./meta'),
apiRoutes = require('./api'),
adminRoutes = require('./admin'),
feedRoutes = require('./feeds'),
pluginRoutes = require('./plugins'),
authRoutes = require('./authentication'),
helpers = require('./helpers');
var setupPageRoute = helpers.setupPageRoute;
function mainRoutes(app, middleware, controllers) {
setupPageRoute(app, '/', middleware, [], controllers.home);
var loginRegisterMiddleware = [middleware.redirectToAccountIfLoggedIn];
setupPageRoute(app, '/login', middleware, loginRegisterMiddleware, controllers.login);
setupPageRoute(app, '/register', middleware, loginRegisterMiddleware, controllers.register);
setupPageRoute(app, '/compose', middleware, [middleware.authenticate], controllers.compose);
setupPageRoute(app, '/confirm/:code', middleware, [], controllers.confirmEmail);
setupPageRoute(app, '/outgoing', middleware, [], controllers.outgoing);
setupPageRoute(app, '/search/:term?', middleware, [middleware.guestSearchingAllowed], controllers.search.search);
setupPageRoute(app, '/reset/:code?', middleware, [], controllers.reset);
setupPageRoute(app, '/tos', middleware, [], controllers.termsOfUse);
}
function topicRoutes(app, middleware, controllers) {
app.get('/api/topic/teaser/:topic_id', controllers.topics.teaser);
setupPageRoute(app, '/topic/:topic_id/:slug/:post_index?', middleware, [], controllers.topics.get);
setupPageRoute(app, '/topic/:topic_id/:slug?', middleware, [], controllers.topics.get);
}
function tagRoutes(app, middleware, controllers) {
setupPageRoute(app, '/tags/:tag', middleware, [middleware.privateTagListing], controllers.tags.getTag);
setupPageRoute(app, '/tags', middleware, [middleware.privateTagListing], controllers.tags.getTags);
}
function categoryRoutes(app, middleware, controllers) {
setupPageRoute(app, '/categories', middleware, [], controllers.categories.list);
setupPageRoute(app, '/popular/:term?', middleware, [], controllers.categories.popular);
setupPageRoute(app, '/recent', middleware, [], controllers.categories.recent);
setupPageRoute(app, '/unread', middleware, [middleware.authenticate], controllers.categories.unread);
app.get('/api/unread/total', middleware.authenticate, controllers.categories.unreadTotal);
setupPageRoute(app, '/category/:category_id/:slug/:topic_index', middleware, [], controllers.categories.get);
setupPageRoute(app, '/category/:category_id/:slug?', middleware, [], controllers.categories.get);
}
function accountRoutes(app, middleware, controllers) {
var middlewares = [middleware.checkGlobalPrivacySettings];
var accountMiddlewares = [middleware.checkGlobalPrivacySettings, middleware.checkAccountPermissions];
setupPageRoute(app, '/user/:userslug', middleware, middlewares, controllers.accounts.getAccount);
setupPageRoute(app, '/user/:userslug/following', middleware, middlewares, controllers.accounts.getFollowing);
setupPageRoute(app, '/user/:userslug/followers', middleware, middlewares, controllers.accounts.getFollowers);
setupPageRoute(app, '/user/:userslug/posts', middleware, middlewares, controllers.accounts.getPosts);
setupPageRoute(app, '/user/:userslug/topics', middleware, middlewares, controllers.accounts.getTopics);
setupPageRoute(app, '/user/:userslug/groups', middleware, middlewares, controllers.accounts.getGroups);
setupPageRoute(app, '/user/:userslug/favourites', middleware, accountMiddlewares, controllers.accounts.getFavourites);
setupPageRoute(app, '/user/:userslug/watched', middleware, accountMiddlewares, controllers.accounts.getWatchedTopics);
setupPageRoute(app, '/user/:userslug/edit', middleware, accountMiddlewares, controllers.accounts.accountEdit);
setupPageRoute(app, '/user/:userslug/settings', middleware, accountMiddlewares, controllers.accounts.accountSettings);
setupPageRoute(app, '/notifications', middleware, [middleware.authenticate], controllers.accounts.getNotifications);
setupPageRoute(app, '/chats/:userslug?', middleware, [middleware.redirectToLoginIfGuest], controllers.accounts.getChats);
}
function userRoutes(app, middleware, controllers) {
var middlewares = [middleware.checkGlobalPrivacySettings];
setupPageRoute(app, '/users', middleware, middlewares, controllers.users.getOnlineUsers);
setupPageRoute(app, '/users/online', middleware, middlewares, controllers.users.getOnlineUsers);
setupPageRoute(app, '/users/sort-posts', middleware, middlewares, controllers.users.getUsersSortedByPosts);
setupPageRoute(app, '/users/sort-reputation', middleware, middlewares, controllers.users.getUsersSortedByReputation);
setupPageRoute(app, '/users/latest', middleware, middlewares, controllers.users.getUsersSortedByJoinDate);
setupPageRoute(app, '/users/search', middleware, middlewares, controllers.users.getUsersForSearch);
}
function groupRoutes(app, middleware, controllers) {
var middlewares = [middleware.checkGlobalPrivacySettings, middleware.exposeGroupName];
setupPageRoute(app, '/groups', middleware, middlewares, controllers.groups.list);
setupPageRoute(app, '/groups/:slug', middleware, middlewares, controllers.groups.details);
setupPageRoute(app, '/groups/:slug/members', middleware, middlewares, controllers.groups.members);
}
module.exports = function(app, middleware) {
var router = express.Router(),
pluginRouter = express.Router(),
authRouter = express.Router(),
relativePath = nconf.get('relative_path');
pluginRouter.render = function() {
app.render.apply(app, arguments);
};
// Set-up for hotswapping (when NodeBB reloads)
pluginRouter.hotswapId = 'plugins';
authRouter.hotswapId = 'auth';
app.use(middleware.maintenanceMode);
app.all(relativePath + '/api/?*', middleware.prepareAPI);
app.all(relativePath + '/api/admin/?*', middleware.isAdmin);
var ensureLoggedIn = require('connect-ensure-login');
app.all(relativePath + '/admin/?*', ensureLoggedIn.ensureLoggedIn(nconf.get('relative_path') + '/login?local=1'), middleware.applyCSRF, middleware.isAdmin);
adminRoutes(router, middleware, controllers);
metaRoutes(router, middleware, controllers);
apiRoutes(router, middleware, controllers);
feedRoutes(router, middleware, controllers);
pluginRoutes(router, middleware, controllers);
/**
* Every view has an associated API route.
*
*/
mainRoutes(router, middleware, controllers);
topicRoutes(router, middleware, controllers);
tagRoutes(router, middleware, controllers);
categoryRoutes(router, middleware, controllers);
accountRoutes(router, middleware, controllers);
userRoutes(router, middleware, controllers);
groupRoutes(router, middleware, controllers);
app.use(relativePath, pluginRouter);
app.use(relativePath, router);
app.use(relativePath, authRouter);
if (process.env.NODE_ENV === 'development') {
require('./debug')(app, middleware, controllers);
}
app.use(function(req, res, next) {
if (req.user || parseInt(meta.config.privateUploads, 10) !== 1) {
return next();
}
if (req.path.startsWith('/uploads/files')) {
return res.status(403).json('not-allowed');
}
next();
});
app.use(relativePath, express.static(path.join(__dirname, '../../', 'public'), {
maxAge: app.enabled('cache') ? 5184000000 : 0
}));
handle404(app, middleware);
handleErrors(app, middleware);
// Add plugin routes
plugins.reloadRoutes();
authRoutes.reloadRoutes();
};
function handle404(app, middleware) {
app.use(function(req, res, next) {
if (plugins.hasListeners('action:meta.override404')) {
return plugins.fireHook('action:meta.override404', {
req: req,
res: res,
error: {}
});
}
var relativePath = nconf.get('relative_path');
var isLanguage = new RegExp('^' + relativePath + '/language/[\\w]{2,}/.*.json'),
isClientScript = new RegExp('^' + relativePath + '\\/src\\/.+\\.js');
if (isClientScript.test(req.url)) {
res.type('text/javascript').status(200).send('');
} else if (isLanguage.test(req.url)) {
res.status(200).json({});
} else if (req.accepts('html')) {
if (process.env.NODE_ENV === 'development') {
winston.warn('Route requested but not found: ' + req.url);
}
res.status(404);
if (res.locals.isAPI) {
return res.json({path: req.path});
}
middleware.buildHeader(req, res, function() {
res.render('404', {path: req.path});
});
} else {
res.status(404).type('txt').send('Not found');
}
});
}
function handleErrors(app, middleware) {
app.use(function(err, req, res, next) {
if (err.code === 'EBADCSRFTOKEN') {
winston.error(req.path + '\n', err.message);
return res.sendStatus(403);
}
winston.error(req.path + '\n', err.stack);
if (parseInt(err.status, 10) === 302 && err.path) {
return res.locals.isAPI ? res.status(302).json(err.path) : res.redirect(err.path);
}
res.status(err.status || 500);
if (res.locals.isAPI) {
return res.json({path: req.path, error: err.message});
} else {
middleware.buildHeader(req, res, function() {
res.render('500', {path: req.path, error: err.message});
});
}
});
}
| Sarabpreet/notcrud | src/routes/index.js | JavaScript | gpl-3.0 | 9,226 |
/* InfoAction.js
*
* copyright (c) 2010-2017, Christian Mayer and the CometVisu contributers.
*
* 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, 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 General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
/**
* The infoaction widget is a combination of an info/text widget and an "action"-widget, e.g. switch or trigger.
*
* Use case: if you have a group of lights, you can show the number of lights currently switched on
* and control the whole group in one widget.
*
* @widgetexample <settings>
* <caption>Example combines an info widget to show the number of lights currently switched on, and an Switch to control them</caption>
* <screenshot name="infoaction_lights">
* <data address="0/0/0">4</data>
* <data address="0/0/1">1</data>
* </screenshot>
* </settings>
* <meta>
* <mappings>
* <mapping name="OnOff">
* <entry value="0">Off</entry>
* <entry value="1">On</entry>
* </mapping>
* </mappings>
* <stylings>
* <styling name="GreyGreen">
* <entry value="0">grey</entry>
* <entry value="1">green</entry>
* </styling>
* </stylings>
* </meta>
* <infoaction>
* <layout colspan="4"/>
* <label>Lights</label>
* <widgetinfo>
* <info>
* <address transform="DPT:9.001">0/0/0</address>
* </info>
* </widgetinfo>
* <widgetaction>
* <switch mapping="OnOff" styling="GreyGreen">
* <layout colspan="3" />
* <address transform="DPT:1.001" mode="readwrite">0/0/1</address>
* </switch>
* </widgetaction>
* </infoaction>
*
*
*
* @author Tobias Bräutigam
* @since 0.10.0 (as widget), 0.9.2 (as plugin)
*/
qx.Class.define('cv.ui.structure.pure.InfoAction', {
extend: cv.ui.structure.AbstractWidget,
include: cv.ui.common.HasChildren,
/*
******************************************************
PROPERTIES
******************************************************
*/
properties: {
anonymous : {
refine: true,
init: true
}
},
/*
******************************************************
MEMBERS
******************************************************
*/
members: {
// overridden
_getInnerDomString: function () {
return this.getChildrenDomString();
}
},
defer: function(statics) {
cv.ui.structure.WidgetFactory.registerClass("infoaction", statics);
}
});
| jensgulow/CometVisu | source/class/cv/ui/structure/pure/InfoAction.js | JavaScript | gpl-3.0 | 2,960 |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at <http://mozilla.org/MPL/2.0/>. */
// @flow
import classnames from "classnames";
import React from "react";
import AccessibleImage from "../AccessibleImage";
import "./styles/CommandBarButton.css";
type Props = {
children: React$Element<any>,
className: string,
pressed?: boolean
};
export function debugBtn(
onClick: ?Function,
type: string,
className: string,
tooltip: string,
disabled: boolean = false,
ariaPressed: boolean = false
) {
return (
<CommandBarButton
className={classnames(type, className)}
disabled={disabled}
key={type}
onClick={onClick}
pressed={ariaPressed}
title={tooltip}
>
<AccessibleImage className={type} />
</CommandBarButton>
);
}
const CommandBarButton = (props: Props) => {
const { children, className, pressed = false, ...rest } = props;
return (
<button
aria-pressed={pressed}
className={classnames("command-bar-button", className)}
{...rest}
>
{children}
</button>
);
};
export default CommandBarButton;
| ruturajv/debugger.html | src/components/shared/Button/CommandBarButton.js | JavaScript | mpl-2.0 | 1,233 |
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = exports.YAMLSet = void 0;
var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
var _get2 = _interopRequireDefault(require("@babel/runtime/helpers/get"));
var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _errors = require("../../errors");
var _Map = _interopRequireWildcard(require("../../schema/Map"));
var _Pair = _interopRequireDefault(require("../../schema/Pair"));
var _parseMap = _interopRequireDefault(require("../../schema/parseMap"));
var _Scalar = _interopRequireDefault(require("../../schema/Scalar"));
var YAMLSet =
/*#__PURE__*/
function (_YAMLMap) {
(0, _inherits2.default)(YAMLSet, _YAMLMap);
function YAMLSet() {
var _this;
(0, _classCallCheck2.default)(this, YAMLSet);
_this = (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(YAMLSet).call(this));
_this.tag = YAMLSet.tag;
return _this;
}
(0, _createClass2.default)(YAMLSet, [{
key: "add",
value: function add(key) {
var pair = key instanceof _Pair.default ? key : new _Pair.default(key);
var prev = (0, _Map.findPair)(this.items, pair.key);
if (!prev) this.items.push(pair);
}
}, {
key: "get",
value: function get(key, keepPair) {
var pair = (0, _Map.findPair)(this.items, key);
return !keepPair && pair instanceof _Pair.default ? pair.key instanceof _Scalar.default ? pair.key.value : pair.key : pair;
}
}, {
key: "set",
value: function set(key, value) {
if (typeof value !== 'boolean') throw new Error("Expected boolean value for set(key, value) in a YAML set, not ".concat((0, _typeof2.default)(value)));
var prev = (0, _Map.findPair)(this.items, key);
if (prev && !value) {
this.items.splice(this.items.indexOf(prev), 1);
} else if (!prev && value) {
this.items.push(new _Pair.default(key));
}
}
}, {
key: "toJSON",
value: function toJSON(_, ctx) {
return (0, _get2.default)((0, _getPrototypeOf2.default)(YAMLSet.prototype), "toJSON", this).call(this, _, ctx, Set);
}
}, {
key: "toString",
value: function toString(ctx, onComment, onChompKeep) {
if (!ctx) return JSON.stringify(this);
if (this.hasAllNullValues()) return (0, _get2.default)((0, _getPrototypeOf2.default)(YAMLSet.prototype), "toString", this).call(this, ctx, onComment, onChompKeep);else throw new Error('Set items must all have null values');
}
}]);
return YAMLSet;
}(_Map.default);
exports.YAMLSet = YAMLSet;
(0, _defineProperty2.default)(YAMLSet, "tag", 'tag:yaml.org,2002:set');
function parseSet(doc, cst) {
var map = (0, _parseMap.default)(doc, cst);
if (!map.hasAllNullValues()) throw new _errors.YAMLSemanticError(cst, 'Set items must all have null values');
return Object.assign(new YAMLSet(), map);
}
function createSet(schema, iterable, ctx) {
var set = new YAMLSet();
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = iterable[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var value = _step.value;
set.items.push(schema.createPair(value, null, ctx));
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return set;
}
var _default = {
identify: function identify(value) {
return value instanceof Set;
},
nodeClass: YAMLSet,
default: false,
tag: 'tag:yaml.org,2002:set',
resolve: parseSet,
createNode: createSet
};
exports.default = _default; | mdranger/mytest | node_modules/yaml/browser/dist/tags/yaml-1.1/set.js | JavaScript | mpl-2.0 | 4,639 |
(function() {
"use strict";
var website = openerp.website;
var _t = openerp._t;
website.add_template_file('/website_event/static/src/xml/website_event.xml');
website.is_editable = true;
website.EditorBar.include({
start: function() {
website.is_editable_button = website.is_editable_button || !!$("#wrap.js_event").size();
var res = this._super();
this.$(".dropdown:has(.oe_content_menu)").removeClass("hidden");
return res;
},
events: _.extend({}, website.EditorBar.prototype.events, {
'click a[data-action=new_event]': function (ev) {
ev.preventDefault();
website.prompt({
id: "editor_new_event",
window_title: _t("New Event"),
input: "Event Name",
}).then(function (event_name) {
website.form('/event/add_event', 'POST', {
event_name: event_name
});
});
}
}),
});
})();
| ovnicraft/openerp-restaurant | website_event/static/src/js/website_event.editor.js | JavaScript | agpl-3.0 | 1,095 |
/**
* @class Ext.History
* @extends Ext.util.Observable
* @ignore
* @private
*
* Mobile-optimized port of Ext.History. Note - iPad on iOS < 4.2 does not have HTML5 History support so we still
* have to poll for changes.
*/
Ext.History = new Ext.util.Observable({
constructor: function() {
Ext.History.superclass.constructor.call(this, config);
this.addEvents(
/**
* @event change
*/
'change'
);
},
/**
* @private
* Initializes event listeners
*/
init: function() {
var me = this;
me.setToken(window.location.hash);
if (Ext.supports.History) {
window.addEventListener('hashchange', this.onChange);
} else {
setInterval(function() {
var newToken = me.cleanToken(window.location.hash),
oldToken = me.getToken();
if (newToken != oldToken) {
me.onChange();
}
}, 50);
}
},
/**
* @private
* Event listener for the hashchange event
*/
onChange: function() {
var me = Ext.History,
newToken = me.cleanToken(window.location.hash);
if (me.token != newToken) {
me.fireEvent('change', newToken);
}
me.setToken(newToken);
},
/**
* Sets a new token, stripping of the leading # if present. Does not fire the 'change' event
* @param {String} token The new token
* @return {String} The cleaned token
*/
setToken: function(token) {
return this.token = this.cleanToken(token);
},
/**
* @private
* Cleans a token by stripping off the leading # if it is present
* @param {String} token The unclean token
* @return {String} The clean token
*/
cleanToken: function(token) {
return token[0] == '#' ? token.substr(1) : token;
},
/**
* Returns the current history token
* @return {String} The current token
*/
getToken: function() {
return this.token;
},
/**
* Adds a token to the history stack by updation the address bar hash
* @param {String} token The new token
*/
add: function(token) {
window.location.hash = this.setToken(token);
if (!Ext.supports.History) {
this.onChange();
}
}
}); | gabegorelick/MedSocial | src/main/webapp/lib/sencha/sencha-touch-1.1.1/src/core/History.js | JavaScript | agpl-3.0 | 2,517 |
/*
Ext JS - JavaScript Library
Copyright (c) 2006-2011, Sencha Inc.
All rights reserved.
licensing@sencha.com
*/
/**
* @class Ext
* @singleton
*/
(function() {
var global = this,
objectPrototype = Object.prototype,
toString = Object.prototype.toString,
enumerables = true,
enumerablesTest = { toString: 1 },
i;
if (typeof Ext === 'undefined') {
global.Ext = {};
}
Ext.global = global;
for (i in enumerablesTest) {
enumerables = null;
}
if (enumerables) {
enumerables = ['hasOwnProperty', 'valueOf', 'isPrototypeOf', 'propertyIsEnumerable',
'toLocaleString', 'toString', 'constructor'];
}
/**
* An array containing extra enumerables for old browsers
* @type Array
*/
Ext.enumerables = enumerables;
/**
* Copies all the properties of config to the specified object.
* Note that if recursive merging and cloning without referencing the original objects / arrays is needed, use
* {@link Ext.Object#merge} instead.
* @param {Object} object The receiver of the properties
* @param {Object} config The source of the properties
* @param {Object} defaults A different object that will also be applied for default values
* @return {Object} returns obj
*/
Ext.apply = function(object, config, defaults) {
if (defaults) {
Ext.apply(object, defaults);
}
if (object && config && typeof config === 'object') {
var i, j, k;
for (i in config) {
object[i] = config[i];
}
if (enumerables) {
for (j = enumerables.length; j--;) {
k = enumerables[j];
if (config.hasOwnProperty(k)) {
object[k] = config[k];
}
}
}
}
return object;
};
Ext.buildSettings = Ext.apply({
baseCSSPrefix: 'x-',
scopeResetCSS: false
}, Ext.buildSettings || {});
Ext.apply(Ext, {
/**
* A reusable empty function
*/
emptyFn: function() {},
baseCSSPrefix: Ext.buildSettings.baseCSSPrefix,
/**
* Copies all the properties of config to object if they don't already exist.
* @function
* @param {Object} object The receiver of the properties
* @param {Object} config The source of the properties
* @return {Object} returns obj
*/
applyIf: function(object, config) {
var property;
if (object) {
for (property in config) {
if (object[property] === undefined) {
object[property] = config[property];
}
}
}
return object;
},
/**
* Iterates either an array or an object. This method delegates to
* {@link Ext.Array#each Ext.Array.each} if the given value is iterable, and {@link Ext.Object#each Ext.Object.each} otherwise.
*
* @param {Object/Array} object The object or array to be iterated.
* @param {Function} fn The function to be called for each iteration. See and {@link Ext.Array#each Ext.Array.each} and
* {@link Ext.Object#each Ext.Object.each} for detailed lists of arguments passed to this function depending on the given object
* type that is being iterated.
* @param {Object} scope (Optional) The scope (`this` reference) in which the specified function is executed.
* Defaults to the object being iterated itself.
* @markdown
*/
iterate: function(object, fn, scope) {
if (Ext.isEmpty(object)) {
return;
}
if (scope === undefined) {
scope = object;
}
if (Ext.isIterable(object)) {
Ext.Array.each.call(Ext.Array, object, fn, scope);
}
else {
Ext.Object.each.call(Ext.Object, object, fn, scope);
}
}
});
Ext.apply(Ext, {
/**
* This method deprecated. Use {@link Ext#define Ext.define} instead.
* @function
* @param {Function} superclass
* @param {Object} overrides
* @return {Function} The subclass constructor from the <tt>overrides</tt> parameter, or a generated one if not provided.
* @deprecated 4.0.0 Use {@link Ext#define Ext.define} instead
*/
extend: function() {
// inline overrides
var objectConstructor = objectPrototype.constructor,
inlineOverrides = function(o) {
for (var m in o) {
if (!o.hasOwnProperty(m)) {
continue;
}
this[m] = o[m];
}
};
return function(subclass, superclass, overrides) {
// First we check if the user passed in just the superClass with overrides
if (Ext.isObject(superclass)) {
overrides = superclass;
superclass = subclass;
subclass = overrides.constructor !== objectConstructor ? overrides.constructor : function() {
superclass.apply(this, arguments);
};
}
//<debug>
if (!superclass) {
Ext.Error.raise({
sourceClass: 'Ext',
sourceMethod: 'extend',
msg: 'Attempting to extend from a class which has not been loaded on the page.'
});
}
//</debug>
// We create a new temporary class
var F = function() {},
subclassProto, superclassProto = superclass.prototype;
F.prototype = superclassProto;
subclassProto = subclass.prototype = new F();
subclassProto.constructor = subclass;
subclass.superclass = superclassProto;
if (superclassProto.constructor === objectConstructor) {
superclassProto.constructor = superclass;
}
subclass.override = function(overrides) {
Ext.override(subclass, overrides);
};
subclassProto.override = inlineOverrides;
subclassProto.proto = subclassProto;
subclass.override(overrides);
subclass.extend = function(o) {
return Ext.extend(subclass, o);
};
return subclass;
};
}(),
/**
* Proxy to {@link Ext.Base#override}. Please refer {@link Ext.Base#override} for further details.
Ext.define('My.cool.Class', {
sayHi: function() {
alert('Hi!');
}
}
Ext.override(My.cool.Class, {
sayHi: function() {
alert('About to say...');
this.callOverridden();
}
});
var cool = new My.cool.Class();
cool.sayHi(); // alerts 'About to say...'
// alerts 'Hi!'
* Please note that `this.callOverridden()` only works if the class was previously
* created with {@link Ext#define)
*
* @param {Object} cls The class to override
* @param {Object} overrides The list of functions to add to origClass. This should be specified as an object literal
* containing one or more methods.
* @method override
* @markdown
*/
override: function(cls, overrides) {
if (cls.prototype.$className) {
return cls.override(overrides);
}
else {
Ext.apply(cls.prototype, overrides);
}
}
});
// A full set of static methods to do type checking
Ext.apply(Ext, {
/**
* Returns the given value itself if it's not empty, as described in {@link Ext#isEmpty}; returns the default
* value (second argument) otherwise.
*
* @param {Mixed} value The value to test
* @param {Mixed} defaultValue The value to return if the original value is empty
* @param {Boolean} allowBlank (optional) true to allow zero length strings to qualify as non-empty (defaults to false)
* @return {Mixed} value, if non-empty, else defaultValue
*/
valueFrom: function(value, defaultValue, allowBlank){
return Ext.isEmpty(value, allowBlank) ? defaultValue : value;
},
/**
* Returns the type of the given variable in string format. List of possible values are:
*
* - `undefined`: If the given value is `undefined`
* - `null`: If the given value is `null`
* - `string`: If the given value is a string
* - `number`: If the given value is a number
* - `boolean`: If the given value is a boolean value
* - `date`: If the given value is a `Date` object
* - `function`: If the given value is a function reference
* - `object`: If the given value is an object
* - `array`: If the given value is an array
* - `regexp`: If the given value is a regular expression
* - `element`: If the given value is a DOM Element
* - `textnode`: If the given value is a DOM text node and contains something other than whitespace
* - `whitespace`: If the given value is a DOM text node and contains only whitespace
*
* @param {Mixed} value
* @return {String}
* @markdown
*/
typeOf: function(value) {
if (value === null) {
return 'null';
}
var type = typeof value;
if (type === 'undefined' || type === 'string' || type === 'number' || type === 'boolean') {
return type;
}
var typeToString = toString.call(value);
switch(typeToString) {
case '[object Array]':
return 'array';
case '[object Date]':
return 'date';
case '[object Boolean]':
return 'boolean';
case '[object Number]':
return 'number';
case '[object RegExp]':
return 'regexp';
}
if (type === 'function') {
return 'function';
}
if (type === 'object') {
if (value.nodeType !== undefined) {
if (value.nodeType === 3) {
return (/\S/).test(value.nodeValue) ? 'textnode' : 'whitespace';
}
else {
return 'element';
}
}
return 'object';
}
//<debug error>
Ext.Error.raise({
sourceClass: 'Ext',
sourceMethod: 'typeOf',
msg: 'Failed to determine the type of the specified value "' + value + '". This is most likely a bug.'
});
//</debug>
},
/**
* Returns true if the passed value is empty, false otherwise. The value is deemed to be empty if it is either:
*
* - `null`
* - `undefined`
* - a zero-length array
* - a zero-length string (Unless the `allowEmptyString` parameter is set to `true`)
*
* @param {Mixed} value The value to test
* @param {Boolean} allowEmptyString (optional) true to allow empty strings (defaults to false)
* @return {Boolean}
* @markdown
*/
isEmpty: function(value, allowEmptyString) {
return (value === null) || (value === undefined) || (!allowEmptyString ? value === '' : false) || (Ext.isArray(value) && value.length === 0);
},
/**
* Returns true if the passed value is a JavaScript Array, false otherwise.
*
* @param {Mixed} target The target to test
* @return {Boolean}
*/
isArray: ('isArray' in Array) ? Array.isArray : function(value) {
return toString.call(value) === '[object Array]';
},
/**
* Returns true if the passed value is a JavaScript Date object, false otherwise.
* @param {Object} object The object to test
* @return {Boolean}
*/
isDate: function(value) {
return toString.call(value) === '[object Date]';
},
/**
* Returns true if the passed value is a JavaScript Object, false otherwise.
* @param {Mixed} value The value to test
* @return {Boolean}
*/
isObject: (toString.call(null) === '[object Object]') ?
function(value) {
return value !== null && value !== undefined && toString.call(value) === '[object Object]' && value.nodeType === undefined;
} :
function(value) {
return toString.call(value) === '[object Object]';
},
/**
* Returns true if the passed value is a JavaScript 'primitive', a string, number or boolean.
* @param {Mixed} value The value to test
* @return {Boolean}
*/
isPrimitive: function(value) {
var type = typeof value;
return type === 'string' || type === 'number' || type === 'boolean';
},
/**
* Returns true if the passed value is a JavaScript Function, false otherwise.
* @param {Mixed} value The value to test
* @return {Boolean}
*/
isFunction:
// Safari 3.x and 4.x returns 'function' for typeof <NodeList>, hence we need to fall back to using
// Object.prorotype.toString (slower)
(typeof document !== 'undefined' && typeof document.getElementsByTagName('body') === 'function') ? function(value) {
return toString.call(value) === '[object Function]';
} : function(value) {
return typeof value === 'function';
},
/**
* Returns true if the passed value is a number. Returns false for non-finite numbers.
* @param {Mixed} value The value to test
* @return {Boolean}
*/
isNumber: function(value) {
return typeof value === 'number' && isFinite(value);
},
/**
* Validates that a value is numeric.
* @param {Mixed} value Examples: 1, '1', '2.34'
* @return {Boolean} True if numeric, false otherwise
*/
isNumeric: function(value) {
return !isNaN(parseFloat(value)) && isFinite(value);
},
/**
* Returns true if the passed value is a string.
* @param {Mixed} value The value to test
* @return {Boolean}
*/
isString: function(value) {
return typeof value === 'string';
},
/**
* Returns true if the passed value is a boolean.
*
* @param {Mixed} value The value to test
* @return {Boolean}
*/
isBoolean: function(value) {
return typeof value === 'boolean';
},
/**
* Returns true if the passed value is an HTMLElement
* @param {Mixed} value The value to test
* @return {Boolean}
*/
isElement: function(value) {
return value ? value.nodeType !== undefined : false;
},
/**
* Returns true if the passed value is a TextNode
* @param {Mixed} value The value to test
* @return {Boolean}
*/
isTextNode: function(value) {
return value ? value.nodeName === "#text" : false;
},
/**
* Returns true if the passed value is defined.
* @param {Mixed} value The value to test
* @return {Boolean}
*/
isDefined: function(value) {
return typeof value !== 'undefined';
},
/**
* Returns true if the passed value is iterable, false otherwise
* @param {Mixed} value The value to test
* @return {Boolean}
*/
isIterable: function(value) {
return (value && typeof value !== 'string') ? value.length !== undefined : false;
}
});
Ext.apply(Ext, {
/**
* Clone almost any type of variable including array, object, DOM nodes and Date without keeping the old reference
* @param {Mixed} item The variable to clone
* @return {Mixed} clone
*/
clone: function(item) {
if (item === null || item === undefined) {
return item;
}
// DOM nodes
// TODO proxy this to Ext.Element.clone to handle automatic id attribute changing
// recursively
if (item.nodeType && item.cloneNode) {
return item.cloneNode(true);
}
var type = toString.call(item);
// Date
if (type === '[object Date]') {
return new Date(item.getTime());
}
var i, j, k, clone, key;
// Array
if (type === '[object Array]') {
i = item.length;
clone = [];
while (i--) {
clone[i] = Ext.clone(item[i]);
}
}
// Object
else if (type === '[object Object]' && item.constructor === Object) {
clone = {};
for (key in item) {
clone[key] = Ext.clone(item[key]);
}
if (enumerables) {
for (j = enumerables.length; j--;) {
k = enumerables[j];
clone[k] = item[k];
}
}
}
return clone || item;
},
/**
* @private
* Generate a unique reference of Ext in the global scope, useful for sandboxing
*/
getUniqueGlobalNamespace: function() {
var uniqueGlobalNamespace = this.uniqueGlobalNamespace;
if (uniqueGlobalNamespace === undefined) {
var i = 0;
do {
uniqueGlobalNamespace = 'ExtSandbox' + (++i);
} while (Ext.global[uniqueGlobalNamespace] !== undefined);
Ext.global[uniqueGlobalNamespace] = Ext;
this.uniqueGlobalNamespace = uniqueGlobalNamespace;
}
return uniqueGlobalNamespace;
},
/**
* @private
*/
functionFactory: function() {
var args = Array.prototype.slice.call(arguments);
if (args.length > 0) {
args[args.length - 1] = 'var Ext=window.' + this.getUniqueGlobalNamespace() + ';' +
args[args.length - 1];
}
return Function.prototype.constructor.apply(Function.prototype, args);
}
});
/**
* Old alias to {@link Ext#typeOf}
* @deprecated 4.0.0 Use {@link Ext#typeOf} instead
*/
Ext.type = Ext.typeOf;
})();
/**
* @author Jacky Nguyen <jacky@sencha.com>
* @docauthor Jacky Nguyen <jacky@sencha.com>
* @class Ext.Version
*
* A utility class that wrap around a string version number and provide convenient
* method to perform comparison. See also: {@link Ext.Version#compare compare}. Example:
var version = new Ext.Version('1.0.2beta');
console.log("Version is " + version); // Version is 1.0.2beta
console.log(version.getMajor()); // 1
console.log(version.getMinor()); // 0
console.log(version.getPatch()); // 2
console.log(version.getBuild()); // 0
console.log(version.getRelease()); // beta
console.log(version.isGreaterThan('1.0.1')); // True
console.log(version.isGreaterThan('1.0.2alpha')); // True
console.log(version.isGreaterThan('1.0.2RC')); // False
console.log(version.isGreaterThan('1.0.2')); // False
console.log(version.isLessThan('1.0.2')); // True
console.log(version.match(1.0)); // True
console.log(version.match('1.0.2')); // True
* @markdown
*/
(function() {
// Current core version
var version = '4.0.0', Version;
Ext.Version = Version = Ext.extend(Object, {
/**
* @constructor
* @param {String/Number} version The version number in the follow standard format: major[.minor[.patch[.build[release]]]]
* Examples: 1.0 or 1.2.3beta or 1.2.3.4RC
* @return {Ext.Version} this
* @param version
*/
constructor: function(version) {
var parts, releaseStartIndex;
if (version instanceof Version) {
return version;
}
this.version = this.shortVersion = String(version).toLowerCase().replace(/_/g, '.').replace(/[\-+]/g, '');
releaseStartIndex = this.version.search(/([^\d\.])/);
if (releaseStartIndex !== -1) {
this.release = this.version.substr(releaseStartIndex, version.length);
this.shortVersion = this.version.substr(0, releaseStartIndex);
}
this.shortVersion = this.shortVersion.replace(/[^\d]/g, '');
parts = this.version.split('.');
this.major = parseInt(parts.shift() || 0, 10);
this.minor = parseInt(parts.shift() || 0, 10);
this.patch = parseInt(parts.shift() || 0, 10);
this.build = parseInt(parts.shift() || 0, 10);
return this;
},
/**
* Override the native toString method
* @private
* @return {String} version
*/
toString: function() {
return this.version;
},
/**
* Override the native valueOf method
* @private
* @return {String} version
*/
valueOf: function() {
return this.version;
},
/**
* Returns the major component value
* @return {Number} major
*/
getMajor: function() {
return this.major || 0;
},
/**
* Returns the minor component value
* @return {Number} minor
*/
getMinor: function() {
return this.minor || 0;
},
/**
* Returns the patch component value
* @return {Number} patch
*/
getPatch: function() {
return this.patch || 0;
},
/**
* Returns the build component value
* @return {Number} build
*/
getBuild: function() {
return this.build || 0;
},
/**
* Returns the release component value
* @return {Number} release
*/
getRelease: function() {
return this.release || '';
},
/**
* Returns whether this version if greater than the supplied argument
* @param {String/Number} target The version to compare with
* @return {Boolean} True if this version if greater than the target, false otherwise
*/
isGreaterThan: function(target) {
return Version.compare(this.version, target) === 1;
},
/**
* Returns whether this version if smaller than the supplied argument
* @param {String/Number} target The version to compare with
* @return {Boolean} True if this version if smaller than the target, false otherwise
*/
isLessThan: function(target) {
return Version.compare(this.version, target) === -1;
},
/**
* Returns whether this version equals to the supplied argument
* @param {String/Number} target The version to compare with
* @return {Boolean} True if this version equals to the target, false otherwise
*/
equals: function(target) {
return Version.compare(this.version, target) === 0;
},
/**
* Returns whether this version matches the supplied argument. Example:
* <pre><code>
* var version = new Ext.Version('1.0.2beta');
* console.log(version.match(1)); // True
* console.log(version.match(1.0)); // True
* console.log(version.match('1.0.2')); // True
* console.log(version.match('1.0.2RC')); // False
* </code></pre>
* @param {String/Number} target The version to compare with
* @return {Boolean} True if this version matches the target, false otherwise
*/
match: function(target) {
target = String(target);
return this.version.substr(0, target.length) === target;
},
/**
* Returns this format: [major, minor, patch, build, release]. Useful for comparison
* @return {Array}
*/
toArray: function() {
return [this.getMajor(), this.getMinor(), this.getPatch(), this.getBuild(), this.getRelease()];
},
/**
* Returns shortVersion version without dots and release
* @return {String}
*/
getShortVersion: function() {
return this.shortVersion;
}
});
Ext.apply(Version, {
// @private
releaseValueMap: {
'dev': -6,
'alpha': -5,
'a': -5,
'beta': -4,
'b': -4,
'rc': -3,
'#': -2,
'p': -1,
'pl': -1
},
/**
* Converts a version component to a comparable value
*
* @static
* @param {Mixed} value The value to convert
* @return {Mixed}
*/
getComponentValue: function(value) {
return !value ? 0 : (isNaN(value) ? this.releaseValueMap[value] || value : parseInt(value, 10));
},
/**
* Compare 2 specified versions, starting from left to right. If a part contains special version strings,
* they are handled in the following order:
* 'dev' < 'alpha' = 'a' < 'beta' = 'b' < 'RC' = 'rc' < '#' < 'pl' = 'p' < 'anything else'
*
* @static
* @param {String} current The current version to compare to
* @param {String} target The target version to compare to
* @return {Number} Returns -1 if the current version is smaller than the target version, 1 if greater, and 0 if they're equivalent
*/
compare: function(current, target) {
var currentValue, targetValue, i;
current = new Version(current).toArray();
target = new Version(target).toArray();
for (i = 0; i < Math.max(current.length, target.length); i++) {
currentValue = this.getComponentValue(current[i]);
targetValue = this.getComponentValue(target[i]);
if (currentValue < targetValue) {
return -1;
} else if (currentValue > targetValue) {
return 1;
}
}
return 0;
}
});
Ext.apply(Ext, {
/**
* @private
*/
versions: {},
/**
* @private
*/
lastRegisteredVersion: null,
/**
* Set version number for the given package name.
*
* @param {String} packageName The package name, for example: 'core', 'touch', 'extjs'
* @param {String/Ext.Version} version The version, for example: '1.2.3alpha', '2.4.0-dev'
* @return {Ext}
*/
setVersion: function(packageName, version) {
Ext.versions[packageName] = new Version(version);
Ext.lastRegisteredVersion = Ext.versions[packageName];
return this;
},
/**
* Get the version number of the supplied package name; will return the last registered version
* (last Ext.setVersion call) if there's no package name given.
*
* @param {String} packageName (Optional) The package name, for example: 'core', 'touch', 'extjs'
* @return {Ext.Version} The version
*/
getVersion: function(packageName) {
if (packageName === undefined) {
return Ext.lastRegisteredVersion;
}
return Ext.versions[packageName];
},
/**
* Create a closure for deprecated code.
*
// This means Ext.oldMethod is only supported in 4.0.0beta and older.
// If Ext.getVersion('extjs') returns a version that is later than '4.0.0beta', for example '4.0.0RC',
// the closure will not be invoked
Ext.deprecate('extjs', '4.0.0beta', function() {
Ext.oldMethod = Ext.newMethod;
...
});
* @param {String} packageName The package name
* @param {String} since The last version before it's deprecated
* @param {Function} closure The callback function to be executed with the specified version is less than the current version
* @param {Object} scope The execution scope (<tt>this</tt>) if the closure
* @markdown
*/
deprecate: function(packageName, since, closure, scope) {
if (Version.compare(Ext.getVersion(packageName), since) < 1) {
closure.call(scope);
}
}
}); // End Versioning
Ext.setVersion('core', version);
})();
/**
* @class Ext.String
*
* A collection of useful static methods to deal with strings
* @singleton
*/
Ext.String = {
trimRegex: /^[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]+|[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]+$/g,
escapeRe: /('|\\)/g,
formatRe: /\{(\d+)\}/g,
escapeRegexRe: /([-.*+?^${}()|[\]\/\\])/g,
/**
* Convert certain characters (&, <, >, and ') to their HTML character equivalents for literal display in web pages.
* @param {String} value The string to encode
* @return {String} The encoded text
*/
htmlEncode: (function() {
var entities = {
'&': '&',
'>': '>',
'<': '<',
'"': '"'
}, keys = [], p, regex;
for (p in entities) {
keys.push(p);
}
regex = new RegExp('(' + keys.join('|') + ')', 'g');
return function(value) {
return (!value) ? value : String(value).replace(regex, function(match, capture) {
return entities[capture];
});
};
})(),
/**
* Convert certain characters (&, <, >, and ') from their HTML character equivalents.
* @param {String} value The string to decode
* @return {String} The decoded text
*/
htmlDecode: (function() {
var entities = {
'&': '&',
'>': '>',
'<': '<',
'"': '"'
}, keys = [], p, regex;
for (p in entities) {
keys.push(p);
}
regex = new RegExp('(' + keys.join('|') + '|&#[0-9]{1,5};' + ')', 'g');
return function(value) {
return (!value) ? value : String(value).replace(regex, function(match, capture) {
if (capture in entities) {
return entities[capture];
} else {
return String.fromCharCode(parseInt(capture.substr(2), 10));
}
});
};
})(),
/**
* Appends content to the query string of a URL, handling logic for whether to place
* a question mark or ampersand.
* @param {String} url The URL to append to.
* @param {String} string The content to append to the URL.
* @return (String) The resulting URL
*/
urlAppend : function(url, string) {
if (!Ext.isEmpty(string)) {
return url + (url.indexOf('?') === -1 ? '?' : '&') + string;
}
return url;
},
/**
* Trims whitespace from either end of a string, leaving spaces within the string intact. Example:
* @example
var s = ' foo bar ';
alert('-' + s + '-'); //alerts "- foo bar -"
alert('-' + Ext.String.trim(s) + '-'); //alerts "-foo bar-"
* @param {String} string The string to escape
* @return {String} The trimmed string
*/
trim: function(string) {
return string.replace(Ext.String.trimRegex, "");
},
/**
* Capitalize the given string
* @param {String} string
* @return {String}
*/
capitalize: function(string) {
return string.charAt(0).toUpperCase() + string.substr(1);
},
/**
* Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length
* @param {String} value The string to truncate
* @param {Number} length The maximum length to allow before truncating
* @param {Boolean} word True to try to find a common word break
* @return {String} The converted text
*/
ellipsis: function(value, len, word) {
if (value && value.length > len) {
if (word) {
var vs = value.substr(0, len - 2),
index = Math.max(vs.lastIndexOf(' '), vs.lastIndexOf('.'), vs.lastIndexOf('!'), vs.lastIndexOf('?'));
if (index !== -1 && index >= (len - 15)) {
return vs.substr(0, index) + "...";
}
}
return value.substr(0, len - 3) + "...";
}
return value;
},
/**
* Escapes the passed string for use in a regular expression
* @param {String} string
* @return {String}
*/
escapeRegex: function(string) {
return string.replace(Ext.String.escapeRegexRe, "\\$1");
},
/**
* Escapes the passed string for ' and \
* @param {String} string The string to escape
* @return {String} The escaped string
*/
escape: function(string) {
return string.replace(Ext.String.escapeRe, "\\$1");
},
/**
* Utility function that allows you to easily switch a string between two alternating values. The passed value
* is compared to the current string, and if they are equal, the other value that was passed in is returned. If
* they are already different, the first value passed in is returned. Note that this method returns the new value
* but does not change the current string.
* <pre><code>
// alternate sort directions
sort = Ext.String.toggle(sort, 'ASC', 'DESC');
// instead of conditional logic:
sort = (sort == 'ASC' ? 'DESC' : 'ASC');
</code></pre>
* @param {String} string The current string
* @param {String} value The value to compare to the current string
* @param {String} other The new value to use if the string already equals the first value passed in
* @return {String} The new value
*/
toggle: function(string, value, other) {
return string === value ? other : value;
},
/**
* Pads the left side of a string with a specified character. This is especially useful
* for normalizing number and date strings. Example usage:
*
* <pre><code>
var s = Ext.String.leftPad('123', 5, '0');
// s now contains the string: '00123'
</code></pre>
* @param {String} string The original string
* @param {Number} size The total length of the output string
* @param {String} character (optional) The character with which to pad the original string (defaults to empty string " ")
* @return {String} The padded string
*/
leftPad: function(string, size, character) {
var result = String(string);
character = character || " ";
while (result.length < size) {
result = character + result;
}
return result;
},
/**
* Allows you to define a tokenized string and pass an arbitrary number of arguments to replace the tokens. Each
* token must be unique, and must increment in the format {0}, {1}, etc. Example usage:
* <pre><code>
var cls = 'my-class', text = 'Some text';
var s = Ext.String.format('<div class="{0}">{1}</div>', cls, text);
// s now contains the string: '<div class="my-class">Some text</div>'
</code></pre>
* @param {String} string The tokenized string to be formatted
* @param {String} value1 The value to replace token {0}
* @param {String} value2 Etc...
* @return {String} The formatted string
*/
format: function(format) {
var args = Ext.Array.toArray(arguments, 1);
return format.replace(Ext.String.formatRe, function(m, i) {
return args[i];
});
}
};
/**
* @class Ext.Number
*
* A collection of useful static methods to deal with numbers
* @singleton
*/
(function() {
var isToFixedBroken = (0.9).toFixed() !== '1';
Ext.Number = {
/**
* Checks whether or not the current number is within a desired range. If the number is already within the
* range it is returned, otherwise the min or max value is returned depending on which side of the range is
* exceeded. Note that this method returns the constrained value but does not change the current number.
* @param {Number} number The number to check
* @param {Number} min The minimum number in the range
* @param {Number} max The maximum number in the range
* @return {Number} The constrained value if outside the range, otherwise the current value
*/
constrain: function(number, min, max) {
number = parseFloat(number);
if (!isNaN(min)) {
number = Math.max(number, min);
}
if (!isNaN(max)) {
number = Math.min(number, max);
}
return number;
},
/**
* Formats a number using fixed-point notation
* @param {Number} value The number to format
* @param {Number} precision The number of digits to show after the decimal point
*/
toFixed: function(value, precision) {
if (isToFixedBroken) {
precision = precision || 0;
var pow = Math.pow(10, precision);
return (Math.round(value * pow) / pow).toFixed(precision);
}
return value.toFixed(precision);
},
/**
* Validate that a value is numeric and convert it to a number if necessary. Returns the specified default value if
* it is not.
Ext.Number.from('1.23', 1); // returns 1.23
Ext.Number.from('abc', 1); // returns 1
* @param {Mixed} value
* @param {Number} defaultValue The value to return if the original value is non-numeric
* @return {Number} value, if numeric, defaultValue otherwise
*/
from: function(value, defaultValue) {
if (isFinite(value)) {
value = parseFloat(value);
}
return !isNaN(value) ? value : defaultValue;
}
};
})();
/**
* This method is deprecated, please use {@link Ext.Number#from Ext.Number.from} instead
*
* @deprecated 4.0.0 Replaced by Ext.Number.from
* @member Ext
* @method num
*/
Ext.num = function() {
return Ext.Number.from.apply(this, arguments);
};
/**
* @author Jacky Nguyen <jacky@sencha.com>
* @docauthor Jacky Nguyen <jacky@sencha.com>
* @class Ext.Array
*
* A set of useful static methods to deal with arrays; provide missing methods for older browsers.
* @singleton
* @markdown
*/
(function() {
var arrayPrototype = Array.prototype,
slice = arrayPrototype.slice,
supportsForEach = 'forEach' in arrayPrototype,
supportsMap = 'map' in arrayPrototype,
supportsIndexOf = 'indexOf' in arrayPrototype,
supportsEvery = 'every' in arrayPrototype,
supportsSome = 'some' in arrayPrototype,
supportsFilter = 'filter' in arrayPrototype,
supportsSort = function() {
var a = [1,2,3,4,5].sort(function(){ return 0; });
return a[0] === 1 && a[1] === 2 && a[2] === 3 && a[3] === 4 && a[4] === 5;
}(),
supportsSliceOnNodeList = true,
ExtArray;
try {
// IE 6 - 8 will throw an error when using Array.prototype.slice on NodeList
if (typeof document !== 'undefined') {
slice.call(document.getElementsByTagName('body'));
}
} catch (e) {
supportsSliceOnNodeList = false;
}
ExtArray = Ext.Array = {
/*
* Iterates an array or an iterable value and invoke the given callback function for each item.
var countries = ['Vietnam', 'Singapore', 'United States', 'Russia'];
Ext.Array.each(countries, function(name, index, countriesItSelf) {
console.log(name);
});
var sum = function() {
var sum = 0;
Ext.Array.each(arguments, function(value) {
sum += value;
});
return sum;
};
sum(1, 2, 3); // returns 6
* The iteration can be stopped by returning false in the function callback.
Ext.Array.each(countries, function(name, index, countriesItSelf) {
if (name === 'Singapore') {
return false; // break here
}
});
* @param {Array/NodeList/Mixed} iterable The value to be iterated. If this
* argument is not iterable, the callback function is called once.
* @param {Function} fn The callback function. If it returns false, the iteration stops and this method returns
* the current `index`. Arguments passed to this callback function are:
- `item`: {Mixed} The item at the current `index` in the passed `array`
- `index`: {Number} The current `index` within the `array`
- `allItems`: {Array/NodeList/Mixed} The `array` passed as the first argument to `Ext.Array.each`
* @param {Object} scope (Optional) The scope (`this` reference) in which the specified function is executed.
* @param {Boolean} reverse (Optional) Reverse the iteration order (loop from the end to the beginning)
* Defaults false
* @return {Boolean} See description for the `fn` parameter.
* @markdown
*/
each: function(array, fn, scope, reverse) {
array = ExtArray.from(array);
var i,
ln = array.length;
if (reverse !== true) {
for (i = 0; i < ln; i++) {
if (fn.call(scope || array[i], array[i], i, array) === false) {
return i;
}
}
}
else {
for (i = ln - 1; i > -1; i--) {
if (fn.call(scope || array[i], array[i], i, array) === false) {
return i;
}
}
}
return true;
},
/**
* Iterates an array and invoke the given callback function for each item. Note that this will simply
* delegate to the native Array.prototype.forEach method if supported.
* It doesn't support stopping the iteration by returning false in the callback function like
* {@link Ext.Array#each}. However, performance could be much better in modern browsers comparing with
* {@link Ext.Array#each}
*
* @param {Array} array The array to iterate
* @param {Function} fn The function callback, to be invoked these arguments:
*
- `item`: {Mixed} The item at the current `index` in the passed `array`
- `index`: {Number} The current `index` within the `array`
- `allItems`: {Array} The `array` itself which was passed as the first argument
* @param {Object} scope (Optional) The execution scope (`this`) in which the specified function is executed.
* @markdown
*/
forEach: function(array, fn, scope) {
if (supportsForEach) {
return array.forEach(fn, scope);
}
var i = 0,
ln = array.length;
for (; i < ln; i++) {
fn.call(scope, array[i], i, array);
}
},
/**
* Get the index of the provided `item` in the given `array`, a supplement for the
* missing arrayPrototype.indexOf in Internet Explorer.
*
* @param {Array} array The array to check
* @param {Mixed} item The item to look for
* @param {Number} from (Optional) The index at which to begin the search
* @return {Number} The index of item in the array (or -1 if it is not found)
* @markdown
*/
indexOf: function(array, item, from) {
if (supportsIndexOf) {
return array.indexOf(item, from);
}
var i, length = array.length;
for (i = (from < 0) ? Math.max(0, length + from) : from || 0; i < length; i++) {
if (array[i] === item) {
return i;
}
}
return -1;
},
/**
* Checks whether or not the given `array` contains the specified `item`
*
* @param {Array} array The array to check
* @param {Mixed} item The item to look for
* @return {Boolean} True if the array contains the item, false otherwise
* @markdown
*/
contains: function(array, item) {
if (supportsIndexOf) {
return array.indexOf(item) !== -1;
}
var i, ln;
for (i = 0, ln = array.length; i < ln; i++) {
if (array[i] === item) {
return true;
}
}
return false;
},
/**
* Converts any iterable (numeric indices and a length property) into a true array.
function test() {
var args = Ext.Array.toArray(arguments),
fromSecondToLastArgs = Ext.Array.toArray(arguments, 1);
alert(args.join(' '));
alert(fromSecondToLastArgs.join(' '));
}
test('just', 'testing', 'here'); // alerts 'just testing here';
// alerts 'testing here';
Ext.Array.toArray(document.getElementsByTagName('div')); // will convert the NodeList into an array
Ext.Array.toArray('splitted'); // returns ['s', 'p', 'l', 'i', 't', 't', 'e', 'd']
Ext.Array.toArray('splitted', 0, 3); // returns ['s', 'p', 'l', 'i']
* @param {Mixed} iterable the iterable object to be turned into a true Array.
* @param {Number} start (Optional) a zero-based index that specifies the start of extraction. Defaults to 0
* @param {Number} end (Optional) a zero-based index that specifies the end of extraction. Defaults to the last
* index of the iterable value
* @return {Array} array
* @markdown
*/
toArray: function(iterable, start, end){
if (!iterable || !iterable.length) {
return [];
}
if (typeof iterable === 'string') {
iterable = iterable.split('');
}
if (supportsSliceOnNodeList) {
return slice.call(iterable, start || 0, end || iterable.length);
}
var array = [],
i;
start = start || 0;
end = end ? ((end < 0) ? iterable.length + end : end) : iterable.length;
for (i = start; i < end; i++) {
array.push(iterable[i]);
}
return array;
},
/**
* Plucks the value of a property from each item in the Array. Example:
*
Ext.Array.pluck(Ext.query("p"), "className"); // [el1.className, el2.className, ..., elN.className]
* @param {Array|NodeList} array The Array of items to pluck the value from.
* @param {String} propertyName The property name to pluck from each element.
* @return {Array} The value from each item in the Array.
*/
pluck: function(array, propertyName) {
var ret = [],
i, ln, item;
for (i = 0, ln = array.length; i < ln; i++) {
item = array[i];
ret.push(item[propertyName]);
}
return ret;
},
/**
* Creates a new array with the results of calling a provided function on every element in this array.
* @param {Array} array
* @param {Function} fn Callback function for each item
* @param {Object} scope Callback function scope
* @return {Array} results
*/
map: function(array, fn, scope) {
if (supportsMap) {
return array.map(fn, scope);
}
var results = [],
i = 0,
len = array.length;
for (; i < len; i++) {
results[i] = fn.call(scope, array[i], i, array);
}
return results;
},
/**
* Executes the specified function for each array element until the function returns a falsy value.
* If such an item is found, the function will return false immediately.
* Otherwise, it will return true.
*
* @param {Array} array
* @param {Function} fn Callback function for each item
* @param {Object} scope Callback function scope
* @return {Boolean} True if no false value is returned by the callback function.
*/
every: function(array, fn, scope) {
//<debug>
if (!fn) {
Ext.Error.raise('Ext.Array.every must have a callback function passed as second argument.');
}
//</debug>
if (supportsEvery) {
return array.every(fn, scope);
}
var i = 0,
ln = array.length;
for (; i < ln; ++i) {
if (!fn.call(scope, array[i], i, array)) {
return false;
}
}
return true;
},
/**
* Executes the specified function for each array element until the function returns a truthy value.
* If such an item is found, the function will return true immediately. Otherwise, it will return false.
*
* @param {Array} array
* @param {Function} fn Callback function for each item
* @param {Object} scope Callback function scope
* @return {Boolean} True if the callback function returns a truthy value.
*/
some: function(array, fn, scope) {
//<debug>
if (!fn) {
Ext.Error.raise('Ext.Array.some must have a callback function passed as second argument.');
}
//</debug>
if (supportsSome) {
return array.some(fn, scope);
}
var i = 0,
ln = array.length;
for (; i < ln; ++i) {
if (fn.call(scope, array[i], i, array)) {
return true;
}
}
return false;
},
/**
* Filter through an array and remove empty item as defined in {@link Ext#isEmpty Ext.isEmpty}
*
* @see Ext.Array.filter
* @param {Array} array
* @return {Array} results
*/
clean: function(array) {
var results = [],
i = 0,
ln = array.length,
item;
for (; i < ln; i++) {
item = array[i];
if (!Ext.isEmpty(item)) {
results.push(item);
}
}
return results;
},
/**
* Returns a new array with unique items
*
* @param {Array} array
* @return {Array} results
*/
unique: function(array) {
var clone = [],
i = 0,
ln = array.length,
item;
for (; i < ln; i++) {
item = array[i];
if (ExtArray.indexOf(clone, item) === -1) {
clone.push(item);
}
}
return clone;
},
/**
* Creates a new array with all of the elements of this array for which
* the provided filtering function returns true.
* @param {Array} array
* @param {Function} fn Callback function for each item
* @param {Object} scope Callback function scope
* @return {Array} results
*/
filter: function(array, fn, scope) {
if (supportsFilter) {
return array.filter(fn, scope);
}
var results = [],
i = 0,
ln = array.length;
for (; i < ln; i++) {
if (fn.call(scope, array[i], i, array)) {
results.push(array[i]);
}
}
return results;
},
/**
* Converts a value to an array if it's not already an array; returns:
*
* - An empty array if given value is `undefined` or `null`
* - Itself if given value is already an array
* - An array copy if given value is {@link Ext#isIterable iterable} (arguments, NodeList and alike)
* - An array with one item which is the given value, otherwise
*
* @param {Array/Mixed} value The value to convert to an array if it's not already is an array
* @param {Boolean} (Optional) newReference True to clone the given array and return a new reference if necessary,
* defaults to false
* @return {Array} array
* @markdown
*/
from: function(value, newReference) {
if (value === undefined || value === null) {
return [];
}
if (Ext.isArray(value)) {
return (newReference) ? slice.call(value) : value;
}
if (value && value.length !== undefined && typeof value !== 'string') {
return Ext.toArray(value);
}
return [value];
},
/**
* Removes the specified item from the array if it exists
*
* @param {Array} array The array
* @param {Mixed} item The item to remove
* @return {Array} The passed array itself
*/
remove: function(array, item) {
var index = ExtArray.indexOf(array, item);
if (index !== -1) {
array.splice(index, 1);
}
return array;
},
/**
* Push an item into the array only if the array doesn't contain it yet
*
* @param {Array} array The array
* @param {Mixed} item The item to include
* @return {Array} The passed array itself
*/
include: function(array, item) {
if (!ExtArray.contains(array, item)) {
array.push(item);
}
},
/**
* Clone a flat array without referencing the previous one. Note that this is different
* from Ext.clone since it doesn't handle recursive cloning. It's simply a convenient, easy-to-remember method
* for Array.prototype.slice.call(array)
*
* @param {Array} array The array
* @return {Array} The clone array
*/
clone: function(array) {
return slice.call(array);
},
/**
* Merge multiple arrays into one with unique items. Alias to {@link Ext.Array#union}.
*
* @param {Array} array,...
* @return {Array} merged
*/
merge: function() {
var args = slice.call(arguments),
array = [],
i, ln;
for (i = 0, ln = args.length; i < ln; i++) {
array = array.concat(args[i]);
}
return ExtArray.unique(array);
},
/**
* Merge multiple arrays into one with unique items that exist in all of the arrays.
*
* @param {Array} array,...
* @return {Array} intersect
*/
intersect: function() {
var intersect = [],
arrays = slice.call(arguments),
i, j, k, minArray, array, x, y, ln, arraysLn, arrayLn;
if (!arrays.length) {
return intersect;
}
// Find the smallest array
for (i = x = 0,ln = arrays.length; i < ln,array = arrays[i]; i++) {
if (!minArray || array.length < minArray.length) {
minArray = array;
x = i;
}
}
minArray = Ext.Array.unique(minArray);
arrays.splice(x, 1);
// Use the smallest unique'd array as the anchor loop. If the other array(s) do contain
// an item in the small array, we're likely to find it before reaching the end
// of the inner loop and can terminate the search early.
for (i = 0,ln = minArray.length; i < ln,x = minArray[i]; i++) {
var count = 0;
for (j = 0,arraysLn = arrays.length; j < arraysLn,array = arrays[j]; j++) {
for (k = 0,arrayLn = array.length; k < arrayLn,y = array[k]; k++) {
if (x === y) {
count++;
break;
}
}
}
if (count === arraysLn) {
intersect.push(x);
}
}
return intersect;
},
/**
* Perform a set difference A-B by subtracting all items in array B from array A.
*
* @param {Array} array A
* @param {Array} array B
* @return {Array} difference
*/
difference: function(arrayA, arrayB) {
var clone = slice.call(arrayA),
ln = clone.length,
i, j, lnB;
for (i = 0,lnB = arrayB.length; i < lnB; i++) {
for (j = 0; j < ln; j++) {
if (clone[j] === arrayB[i]) {
clone.splice(j, 1);
j--;
ln--;
}
}
}
return clone;
},
/**
* Sorts the elements of an Array.
* By default, this method sorts the elements alphabetically and ascending.
*
* @param {Array} array The array to sort.
* @param {Function} sortFn (optional) The comparison function.
* @return {Array} The sorted array.
*/
sort: function(array, sortFn) {
if (supportsSort) {
if (sortFn) {
return array.sort(sortFn);
} else {
return array.sort();
}
}
var length = array.length,
i = 0,
comparison,
j, min, tmp;
for (; i < length; i++) {
min = i;
for (j = i + 1; j < length; j++) {
if (sortFn) {
comparison = sortFn(array[j], array[min]);
if (comparison < 0) {
min = j;
}
} else if (array[j] < array[min]) {
min = j;
}
}
if (min !== i) {
tmp = array[i];
array[i] = array[min];
array[min] = tmp;
}
}
return array;
},
/**
* Recursively flattens into 1-d Array. Injects Arrays inline.
* @param {Array} array The array to flatten
* @return {Array} The new, flattened array.
*/
flatten: function(array) {
var worker = [];
function rFlatten(a) {
var i, ln, v;
for (i = 0, ln = a.length; i < ln; i++) {
v = a[i];
if (Ext.isArray(v)) {
rFlatten(v);
} else {
worker.push(v);
}
}
return worker;
}
return rFlatten(array);
},
/**
* Returns the minimum value in the Array.
* @param {Array|NodeList} array The Array from which to select the minimum value.
* @param {Function} comparisonFn (optional) a function to perform the comparision which determines minimization.
* If omitted the "<" operator will be used. Note: gt = 1; eq = 0; lt = -1
* @return {Mixed} minValue The minimum value
*/
min: function(array, comparisonFn) {
var min = array[0],
i, ln, item;
for (i = 0, ln = array.length; i < ln; i++) {
item = array[i];
if (comparisonFn) {
if (comparisonFn(min, item) === 1) {
min = item;
}
}
else {
if (item < min) {
min = item;
}
}
}
return min;
},
/**
* Returns the maximum value in the Array
* @param {Array|NodeList} array The Array from which to select the maximum value.
* @param {Function} comparisonFn (optional) a function to perform the comparision which determines maximization.
* If omitted the ">" operator will be used. Note: gt = 1; eq = 0; lt = -1
* @return {Mixed} maxValue The maximum value
*/
max: function(array, comparisonFn) {
var max = array[0],
i, ln, item;
for (i = 0, ln = array.length; i < ln; i++) {
item = array[i];
if (comparisonFn) {
if (comparisonFn(max, item) === -1) {
max = item;
}
}
else {
if (item > max) {
max = item;
}
}
}
return max;
},
/**
* Calculates the mean of all items in the array
* @param {Array} array The Array to calculate the mean value of.
* @return {Number} The mean.
*/
mean: function(array) {
return array.length > 0 ? ExtArray.sum(array) / array.length : undefined;
},
/**
* Calculates the sum of all items in the given array
* @param {Array} array The Array to calculate the sum value of.
* @return {Number} The sum.
*/
sum: function(array) {
var sum = 0,
i, ln, item;
for (i = 0,ln = array.length; i < ln; i++) {
item = array[i];
sum += item;
}
return sum;
}
};
/**
* Convenient alias to {@link Ext.Array#each}
* @member Ext
* @method each
*/
Ext.each = Ext.Array.each;
/**
* Alias to {@link Ext.Array#merge}.
* @member Ext.Array
* @method union
*/
Ext.Array.union = Ext.Array.merge;
/**
* Old alias to {@link Ext.Array#min}
* @deprecated 4.0.0 Use {@link Ext.Array#min} instead
* @member Ext
* @method min
*/
Ext.min = Ext.Array.min;
/**
* Old alias to {@link Ext.Array#max}
* @deprecated 4.0.0 Use {@link Ext.Array#max} instead
* @member Ext
* @method max
*/
Ext.max = Ext.Array.max;
/**
* Old alias to {@link Ext.Array#sum}
* @deprecated 4.0.0 Use {@link Ext.Array#sum} instead
* @member Ext
* @method sum
*/
Ext.sum = Ext.Array.sum;
/**
* Old alias to {@link Ext.Array#mean}
* @deprecated 4.0.0 Use {@link Ext.Array#mean} instead
* @member Ext
* @method mean
*/
Ext.mean = Ext.Array.mean;
/**
* Old alias to {@link Ext.Array#flatten}
* @deprecated 4.0.0 Use {@link Ext.Array#flatten} instead
* @member Ext
* @method flatten
*/
Ext.flatten = Ext.Array.flatten;
/**
* Old alias to {@link Ext.Array#clean Ext.Array.clean}
* @deprecated 4.0.0 Use {@link Ext.Array.clean} instead
* @member Ext
* @method clean
*/
Ext.clean = Ext.Array.clean;
/**
* Old alias to {@link Ext.Array#unique Ext.Array.unique}
* @deprecated 4.0.0 Use {@link Ext.Array.unique} instead
* @member Ext
* @method unique
*/
Ext.unique = Ext.Array.unique;
/**
* Old alias to {@link Ext.Array#pluck Ext.Array.pluck}
* @deprecated 4.0.0 Use {@link Ext.Array#pluck Ext.Array.pluck} instead
* @member Ext
* @method pluck
*/
Ext.pluck = Ext.Array.pluck;
/**
* Convenient alias to {@link Ext.Array#toArray Ext.Array.toArray}
* @param {Iterable} the iterable object to be turned into a true Array.
* @member Ext
* @method toArray
* @return {Array} array
*/
Ext.toArray = function() {
return ExtArray.toArray.apply(ExtArray, arguments);
}
})();
/**
* @class Ext.Function
*
* A collection of useful static methods to deal with function callbacks
* @singleton
*/
Ext.Function = {
/**
* A very commonly used method throughout the framework. It acts as a wrapper around another method
* which originally accepts 2 arguments for <code>name</code> and <code>value</code>.
* The wrapped function then allows "flexible" value setting of either:
*
* <ul>
* <li><code>name</code> and <code>value</code> as 2 arguments</li>
* <li>one single object argument with multiple key - value pairs</li>
* </ul>
*
* For example:
* <pre><code>
var setValue = Ext.Function.flexSetter(function(name, value) {
this[name] = value;
});
// Afterwards
// Setting a single name - value
setValue('name1', 'value1');
// Settings multiple name - value pairs
setValue({
name1: 'value1',
name2: 'value2',
name3: 'value3'
});
* </code></pre>
* @param {Function} setter
* @returns {Function} flexSetter
*/
flexSetter: function(fn) {
return function(a, b) {
var k, i;
if (a === null) {
return this;
}
if (typeof a !== 'string') {
for (k in a) {
if (a.hasOwnProperty(k)) {
fn.call(this, k, a[k]);
}
}
if (Ext.enumerables) {
for (i = Ext.enumerables.length; i--;) {
k = Ext.enumerables[i];
if (a.hasOwnProperty(k)) {
fn.call(this, k, a[k]);
}
}
}
} else {
fn.call(this, a, b);
}
return this;
};
},
/**
* Create a new function from the provided <code>fn</code>, change <code>this</code> to the provided scope, optionally
* overrides arguments for the call. (Defaults to the arguments passed by the caller)
*
* @param {Function} fn The function to delegate.
* @param {Object} scope (optional) The scope (<code><b>this</b></code> reference) in which the function is executed.
* <b>If omitted, defaults to the browser window.</b>
* @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
* @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
* if a number the args are inserted at the specified position
* @return {Function} The new function
*/
bind: function(fn, scope, args, appendArgs) {
var method = fn,
applyArgs;
return function() {
var callArgs = args || arguments;
if (appendArgs === true) {
callArgs = Array.prototype.slice.call(arguments, 0);
callArgs = callArgs.concat(args);
}
else if (Ext.isNumber(appendArgs)) {
callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first
applyArgs = [appendArgs, 0].concat(args); // create method call params
Array.prototype.splice.apply(callArgs, applyArgs); // splice them in
}
return method.apply(scope || window, callArgs);
};
},
/**
* Create a new function from the provided <code>fn</code>, the arguments of which are pre-set to `args`.
* New arguments passed to the newly created callback when it's invoked are appended after the pre-set ones.
* This is especially useful when creating callbacks.
* For example:
*
var originalFunction = function(){
alert(Ext.Array.from(arguments).join(' '));
};
var callback = Ext.Function.pass(originalFunction, ['Hello', 'World']);
callback(); // alerts 'Hello World'
callback('by Me'); // alerts 'Hello World by Me'
* @param {Function} fn The original function
* @param {Array} args The arguments to pass to new callback
* @param {Object} scope (optional) The scope (<code><b>this</b></code> reference) in which the function is executed.
* @return {Function} The new callback function
*/
pass: function(fn, args, scope) {
if (args) {
args = Ext.Array.from(args);
}
return function() {
return fn.apply(scope, args.concat(Ext.Array.toArray(arguments)));
};
},
/**
* Create an alias to the provided method property with name <code>methodName</code> of <code>object</code>.
* Note that the execution scope will still be bound to the provided <code>object</code> itself.
*
* @param {Object/Function} object
* @param {String} methodName
* @return {Function} aliasFn
*/
alias: function(object, methodName) {
return function() {
return object[methodName].apply(object, arguments);
};
},
/**
* Creates an interceptor function. The passed function is called before the original one. If it returns false,
* the original one is not called. The resulting function returns the results of the original function.
* The passed function is called with the parameters of the original function. Example usage:
* <pre><code>
var sayHi = function(name){
alert('Hi, ' + name);
}
sayHi('Fred'); // alerts "Hi, Fred"
// create a new function that validates input without
// directly modifying the original function:
var sayHiToFriend = Ext.Function.createInterceptor(sayHi, function(name){
return name == 'Brian';
});
sayHiToFriend('Fred'); // no alert
sayHiToFriend('Brian'); // alerts "Hi, Brian"
</code></pre>
* @param {Function} origFn The original function.
* @param {Function} newFn The function to call before the original
* @param {Object} scope (optional) The scope (<code><b>this</b></code> reference) in which the passed function is executed.
* <b>If omitted, defaults to the scope in which the original function is called or the browser window.</b>
* @param {Mixed} returnValue (optional) The value to return if the passed function return false (defaults to null).
* @return {Function} The new function
*/
createInterceptor: function(origFn, newFn, scope, returnValue) {
var method = origFn;
if (!Ext.isFunction(newFn)) {
return origFn;
}
else {
return function() {
var me = this,
args = arguments;
newFn.target = me;
newFn.method = origFn;
return (newFn.apply(scope || me || window, args) !== false) ? origFn.apply(me || window, args) : returnValue || null;
};
}
},
/**
* Creates a delegate (callback) which, when called, executes after a specific delay.
* @param {Function} fn The function which will be called on a delay when the returned function is called.
* Optionally, a replacement (or additional) argument list may be specified.
* @param {Number} delay The number of milliseconds to defer execution by whenever called.
* @param {Object} scope (optional) The scope (<code>this</code> reference) used by the function at execution time.
* @param {Array} args (optional) Override arguments for the call. (Defaults to the arguments passed by the caller)
* @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
* if a number the args are inserted at the specified position.
* @return {Function} A function which, when called, executes the original function after the specified delay.
*/
createDelayed: function(fn, delay, scope, args, appendArgs) {
if (scope || args) {
fn = Ext.Function.bind(fn, scope, args, appendArgs);
}
return function() {
var me = this;
setTimeout(function() {
fn.apply(me, arguments);
}, delay);
};
},
/**
* Calls this function after the number of millseconds specified, optionally in a specific scope. Example usage:
* <pre><code>
var sayHi = function(name){
alert('Hi, ' + name);
}
// executes immediately:
sayHi('Fred');
// executes after 2 seconds:
Ext.Function.defer(sayHi, 2000, this, ['Fred']);
// this syntax is sometimes useful for deferring
// execution of an anonymous function:
Ext.Function.defer(function(){
alert('Anonymous');
}, 100);
</code></pre>
* @param {Function} fn The function to defer.
* @param {Number} millis The number of milliseconds for the setTimeout call (if less than or equal to 0 the function is executed immediately)
* @param {Object} scope (optional) The scope (<code><b>this</b></code> reference) in which the function is executed.
* <b>If omitted, defaults to the browser window.</b>
* @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller)
* @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding,
* if a number the args are inserted at the specified position
* @return {Number} The timeout id that can be used with clearTimeout
*/
defer: function(fn, millis, obj, args, appendArgs) {
fn = Ext.Function.bind(fn, obj, args, appendArgs);
if (millis > 0) {
return setTimeout(fn, millis);
}
fn();
return 0;
},
/**
* Create a combined function call sequence of the original function + the passed function.
* The resulting function returns the results of the original function.
* The passed function is called with the parameters of the original function. Example usage:
*
* <pre><code>
var sayHi = function(name){
alert('Hi, ' + name);
}
sayHi('Fred'); // alerts "Hi, Fred"
var sayGoodbye = Ext.Function.createSequence(sayHi, function(name){
alert('Bye, ' + name);
});
sayGoodbye('Fred'); // both alerts show
* </code></pre>
*
* @param {Function} origFn The original function.
* @param {Function} newFn The function to sequence
* @param {Object} scope (optional) The scope (this reference) in which the passed function is executed.
* If omitted, defaults to the scope in which the original function is called or the browser window.
* @return {Function} The new function
*/
createSequence: function(origFn, newFn, scope) {
if (!Ext.isFunction(newFn)) {
return origFn;
}
else {
return function() {
var retval = origFn.apply(this || window, arguments);
newFn.apply(scope || this || window, arguments);
return retval;
};
}
},
/**
* <p>Creates a delegate function, optionally with a bound scope which, when called, buffers
* the execution of the passed function for the configured number of milliseconds.
* If called again within that period, the impending invocation will be canceled, and the
* timeout period will begin again.</p>
*
* @param {Function} fn The function to invoke on a buffered timer.
* @param {Number} buffer The number of milliseconds by which to buffer the invocation of the
* function.
* @param {Object} scope (optional) The scope (<code><b>this</b></code> reference) in which
* the passed function is executed. If omitted, defaults to the scope specified by the caller.
* @param {Array} args (optional) Override arguments for the call. Defaults to the arguments
* passed by the caller.
* @return {Function} A function which invokes the passed function after buffering for the specified time.
*/
createBuffered: function(fn, buffer, scope, args) {
return function(){
var timerId;
return function() {
var me = this;
if (timerId) {
clearInterval(timerId);
timerId = null;
}
timerId = setTimeout(function(){
fn.apply(scope || me, args || arguments);
}, buffer);
};
}();
},
/**
* <p>Creates a throttled version of the passed function which, when called repeatedly and
* rapidly, invokes the passed function only after a certain interval has elapsed since the
* previous invocation.</p>
*
* <p>This is useful for wrapping functions which may be called repeatedly, such as
* a handler of a mouse move event when the processing is expensive.</p>
*
* @param fn {Function} The function to execute at a regular time interval.
* @param interval {Number} The interval <b>in milliseconds</b> on which the passed function is executed.
* @param scope (optional) The scope (<code><b>this</b></code> reference) in which
* the passed function is executed. If omitted, defaults to the scope specified by the caller.
* @returns {Function} A function which invokes the passed function at the specified interval.
*/
createThrottled: function(fn, interval, scope) {
var lastCallTime, elapsed, lastArgs, timer, execute = function() {
fn.apply(scope || this, lastArgs);
lastCallTime = new Date().getTime();
};
return function() {
elapsed = new Date().getTime() - lastCallTime;
lastArgs = arguments;
clearTimeout(timer);
if (!lastCallTime || (elapsed >= interval)) {
execute();
} else {
timer = setTimeout(execute, interval - elapsed);
}
};
}
};
/**
* Shorthand for {@link Ext.Function#defer}
* @member Ext
* @method defer
*/
Ext.defer = Ext.Function.alias(Ext.Function, 'defer');
/**
* Shorthand for {@link Ext.Function#pass}
* @member Ext
* @method pass
*/
Ext.pass = Ext.Function.alias(Ext.Function, 'pass');
/**
* Shorthand for {@link Ext.Function#bind}
* @member Ext
* @method bind
*/
Ext.bind = Ext.Function.alias(Ext.Function, 'bind');
/**
* @author Jacky Nguyen <jacky@sencha.com>
* @docauthor Jacky Nguyen <jacky@sencha.com>
* @class Ext.Object
*
* A collection of useful static methods to deal with objects
*
* @singleton
*/
(function() {
var ExtObject = Ext.Object = {
/**
* Convert a `name` - `value` pair to an array of objects with support for nested structures; useful to construct
* query strings. For example:
var objects = Ext.Object.toQueryObjects('hobbies', ['reading', 'cooking', 'swimming']);
// objects then equals:
[
{ name: 'hobbies', value: 'reading' },
{ name: 'hobbies', value: 'cooking' },
{ name: 'hobbies', value: 'swimming' },
];
var objects = Ext.Object.toQueryObjects('dateOfBirth', {
day: 3,
month: 8,
year: 1987,
extra: {
hour: 4
minute: 30
}
}, true); // Recursive
// objects then equals:
[
{ name: 'dateOfBirth[day]', value: 3 },
{ name: 'dateOfBirth[month]', value: 8 },
{ name: 'dateOfBirth[year]', value: 1987 },
{ name: 'dateOfBirth[extra][hour]', value: 4 },
{ name: 'dateOfBirth[extra][minute]', value: 30 },
];
* @param {String} name
* @param {Mixed} value
* @param {Boolean} recursive
* @markdown
*/
toQueryObjects: function(name, value, recursive) {
var self = ExtObject.toQueryObjects,
objects = [],
i, ln;
if (Ext.isArray(value)) {
for (i = 0, ln = value.length; i < ln; i++) {
if (recursive) {
objects = objects.concat(self(name + '[' + i + ']', value[i], true));
}
else {
objects.push({
name: name,
value: value[i]
});
}
}
}
else if (Ext.isObject(value)) {
for (i in value) {
if (value.hasOwnProperty(i)) {
if (recursive) {
objects = objects.concat(self(name + '[' + i + ']', value[i], true));
}
else {
objects.push({
name: name,
value: value[i]
});
}
}
}
}
else {
objects.push({
name: name,
value: value
});
}
return objects;
},
/**
* Takes an object and converts it to an encoded query string
- Non-recursive:
Ext.Object.toQueryString({foo: 1, bar: 2}); // returns "foo=1&bar=2"
Ext.Object.toQueryString({foo: null, bar: 2}); // returns "foo=&bar=2"
Ext.Object.toQueryString({'some price': '$300'}); // returns "some%20price=%24300"
Ext.Object.toQueryString({date: new Date(2011, 0, 1)}); // returns "date=%222011-01-01T00%3A00%3A00%22"
Ext.Object.toQueryString({colors: ['red', 'green', 'blue']}); // returns "colors=red&colors=green&colors=blue"
- Recursive:
Ext.Object.toQueryString({
username: 'Jacky',
dateOfBirth: {
day: 1,
month: 2,
year: 1911
},
hobbies: ['coding', 'eating', 'sleeping', ['nested', 'stuff']]
}, true); // returns the following string (broken down and url-decoded for ease of reading purpose):
// username=Jacky
// &dateOfBirth[day]=1&dateOfBirth[month]=2&dateOfBirth[year]=1911
// &hobbies[0]=coding&hobbies[1]=eating&hobbies[2]=sleeping&hobbies[3][0]=nested&hobbies[3][1]=stuff
*
* @param {Object} object The object to encode
* @param {Boolean} recursive (optional) Whether or not to interpret the object in recursive format.
* (PHP / Ruby on Rails servers and similar). Defaults to false
* @return {String} queryString
* @markdown
*/
toQueryString: function(object, recursive) {
var paramObjects = [],
params = [],
i, j, ln, paramObject, value;
for (i in object) {
if (object.hasOwnProperty(i)) {
paramObjects = paramObjects.concat(ExtObject.toQueryObjects(i, object[i], recursive));
}
}
for (j = 0, ln = paramObjects.length; j < ln; j++) {
paramObject = paramObjects[j];
value = paramObject.value;
if (Ext.isEmpty(value)) {
value = '';
}
else if (Ext.isDate(value)) {
value = Ext.Date.toString(value);
}
params.push(encodeURIComponent(paramObject.name) + '=' + encodeURIComponent(String(value)));
}
return params.join('&');
},
/**
* Converts a query string back into an object.
*
- Non-recursive:
Ext.Object.fromQueryString(foo=1&bar=2); // returns {foo: 1, bar: 2}
Ext.Object.fromQueryString(foo=&bar=2); // returns {foo: null, bar: 2}
Ext.Object.fromQueryString(some%20price=%24300); // returns {'some price': '$300'}
Ext.Object.fromQueryString(colors=red&colors=green&colors=blue); // returns {colors: ['red', 'green', 'blue']}
- Recursive:
Ext.Object.fromQueryString("username=Jacky&dateOfBirth[day]=1&dateOfBirth[month]=2&dateOfBirth[year]=1911&hobbies[0]=coding&hobbies[1]=eating&hobbies[2]=sleeping&hobbies[3][0]=nested&hobbies[3][1]=stuff", true);
// returns
{
username: 'Jacky',
dateOfBirth: {
day: '1',
month: '2',
year: '1911'
},
hobbies: ['coding', 'eating', 'sleeping', ['nested', 'stuff']]
}
* @param {String} queryString The query string to decode
* @param {Boolean} recursive (Optional) Whether or not to recursively decode the string. This format is supported by
* PHP / Ruby on Rails servers and similar. Defaults to false
* @return {Object}
*/
fromQueryString: function(queryString, recursive) {
var parts = queryString.replace(/^\?/, '').split('&'),
object = {},
temp, components, name, value, i, ln,
part, j, subLn, matchedKeys, matchedName,
keys, key, nextKey;
for (i = 0, ln = parts.length; i < ln; i++) {
part = parts[i];
if (part.length > 0) {
components = part.split('=');
name = decodeURIComponent(components[0]);
value = (components[1] !== undefined) ? decodeURIComponent(components[1]) : '';
if (!recursive) {
if (object.hasOwnProperty(name)) {
if (!Ext.isArray(object[name])) {
object[name] = [object[name]];
}
object[name].push(value);
}
else {
object[name] = value;
}
}
else {
matchedKeys = name.match(/(\[):?([^\]]*)\]/g);
matchedName = name.match(/^([^\[]+)/);
//<debug error>
if (!matchedName) {
Ext.Error.raise({
sourceClass: "Ext.Object",
sourceMethod: "fromQueryString",
queryString: queryString,
recursive: recursive,
msg: 'Malformed query string given, failed parsing name from "' + part + '"'
});
}
//</debug>
name = matchedName[0];
keys = [];
if (matchedKeys === null) {
object[name] = value;
continue;
}
for (j = 0, subLn = matchedKeys.length; j < subLn; j++) {
key = matchedKeys[j];
key = (key.length === 2) ? '' : key.substring(1, key.length - 1);
keys.push(key);
}
keys.unshift(name);
temp = object;
for (j = 0, subLn = keys.length; j < subLn; j++) {
key = keys[j];
if (j === subLn - 1) {
if (Ext.isArray(temp) && key === '') {
temp.push(value);
}
else {
temp[key] = value;
}
}
else {
if (temp[key] === undefined || typeof temp[key] === 'string') {
nextKey = keys[j+1];
temp[key] = (Ext.isNumeric(nextKey) || nextKey === '') ? [] : {};
}
temp = temp[key];
}
}
}
}
}
return object;
},
/**
* Iterate through an object and invoke the given callback function for each iteration. The iteration can be stop
* by returning `false` in the callback function. For example:
var person = {
name: 'Jacky'
hairColor: 'black'
loves: ['food', 'sleeping', 'wife']
};
Ext.Object.each(person, function(key, value, myself) {
console.log(key + ":" + value);
if (key === 'hairColor') {
return false; // stop the iteration
}
});
* @param {Object} object The object to iterate
* @param {Function} fn The callback function. Passed arguments for each iteration are:
- {String} `key`
- {Mixed} `value`
- {Object} `object` The object itself
* @param {Object} scope (Optional) The execution scope (`this`) of the callback function
* @markdown
*/
each: function(object, fn, scope) {
for (var property in object) {
if (object.hasOwnProperty(property)) {
if (fn.call(scope || object, property, object[property], object) === false) {
return;
}
}
}
},
/**
* Merges any number of objects recursively without referencing them or their children.
var extjs = {
companyName: 'Ext JS',
products: ['Ext JS', 'Ext GWT', 'Ext Designer'],
isSuperCool: true
office: {
size: 2000,
location: 'Palo Alto',
isFun: true
}
};
var newStuff = {
companyName: 'Sencha Inc.',
products: ['Ext JS', 'Ext GWT', 'Ext Designer', 'Sencha Touch', 'Sencha Animator'],
office: {
size: 40000,
location: 'Redwood City'
}
};
var sencha = Ext.Object.merge(extjs, newStuff);
// extjs and sencha then equals to
{
companyName: 'Sencha Inc.',
products: ['Ext JS', 'Ext GWT', 'Ext Designer', 'Sencha Touch', 'Sencha Animator'],
isSuperCool: true
office: {
size: 30000,
location: 'Redwood City'
isFun: true
}
}
* @param {Object} object,...
* @return {Object} merged The object that is created as a result of merging all the objects passed in.
* @markdown
*/
merge: function(source, key, value) {
if (typeof key === 'string') {
if (value && value.constructor === Object) {
if (source[key] && source[key].constructor === Object) {
ExtObject.merge(source[key], value);
}
else {
source[key] = Ext.clone(value);
}
}
else {
source[key] = value;
}
return source;
}
var i = 1,
ln = arguments.length,
object, property;
for (; i < ln; i++) {
object = arguments[i];
for (property in object) {
if (object.hasOwnProperty(property)) {
ExtObject.merge(source, property, object[property]);
}
}
}
return source;
},
/**
* Returns the first matching key corresponding to the given value.
* If no matching value is found, null is returned.
var person = {
name: 'Jacky',
loves: 'food'
};
alert(Ext.Object.getKey(sencha, 'loves')); // alerts 'food'
* @param {Object} object
* @param {Object} value The value to find
* @markdown
*/
getKey: function(object, value) {
for (var property in object) {
if (object.hasOwnProperty(property) && object[property] === value) {
return property;
}
}
return null;
},
/**
* Gets all values of the given object as an array.
var values = Ext.Object.getValues({
name: 'Jacky',
loves: 'food'
}); // ['Jacky', 'food']
* @param {Object} object
* @return {Array} An array of values from the object
* @markdown
*/
getValues: function(object) {
var values = [],
property;
for (property in object) {
if (object.hasOwnProperty(property)) {
values.push(object[property]);
}
}
return values;
},
/**
* Gets all keys of the given object as an array.
var values = Ext.Object.getKeys({
name: 'Jacky',
loves: 'food'
}); // ['name', 'loves']
* @param {Object} object
* @return {Array} An array of keys from the object
*/
getKeys: ('keys' in Object.prototype) ? Object.keys : function(object) {
var keys = [],
property;
for (property in object) {
if (object.hasOwnProperty(property)) {
keys.push(property);
}
}
return keys;
},
/**
* Gets the total number of this object's own properties
var size = Ext.Object.getSize({
name: 'Jacky',
loves: 'food'
}); // size equals 2
* @param {Object} object
* @return {Number} size
* @markdown
*/
getSize: function(object) {
var size = 0,
property;
for (property in object) {
if (object.hasOwnProperty(property)) {
size++;
}
}
return size;
}
};
/**
* A convenient alias method for {@link Ext.Object#merge}
*
* @member Ext
* @method merge
*/
Ext.merge = Ext.Object.merge;
/**
* A convenient alias method for {@link Ext.Object#toQueryString}
*
* @member Ext
* @method urlEncode
* @deprecated 4.0.0 Use {@link Ext.Object#toQueryString Ext.Object.toQueryString} instead
*/
Ext.urlEncode = function() {
var args = Ext.Array.from(arguments),
prefix = '';
// Support for the old `pre` argument
if ((typeof args[1] === 'string')) {
prefix = args[1] + '&';
args[1] = false;
}
return prefix + Ext.Object.toQueryString.apply(Ext.Object, args);
};
/**
* A convenient alias method for {@link Ext.Object#fromQueryString}
*
* @member Ext
* @method urlDecode
* @deprecated 4.0.0 Use {@link Ext.Object#fromQueryString Ext.Object.fromQueryString} instead
*/
Ext.urlDecode = function() {
return Ext.Object.fromQueryString.apply(Ext.Object, arguments);
};
})();
/**
* @class Ext.Date
* A set of useful static methods to deal with date
* Note that if Ext.Date is required and loaded, it will copy all methods / properties to
* this object for convenience
*
* The date parsing and formatting syntax contains a subset of
* <a href="http://www.php.net/date">PHP's date() function</a>, and the formats that are
* supported will provide results equivalent to their PHP versions.
*
* The following is a list of all currently supported formats:
* <pre class="">
Format Description Example returned values
------ ----------------------------------------------------------------------- -----------------------
d Day of the month, 2 digits with leading zeros 01 to 31
D A short textual representation of the day of the week Mon to Sun
j Day of the month without leading zeros 1 to 31
l A full textual representation of the day of the week Sunday to Saturday
N ISO-8601 numeric representation of the day of the week 1 (for Monday) through 7 (for Sunday)
S English ordinal suffix for the day of the month, 2 characters st, nd, rd or th. Works well with j
w Numeric representation of the day of the week 0 (for Sunday) to 6 (for Saturday)
z The day of the year (starting from 0) 0 to 364 (365 in leap years)
W ISO-8601 week number of year, weeks starting on Monday 01 to 53
F A full textual representation of a month, such as January or March January to December
m Numeric representation of a month, with leading zeros 01 to 12
M A short textual representation of a month Jan to Dec
n Numeric representation of a month, without leading zeros 1 to 12
t Number of days in the given month 28 to 31
L Whether it's a leap year 1 if it is a leap year, 0 otherwise.
o ISO-8601 year number (identical to (Y), but if the ISO week number (W) Examples: 1998 or 2004
belongs to the previous or next year, that year is used instead)
Y A full numeric representation of a year, 4 digits Examples: 1999 or 2003
y A two digit representation of a year Examples: 99 or 03
a Lowercase Ante meridiem and Post meridiem am or pm
A Uppercase Ante meridiem and Post meridiem AM or PM
g 12-hour format of an hour without leading zeros 1 to 12
G 24-hour format of an hour without leading zeros 0 to 23
h 12-hour format of an hour with leading zeros 01 to 12
H 24-hour format of an hour with leading zeros 00 to 23
i Minutes, with leading zeros 00 to 59
s Seconds, with leading zeros 00 to 59
u Decimal fraction of a second Examples:
(minimum 1 digit, arbitrary number of digits allowed) 001 (i.e. 0.001s) or
100 (i.e. 0.100s) or
999 (i.e. 0.999s) or
999876543210 (i.e. 0.999876543210s)
O Difference to Greenwich time (GMT) in hours and minutes Example: +1030
P Difference to Greenwich time (GMT) with colon between hours and minutes Example: -08:00
T Timezone abbreviation of the machine running the code Examples: EST, MDT, PDT ...
Z Timezone offset in seconds (negative if west of UTC, positive if east) -43200 to 50400
c ISO 8601 date
Notes: Examples:
1) If unspecified, the month / day defaults to the current month / day, 1991 or
the time defaults to midnight, while the timezone defaults to the 1992-10 or
browser's timezone. If a time is specified, it must include both hours 1993-09-20 or
and minutes. The "T" delimiter, seconds, milliseconds and timezone 1994-08-19T16:20+01:00 or
are optional. 1995-07-18T17:21:28-02:00 or
2) The decimal fraction of a second, if specified, must contain at 1996-06-17T18:22:29.98765+03:00 or
least 1 digit (there is no limit to the maximum number 1997-05-16T19:23:30,12345-0400 or
of digits allowed), and may be delimited by either a '.' or a ',' 1998-04-15T20:24:31.2468Z or
Refer to the examples on the right for the various levels of 1999-03-14T20:24:32Z or
date-time granularity which are supported, or see 2000-02-13T21:25:33
http://www.w3.org/TR/NOTE-datetime for more info. 2001-01-12 22:26:34
U Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) 1193432466 or -2138434463
MS Microsoft AJAX serialized dates \/Date(1238606590509)\/ (i.e. UTC milliseconds since epoch) or
\/Date(1238606590509+0800)\/
</pre>
*
* Example usage (note that you must escape format specifiers with '\\' to render them as character literals):
* <pre><code>
// Sample date:
// 'Wed Jan 10 2007 15:05:01 GMT-0600 (Central Standard Time)'
var dt = new Date('1/10/2007 03:05:01 PM GMT-0600');
console.log(Ext.Date.format(dt, 'Y-m-d')); // 2007-01-10
console.log(Ext.Date.format(dt, 'F j, Y, g:i a')); // January 10, 2007, 3:05 pm
console.log(Ext.Date.format(dt, 'l, \\t\\he jS \\of F Y h:i:s A')); // Wednesday, the 10th of January 2007 03:05:01 PM
</code></pre>
*
* Here are some standard date/time patterns that you might find helpful. They
* are not part of the source of Ext.Date, but to use them you can simply copy this
* block of code into any script that is included after Ext.Date and they will also become
* globally available on the Date object. Feel free to add or remove patterns as needed in your code.
* <pre><code>
Ext.Date.patterns = {
ISO8601Long:"Y-m-d H:i:s",
ISO8601Short:"Y-m-d",
ShortDate: "n/j/Y",
LongDate: "l, F d, Y",
FullDateTime: "l, F d, Y g:i:s A",
MonthDay: "F d",
ShortTime: "g:i A",
LongTime: "g:i:s A",
SortableDateTime: "Y-m-d\\TH:i:s",
UniversalSortableDateTime: "Y-m-d H:i:sO",
YearMonth: "F, Y"
};
</code></pre>
*
* Example usage:
* <pre><code>
var dt = new Date();
console.log(Ext.Date.format(dt, Ext.Date.patterns.ShortDate));
</code></pre>
* <p>Developer-written, custom formats may be used by supplying both a formatting and a parsing function
* which perform to specialized requirements. The functions are stored in {@link #parseFunctions} and {@link #formatFunctions}.</p>
* @singleton
*/
/*
* Most of the date-formatting functions below are the excellent work of Baron Schwartz.
* (see http://www.xaprb.com/blog/2005/12/12/javascript-closures-for-runtime-efficiency/)
* They generate precompiled functions from format patterns instead of parsing and
* processing each pattern every time a date is formatted. These functions are available
* on every Date object.
*/
(function() {
// create private copy of Ext's Ext.util.Format.format() method
// - to remove unnecessary dependency
// - to resolve namespace conflict with MS-Ajax's implementation
function xf(format) {
var args = Array.prototype.slice.call(arguments, 1);
return format.replace(/\{(\d+)\}/g, function(m, i) {
return args[i];
});
}
Ext.Date = {
/**
* Returns the current timestamp
* @return {Date} The current timestamp
*/
now: Date.now || function() {
return +new Date();
},
/**
* @private
* Private for now
*/
toString: function(date) {
var pad = Ext.String.leftPad;
return date.getFullYear() + "-"
+ pad(date.getMonth() + 1, 2, '0') + "-"
+ pad(date.getDate(), 2, '0') + "T"
+ pad(date.getHours(), 2, '0') + ":"
+ pad(date.getMinutes(), 2, '0') + ":"
+ pad(date.getSeconds(), 2, '0');
},
/**
* Returns the number of milliseconds between two dates
* @param {Date} dateA The first date
* @param {Date} dateB (optional) The second date, defaults to now
* @return {Number} The difference in milliseconds
*/
getElapsed: function(dateA, dateB) {
return Math.abs(dateA - (dateB || new Date()));
},
/**
* Global flag which determines if strict date parsing should be used.
* Strict date parsing will not roll-over invalid dates, which is the
* default behaviour of javascript Date objects.
* (see {@link #parse} for more information)
* Defaults to <tt>false</tt>.
* @static
* @type Boolean
*/
useStrict: false,
// private
formatCodeToRegex: function(character, currentGroup) {
// Note: currentGroup - position in regex result array (see notes for Ext.Date.parseCodes below)
var p = utilDate.parseCodes[character];
if (p) {
p = typeof p == 'function'? p() : p;
utilDate.parseCodes[character] = p; // reassign function result to prevent repeated execution
}
return p ? Ext.applyIf({
c: p.c ? xf(p.c, currentGroup || "{0}") : p.c
}, p) : {
g: 0,
c: null,
s: Ext.String.escapeRegex(character) // treat unrecognised characters as literals
};
},
/**
* <p>An object hash in which each property is a date parsing function. The property name is the
* format string which that function parses.</p>
* <p>This object is automatically populated with date parsing functions as
* date formats are requested for Ext standard formatting strings.</p>
* <p>Custom parsing functions may be inserted into this object, keyed by a name which from then on
* may be used as a format string to {@link #parse}.<p>
* <p>Example:</p><pre><code>
Ext.Date.parseFunctions['x-date-format'] = myDateParser;
</code></pre>
* <p>A parsing function should return a Date object, and is passed the following parameters:<div class="mdetail-params"><ul>
* <li><code>date</code> : String<div class="sub-desc">The date string to parse.</div></li>
* <li><code>strict</code> : Boolean<div class="sub-desc">True to validate date strings while parsing
* (i.e. prevent javascript Date "rollover") (The default must be false).
* Invalid date strings should return null when parsed.</div></li>
* </ul></div></p>
* <p>To enable Dates to also be <i>formatted</i> according to that format, a corresponding
* formatting function must be placed into the {@link #formatFunctions} property.
* @property parseFunctions
* @static
* @type Object
*/
parseFunctions: {
"MS": function(input, strict) {
// note: the timezone offset is ignored since the MS Ajax server sends
// a UTC milliseconds-since-Unix-epoch value (negative values are allowed)
var re = new RegExp('\\/Date\\(([-+])?(\\d+)(?:[+-]\\d{4})?\\)\\/');
var r = (input || '').match(re);
return r? new Date(((r[1] || '') + r[2]) * 1) : null;
}
},
parseRegexes: [],
/**
* <p>An object hash in which each property is a date formatting function. The property name is the
* format string which corresponds to the produced formatted date string.</p>
* <p>This object is automatically populated with date formatting functions as
* date formats are requested for Ext standard formatting strings.</p>
* <p>Custom formatting functions may be inserted into this object, keyed by a name which from then on
* may be used as a format string to {@link #format}. Example:</p><pre><code>
Ext.Date.formatFunctions['x-date-format'] = myDateFormatter;
</code></pre>
* <p>A formatting function should return a string representation of the passed Date object, and is passed the following parameters:<div class="mdetail-params"><ul>
* <li><code>date</code> : Date<div class="sub-desc">The Date to format.</div></li>
* </ul></div></p>
* <p>To enable date strings to also be <i>parsed</i> according to that format, a corresponding
* parsing function must be placed into the {@link #parseFunctions} property.
* @property formatFunctions
* @static
* @type Object
*/
formatFunctions: {
"MS": function() {
// UTC milliseconds since Unix epoch (MS-AJAX serialized date format (MRSF))
return '\\/Date(' + this.getTime() + ')\\/';
}
},
y2kYear : 50,
/**
* Date interval constant
* @static
* @type String
*/
MILLI : "ms",
/**
* Date interval constant
* @static
* @type String
*/
SECOND : "s",
/**
* Date interval constant
* @static
* @type String
*/
MINUTE : "mi",
/** Date interval constant
* @static
* @type String
*/
HOUR : "h",
/**
* Date interval constant
* @static
* @type String
*/
DAY : "d",
/**
* Date interval constant
* @static
* @type String
*/
MONTH : "mo",
/**
* Date interval constant
* @static
* @type String
*/
YEAR : "y",
/**
* <p>An object hash containing default date values used during date parsing.</p>
* <p>The following properties are available:<div class="mdetail-params"><ul>
* <li><code>y</code> : Number<div class="sub-desc">The default year value. (defaults to undefined)</div></li>
* <li><code>m</code> : Number<div class="sub-desc">The default 1-based month value. (defaults to undefined)</div></li>
* <li><code>d</code> : Number<div class="sub-desc">The default day value. (defaults to undefined)</div></li>
* <li><code>h</code> : Number<div class="sub-desc">The default hour value. (defaults to undefined)</div></li>
* <li><code>i</code> : Number<div class="sub-desc">The default minute value. (defaults to undefined)</div></li>
* <li><code>s</code> : Number<div class="sub-desc">The default second value. (defaults to undefined)</div></li>
* <li><code>ms</code> : Number<div class="sub-desc">The default millisecond value. (defaults to undefined)</div></li>
* </ul></div></p>
* <p>Override these properties to customize the default date values used by the {@link #parse} method.</p>
* <p><b>Note: In countries which experience Daylight Saving Time (i.e. DST), the <tt>h</tt>, <tt>i</tt>, <tt>s</tt>
* and <tt>ms</tt> properties may coincide with the exact time in which DST takes effect.
* It is the responsiblity of the developer to account for this.</b></p>
* Example Usage:
* <pre><code>
// set default day value to the first day of the month
Ext.Date.defaults.d = 1;
// parse a February date string containing only year and month values.
// setting the default day value to 1 prevents weird date rollover issues
// when attempting to parse the following date string on, for example, March 31st 2009.
Ext.Date.parse('2009-02', 'Y-m'); // returns a Date object representing February 1st 2009
</code></pre>
* @property defaults
* @static
* @type Object
*/
defaults: {},
/**
* An array of textual day names.
* Override these values for international dates.
* Example:
* <pre><code>
Ext.Date.dayNames = [
'SundayInYourLang',
'MondayInYourLang',
...
];
</code></pre>
* @type Array
* @static
*/
dayNames : [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
/**
* An array of textual month names.
* Override these values for international dates.
* Example:
* <pre><code>
Ext.Date.monthNames = [
'JanInYourLang',
'FebInYourLang',
...
];
</code></pre>
* @type Array
* @static
*/
monthNames : [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
/**
* An object hash of zero-based javascript month numbers (with short month names as keys. note: keys are case-sensitive).
* Override these values for international dates.
* Example:
* <pre><code>
Ext.Date.monthNumbers = {
'ShortJanNameInYourLang':0,
'ShortFebNameInYourLang':1,
...
};
</code></pre>
* @type Object
* @static
*/
monthNumbers : {
Jan:0,
Feb:1,
Mar:2,
Apr:3,
May:4,
Jun:5,
Jul:6,
Aug:7,
Sep:8,
Oct:9,
Nov:10,
Dec:11
},
/**
* <p>The date format string that the {@link #dateRenderer} and {@link #date} functions use.
* see {@link #Date} for details.</p>
* <p>This defaults to <code>m/d/Y</code>, but may be overridden in a locale file.</p>
* @property defaultFormat
* @static
* @type String
*/
defaultFormat : "m/d/Y",
/**
* Get the short month name for the given month number.
* Override this function for international dates.
* @param {Number} month A zero-based javascript month number.
* @return {String} The short month name.
* @static
*/
getShortMonthName : function(month) {
return utilDate.monthNames[month].substring(0, 3);
},
/**
* Get the short day name for the given day number.
* Override this function for international dates.
* @param {Number} day A zero-based javascript day number.
* @return {String} The short day name.
* @static
*/
getShortDayName : function(day) {
return utilDate.dayNames[day].substring(0, 3);
},
/**
* Get the zero-based javascript month number for the given short/full month name.
* Override this function for international dates.
* @param {String} name The short/full month name.
* @return {Number} The zero-based javascript month number.
* @static
*/
getMonthNumber : function(name) {
// handle camel casing for english month names (since the keys for the Ext.Date.monthNumbers hash are case sensitive)
return utilDate.monthNumbers[name.substring(0, 1).toUpperCase() + name.substring(1, 3).toLowerCase()];
},
/**
* Checks if the specified format contains hour information
* @param {String} format The format to check
* @return {Boolean} True if the format contains hour information
* @static
*/
formatContainsHourInfo : (function(){
var stripEscapeRe = /(\\.)/g,
hourInfoRe = /([gGhHisucUOPZ]|MS)/;
return function(format){
return hourInfoRe.test(format.replace(stripEscapeRe, ''));
};
})(),
/**
* Checks if the specified format contains information about
* anything other than the time.
* @param {String} format The format to check
* @return {Boolean} True if the format contains information about
* date/day information.
* @static
*/
formatContainsDateInfo : (function(){
var stripEscapeRe = /(\\.)/g,
dateInfoRe = /([djzmnYycU]|MS)/;
return function(format){
return dateInfoRe.test(format.replace(stripEscapeRe, ''));
};
})(),
/**
* The base format-code to formatting-function hashmap used by the {@link #format} method.
* Formatting functions are strings (or functions which return strings) which
* will return the appropriate value when evaluated in the context of the Date object
* from which the {@link #format} method is called.
* Add to / override these mappings for custom date formatting.
* Note: Ext.Date.format() treats characters as literals if an appropriate mapping cannot be found.
* Example:
* <pre><code>
Ext.Date.formatCodes.x = "Ext.util.Format.leftPad(this.getDate(), 2, '0')";
console.log(Ext.Date.format(new Date(), 'X'); // returns the current day of the month
</code></pre>
* @type Object
* @static
*/
formatCodes : {
d: "Ext.String.leftPad(this.getDate(), 2, '0')",
D: "Ext.Date.getShortDayName(this.getDay())", // get localised short day name
j: "this.getDate()",
l: "Ext.Date.dayNames[this.getDay()]",
N: "(this.getDay() ? this.getDay() : 7)",
S: "Ext.Date.getSuffix(this)",
w: "this.getDay()",
z: "Ext.Date.getDayOfYear(this)",
W: "Ext.String.leftPad(Ext.Date.getWeekOfYear(this), 2, '0')",
F: "Ext.Date.monthNames[this.getMonth()]",
m: "Ext.String.leftPad(this.getMonth() + 1, 2, '0')",
M: "Ext.Date.getShortMonthName(this.getMonth())", // get localised short month name
n: "(this.getMonth() + 1)",
t: "Ext.Date.getDaysInMonth(this)",
L: "(Ext.Date.isLeapYear(this) ? 1 : 0)",
o: "(this.getFullYear() + (Ext.Date.getWeekOfYear(this) == 1 && this.getMonth() > 0 ? +1 : (Ext.Date.getWeekOfYear(this) >= 52 && this.getMonth() < 11 ? -1 : 0)))",
Y: "Ext.String.leftPad(this.getFullYear(), 4, '0')",
y: "('' + this.getFullYear()).substring(2, 4)",
a: "(this.getHours() < 12 ? 'am' : 'pm')",
A: "(this.getHours() < 12 ? 'AM' : 'PM')",
g: "((this.getHours() % 12) ? this.getHours() % 12 : 12)",
G: "this.getHours()",
h: "Ext.String.leftPad((this.getHours() % 12) ? this.getHours() % 12 : 12, 2, '0')",
H: "Ext.String.leftPad(this.getHours(), 2, '0')",
i: "Ext.String.leftPad(this.getMinutes(), 2, '0')",
s: "Ext.String.leftPad(this.getSeconds(), 2, '0')",
u: "Ext.String.leftPad(this.getMilliseconds(), 3, '0')",
O: "Ext.Date.getGMTOffset(this)",
P: "Ext.Date.getGMTOffset(this, true)",
T: "Ext.Date.getTimezone(this)",
Z: "(this.getTimezoneOffset() * -60)",
c: function() { // ISO-8601 -- GMT format
for (var c = "Y-m-dTH:i:sP", code = [], i = 0, l = c.length; i < l; ++i) {
var e = c.charAt(i);
code.push(e == "T" ? "'T'" : utilDate.getFormatCode(e)); // treat T as a character literal
}
return code.join(" + ");
},
/*
c: function() { // ISO-8601 -- UTC format
return [
"this.getUTCFullYear()", "'-'",
"Ext.util.Format.leftPad(this.getUTCMonth() + 1, 2, '0')", "'-'",
"Ext.util.Format.leftPad(this.getUTCDate(), 2, '0')",
"'T'",
"Ext.util.Format.leftPad(this.getUTCHours(), 2, '0')", "':'",
"Ext.util.Format.leftPad(this.getUTCMinutes(), 2, '0')", "':'",
"Ext.util.Format.leftPad(this.getUTCSeconds(), 2, '0')",
"'Z'"
].join(" + ");
},
*/
U: "Math.round(this.getTime() / 1000)"
},
/**
* Checks if the passed Date parameters will cause a javascript Date "rollover".
* @param {Number} year 4-digit year
* @param {Number} month 1-based month-of-year
* @param {Number} day Day of month
* @param {Number} hour (optional) Hour
* @param {Number} minute (optional) Minute
* @param {Number} second (optional) Second
* @param {Number} millisecond (optional) Millisecond
* @return {Boolean} true if the passed parameters do not cause a Date "rollover", false otherwise.
* @static
*/
isValid : function(y, m, d, h, i, s, ms) {
// setup defaults
h = h || 0;
i = i || 0;
s = s || 0;
ms = ms || 0;
// Special handling for year < 100
var dt = utilDate.add(new Date(y < 100 ? 100 : y, m - 1, d, h, i, s, ms), utilDate.YEAR, y < 100 ? y - 100 : 0);
return y == dt.getFullYear() &&
m == dt.getMonth() + 1 &&
d == dt.getDate() &&
h == dt.getHours() &&
i == dt.getMinutes() &&
s == dt.getSeconds() &&
ms == dt.getMilliseconds();
},
/**
* Parses the passed string using the specified date format.
* Note that this function expects normal calendar dates, meaning that months are 1-based (i.e. 1 = January).
* The {@link #defaults} hash will be used for any date value (i.e. year, month, day, hour, minute, second or millisecond)
* which cannot be found in the passed string. If a corresponding default date value has not been specified in the {@link #defaults} hash,
* the current date's year, month, day or DST-adjusted zero-hour time value will be used instead.
* Keep in mind that the input date string must precisely match the specified format string
* in order for the parse operation to be successful (failed parse operations return a null value).
* <p>Example:</p><pre><code>
//dt = Fri May 25 2007 (current date)
var dt = new Date();
//dt = Thu May 25 2006 (today's month/day in 2006)
dt = Ext.Date.parse("2006", "Y");
//dt = Sun Jan 15 2006 (all date parts specified)
dt = Ext.Date.parse("2006-01-15", "Y-m-d");
//dt = Sun Jan 15 2006 15:20:01
dt = Ext.Date.parse("2006-01-15 3:20:01 PM", "Y-m-d g:i:s A");
// attempt to parse Sun Feb 29 2006 03:20:01 in strict mode
dt = Ext.Date.parse("2006-02-29 03:20:01", "Y-m-d H:i:s", true); // returns null
</code></pre>
* @param {String} input The raw date string.
* @param {String} format The expected date string format.
* @param {Boolean} strict (optional) True to validate date strings while parsing (i.e. prevents javascript Date "rollover")
(defaults to false). Invalid date strings will return null when parsed.
* @return {Date} The parsed Date.
* @static
*/
parse : function(input, format, strict) {
var p = utilDate.parseFunctions;
if (p[format] == null) {
utilDate.createParser(format);
}
return p[format](input, Ext.isDefined(strict) ? strict : utilDate.useStrict);
},
// Backwards compat
parseDate: function(input, format, strict){
return utilDate.parse(input, format, strict);
},
// private
getFormatCode : function(character) {
var f = utilDate.formatCodes[character];
if (f) {
f = typeof f == 'function'? f() : f;
utilDate.formatCodes[character] = f; // reassign function result to prevent repeated execution
}
// note: unknown characters are treated as literals
return f || ("'" + Ext.String.escape(character) + "'");
},
// private
createFormat : function(format) {
var code = [],
special = false,
ch = '';
for (var i = 0; i < format.length; ++i) {
ch = format.charAt(i);
if (!special && ch == "\\") {
special = true;
} else if (special) {
special = false;
code.push("'" + Ext.String.escape(ch) + "'");
} else {
code.push(utilDate.getFormatCode(ch));
}
}
utilDate.formatFunctions[format] = Ext.functionFactory("return " + code.join('+'));
},
// private
createParser : (function() {
var code = [
"var dt, y, m, d, h, i, s, ms, o, z, zz, u, v,",
"def = Ext.Date.defaults,",
"results = String(input).match(Ext.Date.parseRegexes[{0}]);", // either null, or an array of matched strings
"if(results){",
"{1}",
"if(u != null){", // i.e. unix time is defined
"v = new Date(u * 1000);", // give top priority to UNIX time
"}else{",
// create Date object representing midnight of the current day;
// this will provide us with our date defaults
// (note: clearTime() handles Daylight Saving Time automatically)
"dt = Ext.Date.clearTime(new Date);",
// date calculations (note: these calculations create a dependency on Ext.Number.from())
"y = Ext.Number.from(y, Ext.Number.from(def.y, dt.getFullYear()));",
"m = Ext.Number.from(m, Ext.Number.from(def.m - 1, dt.getMonth()));",
"d = Ext.Number.from(d, Ext.Number.from(def.d, dt.getDate()));",
// time calculations (note: these calculations create a dependency on Ext.Number.from())
"h = Ext.Number.from(h, Ext.Number.from(def.h, dt.getHours()));",
"i = Ext.Number.from(i, Ext.Number.from(def.i, dt.getMinutes()));",
"s = Ext.Number.from(s, Ext.Number.from(def.s, dt.getSeconds()));",
"ms = Ext.Number.from(ms, Ext.Number.from(def.ms, dt.getMilliseconds()));",
"if(z >= 0 && y >= 0){",
// both the year and zero-based day of year are defined and >= 0.
// these 2 values alone provide sufficient info to create a full date object
// create Date object representing January 1st for the given year
// handle years < 100 appropriately
"v = Ext.Date.add(new Date(y < 100 ? 100 : y, 0, 1, h, i, s, ms), Ext.Date.YEAR, y < 100 ? y - 100 : 0);",
// then add day of year, checking for Date "rollover" if necessary
"v = !strict? v : (strict === true && (z <= 364 || (Ext.Date.isLeapYear(v) && z <= 365))? Ext.Date.add(v, Ext.Date.DAY, z) : null);",
"}else if(strict === true && !Ext.Date.isValid(y, m + 1, d, h, i, s, ms)){", // check for Date "rollover"
"v = null;", // invalid date, so return null
"}else{",
// plain old Date object
// handle years < 100 properly
"v = Ext.Date.add(new Date(y < 100 ? 100 : y, m, d, h, i, s, ms), Ext.Date.YEAR, y < 100 ? y - 100 : 0);",
"}",
"}",
"}",
"if(v){",
// favour UTC offset over GMT offset
"if(zz != null){",
// reset to UTC, then add offset
"v = Ext.Date.add(v, Ext.Date.SECOND, -v.getTimezoneOffset() * 60 - zz);",
"}else if(o){",
// reset to GMT, then add offset
"v = Ext.Date.add(v, Ext.Date.MINUTE, -v.getTimezoneOffset() + (sn == '+'? -1 : 1) * (hr * 60 + mn));",
"}",
"}",
"return v;"
].join('\n');
return function(format) {
var regexNum = utilDate.parseRegexes.length,
currentGroup = 1,
calc = [],
regex = [],
special = false,
ch = "";
for (var i = 0; i < format.length; ++i) {
ch = format.charAt(i);
if (!special && ch == "\\") {
special = true;
} else if (special) {
special = false;
regex.push(Ext.String.escape(ch));
} else {
var obj = utilDate.formatCodeToRegex(ch, currentGroup);
currentGroup += obj.g;
regex.push(obj.s);
if (obj.g && obj.c) {
calc.push(obj.c);
}
}
}
utilDate.parseRegexes[regexNum] = new RegExp("^" + regex.join('') + "$", 'i');
utilDate.parseFunctions[format] = Ext.functionFactory("input", "strict", xf(code, regexNum, calc.join('')));
};
})(),
// private
parseCodes : {
/*
* Notes:
* g = {Number} calculation group (0 or 1. only group 1 contributes to date calculations.)
* c = {String} calculation method (required for group 1. null for group 0. {0} = currentGroup - position in regex result array)
* s = {String} regex pattern. all matches are stored in results[], and are accessible by the calculation mapped to 'c'
*/
d: {
g:1,
c:"d = parseInt(results[{0}], 10);\n",
s:"(\\d{2})" // day of month with leading zeroes (01 - 31)
},
j: {
g:1,
c:"d = parseInt(results[{0}], 10);\n",
s:"(\\d{1,2})" // day of month without leading zeroes (1 - 31)
},
D: function() {
for (var a = [], i = 0; i < 7; a.push(utilDate.getShortDayName(i)), ++i); // get localised short day names
return {
g:0,
c:null,
s:"(?:" + a.join("|") +")"
};
},
l: function() {
return {
g:0,
c:null,
s:"(?:" + utilDate.dayNames.join("|") + ")"
};
},
N: {
g:0,
c:null,
s:"[1-7]" // ISO-8601 day number (1 (monday) - 7 (sunday))
},
S: {
g:0,
c:null,
s:"(?:st|nd|rd|th)"
},
w: {
g:0,
c:null,
s:"[0-6]" // javascript day number (0 (sunday) - 6 (saturday))
},
z: {
g:1,
c:"z = parseInt(results[{0}], 10);\n",
s:"(\\d{1,3})" // day of the year (0 - 364 (365 in leap years))
},
W: {
g:0,
c:null,
s:"(?:\\d{2})" // ISO-8601 week number (with leading zero)
},
F: function() {
return {
g:1,
c:"m = parseInt(Ext.Date.getMonthNumber(results[{0}]), 10);\n", // get localised month number
s:"(" + utilDate.monthNames.join("|") + ")"
};
},
M: function() {
for (var a = [], i = 0; i < 12; a.push(utilDate.getShortMonthName(i)), ++i); // get localised short month names
return Ext.applyIf({
s:"(" + a.join("|") + ")"
}, utilDate.formatCodeToRegex("F"));
},
m: {
g:1,
c:"m = parseInt(results[{0}], 10) - 1;\n",
s:"(\\d{2})" // month number with leading zeros (01 - 12)
},
n: {
g:1,
c:"m = parseInt(results[{0}], 10) - 1;\n",
s:"(\\d{1,2})" // month number without leading zeros (1 - 12)
},
t: {
g:0,
c:null,
s:"(?:\\d{2})" // no. of days in the month (28 - 31)
},
L: {
g:0,
c:null,
s:"(?:1|0)"
},
o: function() {
return utilDate.formatCodeToRegex("Y");
},
Y: {
g:1,
c:"y = parseInt(results[{0}], 10);\n",
s:"(\\d{4})" // 4-digit year
},
y: {
g:1,
c:"var ty = parseInt(results[{0}], 10);\n"
+ "y = ty > Ext.Date.y2kYear ? 1900 + ty : 2000 + ty;\n", // 2-digit year
s:"(\\d{1,2})"
},
/**
* In the am/pm parsing routines, we allow both upper and lower case
* even though it doesn't exactly match the spec. It gives much more flexibility
* in being able to specify case insensitive regexes.
*/
a: {
g:1,
c:"if (/(am)/i.test(results[{0}])) {\n"
+ "if (!h || h == 12) { h = 0; }\n"
+ "} else { if (!h || h < 12) { h = (h || 0) + 12; }}",
s:"(am|pm|AM|PM)"
},
A: {
g:1,
c:"if (/(am)/i.test(results[{0}])) {\n"
+ "if (!h || h == 12) { h = 0; }\n"
+ "} else { if (!h || h < 12) { h = (h || 0) + 12; }}",
s:"(AM|PM|am|pm)"
},
g: function() {
return utilDate.formatCodeToRegex("G");
},
G: {
g:1,
c:"h = parseInt(results[{0}], 10);\n",
s:"(\\d{1,2})" // 24-hr format of an hour without leading zeroes (0 - 23)
},
h: function() {
return utilDate.formatCodeToRegex("H");
},
H: {
g:1,
c:"h = parseInt(results[{0}], 10);\n",
s:"(\\d{2})" // 24-hr format of an hour with leading zeroes (00 - 23)
},
i: {
g:1,
c:"i = parseInt(results[{0}], 10);\n",
s:"(\\d{2})" // minutes with leading zeros (00 - 59)
},
s: {
g:1,
c:"s = parseInt(results[{0}], 10);\n",
s:"(\\d{2})" // seconds with leading zeros (00 - 59)
},
u: {
g:1,
c:"ms = results[{0}]; ms = parseInt(ms, 10)/Math.pow(10, ms.length - 3);\n",
s:"(\\d+)" // decimal fraction of a second (minimum = 1 digit, maximum = unlimited)
},
O: {
g:1,
c:[
"o = results[{0}];",
"var sn = o.substring(0,1),", // get + / - sign
"hr = o.substring(1,3)*1 + Math.floor(o.substring(3,5) / 60),", // get hours (performs minutes-to-hour conversion also, just in case)
"mn = o.substring(3,5) % 60;", // get minutes
"o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))? (sn + Ext.String.leftPad(hr, 2, '0') + Ext.String.leftPad(mn, 2, '0')) : null;\n" // -12hrs <= GMT offset <= 14hrs
].join("\n"),
s: "([+\-]\\d{4})" // GMT offset in hrs and mins
},
P: {
g:1,
c:[
"o = results[{0}];",
"var sn = o.substring(0,1),", // get + / - sign
"hr = o.substring(1,3)*1 + Math.floor(o.substring(4,6) / 60),", // get hours (performs minutes-to-hour conversion also, just in case)
"mn = o.substring(4,6) % 60;", // get minutes
"o = ((-12 <= (hr*60 + mn)/60) && ((hr*60 + mn)/60 <= 14))? (sn + Ext.String.leftPad(hr, 2, '0') + Ext.String.leftPad(mn, 2, '0')) : null;\n" // -12hrs <= GMT offset <= 14hrs
].join("\n"),
s: "([+\-]\\d{2}:\\d{2})" // GMT offset in hrs and mins (with colon separator)
},
T: {
g:0,
c:null,
s:"[A-Z]{1,4}" // timezone abbrev. may be between 1 - 4 chars
},
Z: {
g:1,
c:"zz = results[{0}] * 1;\n" // -43200 <= UTC offset <= 50400
+ "zz = (-43200 <= zz && zz <= 50400)? zz : null;\n",
s:"([+\-]?\\d{1,5})" // leading '+' sign is optional for UTC offset
},
c: function() {
var calc = [],
arr = [
utilDate.formatCodeToRegex("Y", 1), // year
utilDate.formatCodeToRegex("m", 2), // month
utilDate.formatCodeToRegex("d", 3), // day
utilDate.formatCodeToRegex("h", 4), // hour
utilDate.formatCodeToRegex("i", 5), // minute
utilDate.formatCodeToRegex("s", 6), // second
{c:"ms = results[7] || '0'; ms = parseInt(ms, 10)/Math.pow(10, ms.length - 3);\n"}, // decimal fraction of a second (minimum = 1 digit, maximum = unlimited)
{c:[ // allow either "Z" (i.e. UTC) or "-0530" or "+08:00" (i.e. UTC offset) timezone delimiters. assumes local timezone if no timezone is specified
"if(results[8]) {", // timezone specified
"if(results[8] == 'Z'){",
"zz = 0;", // UTC
"}else if (results[8].indexOf(':') > -1){",
utilDate.formatCodeToRegex("P", 8).c, // timezone offset with colon separator
"}else{",
utilDate.formatCodeToRegex("O", 8).c, // timezone offset without colon separator
"}",
"}"
].join('\n')}
];
for (var i = 0, l = arr.length; i < l; ++i) {
calc.push(arr[i].c);
}
return {
g:1,
c:calc.join(""),
s:[
arr[0].s, // year (required)
"(?:", "-", arr[1].s, // month (optional)
"(?:", "-", arr[2].s, // day (optional)
"(?:",
"(?:T| )?", // time delimiter -- either a "T" or a single blank space
arr[3].s, ":", arr[4].s, // hour AND minute, delimited by a single colon (optional). MUST be preceded by either a "T" or a single blank space
"(?::", arr[5].s, ")?", // seconds (optional)
"(?:(?:\\.|,)(\\d+))?", // decimal fraction of a second (e.g. ",12345" or ".98765") (optional)
"(Z|(?:[-+]\\d{2}(?::)?\\d{2}))?", // "Z" (UTC) or "-0530" (UTC offset without colon delimiter) or "+08:00" (UTC offset with colon delimiter) (optional)
")?",
")?",
")?"
].join("")
};
},
U: {
g:1,
c:"u = parseInt(results[{0}], 10);\n",
s:"(-?\\d+)" // leading minus sign indicates seconds before UNIX epoch
}
},
//Old Ext.Date prototype methods.
// private
dateFormat: function(date, format) {
return utilDate.format(date, format);
},
/**
* Formats a date given the supplied format string.
* @param {Date} date The date to format
* @param {String} format The format string
* @return {String} The formatted date
*/
format: function(date, format) {
if (utilDate.formatFunctions[format] == null) {
utilDate.createFormat(format);
}
var result = utilDate.formatFunctions[format].call(date);
return result + '';
},
/**
* Get the timezone abbreviation of the current date (equivalent to the format specifier 'T').
*
* Note: The date string returned by the javascript Date object's toString() method varies
* between browsers (e.g. FF vs IE) and system region settings (e.g. IE in Asia vs IE in America).
* For a given date string e.g. "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)",
* getTimezone() first tries to get the timezone abbreviation from between a pair of parentheses
* (which may or may not be present), failing which it proceeds to get the timezone abbreviation
* from the GMT offset portion of the date string.
* @param {Date} date The date
* @return {String} The abbreviated timezone name (e.g. 'CST', 'PDT', 'EDT', 'MPST' ...).
*/
getTimezone : function(date) {
// the following list shows the differences between date strings from different browsers on a WinXP SP2 machine from an Asian locale:
//
// Opera : "Thu, 25 Oct 2007 22:53:45 GMT+0800" -- shortest (weirdest) date string of the lot
// Safari : "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)" -- value in parentheses always gives the correct timezone (same as FF)
// FF : "Thu Oct 25 2007 22:55:35 GMT+0800 (Malay Peninsula Standard Time)" -- value in parentheses always gives the correct timezone
// IE : "Thu Oct 25 22:54:35 UTC+0800 2007" -- (Asian system setting) look for 3-4 letter timezone abbrev
// IE : "Thu Oct 25 17:06:37 PDT 2007" -- (American system setting) look for 3-4 letter timezone abbrev
//
// this crazy regex attempts to guess the correct timezone abbreviation despite these differences.
// step 1: (?:\((.*)\) -- find timezone in parentheses
// step 2: ([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?) -- if nothing was found in step 1, find timezone from timezone offset portion of date string
// step 3: remove all non uppercase characters found in step 1 and 2
return date.toString().replace(/^.* (?:\((.*)\)|([A-Z]{1,4})(?:[\-+][0-9]{4})?(?: -?\d+)?)$/, "$1$2").replace(/[^A-Z]/g, "");
},
/**
* Get the offset from GMT of the current date (equivalent to the format specifier 'O').
* @param {Date} date The date
* @param {Boolean} colon (optional) true to separate the hours and minutes with a colon (defaults to false).
* @return {String} The 4-character offset string prefixed with + or - (e.g. '-0600').
*/
getGMTOffset : function(date, colon) {
var offset = date.getTimezoneOffset();
return (offset > 0 ? "-" : "+")
+ Ext.String.leftPad(Math.floor(Math.abs(offset) / 60), 2, "0")
+ (colon ? ":" : "")
+ Ext.String.leftPad(Math.abs(offset % 60), 2, "0");
},
/**
* Get the numeric day number of the year, adjusted for leap year.
* @param {Date} date The date
* @return {Number} 0 to 364 (365 in leap years).
*/
getDayOfYear: function(date) {
var num = 0,
d = Ext.Date.clone(date),
m = date.getMonth(),
i;
for (i = 0, d.setDate(1), d.setMonth(0); i < m; d.setMonth(++i)) {
num += utilDate.getDaysInMonth(d);
}
return num + date.getDate() - 1;
},
/**
* Get the numeric ISO-8601 week number of the year.
* (equivalent to the format specifier 'W', but without a leading zero).
* @param {Date} date The date
* @return {Number} 1 to 53
*/
getWeekOfYear : (function() {
// adapted from http://www.merlyn.demon.co.uk/weekcalc.htm
var ms1d = 864e5, // milliseconds in a day
ms7d = 7 * ms1d; // milliseconds in a week
return function(date) { // return a closure so constants get calculated only once
var DC3 = Date.UTC(date.getFullYear(), date.getMonth(), date.getDate() + 3) / ms1d, // an Absolute Day Number
AWN = Math.floor(DC3 / 7), // an Absolute Week Number
Wyr = new Date(AWN * ms7d).getUTCFullYear();
return AWN - Math.floor(Date.UTC(Wyr, 0, 7) / ms7d) + 1;
};
})(),
/**
* Checks if the current date falls within a leap year.
* @param {Date} date The date
* @return {Boolean} True if the current date falls within a leap year, false otherwise.
*/
isLeapYear : function(date) {
var year = date.getFullYear();
return !!((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
},
/**
* Get the first day of the current month, adjusted for leap year. The returned value
* is the numeric day index within the week (0-6) which can be used in conjunction with
* the {@link #monthNames} array to retrieve the textual day name.
* Example:
* <pre><code>
var dt = new Date('1/10/2007'),
firstDay = Ext.Date.getFirstDayOfMonth(dt);
console.log(Ext.Date.dayNames[firstDay]); //output: 'Monday'
* </code></pre>
* @param {Date} date The date
* @return {Number} The day number (0-6).
*/
getFirstDayOfMonth : function(date) {
var day = (date.getDay() - (date.getDate() - 1)) % 7;
return (day < 0) ? (day + 7) : day;
},
/**
* Get the last day of the current month, adjusted for leap year. The returned value
* is the numeric day index within the week (0-6) which can be used in conjunction with
* the {@link #monthNames} array to retrieve the textual day name.
* Example:
* <pre><code>
var dt = new Date('1/10/2007'),
lastDay = Ext.Date.getLastDayOfMonth(dt);
console.log(Ext.Date.dayNames[lastDay]); //output: 'Wednesday'
* </code></pre>
* @param {Date} date The date
* @return {Number} The day number (0-6).
*/
getLastDayOfMonth : function(date) {
return utilDate.getLastDateOfMonth(date).getDay();
},
/**
* Get the date of the first day of the month in which this date resides.
* @param {Date} date The date
* @return {Date}
*/
getFirstDateOfMonth : function(date) {
return new Date(date.getFullYear(), date.getMonth(), 1);
},
/**
* Get the date of the last day of the month in which this date resides.
* @param {Date} date The date
* @return {Date}
*/
getLastDateOfMonth : function(date) {
return new Date(date.getFullYear(), date.getMonth(), utilDate.getDaysInMonth(date));
},
/**
* Get the number of days in the current month, adjusted for leap year.
* @param {Date} date The date
* @return {Number} The number of days in the month.
*/
getDaysInMonth: (function() {
var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
return function(date) { // return a closure for efficiency
var m = date.getMonth();
return m == 1 && utilDate.isLeapYear(date) ? 29 : daysInMonth[m];
};
})(),
/**
* Get the English ordinal suffix of the current day (equivalent to the format specifier 'S').
* @param {Date} date The date
* @return {String} 'st, 'nd', 'rd' or 'th'.
*/
getSuffix : function(date) {
switch (date.getDate()) {
case 1:
case 21:
case 31:
return "st";
case 2:
case 22:
return "nd";
case 3:
case 23:
return "rd";
default:
return "th";
}
},
/**
* Creates and returns a new Date instance with the exact same date value as the called instance.
* Dates are copied and passed by reference, so if a copied date variable is modified later, the original
* variable will also be changed. When the intention is to create a new variable that will not
* modify the original instance, you should create a clone.
*
* Example of correctly cloning a date:
* <pre><code>
//wrong way:
var orig = new Date('10/1/2006');
var copy = orig;
copy.setDate(5);
console.log(orig); //returns 'Thu Oct 05 2006'!
//correct way:
var orig = new Date('10/1/2006'),
copy = Ext.Date.clone(orig);
copy.setDate(5);
console.log(orig); //returns 'Thu Oct 01 2006'
* </code></pre>
* @param {Date} date The date
* @return {Date} The new Date instance.
*/
clone : function(date) {
return new Date(date.getTime());
},
/**
* Checks if the current date is affected by Daylight Saving Time (DST).
* @param {Date} date The date
* @return {Boolean} True if the current date is affected by DST.
*/
isDST : function(date) {
// adapted from http://sencha.com/forum/showthread.php?p=247172#post247172
// courtesy of @geoffrey.mcgill
return new Date(date.getFullYear(), 0, 1).getTimezoneOffset() != date.getTimezoneOffset();
},
/**
* Attempts to clear all time information from this Date by setting the time to midnight of the same day,
* automatically adjusting for Daylight Saving Time (DST) where applicable.
* (note: DST timezone information for the browser's host operating system is assumed to be up-to-date)
* @param {Date} date The date
* @param {Boolean} clone true to create a clone of this date, clear the time and return it (defaults to false).
* @return {Date} this or the clone.
*/
clearTime : function(date, clone) {
if (clone) {
return Ext.Date.clearTime(Ext.Date.clone(date));
}
// get current date before clearing time
var d = date.getDate();
// clear time
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
if (date.getDate() != d) { // account for DST (i.e. day of month changed when setting hour = 0)
// note: DST adjustments are assumed to occur in multiples of 1 hour (this is almost always the case)
// refer to http://www.timeanddate.com/time/aboutdst.html for the (rare) exceptions to this rule
// increment hour until cloned date == current date
for (var hr = 1, c = utilDate.add(date, Ext.Date.HOUR, hr); c.getDate() != d; hr++, c = utilDate.add(date, Ext.Date.HOUR, hr));
date.setDate(d);
date.setHours(c.getHours());
}
return date;
},
/**
* Provides a convenient method for performing basic date arithmetic. This method
* does not modify the Date instance being called - it creates and returns
* a new Date instance containing the resulting date value.
*
* Examples:
* <pre><code>
// Basic usage:
var dt = Ext.Date.add(new Date('10/29/2006'), Ext.Date.DAY, 5);
console.log(dt); //returns 'Fri Nov 03 2006 00:00:00'
// Negative values will be subtracted:
var dt2 = Ext.Date.add(new Date('10/1/2006'), Ext.Date.DAY, -5);
console.log(dt2); //returns 'Tue Sep 26 2006 00:00:00'
* </code></pre>
*
* @param {Date} date The date to modify
* @param {String} interval A valid date interval enum value.
* @param {Number} value The amount to add to the current date.
* @return {Date} The new Date instance.
*/
add : function(date, interval, value) {
var d = Ext.Date.clone(date),
Date = Ext.Date;
if (!interval || value === 0) return d;
switch(interval.toLowerCase()) {
case Ext.Date.MILLI:
d.setMilliseconds(d.getMilliseconds() + value);
break;
case Ext.Date.SECOND:
d.setSeconds(d.getSeconds() + value);
break;
case Ext.Date.MINUTE:
d.setMinutes(d.getMinutes() + value);
break;
case Ext.Date.HOUR:
d.setHours(d.getHours() + value);
break;
case Ext.Date.DAY:
d.setDate(d.getDate() + value);
break;
case Ext.Date.MONTH:
var day = date.getDate();
if (day > 28) {
day = Math.min(day, Ext.Date.getLastDateOfMonth(Ext.Date.add(Ext.Date.getFirstDateOfMonth(date), 'mo', value)).getDate());
}
d.setDate(day);
d.setMonth(date.getMonth() + value);
break;
case Ext.Date.YEAR:
d.setFullYear(date.getFullYear() + value);
break;
}
return d;
},
/**
* Checks if a date falls on or between the given start and end dates.
* @param {Date} date The date to check
* @param {Date} start Start date
* @param {Date} end End date
* @return {Boolean} true if this date falls on or between the given start and end dates.
*/
between : function(date, start, end) {
var t = date.getTime();
return start.getTime() <= t && t <= end.getTime();
},
//Maintains compatibility with old static and prototype window.Date methods.
compat: function() {
var nativeDate = window.Date,
p, u,
statics = ['useStrict', 'formatCodeToRegex', 'parseFunctions', 'parseRegexes', 'formatFunctions', 'y2kYear', 'MILLI', 'SECOND', 'MINUTE', 'HOUR', 'DAY', 'MONTH', 'YEAR', 'defaults', 'dayNames', 'monthNames', 'monthNumbers', 'getShortMonthName', 'getShortDayName', 'getMonthNumber', 'formatCodes', 'isValid', 'parseDate', 'getFormatCode', 'createFormat', 'createParser', 'parseCodes'],
proto = ['dateFormat', 'format', 'getTimezone', 'getGMTOffset', 'getDayOfYear', 'getWeekOfYear', 'isLeapYear', 'getFirstDayOfMonth', 'getLastDayOfMonth', 'getDaysInMonth', 'getSuffix', 'clone', 'isDST', 'clearTime', 'add', 'between'];
//Append statics
Ext.Array.forEach(statics, function(s) {
nativeDate[s] = utilDate[s];
});
//Append to prototype
Ext.Array.forEach(proto, function(s) {
nativeDate.prototype[s] = function() {
var args = Array.prototype.slice.call(arguments);
args.unshift(this);
return utilDate[s].apply(utilDate, args);
};
});
}
};
var utilDate = Ext.Date;
})();
/**
* @author Jacky Nguyen <jacky@sencha.com>
* @docauthor Jacky Nguyen <jacky@sencha.com>
* @class Ext.Base
*
* The root of all classes created with {@link Ext#define}
* All prototype and static members of this class are inherited by any other class
*
*/
(function(flexSetter) {
var Base = Ext.Base = function() {};
Base.prototype = {
$className: 'Ext.Base',
$class: Base,
/**
* Get the reference to the current class from which this object was instantiated. Unlike {@link Ext.Base#statics},
* `this.self` is scope-dependent and it's meant to be used for dynamic inheritance. See {@link Ext.Base#statics}
* for a detailed comparison
Ext.define('My.Cat', {
statics: {
speciesName: 'Cat' // My.Cat.speciesName = 'Cat'
},
constructor: function() {
alert(this.self.speciesName); / dependent on 'this'
return this;
},
clone: function() {
return new this.self();
}
});
Ext.define('My.SnowLeopard', {
extend: 'My.Cat',
statics: {
speciesName: 'Snow Leopard' // My.SnowLeopard.speciesName = 'Snow Leopard'
}
});
var cat = new My.Cat(); // alerts 'Cat'
var snowLeopard = new My.SnowLeopard(); // alerts 'Snow Leopard'
var clone = snowLeopard.clone();
alert(Ext.getClassName(clone)); // alerts 'My.SnowLeopard'
* @type Class
* @protected
* @markdown
*/
self: Base,
/**
* Default constructor, simply returns `this`
*
* @constructor
* @protected
* @return {Object} this
*/
constructor: function() {
return this;
},
/**
* Initialize configuration for this class. a typical example:
Ext.define('My.awesome.Class', {
// The default config
config: {
name: 'Awesome',
isAwesome: true
},
constructor: function(config) {
this.initConfig(config);
return this;
}
});
var awesome = new My.awesome.Class({
name: 'Super Awesome'
});
alert(awesome.getName()); // 'Super Awesome'
* @protected
* @param {Object} config
* @return {Object} mixins The mixin prototypes as key - value pairs
* @markdown
*/
initConfig: function(config) {
if (!this.$configInited) {
this.config = Ext.Object.merge({}, this.config || {}, config || {});
this.applyConfig(this.config);
this.$configInited = true;
}
return this;
},
/**
* @private
*/
setConfig: function(config) {
this.applyConfig(config || {});
return this;
},
/**
* @private
*/
applyConfig: flexSetter(function(name, value) {
var setter = 'set' + Ext.String.capitalize(name);
if (typeof this[setter] === 'function') {
this[setter].call(this, value);
}
return this;
}),
/**
* Call the parent's overridden method. For example:
Ext.define('My.own.A', {
constructor: function(test) {
alert(test);
}
});
Ext.define('My.own.B', {
extend: 'My.own.A',
constructor: function(test) {
alert(test);
this.callParent([test + 1]);
}
});
Ext.define('My.own.C', {
extend: 'My.own.B',
constructor: function() {
alert("Going to call parent's overriden constructor...");
this.callParent(arguments);
}
});
var a = new My.own.A(1); // alerts '1'
var b = new My.own.B(1); // alerts '1', then alerts '2'
var c = new My.own.C(2); // alerts "Going to call parent's overriden constructor..."
// alerts '2', then alerts '3'
* @protected
* @param {Array/Arguments} args The arguments, either an array or the `arguments` object
* from the current method, for example: `this.callParent(arguments)`
* @return {Mixed} Returns the result from the superclass' method
* @markdown
*/
callParent: function(args) {
var method = this.callParent.caller,
parentClass, methodName;
if (!method.$owner) {
//<debug error>
if (!method.caller) {
Ext.Error.raise({
sourceClass: Ext.getClassName(this),
sourceMethod: "callParent",
msg: "Attempting to call a protected method from the public scope, which is not allowed"
});
}
//</debug>
method = method.caller;
}
parentClass = method.$owner.superclass;
methodName = method.$name;
//<debug error>
if (!(methodName in parentClass)) {
Ext.Error.raise({
sourceClass: Ext.getClassName(this),
sourceMethod: methodName,
msg: "this.callParent() was called but there's no such method (" + methodName +
") found in the parent class (" + (Ext.getClassName(parentClass) || 'Object') + ")"
});
}
//</debug>
return parentClass[methodName].apply(this, args || []);
},
/**
* Get the reference to the class from which this object was instantiated. Note that unlike {@link Ext.Base#self},
* `this.statics()` is scope-independent and it always returns the class from which it was called, regardless of what
* `this` points to during run-time
Ext.define('My.Cat', {
statics: {
totalCreated: 0,
speciesName: 'Cat' // My.Cat.speciesName = 'Cat'
},
constructor: function() {
var statics = this.statics();
alert(statics.speciesName); // always equals to 'Cat' no matter what 'this' refers to
// equivalent to: My.Cat.speciesName
alert(this.self.speciesName); // dependent on 'this'
statics.totalCreated++;
return this;
},
clone: function() {
var cloned = new this.self; // dependent on 'this'
cloned.groupName = this.statics().speciesName; // equivalent to: My.Cat.speciesName
return cloned;
}
});
Ext.define('My.SnowLeopard', {
extend: 'My.Cat',
statics: {
speciesName: 'Snow Leopard' // My.SnowLeopard.speciesName = 'Snow Leopard'
},
constructor: function() {
this.callParent();
}
});
var cat = new My.Cat(); // alerts 'Cat', then alerts 'Cat'
var snowLeopard = new My.SnowLeopard(); // alerts 'Cat', then alerts 'Snow Leopard'
var clone = snowLeopard.clone();
alert(Ext.getClassName(clone)); // alerts 'My.SnowLeopard'
alert(clone.groupName); // alerts 'Cat'
alert(My.Cat.totalCreated); // alerts 3
* @protected
* @return {Class}
* @markdown
*/
statics: function() {
var method = this.statics.caller,
self = this.self;
if (!method) {
return self;
}
return method.$owner;
},
/**
* Call the original method that was previously overridden with {@link Ext.Base#override}
Ext.define('My.Cat', {
constructor: function() {
alert("I'm a cat!");
return this;
}
});
My.Cat.override({
constructor: function() {
alert("I'm going to be a cat!");
var instance = this.callOverridden();
alert("Meeeeoooowwww");
return instance;
}
});
var kitty = new My.Cat(); // alerts "I'm going to be a cat!"
// alerts "I'm a cat!"
// alerts "Meeeeoooowwww"
* @param {Array/Arguments} args The arguments, either an array or the `arguments` object
* @return {Mixed} Returns the result after calling the overridden method
* @markdown
*/
callOverridden: function(args) {
var method = this.callOverridden.caller;
//<debug error>
if (!method.$owner) {
Ext.Error.raise({
sourceClass: Ext.getClassName(this),
sourceMethod: "callOverridden",
msg: "Attempting to call a protected method from the public scope, which is not allowed"
});
}
if (!method.$previous) {
Ext.Error.raise({
sourceClass: Ext.getClassName(this),
sourceMethod: "callOverridden",
msg: "this.callOverridden was called in '" + method.$name +
"' but this method has never been overridden"
});
}
//</debug>
return method.$previous.apply(this, args || []);
},
destroy: function() {}
};
// These static properties will be copied to every newly created class with {@link Ext#define}
Ext.apply(Ext.Base, {
/**
* Create a new instance of this Class.
Ext.define('My.cool.Class', {
...
});
My.cool.Class.create({
someConfig: true
});
* @property create
* @static
* @type Function
* @markdown
*/
create: function() {
return Ext.create.apply(Ext, [this].concat(Array.prototype.slice.call(arguments, 0)));
},
/**
* @private
*/
own: flexSetter(function(name, value) {
if (typeof value === 'function') {
this.ownMethod(name, value);
}
else {
this.prototype[name] = value;
}
}),
/**
* @private
*/
ownMethod: function(name, fn) {
var originalFn;
if (fn.$owner !== undefined && fn !== Ext.emptyFn) {
originalFn = fn;
fn = function() {
return originalFn.apply(this, arguments);
};
}
//<debug>
var className;
className = Ext.getClassName(this);
if (className) {
fn.displayName = className + '#' + name;
}
//</debug>
fn.$owner = this;
fn.$name = name;
this.prototype[name] = fn;
},
/**
* Add / override static properties of this class.
Ext.define('My.cool.Class', {
...
});
My.cool.Class.addStatics({
someProperty: 'someValue', // My.cool.Class.someProperty = 'someValue'
method1: function() { ... }, // My.cool.Class.method1 = function() { ... };
method2: function() { ... } // My.cool.Class.method2 = function() { ... };
});
* @property addStatics
* @static
* @type Function
* @param {Object} members
* @markdown
*/
addStatics: function(members) {
for (var name in members) {
if (members.hasOwnProperty(name)) {
this[name] = members[name];
}
}
return this;
},
/**
* Add methods / properties to the prototype of this class.
Ext.define('My.awesome.Cat', {
constructor: function() {
...
}
});
My.awesome.Cat.implement({
meow: function() {
alert('Meowww...');
}
});
var kitty = new My.awesome.Cat;
kitty.meow();
* @property implement
* @static
* @type Function
* @param {Object} members
* @markdown
*/
implement: function(members) {
var prototype = this.prototype,
name, i, member, previous;
//<debug>
var className = Ext.getClassName(this);
//</debug>
for (name in members) {
if (members.hasOwnProperty(name)) {
member = members[name];
if (typeof member === 'function') {
member.$owner = this;
member.$name = name;
//<debug>
if (className) {
member.displayName = className + '#' + name;
}
//</debug>
}
prototype[name] = member;
}
}
if (Ext.enumerables) {
var enumerables = Ext.enumerables;
for (i = enumerables.length; i--;) {
name = enumerables[i];
if (members.hasOwnProperty(name)) {
member = members[name];
member.$owner = this;
member.$name = name;
prototype[name] = member;
}
}
}
},
/**
* Borrow another class' members to the prototype of this class.
Ext.define('Bank', {
money: '$$$',
printMoney: function() {
alert('$$$$$$$');
}
});
Ext.define('Thief', {
...
});
Thief.borrow(Bank, ['money', 'printMoney']);
var steve = new Thief();
alert(steve.money); // alerts '$$$'
steve.printMoney(); // alerts '$$$$$$$'
* @property borrow
* @static
* @type Function
* @param {Ext.Base} fromClass The class to borrow members from
* @param {Array/String} members The names of the members to borrow
* @return {Ext.Base} this
* @markdown
*/
borrow: function(fromClass, members) {
var fromPrototype = fromClass.prototype,
i, ln, member;
members = Ext.Array.from(members);
for (i = 0, ln = members.length; i < ln; i++) {
member = members[i];
this.own(member, fromPrototype[member]);
}
return this;
},
/**
* Override prototype members of this class. Overridden methods can be invoked via
* {@link Ext.Base#callOverridden}
Ext.define('My.Cat', {
constructor: function() {
alert("I'm a cat!");
return this;
}
});
My.Cat.override({
constructor: function() {
alert("I'm going to be a cat!");
var instance = this.callOverridden();
alert("Meeeeoooowwww");
return instance;
}
});
var kitty = new My.Cat(); // alerts "I'm going to be a cat!"
// alerts "I'm a cat!"
// alerts "Meeeeoooowwww"
* @property override
* @static
* @type Function
* @param {Object} members
* @return {Ext.Base} this
* @markdown
*/
override: function(members) {
var prototype = this.prototype,
name, i, member, previous;
for (name in members) {
if (members.hasOwnProperty(name)) {
member = members[name];
if (typeof member === 'function') {
if (typeof prototype[name] === 'function') {
previous = prototype[name];
member.$previous = previous;
}
this.ownMethod(name, member);
}
else {
prototype[name] = member;
}
}
}
if (Ext.enumerables) {
var enumerables = Ext.enumerables;
for (i = enumerables.length; i--;) {
name = enumerables[i];
if (members.hasOwnProperty(name)) {
if (prototype[name] !== undefined) {
previous = prototype[name];
members[name].$previous = previous;
}
this.ownMethod(name, members[name]);
}
}
}
return this;
},
/**
* Used internally by the mixins pre-processor
* @private
*/
mixin: flexSetter(function(name, cls) {
var mixin = cls.prototype,
my = this.prototype,
i, fn;
for (i in mixin) {
if (mixin.hasOwnProperty(i)) {
if (my[i] === undefined) {
if (typeof mixin[i] === 'function') {
fn = mixin[i];
if (fn.$owner === undefined) {
this.ownMethod(i, fn);
}
else {
my[i] = fn;
}
}
else {
my[i] = mixin[i];
}
}
else if (i === 'config' && my.config && mixin.config) {
Ext.Object.merge(my.config, mixin.config);
}
}
}
if (my.mixins === undefined) {
my.mixins = {};
}
my.mixins[name] = mixin;
}),
/**
* Get the current class' name in string format.
Ext.define('My.cool.Class', {
constructor: function() {
alert(this.self.getName()); // alerts 'My.cool.Class'
}
});
My.cool.Class.getName(); // 'My.cool.Class'
* @return {String} className
* @markdown
*/
getName: function() {
return Ext.getClassName(this);
},
/**
* Create aliases for existing prototype methods. Example:
Ext.define('My.cool.Class', {
method1: function() { ... },
method2: function() { ... }
});
var test = new My.cool.Class();
My.cool.Class.createAlias({
method3: 'method1',
method4: 'method2'
});
test.method3(); // test.method1()
My.cool.Class.createAlias('method5', 'method3');
test.method5(); // test.method3() -> test.method1()
* @property createAlias
* @static
* @type Function
* @param {String/Object} alias The new method name, or an object to set multiple aliases. See
* {@link Ext.Function#flexSetter flexSetter}
* @param {String/Object} origin The original method name
* @markdown
*/
createAlias: flexSetter(function(alias, origin) {
this.prototype[alias] = this.prototype[origin];
})
});
})(Ext.Function.flexSetter);
/**
* @author Jacky Nguyen <jacky@sencha.com>
* @docauthor Jacky Nguyen <jacky@sencha.com>
* @class Ext.Class
*
* Handles class creation throughout the whole framework. Note that most of the time {@link Ext#define Ext.define} should
* be used instead, since it's a higher level wrapper that aliases to {@link Ext.ClassManager#create}
* to enable namespacing and dynamic dependency resolution.
*
* # Basic syntax: #
*
* Ext.define(className, properties);
*
* in which `properties` is an object represent a collection of properties that apply to the class. See
* {@link Ext.ClassManager#create} for more detailed instructions.
*
* Ext.define('Person', {
* name: 'Unknown',
*
* constructor: function(name) {
* if (name) {
* this.name = name;
* }
*
* return this;
* },
*
* eat: function(foodType) {
* alert("I'm eating: " + foodType);
*
* return this;
* }
* });
*
* var aaron = new Person("Aaron");
* aaron.eat("Sandwich"); // alert("I'm eating: Sandwich");
*
* Ext.Class has a powerful set of extensible {@link Ext.Class#registerPreprocessor pre-processors} which takes care of
* everything related to class creation, including but not limited to inheritance, mixins, configuration, statics, etc.
*
* # Inheritance: #
*
* Ext.define('Developer', {
* extend: 'Person',
*
* constructor: function(name, isGeek) {
* this.isGeek = isGeek;
*
* // Apply a method from the parent class' prototype
* this.callParent([name]);
*
* return this;
*
* },
*
* code: function(language) {
* alert("I'm coding in: " + language);
*
* this.eat("Bugs");
*
* return this;
* }
* });
*
* var jacky = new Developer("Jacky", true);
* jacky.code("JavaScript"); // alert("I'm coding in: JavaScript");
* // alert("I'm eating: Bugs");
*
* See {@link Ext.Base#callParent} for more details on calling superclass' methods
*
* # Mixins: #
*
* Ext.define('CanPlayGuitar', {
* playGuitar: function() {
* alert("F#...G...D...A");
* }
* });
*
* Ext.define('CanComposeSongs', {
* composeSongs: function() { ... }
* });
*
* Ext.define('CanSing', {
* sing: function() {
* alert("I'm on the highway to hell...")
* }
* });
*
* Ext.define('Musician', {
* extend: 'Person',
*
* mixins: {
* canPlayGuitar: 'CanPlayGuitar',
* canComposeSongs: 'CanComposeSongs',
* canSing: 'CanSing'
* }
* })
*
* Ext.define('CoolPerson', {
* extend: 'Person',
*
* mixins: {
* canPlayGuitar: 'CanPlayGuitar',
* canSing: 'CanSing'
* },
*
* sing: function() {
* alert("Ahem....");
*
* this.mixins.canSing.sing.call(this);
*
* alert("[Playing guitar at the same time...]");
*
* this.playGuitar();
* }
* });
*
* var me = new CoolPerson("Jacky");
*
* me.sing(); // alert("Ahem...");
* // alert("I'm on the highway to hell...");
* // alert("[Playing guitar at the same time...]");
* // alert("F#...G...D...A");
*
* # Config: #
*
* Ext.define('SmartPhone', {
* config: {
* hasTouchScreen: false,
* operatingSystem: 'Other',
* price: 500
* },
*
* isExpensive: false,
*
* constructor: function(config) {
* this.initConfig(config);
*
* return this;
* },
*
* applyPrice: function(price) {
* this.isExpensive = (price > 500);
*
* return price;
* },
*
* applyOperatingSystem: function(operatingSystem) {
* if (!(/^(iOS|Android|BlackBerry)$/i).test(operatingSystem)) {
* return 'Other';
* }
*
* return operatingSystem;
* }
* });
*
* var iPhone = new SmartPhone({
* hasTouchScreen: true,
* operatingSystem: 'iOS'
* });
*
* iPhone.getPrice(); // 500;
* iPhone.getOperatingSystem(); // 'iOS'
* iPhone.getHasTouchScreen(); // true;
* iPhone.hasTouchScreen(); // true
*
* iPhone.isExpensive; // false;
* iPhone.setPrice(600);
* iPhone.getPrice(); // 600
* iPhone.isExpensive; // true;
*
* iPhone.setOperatingSystem('AlienOS');
* iPhone.getOperatingSystem(); // 'Other'
*
* # Statics: #
*
* Ext.define('Computer', {
* statics: {
* factory: function(brand) {
* // 'this' in static methods refer to the class itself
* return new this(brand);
* }
* },
*
* constructor: function() { ... }
* });
*
* var dellComputer = Computer.factory('Dell');
*
* Also see {@link Ext.Base#statics} and {@link Ext.Base#self} for more details on accessing
* static properties within class methods
*
*/
(function() {
var Class,
Base = Ext.Base,
baseStaticProperties = [],
baseStaticProperty;
for (baseStaticProperty in Base) {
if (Base.hasOwnProperty(baseStaticProperty)) {
baseStaticProperties.push(baseStaticProperty);
}
}
/**
* @constructor
* @param {Object} classData An object represent the properties of this class
* @param {Function} createdFn Optional, the callback function to be executed when this class is fully created.
* Note that the creation process can be asynchronous depending on the pre-processors used.
* @return {Ext.Base} The newly created class
*/
Ext.Class = Class = function(newClass, classData, onClassCreated) {
if (typeof newClass !== 'function') {
onClassCreated = classData;
classData = newClass;
newClass = function() {
return this.constructor.apply(this, arguments);
};
}
if (!classData) {
classData = {};
}
var preprocessorStack = classData.preprocessors || Class.getDefaultPreprocessors(),
registeredPreprocessors = Class.getPreprocessors(),
index = 0,
preprocessors = [],
preprocessor, preprocessors, staticPropertyName, process, i, j, ln;
for (i = 0, ln = baseStaticProperties.length; i < ln; i++) {
staticPropertyName = baseStaticProperties[i];
newClass[staticPropertyName] = Base[staticPropertyName];
}
delete classData.preprocessors;
for (j = 0, ln = preprocessorStack.length; j < ln; j++) {
preprocessor = preprocessorStack[j];
if (typeof preprocessor === 'string') {
preprocessor = registeredPreprocessors[preprocessor];
if (!preprocessor.always) {
if (classData.hasOwnProperty(preprocessor.name)) {
preprocessors.push(preprocessor.fn);
}
}
else {
preprocessors.push(preprocessor.fn);
}
}
else {
preprocessors.push(preprocessor);
}
}
classData.onClassCreated = onClassCreated;
classData.onBeforeClassCreated = function(cls, data) {
onClassCreated = data.onClassCreated;
delete data.onBeforeClassCreated;
delete data.onClassCreated;
cls.implement(data);
if (onClassCreated) {
onClassCreated.call(cls, cls);
}
};
process = function(cls, data) {
preprocessor = preprocessors[index++];
if (!preprocessor) {
data.onBeforeClassCreated.apply(this, arguments);
return;
}
if (preprocessor.call(this, cls, data, process) !== false) {
process.apply(this, arguments);
}
};
process.call(Class, newClass, classData);
return newClass;
};
Ext.apply(Class, {
/** @private */
preprocessors: {},
/**
* Register a new pre-processor to be used during the class creation process
*
* @member Ext.Class registerPreprocessor
* @param {String} name The pre-processor's name
* @param {Function} fn The callback function to be executed. Typical format:
function(cls, data, fn) {
// Your code here
// Execute this when the processing is finished.
// Asynchronous processing is perfectly ok
if (fn) {
fn.call(this, cls, data);
}
});
* Passed arguments for this function are:
*
* - `{Function} cls`: The created class
* - `{Object} data`: The set of properties passed in {@link Ext.Class} constructor
* - `{Function} fn`: The callback function that <b>must</b> to be executed when this pre-processor finishes,
* regardless of whether the processing is synchronous or aynchronous
*
* @return {Ext.Class} this
* @markdown
*/
registerPreprocessor: function(name, fn, always) {
this.preprocessors[name] = {
name: name,
always: always || false,
fn: fn
};
return this;
},
/**
* Retrieve a pre-processor callback function by its name, which has been registered before
*
* @param {String} name
* @return {Function} preprocessor
*/
getPreprocessor: function(name) {
return this.preprocessors[name];
},
getPreprocessors: function() {
return this.preprocessors;
},
/**
* Retrieve the array stack of default pre-processors
*
* @return {Function} defaultPreprocessors
*/
getDefaultPreprocessors: function() {
return this.defaultPreprocessors || [];
},
/**
* Set the default array stack of default pre-processors
*
* @param {Array} preprocessors
* @return {Ext.Class} this
*/
setDefaultPreprocessors: function(preprocessors) {
this.defaultPreprocessors = Ext.Array.from(preprocessors);
return this;
},
/**
* Insert this pre-processor at a specific position in the stack, optionally relative to
* any existing pre-processor. For example:
Ext.Class.registerPreprocessor('debug', function(cls, data, fn) {
// Your code here
if (fn) {
fn.call(this, cls, data);
}
}).insertDefaultPreprocessor('debug', 'last');
* @param {String} name The pre-processor name. Note that it needs to be registered with
* {@link Ext#registerPreprocessor registerPreprocessor} before this
* @param {String} offset The insertion position. Four possible values are:
* 'first', 'last', or: 'before', 'after' (relative to the name provided in the third argument)
* @param {String} relativeName
* @return {Ext.Class} this
* @markdown
*/
setDefaultPreprocessorPosition: function(name, offset, relativeName) {
var defaultPreprocessors = this.defaultPreprocessors,
index;
if (typeof offset === 'string') {
if (offset === 'first') {
defaultPreprocessors.unshift(name);
return this;
}
else if (offset === 'last') {
defaultPreprocessors.push(name);
return this;
}
offset = (offset === 'after') ? 1 : -1;
}
index = Ext.Array.indexOf(defaultPreprocessors, relativeName);
if (index !== -1) {
defaultPreprocessors.splice(Math.max(0, index + offset), 0, name);
}
return this;
}
});
Class.registerPreprocessor('extend', function(cls, data) {
var extend = data.extend,
base = Ext.Base,
basePrototype = base.prototype,
prototype = function() {},
parent, i, k, ln, staticName, parentStatics,
parentPrototype, clsPrototype;
if (extend && extend !== Object) {
parent = extend;
}
else {
parent = base;
}
parentPrototype = parent.prototype;
prototype.prototype = parentPrototype;
clsPrototype = cls.prototype = new prototype();
if (!('$class' in parent)) {
for (i in basePrototype) {
if (!parentPrototype[i]) {
parentPrototype[i] = basePrototype[i];
}
}
}
clsPrototype.self = cls;
cls.superclass = clsPrototype.superclass = parentPrototype;
delete data.extend;
// Statics inheritance
parentStatics = parentPrototype.$inheritableStatics;
if (parentStatics) {
for (k = 0, ln = parentStatics.length; k < ln; k++) {
staticName = parentStatics[k];
if (!cls.hasOwnProperty(staticName)) {
cls[staticName] = parent[staticName];
}
}
}
// Merge the parent class' config object without referencing it
if (parentPrototype.config) {
clsPrototype.config = Ext.Object.merge({}, parentPrototype.config);
}
else {
clsPrototype.config = {};
}
if (clsPrototype.$onExtended) {
clsPrototype.$onExtended.call(cls, cls, data);
}
if (data.onClassExtended) {
clsPrototype.$onExtended = data.onClassExtended;
delete data.onClassExtended;
}
}, true);
Class.registerPreprocessor('statics', function(cls, data) {
var statics = data.statics,
name;
for (name in statics) {
if (statics.hasOwnProperty(name)) {
cls[name] = statics[name];
}
}
delete data.statics;
});
Class.registerPreprocessor('inheritableStatics', function(cls, data) {
var statics = data.inheritableStatics,
inheritableStatics,
prototype = cls.prototype,
name;
inheritableStatics = prototype.$inheritableStatics;
if (!inheritableStatics) {
inheritableStatics = prototype.$inheritableStatics = [];
}
for (name in statics) {
if (statics.hasOwnProperty(name)) {
cls[name] = statics[name];
inheritableStatics.push(name);
}
}
delete data.inheritableStatics;
});
Class.registerPreprocessor('mixins', function(cls, data) {
cls.mixin(data.mixins);
delete data.mixins;
});
Class.registerPreprocessor('config', function(cls, data) {
var prototype = cls.prototype;
Ext.Object.each(data.config, function(name) {
var cName = name.charAt(0).toUpperCase() + name.substr(1),
pName = name,
apply = 'apply' + cName,
setter = 'set' + cName,
getter = 'get' + cName;
if (!(apply in prototype) && !data.hasOwnProperty(apply)) {
data[apply] = function(val) {
return val;
};
}
if (!(setter in prototype) && !data.hasOwnProperty(setter)) {
data[setter] = function(val) {
var ret = this[apply].call(this, val, this[pName]);
if (ret !== undefined) {
this[pName] = ret;
}
return this;
};
}
if (!(getter in prototype) && !data.hasOwnProperty(getter)) {
data[getter] = function() {
return this[pName];
};
}
});
Ext.Object.merge(prototype.config, data.config);
delete data.config;
});
Class.setDefaultPreprocessors(['extend', 'statics', 'inheritableStatics', 'mixins', 'config']);
// Backwards compatible
Ext.extend = function(subclass, superclass, members) {
if (arguments.length === 2 && Ext.isObject(superclass)) {
members = superclass;
superclass = subclass;
subclass = null;
}
var cls;
if (!superclass) {
Ext.Error.raise("Attempting to extend from a class which has not been loaded on the page.");
}
members.extend = superclass;
members.preprocessors = ['extend', 'mixins', 'config', 'statics'];
if (subclass) {
cls = new Class(subclass, members);
}
else {
cls = new Class(members);
}
cls.prototype.override = function(o) {
for (var m in o) {
if (o.hasOwnProperty(m)) {
this[m] = o[m];
}
}
};
return cls;
};
})();
/**
* @author Jacky Nguyen <jacky@sencha.com>
* @docauthor Jacky Nguyen <jacky@sencha.com>
* @class Ext.ClassManager
Ext.ClassManager manages all classes and handles mapping from string class name to
actual class objects throughout the whole framework. It is not generally accessed directly, rather through
these convenient shorthands:
- {@link Ext#define Ext.define}
- {@link Ext#create Ext.create}
- {@link Ext#widget Ext.widget}
- {@link Ext#getClass Ext.getClass}
- {@link Ext#getClassName Ext.getClassName}
* @singleton
* @markdown
*/
(function(Class, alias) {
var slice = Array.prototype.slice;
var Manager = Ext.ClassManager = {
/**
* @property classes
* @type Object
* All classes which were defined through the ClassManager. Keys are the
* name of the classes and the values are references to the classes.
* @private
*/
classes: {},
/**
* @private
*/
existCache: {},
/**
* @private
*/
namespaceRewrites: [{
from: 'Ext.',
to: Ext
}],
/**
* @private
*/
maps: {
alternateToName: {},
aliasToName: {},
nameToAliases: {}
},
/** @private */
enableNamespaceParseCache: true,
/** @private */
namespaceParseCache: {},
/** @private */
instantiators: [],
//<debug>
/** @private */
instantiationCounts: {},
//</debug>
/**
* Checks if a class has already been created.
*
* @param {String} className
* @return {Boolean} exist
*/
isCreated: function(className) {
var i, ln, part, root, parts;
//<debug error>
if (typeof className !== 'string' || className.length < 1) {
Ext.Error.raise({
sourceClass: "Ext.ClassManager",
sourceMethod: "exist",
msg: "Invalid classname, must be a string and must not be empty"
});
}
//</debug>
if (this.classes.hasOwnProperty(className) || this.existCache.hasOwnProperty(className)) {
return true;
}
root = Ext.global;
parts = this.parseNamespace(className);
for (i = 0, ln = parts.length; i < ln; i++) {
part = parts[i];
if (typeof part !== 'string') {
root = part;
} else {
if (!root || !root[part]) {
return false;
}
root = root[part];
}
}
Ext.Loader.historyPush(className);
this.existCache[className] = true;
return true;
},
/**
* Supports namespace rewriting
* @private
*/
parseNamespace: function(namespace) {
//<debug error>
if (typeof namespace !== 'string') {
Ext.Error.raise({
sourceClass: "Ext.ClassManager",
sourceMethod: "parseNamespace",
msg: "Invalid namespace, must be a string"
});
}
//</debug>
var cache = this.namespaceParseCache;
if (this.enableNamespaceParseCache) {
if (cache.hasOwnProperty(namespace)) {
return cache[namespace];
}
}
var parts = [],
rewrites = this.namespaceRewrites,
rewrite, from, to, i, ln, root = Ext.global;
for (i = 0, ln = rewrites.length; i < ln; i++) {
rewrite = rewrites[i];
from = rewrite.from;
to = rewrite.to;
if (namespace === from || namespace.substring(0, from.length) === from) {
namespace = namespace.substring(from.length);
if (typeof to !== 'string') {
root = to;
} else {
parts = parts.concat(to.split('.'));
}
break;
}
}
parts.push(root);
parts = parts.concat(namespace.split('.'));
if (this.enableNamespaceParseCache) {
cache[namespace] = parts;
}
return parts;
},
/**
* Creates a namespace and assign the `value` to the created object
Ext.ClassManager.setNamespace('MyCompany.pkg.Example', someObject);
alert(MyCompany.pkg.Example === someObject); // alerts true
* @param {String} name
* @param {Mixed} value
* @markdown
*/
setNamespace: function(name, value) {
var root = Ext.global,
parts = this.parseNamespace(name),
leaf = parts.pop(),
i, ln, part;
for (i = 0, ln = parts.length; i < ln; i++) {
part = parts[i];
if (typeof part !== 'string') {
root = part;
} else {
if (!root[part]) {
root[part] = {};
}
root = root[part];
}
}
root[leaf] = value;
return root[leaf];
},
/**
* The new Ext.ns, supports namespace rewriting
* @private
*/
createNamespaces: function() {
var root = Ext.global,
parts, part, i, j, ln, subLn;
for (i = 0, ln = arguments.length; i < ln; i++) {
parts = this.parseNamespace(arguments[i]);
for (j = 0, subLn = parts.length; j < subLn; j++) {
part = parts[j];
if (typeof part !== 'string') {
root = part;
} else {
if (!root[part]) {
root[part] = {};
}
root = root[part];
}
}
}
return root;
},
/**
* Sets a name reference to a class.
*
* @param {String} name
* @param {Object} value
* @return {Ext.ClassManager} this
*/
set: function(name, value) {
var targetName = this.getName(value);
this.classes[name] = this.setNamespace(name, value);
if (targetName && targetName !== name) {
this.maps.alternateToName[name] = targetName;
}
return this;
},
/**
* Retrieve a class by its name.
*
* @param {String} name
* @return {Class} class
*/
get: function(name) {
if (this.classes.hasOwnProperty(name)) {
return this.classes[name];
}
var root = Ext.global,
parts = this.parseNamespace(name),
part, i, ln;
for (i = 0, ln = parts.length; i < ln; i++) {
part = parts[i];
if (typeof part !== 'string') {
root = part;
} else {
if (!root || !root[part]) {
return null;
}
root = root[part];
}
}
return root;
},
/**
* Register the alias for a class.
*
* @param {Class/String} cls a reference to a class or a className
* @param {String} alias Alias to use when referring to this class
*/
setAlias: function(cls, alias) {
var aliasToNameMap = this.maps.aliasToName,
nameToAliasesMap = this.maps.nameToAliases,
className;
if (typeof cls === 'string') {
className = cls;
} else {
className = this.getName(cls);
}
if (alias && aliasToNameMap[alias] !== className) {
//<debug info>
if (aliasToNameMap.hasOwnProperty(alias) && Ext.isDefined(Ext.global.console)) {
Ext.global.console.log("[Ext.ClassManager] Overriding existing alias: '" + alias + "' " +
"of: '" + aliasToNameMap[alias] + "' with: '" + className + "'. Be sure it's intentional.");
}
//</debug>
aliasToNameMap[alias] = className;
}
if (!nameToAliasesMap[className]) {
nameToAliasesMap[className] = [];
}
if (alias) {
Ext.Array.include(nameToAliasesMap[className], alias);
}
return this;
},
/**
* Get a reference to the class by its alias.
*
* @param {String} alias
* @return {Class} class
*/
getByAlias: function(alias) {
return this.get(this.getNameByAlias(alias));
},
/**
* Get the name of a class by its alias.
*
* @param {String} alias
* @return {String} className
*/
getNameByAlias: function(alias) {
return this.maps.aliasToName[alias] || '';
},
/**
* Get the name of a class by its alternate name.
*
* @param {String} alternate
* @return {String} className
*/
getNameByAlternate: function(alternate) {
return this.maps.alternateToName[alternate] || '';
},
/**
* Get the aliases of a class by the class name
*
* @param {String} name
* @return {Array} aliases
*/
getAliasesByName: function(name) {
return this.maps.nameToAliases[name] || [];
},
/**
* Get the name of the class by its reference or its instance;
* usually invoked by the shorthand {@link Ext#getClassName Ext.getClassName}
Ext.ClassManager.getName(Ext.Action); // returns "Ext.Action"
* @param {Class/Object} object
* @return {String} className
* @markdown
*/
getName: function(object) {
return object && object.$className || '';
},
/**
* Get the class of the provided object; returns null if it's not an instance
* of any class created with Ext.define. This is usually invoked by the shorthand {@link Ext#getClass Ext.getClass}
*
var component = new Ext.Component();
Ext.ClassManager.getClass(component); // returns Ext.Component
*
* @param {Object} object
* @return {Class} class
* @markdown
*/
getClass: function(object) {
return object && object.self || null;
},
/**
* Defines a class. This is usually invoked via the alias {@link Ext#define Ext.define}
Ext.ClassManager.create('My.awesome.Class', {
someProperty: 'something',
someMethod: function() { ... }
...
}, function() {
alert('Created!');
alert(this === My.awesome.Class); // alerts true
var myInstance = new this();
});
* @param {String} className The class name to create in string dot-namespaced format, for example:
* 'My.very.awesome.Class', 'FeedViewer.plugin.CoolPager'
* It is highly recommended to follow this simple convention:
- The root and the class name are 'CamelCased'
- Everything else is lower-cased
* @param {Object} data The key - value pairs of properties to apply to this class. Property names can be of any valid
* strings, except those in the reserved listed below:
- `mixins`
- `statics`
- `config`
- `alias`
- `self`
- `singleton`
- `alternateClassName`
*
* @param {Function} createdFn Optional callback to execute after the class is created, the execution scope of which
* (`this`) will be the newly created class itself.
* @return {Ext.Base}
* @markdown
*/
create: function(className, data, createdFn) {
var manager = this;
//<debug error>
if (typeof className !== 'string') {
Ext.Error.raise({
sourceClass: "Ext",
sourceMethod: "define",
msg: "Invalid class name '" + className + "' specified, must be a non-empty string"
});
}
//</debug>
data.$className = className;
return new Class(data, function() {
var postprocessorStack = data.postprocessors || manager.defaultPostprocessors,
registeredPostprocessors = manager.postprocessors,
index = 0,
postprocessors = [],
postprocessor, postprocessors, process, i, ln;
delete data.postprocessors;
for (i = 0, ln = postprocessorStack.length; i < ln; i++) {
postprocessor = postprocessorStack[i];
if (typeof postprocessor === 'string') {
postprocessor = registeredPostprocessors[postprocessor];
if (!postprocessor.always) {
if (data[postprocessor.name] !== undefined) {
postprocessors.push(postprocessor.fn);
}
}
else {
postprocessors.push(postprocessor.fn);
}
}
else {
postprocessors.push(postprocessor);
}
}
process = function(clsName, cls, clsData) {
postprocessor = postprocessors[index++];
if (!postprocessor) {
manager.set(className, cls);
Ext.Loader.historyPush(className);
if (createdFn) {
createdFn.call(cls, cls);
}
return;
}
if (postprocessor.call(this, clsName, cls, clsData, process) !== false) {
process.apply(this, arguments);
}
};
process.call(manager, className, this, data);
});
},
/**
* Instantiate a class by its alias; usually invoked by the convenient shorthand {@link Ext#createByAlias Ext.createByAlias}
* If {@link Ext.Loader} is {@link Ext.Loader#setConfig enabled} and the class has not been defined yet, it will
* attempt to load the class via synchronous loading.
var window = Ext.ClassManager.instantiateByAlias('widget.window', { width: 600, height: 800, ... });
* @param {String} alias
* @param {Mixed} args,... Additional arguments after the alias will be passed to the
* class constructor.
* @return {Object} instance
* @markdown
*/
instantiateByAlias: function() {
var alias = arguments[0],
args = slice.call(arguments),
className = this.getNameByAlias(alias);
if (!className) {
className = this.maps.aliasToName[alias];
//<debug error>
if (!className) {
Ext.Error.raise({
sourceClass: "Ext",
sourceMethod: "createByAlias",
msg: "Cannot create an instance of unrecognized alias: " + alias
});
}
//</debug>
//<debug warn>
if (Ext.global.console) {
Ext.global.console.warn("[Ext.Loader] Synchronously loading '" + className + "'; consider adding " +
"Ext.require('" + alias + "') above Ext.onReady");
}
//</debug>
Ext.syncRequire(className);
}
args[0] = className;
return this.instantiate.apply(this, args);
},
/**
* Instantiate a class by either full name, alias or alternate name; usually invoked by the convenient
* shorthand {@link Ext#create Ext.create}
*
* If {@link Ext.Loader} is {@link Ext.Loader#setConfig enabled} and the class has not been defined yet, it will
* attempt to load the class via synchronous loading.
*
* For example, all these three lines return the same result:
// alias
var window = Ext.ClassManager.instantiate('widget.window', { width: 600, height: 800, ... });
// alternate name
var window = Ext.ClassManager.instantiate('Ext.Window', { width: 600, height: 800, ... });
// full class name
var window = Ext.ClassManager.instantiate('Ext.window.Window', { width: 600, height: 800, ... });
* @param {String} name
* @param {Mixed} args,... Additional arguments after the name will be passed to the class' constructor.
* @return {Object} instance
* @markdown
*/
instantiate: function() {
var name = arguments[0],
args = slice.call(arguments, 1),
alias = name,
possibleName, cls;
if (typeof name !== 'function') {
//<debug error>
if ((typeof name !== 'string' || name.length < 1)) {
Ext.Error.raise({
sourceClass: "Ext",
sourceMethod: "create",
msg: "Invalid class name or alias '" + name + "' specified, must be a non-empty string"
});
}
//</debug>
cls = this.get(name);
}
else {
cls = name;
}
// No record of this class name, it's possibly an alias, so look it up
if (!cls) {
possibleName = this.getNameByAlias(name);
if (possibleName) {
name = possibleName;
cls = this.get(name);
}
}
// Still no record of this class name, it's possibly an alternate name, so look it up
if (!cls) {
possibleName = this.getNameByAlternate(name);
if (possibleName) {
name = possibleName;
cls = this.get(name);
}
}
// Still not existing at this point, try to load it via synchronous mode as the last resort
if (!cls) {
//<debug warn>
if (Ext.global.console) {
Ext.global.console.warn("[Ext.Loader] Synchronously loading '" + name + "'; consider adding " +
"Ext.require('" + ((possibleName) ? alias : name) + "') above Ext.onReady");
}
//</debug>
Ext.syncRequire(name);
cls = this.get(name);
}
//<debug error>
if (!cls) {
Ext.Error.raise({
sourceClass: "Ext",
sourceMethod: "create",
msg: "Cannot create an instance of unrecognized class name / alias: " + alias
});
}
if (typeof cls !== 'function') {
Ext.Error.raise({
sourceClass: "Ext",
sourceMethod: "create",
msg: "'" + name + "' is a singleton and cannot be instantiated"
});
}
//</debug>
//<debug>
if (!this.instantiationCounts[name]) {
this.instantiationCounts[name] = 0;
}
this.instantiationCounts[name]++;
//</debug>
return this.getInstantiator(args.length)(cls, args);
},
/**
* @private
* @param name
* @param args
*/
dynInstantiate: function(name, args) {
args = Ext.Array.from(args, true);
args.unshift(name);
return this.instantiate.apply(this, args);
},
/**
* @private
* @param length
*/
getInstantiator: function(length) {
if (!this.instantiators[length]) {
var i = length,
args = [];
for (i = 0; i < length; i++) {
args.push('a['+i+']');
}
this.instantiators[length] = new Function('c', 'a', 'return new c('+args.join(',')+')');
}
return this.instantiators[length];
},
/**
* @private
*/
postprocessors: {},
/**
* @private
*/
defaultPostprocessors: [],
/**
* Register a post-processor function.
*
* @param {String} name
* @param {Function} postprocessor
*/
registerPostprocessor: function(name, fn, always) {
this.postprocessors[name] = {
name: name,
always: always || false,
fn: fn
};
return this;
},
/**
* Set the default post processors array stack which are applied to every class.
*
* @param {String/Array} The name of a registered post processor or an array of registered names.
* @return {Ext.ClassManager} this
*/
setDefaultPostprocessors: function(postprocessors) {
this.defaultPostprocessors = Ext.Array.from(postprocessors);
return this;
},
/**
* Insert this post-processor at a specific position in the stack, optionally relative to
* any existing post-processor
*
* @param {String} name The post-processor name. Note that it needs to be registered with
* {@link Ext.ClassManager#registerPostprocessor} before this
* @param {String} offset The insertion position. Four possible values are:
* 'first', 'last', or: 'before', 'after' (relative to the name provided in the third argument)
* @param {String} relativeName
* @return {Ext.ClassManager} this
*/
setDefaultPostprocessorPosition: function(name, offset, relativeName) {
var defaultPostprocessors = this.defaultPostprocessors,
index;
if (typeof offset === 'string') {
if (offset === 'first') {
defaultPostprocessors.unshift(name);
return this;
}
else if (offset === 'last') {
defaultPostprocessors.push(name);
return this;
}
offset = (offset === 'after') ? 1 : -1;
}
index = Ext.Array.indexOf(defaultPostprocessors, relativeName);
if (index !== -1) {
defaultPostprocessors.splice(Math.max(0, index + offset), 0, name);
}
return this;
},
/**
* Converts a string expression to an array of matching class names. An expression can either refers to class aliases
* or class names. Expressions support wildcards:
// returns ['Ext.window.Window']
var window = Ext.ClassManager.getNamesByExpression('widget.window');
// returns ['widget.panel', 'widget.window', ...]
var allWidgets = Ext.ClassManager.getNamesByExpression('widget.*');
// returns ['Ext.data.Store', 'Ext.data.ArrayProxy', ...]
var allData = Ext.ClassManager.getNamesByExpression('Ext.data.*');
* @param {String} expression
* @return {Array} classNames
* @markdown
*/
getNamesByExpression: function(expression) {
var nameToAliasesMap = this.maps.nameToAliases,
names = [],
name, alias, aliases, possibleName, regex, i, ln;
//<debug error>
if (typeof expression !== 'string' || expression.length < 1) {
Ext.Error.raise({
sourceClass: "Ext.ClassManager",
sourceMethod: "getNamesByExpression",
msg: "Expression " + expression + " is invalid, must be a non-empty string"
});
}
//</debug>
if (expression.indexOf('*') !== -1) {
expression = expression.replace(/\*/g, '(.*?)');
regex = new RegExp('^' + expression + '$');
for (name in nameToAliasesMap) {
if (nameToAliasesMap.hasOwnProperty(name)) {
aliases = nameToAliasesMap[name];
if (name.search(regex) !== -1) {
names.push(name);
}
else {
for (i = 0, ln = aliases.length; i < ln; i++) {
alias = aliases[i];
if (alias.search(regex) !== -1) {
names.push(name);
break;
}
}
}
}
}
} else {
possibleName = this.getNameByAlias(expression);
if (possibleName) {
names.push(possibleName);
} else {
possibleName = this.getNameByAlternate(expression);
if (possibleName) {
names.push(possibleName);
} else {
names.push(expression);
}
}
}
return names;
}
};
Manager.registerPostprocessor('alias', function(name, cls, data) {
var aliases = data.alias,
widgetPrefix = 'widget.',
i, ln, alias;
if (!(aliases instanceof Array)) {
aliases = [aliases];
}
for (i = 0, ln = aliases.length; i < ln; i++) {
alias = aliases[i];
//<debug error>
if (typeof alias !== 'string') {
Ext.Error.raise({
sourceClass: "Ext",
sourceMethod: "define",
msg: "Invalid alias of: '" + alias + "' for class: '" + name + "'; must be a valid string"
});
}
//</debug>
this.setAlias(cls, alias);
}
// This is ugly, will change to make use of parseNamespace for alias later on
for (i = 0, ln = aliases.length; i < ln; i++) {
alias = aliases[i];
if (alias.substring(0, widgetPrefix.length) === widgetPrefix) {
// Only the first alias with 'widget.' prefix will be used for xtype
cls.xtype = cls.$xtype = alias.substring(widgetPrefix.length);
break;
}
}
});
Manager.registerPostprocessor('singleton', function(name, cls, data, fn) {
fn.call(this, name, new cls(), data);
return false;
});
Manager.registerPostprocessor('alternateClassName', function(name, cls, data) {
var alternates = data.alternateClassName,
i, ln, alternate;
if (!(alternates instanceof Array)) {
alternates = [alternates];
}
for (i = 0, ln = alternates.length; i < ln; i++) {
alternate = alternates[i];
//<debug error>
if (typeof alternate !== 'string') {
Ext.Error.raise({
sourceClass: "Ext",
sourceMethod: "define",
msg: "Invalid alternate of: '" + alternate + "' for class: '" + name + "'; must be a valid string"
});
}
//</debug>
this.set(alternate, cls);
}
});
Manager.setDefaultPostprocessors(['alias', 'singleton', 'alternateClassName']);
Ext.apply(Ext, {
/**
* Convenient shorthand, see {@link Ext.ClassManager#instantiate}
* @member Ext
* @method create
*/
create: alias(Manager, 'instantiate'),
/**
* @private
* API to be stablized
*
* @param {Mixed} item
* @param {String} namespace
*/
factory: function(item, namespace) {
if (item instanceof Array) {
var i, ln;
for (i = 0, ln = item.length; i < ln; i++) {
item[i] = Ext.factory(item[i], namespace);
}
return item;
}
var isString = (typeof item === 'string');
if (isString || (item instanceof Object && item.constructor === Object)) {
var name, config = {};
if (isString) {
name = item;
}
else {
name = item.className;
config = item;
delete config.className;
}
if (namespace !== undefined && name.indexOf(namespace) === -1) {
name = namespace + '.' + Ext.String.capitalize(name);
}
return Ext.create(name, config);
}
if (typeof item === 'function') {
return Ext.create(item);
}
return item;
},
/**
* Convenient shorthand to create a widget by its xtype, also see {@link Ext.ClassManager#instantiateByAlias}
var button = Ext.widget('button'); // Equivalent to Ext.create('widget.button')
var panel = Ext.widget('panel'); // Equivalent to Ext.create('widget.panel')
* @member Ext
* @method widget
* @markdown
*/
widget: function(name) {
var args = slice.call(arguments);
args[0] = 'widget.' + name;
return Manager.instantiateByAlias.apply(Manager, args);
},
/**
* Convenient shorthand, see {@link Ext.ClassManager#instantiateByAlias}
* @member Ext
* @method createByAlias
*/
createByAlias: alias(Manager, 'instantiateByAlias'),
/**
* Convenient shorthand for {@link Ext.ClassManager#create}, see detailed {@link Ext.Class explanation}
* @member Ext
* @method define
*/
define: alias(Manager, 'create'),
/**
* Convenient shorthand, see {@link Ext.ClassManager#getName}
* @member Ext
* @method getClassName
*/
getClassName: alias(Manager, 'getName'),
/**
*
* @param {Mixed} object
*/
getDisplayName: function(object) {
if (object.displayName) {
return object.displayName;
}
if (object.$name && object.$class) {
return Ext.getClassName(object.$class) + '#' + object.$name;
}
if (object.$className) {
return object.$className;
}
return 'Anonymous';
},
/**
* Convenient shorthand, see {@link Ext.ClassManager#getClass}
* @member Ext
* @method getClassName
*/
getClass: alias(Manager, 'getClass'),
/**
* Creates namespaces to be used for scoping variables and classes so that they are not global.
* Specifying the last node of a namespace implicitly creates all other nodes. Usage:
Ext.namespace('Company', 'Company.data');
// equivalent and preferable to the above syntax
Ext.namespace('Company.data');
Company.Widget = function() { ... };
Company.data.CustomStore = function(config) { ... };
* @param {String} namespace1
* @param {String} namespace2
* @param {String} etc
* @return {Object} The namespace object. (If multiple arguments are passed, this will be the last namespace created)
* @function
* @member Ext
* @method namespace
* @markdown
*/
namespace: alias(Manager, 'createNamespaces')
});
Ext.createWidget = Ext.widget;
/**
* Convenient alias for {@link Ext#namespace Ext.namespace}
* @member Ext
* @method ns
*/
Ext.ns = Ext.namespace;
Class.registerPreprocessor('className', function(cls, data) {
if (data.$className) {
cls.$className = data.$className;
//<debug>
cls.displayName = cls.$className;
//</debug>
}
}, true);
Class.setDefaultPreprocessorPosition('className', 'first');
})(Ext.Class, Ext.Function.alias);
/**
* @author Jacky Nguyen <jacky@sencha.com>
* @docauthor Jacky Nguyen <jacky@sencha.com>
* @class Ext.Loader
*
Ext.Loader is the heart of the new dynamic dependency loading capability in Ext JS 4+. It is most commonly used
via the {@link Ext#require} shorthand. Ext.Loader supports both asynchronous and synchronous loading
approaches, and leverage their advantages for the best development flow. We'll discuss about the pros and cons of each approach:
# Asynchronous Loading #
- Advantages:
+ Cross-domain
+ No web server needed: you can run the application via the file system protocol (i.e: `file://path/to/your/index
.html`)
+ Best possible debugging experience: error messages come with the exact file name and line number
- Disadvantages:
+ Dependencies need to be specified before-hand
### Method 1: Explicitly include what you need: ###
// Syntax
Ext.require({String/Array} expressions);
// Example: Single alias
Ext.require('widget.window');
// Example: Single class name
Ext.require('Ext.window.Window');
// Example: Multiple aliases / class names mix
Ext.require(['widget.window', 'layout.border', 'Ext.data.Connection']);
// Wildcards
Ext.require(['widget.*', 'layout.*', 'Ext.data.*']);
### Method 2: Explicitly exclude what you don't need: ###
// Syntax: Note that it must be in this chaining format.
Ext.exclude({String/Array} expressions)
.require({String/Array} expressions);
// Include everything except Ext.data.*
Ext.exclude('Ext.data.*').require('*');
// Include all widgets except widget.checkbox*,
// which will match widget.checkbox, widget.checkboxfield, widget.checkboxgroup, etc.
Ext.exclude('widget.checkbox*').require('widget.*');
# Synchronous Loading on Demand #
- *Advantages:*
+ There's no need to specify dependencies before-hand, which is always the convenience of including ext-all.js
before
- *Disadvantages:*
+ Not as good debugging experience since file name won't be shown (except in Firebug at the moment)
+ Must be from the same domain due to XHR restriction
+ Need a web server, same reason as above
There's one simple rule to follow: Instantiate everything with Ext.create instead of the `new` keyword
Ext.create('widget.window', { ... }); // Instead of new Ext.window.Window({...});
Ext.create('Ext.window.Window', {}); // Same as above, using full class name instead of alias
Ext.widget('window', {}); // Same as above, all you need is the traditional `xtype`
Behind the scene, {@link Ext.ClassManager} will automatically check whether the given class name / alias has already
existed on the page. If it's not, Ext.Loader will immediately switch itself to synchronous mode and automatic load the given
class and all its dependencies.
# Hybrid Loading - The Best of Both Worlds #
It has all the advantages combined from asynchronous and synchronous loading. The development flow is simple:
### Step 1: Start writing your application using synchronous approach. Ext.Loader will automatically fetch all
dependencies on demand as they're needed during run-time. For example: ###
Ext.onReady(function(){
var window = Ext.createWidget('window', {
width: 500,
height: 300,
layout: {
type: 'border',
padding: 5
},
title: 'Hello Dialog',
items: [{
title: 'Navigation',
collapsible: true,
region: 'west',
width: 200,
html: 'Hello',
split: true
}, {
title: 'TabPanel',
region: 'center'
}]
});
window.show();
})
### Step 2: Along the way, when you need better debugging ability, watch the console for warnings like these: ###
[Ext.Loader] Synchronously loading 'Ext.window.Window'; consider adding Ext.require('Ext.window.Window') before your application's code
ClassManager.js:432
[Ext.Loader] Synchronously loading 'Ext.layout.container.Border'; consider adding Ext.require('Ext.layout.container.Border') before your application's code
Simply copy and paste the suggested code above `Ext.onReady`, i.e:
Ext.require('Ext.window.Window');
Ext.require('Ext.layout.container.Border');
Ext.onReady(...);
Everything should now load via asynchronous mode.
# Deployment #
It's important to note that dynamic loading should only be used during development on your local machines.
During production, all dependencies should be combined into one single JavaScript file. Ext.Loader makes
the whole process of transitioning from / to between development / maintenance and production as easy as
possible. Internally {@link Ext.Loader#history Ext.Loader.history} maintains the list of all dependencies your application
needs in the exact loading sequence. It's as simple as concatenating all files in this array into one,
then include it on top of your application.
This process will be automated with Sencha Command, to be released and documented towards Ext JS 4 Final.
* @singleton
* @markdown
*/
(function(Manager, Class, flexSetter, alias) {
var
//<if nonBrowser>
isNonBrowser = typeof window === 'undefined',
isNodeJS = isNonBrowser && (typeof require === 'function'),
isPhantomJS = (typeof phantom !== 'undefined' && phantom.fs),
//</if>
dependencyProperties = ['extend', 'mixins', 'requires'],
Loader;
Loader = Ext.Loader = {
/**
* @private
*/
documentHead: typeof document !== 'undefined' && (document.head || document.getElementsByTagName('head')[0]),
/**
* Flag indicating whether there are still files being loaded
* @private
*/
isLoading: false,
/**
* Maintain the queue for all dependencies. Each item in the array is an object of the format:
* {
* requires: [...], // The required classes for this queue item
* callback: function() { ... } // The function to execute when all classes specified in requires exist
* }
* @private
*/
queue: [],
/**
* Maintain the list of files that have already been handled so that they never get double-loaded
* @private
*/
isFileLoaded: {},
/**
* Maintain the list of listeners to execute when all required scripts are fully loaded
* @private
*/
readyListeners: [],
/**
* Contains optional dependencies to be loaded last
* @private
*/
optionalRequires: [],
/**
* Map of fully qualified class names to an array of dependent classes.
* @private
*/
requiresMap: {},
/**
* @private
*/
numPendingFiles: 0,
/**
* @private
*/
numLoadedFiles: 0,
/** @private */
hasFileLoadError: false,
/**
* @private
*/
classNameToFilePathMap: {},
/**
* An array of class names to keep track of the dependency loading order.
* This is not guaranteed to be the same everytime due to the asynchronous
* nature of the Loader.
*
* @property history
* @type Array
*/
history: [],
/**
* Configuration
* @private
*/
config: {
/**
* Whether or not to enable the dynamic dependency loading feature
* Defaults to false
* @cfg {Boolean} enabled
*/
enabled: false,
/**
* @cfg {Boolean} disableCaching
* Appends current timestamp to script files to prevent caching
* Defaults to true
*/
disableCaching: true,
/**
* @cfg {String} disableCachingParam
* The get parameter name for the cache buster's timestamp.
* Defaults to '_dc'
*/
disableCachingParam: '_dc',
/**
* @cfg {Object} paths
* The mapping from namespaces to file paths
{
'Ext': '.', // This is set by default, Ext.layout.container.Container will be
// loaded from ./layout/Container.js
'My': './src/my_own_folder' // My.layout.Container will be loaded from
// ./src/my_own_folder/layout/Container.js
}
* Note that all relative paths are relative to the current HTML document.
* If not being specified, for example, <code>Other.awesome.Class</code>
* will simply be loaded from <code>./Other/awesome/Class.js</code>
*/
paths: {
'Ext': '.'
}
},
/**
* Set the configuration for the loader. This should be called right after ext-core.js
* (or ext-core-debug.js) is included in the page, i.e:
<script type="text/javascript" src="ext-core-debug.js"></script>
<script type="text/javascript">
Ext.Loader.setConfig({
enabled: true,
paths: {
'My': 'my_own_path'
}
});
<script>
<script type="text/javascript">
Ext.require(...);
Ext.onReady(function() {
// application code here
});
</script>
* Refer to {@link Ext.Loader#configs} for the list of possible properties
*
* @param {Object} config The config object to override the default values in {@link Ext.Loader#config}
* @return {Ext.Loader} this
* @markdown
*/
setConfig: function(name, value) {
if (Ext.isObject(name) && arguments.length === 1) {
Ext.Object.merge(this.config, name);
}
else {
this.config[name] = (Ext.isObject(value)) ? Ext.Object.merge(this.config[name], value) : value;
}
return this;
},
/**
* Get the config value corresponding to the specified name. If no name is given, will return the config object
* @param {String} name The config property name
* @return {Object/Mixed}
*/
getConfig: function(name) {
if (name) {
return this.config[name];
}
return this.config;
},
/**
* Sets the path of a namespace.
* For Example:
Ext.Loader.setPath('Ext', '.');
* @param {String/Object} name See {@link Ext.Function#flexSetter flexSetter}
* @param {String} path See {@link Ext.Function#flexSetter flexSetter}
* @return {Ext.Loader} this
* @markdown
*/
setPath: flexSetter(function(name, path) {
//<if nonBrowser>
if (isNonBrowser) {
if (isNodeJS) {
path = require('fs').realpathSync(path);
}
}
//</if>
this.config.paths[name] = path;
return this;
}),
/**
* Translates a className to a file path by adding the
* the proper prefix and converting the .'s to /'s. For example:
Ext.Loader.setPath('My', '/path/to/My');
alert(Ext.Loader.getPath('My.awesome.Class')); // alerts '/path/to/My/awesome/Class.js'
* Note that the deeper namespace levels, if explicitly set, are always resolved first. For example:
Ext.Loader.setPath({
'My': '/path/to/lib',
'My.awesome': '/other/path/for/awesome/stuff',
'My.awesome.more': '/more/awesome/path'
});
alert(Ext.Loader.getPath('My.awesome.Class')); // alerts '/other/path/for/awesome/stuff/Class.js'
alert(Ext.Loader.getPath('My.awesome.more.Class')); // alerts '/more/awesome/path/Class.js'
alert(Ext.Loader.getPath('My.cool.Class')); // alerts '/path/to/lib/cool/Class.js'
alert(Ext.Loader.getPath('Unknown.strange.Stuff')); // alerts 'Unknown/strange/Stuff.js'
* @param {String} className
* @return {String} path
* @markdown
*/
getPath: function(className) {
var path = '',
paths = this.config.paths,
prefix = this.getPrefix(className);
if (prefix.length > 0) {
if (prefix === className) {
return paths[prefix];
}
path = paths[prefix];
className = className.substring(prefix.length + 1);
}
if (path.length > 0) {
path += '/';
}
return path.replace(/\/\.\//g, '/') + className.replace(/\./g, "/") + '.js';
},
/**
* @private
* @param {String} className
*/
getPrefix: function(className) {
var paths = this.config.paths,
prefix, deepestPrefix = '';
if (paths.hasOwnProperty(className)) {
return className;
}
for (prefix in paths) {
if (paths.hasOwnProperty(prefix) && prefix + '.' === className.substring(0, prefix.length + 1)) {
if (prefix.length > deepestPrefix.length) {
deepestPrefix = prefix;
}
}
}
return deepestPrefix;
},
/**
* Refresh all items in the queue. If all dependencies for an item exist during looping,
* it will execute the callback and call refreshQueue again. Triggers onReady when the queue is
* empty
* @private
*/
refreshQueue: function() {
var ln = this.queue.length,
i, item, j, requires;
if (ln === 0) {
this.triggerReady();
return;
}
for (i = 0; i < ln; i++) {
item = this.queue[i];
if (item) {
requires = item.requires;
// Don't bother checking when the number of files loaded
// is still less than the array length
if (requires.length > this.numLoadedFiles) {
continue;
}
j = 0;
do {
if (Manager.isCreated(requires[j])) {
// Take out from the queue
requires.splice(j, 1);
}
else {
j++;
}
} while (j < requires.length);
if (item.requires.length === 0) {
this.queue.splice(i, 1);
item.callback.call(item.scope);
this.refreshQueue();
break;
}
}
}
return this;
},
/**
* Inject a script element to document's head, call onLoad and onError accordingly
* @private
*/
injectScriptElement: function(url, onLoad, onError, scope) {
var script = document.createElement('script'),
me = this,
onLoadFn = function() {
me.cleanupScriptElement(script);
onLoad.call(scope);
},
onErrorFn = function() {
me.cleanupScriptElement(script);
onError.call(scope);
};
script.type = 'text/javascript';
script.src = url;
script.onload = onLoadFn;
script.onerror = onErrorFn;
script.onreadystatechange = function() {
if (this.readyState === 'loaded' || this.readyState === 'complete') {
onLoadFn();
}
};
this.documentHead.appendChild(script);
return script;
},
/**
* @private
*/
cleanupScriptElement: function(script) {
script.onload = null;
script.onreadystatechange = null;
script.onerror = null;
return this;
},
/**
* Load a script file, supports both asynchronous and synchronous approaches
*
* @param {String} url
* @param {Function} onLoad
* @param {Scope} scope
* @param {Boolean} synchronous
* @private
*/
loadScriptFile: function(url, onLoad, onError, scope, synchronous) {
var me = this,
noCacheUrl = url + (this.getConfig('disableCaching') ? ('?' + this.getConfig('disableCachingParam') + '=' + Ext.Date.now()) : ''),
fileName = url.split('/').pop(),
isCrossOriginRestricted = false,
xhr, status, onScriptError;
scope = scope || this;
this.isLoading = true;
if (!synchronous) {
onScriptError = function() {
onError.call(scope, "Failed loading '" + url + "', please verify that the file exists", synchronous);
};
if (!Ext.isReady && Ext.onDocumentReady) {
Ext.onDocumentReady(function() {
me.injectScriptElement(noCacheUrl, onLoad, onScriptError, scope);
});
}
else {
this.injectScriptElement(noCacheUrl, onLoad, onScriptError, scope);
}
}
else {
if (typeof XMLHttpRequest !== 'undefined') {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
try {
xhr.open('GET', noCacheUrl, false);
xhr.send(null);
} catch (e) {
isCrossOriginRestricted = true;
}
status = (xhr.status === 1223) ? 204 : xhr.status;
if (!isCrossOriginRestricted) {
isCrossOriginRestricted = (status === 0);
}
if (isCrossOriginRestricted
//<if isNonBrowser>
&& !isPhantomJS
//</if>
) {
onError.call(this, "Failed loading synchronously via XHR: '" + url + "'; It's likely that the file is either " +
"being loaded from a different domain or from the local file system whereby cross origin " +
"requests are not allowed due to security reasons. Use asynchronous loading with " +
"Ext.require instead.", synchronous);
}
else if (status >= 200 && status < 300
//<if isNonBrowser>
|| isPhantomJS
//</if>
) {
// Firebug friendly, file names are still shown even though they're eval'ed code
new Function(xhr.responseText + "\n//@ sourceURL=" + fileName)();
onLoad.call(scope);
}
else {
onError.call(this, "Failed loading synchronously via XHR: '" + url + "'; please " +
"verify that the file exists. " +
"XHR status code: " + status, synchronous);
}
// Prevent potential IE memory leak
xhr = null;
}
},
/**
* Explicitly exclude files from being loaded. Useful when used in conjunction with a broad include expression.
* Can be chained with more `require` and `exclude` methods, eg:
Ext.exclude('Ext.data.*').require('*');
Ext.exclude('widget.button*').require('widget.*');
* @param {Array} excludes
* @return {Object} object contains `require` method for chaining
* @markdown
*/
exclude: function(excludes) {
var me = this;
return {
require: function(expressions, fn, scope) {
return me.require(expressions, fn, scope, excludes);
},
syncRequire: function(expressions, fn, scope) {
return me.syncRequire(expressions, fn, scope, excludes);
}
};
},
/**
* Synchronously loads all classes by the given names and all their direct dependencies; optionally executes the given callback function when finishes, within the optional scope. This method is aliased by {@link Ext#syncRequire} for convenience
* @param {String/Array} expressions Can either be a string or an array of string
* @param {Function} fn (Optional) The callback function
* @param {Object} scope (Optional) The execution scope (`this`) of the callback function
* @param {String/Array} excludes (Optional) Classes to be excluded, useful when being used with expressions
* @markdown
*/
syncRequire: function() {
this.syncModeEnabled = true;
this.require.apply(this, arguments);
this.refreshQueue();
this.syncModeEnabled = false;
},
/**
* Loads all classes by the given names and all their direct dependencies; optionally executes the given callback function when
* finishes, within the optional scope. This method is aliased by {@link Ext#require Ext.require} for convenience
* @param {String/Array} expressions Can either be a string or an array of string
* @param {Function} fn (Optional) The callback function
* @param {Object} scope (Optional) The execution scope (`this`) of the callback function
* @param {String/Array} excludes (Optional) Classes to be excluded, useful when being used with expressions
* @markdown
*/
require: function(expressions, fn, scope, excludes) {
var filePath, expression, exclude, className, excluded = {},
excludedClassNames = [],
possibleClassNames = [],
possibleClassName, classNames = [],
i, j, ln, subLn;
expressions = Ext.Array.from(expressions);
excludes = Ext.Array.from(excludes);
fn = fn || Ext.emptyFn;
scope = scope || Ext.global;
for (i = 0, ln = excludes.length; i < ln; i++) {
exclude = excludes[i];
if (typeof exclude === 'string' && exclude.length > 0) {
excludedClassNames = Manager.getNamesByExpression(exclude);
for (j = 0, subLn = excludedClassNames.length; j < subLn; j++) {
excluded[excludedClassNames[j]] = true;
}
}
}
for (i = 0, ln = expressions.length; i < ln; i++) {
expression = expressions[i];
if (typeof expression === 'string' && expression.length > 0) {
possibleClassNames = Manager.getNamesByExpression(expression);
for (j = 0, subLn = possibleClassNames.length; j < subLn; j++) {
possibleClassName = possibleClassNames[j];
if (!excluded.hasOwnProperty(possibleClassName) && !Manager.isCreated(possibleClassName)) {
Ext.Array.include(classNames, possibleClassName);
}
}
}
}
// If the dynamic dependency feature is not being used, throw an error
// if the dependencies are not defined
if (!this.config.enabled) {
if (classNames.length > 0) {
Ext.Error.raise({
sourceClass: "Ext.Loader",
sourceMethod: "require",
msg: "Ext.Loader is not enabled, so dependencies cannot be resolved dynamically. " +
"Missing required class" + ((classNames.length > 1) ? "es" : "") + ": " + classNames.join(', ')
});
}
}
if (classNames.length === 0) {
fn.call(scope);
return this;
}
this.queue.push({
requires: classNames,
callback: fn,
scope: scope
});
classNames = classNames.slice();
for (i = 0, ln = classNames.length; i < ln; i++) {
className = classNames[i];
if (!this.isFileLoaded.hasOwnProperty(className)) {
this.isFileLoaded[className] = false;
filePath = this.getPath(className);
this.classNameToFilePathMap[className] = filePath;
this.numPendingFiles++;
//<if nonBrowser>
if (isNonBrowser) {
if (isNodeJS) {
require(filePath);
}
// Temporary support for hammerjs
else {
var f = fs.open(filePath),
content = '',
line;
while (true) {
line = f.readLine();
if (line.length === 0) {
break;
}
content += line;
}
f.close();
eval(content);
}
this.onFileLoaded(className, filePath);
if (ln === 1) {
return Manager.get(className);
}
continue;
}
//</if>
this.loadScriptFile(
filePath,
Ext.Function.pass(this.onFileLoaded, [className, filePath], this),
Ext.Function.pass(this.onFileLoadError, [className, filePath]),
this,
this.syncModeEnabled
);
}
}
return this;
},
/**
* @private
* @param {String} className
* @param {String} filePath
*/
onFileLoaded: function(className, filePath) {
this.numLoadedFiles++;
this.isFileLoaded[className] = true;
this.numPendingFiles--;
if (this.numPendingFiles === 0) {
this.refreshQueue();
}
//<debug>
if (this.numPendingFiles <= 1) {
window.status = "Finished loading all dependencies, onReady fired!";
}
else {
window.status = "Loading dependencies, " + this.numPendingFiles + " files left...";
}
//</debug>
//<debug>
if (!this.syncModeEnabled && this.numPendingFiles === 0 && this.isLoading && !this.hasFileLoadError) {
var queue = this.queue,
requires,
i, ln, j, subLn, missingClasses = [], missingPaths = [];
for (i = 0, ln = queue.length; i < ln; i++) {
requires = queue[i].requires;
for (j = 0, subLn = requires.length; j < ln; j++) {
if (this.isFileLoaded[requires[j]]) {
missingClasses.push(requires[j]);
}
}
}
if (missingClasses.length < 1) {
return;
}
missingClasses = Ext.Array.filter(missingClasses, function(item) {
return !this.requiresMap.hasOwnProperty(item);
}, this);
for (i = 0,ln = missingClasses.length; i < ln; i++) {
missingPaths.push(this.classNameToFilePathMap[missingClasses[i]]);
}
Ext.Error.raise({
sourceClass: "Ext.Loader",
sourceMethod: "onFileLoaded",
msg: "The following classes are not declared even if their files have been " +
"loaded: '" + missingClasses.join("', '") + "'. Please check the source code of their " +
"corresponding files for possible typos: '" + missingPaths.join("', '") + "'"
});
}
//</debug>
},
/**
* @private
*/
onFileLoadError: function(className, filePath, errorMessage, isSynchronous) {
this.numPendingFiles--;
this.hasFileLoadError = true;
//<debug error>
Ext.Error.raise({
sourceClass: "Ext.Loader",
classToLoad: className,
loadPath: filePath,
loadingType: isSynchronous ? 'synchronous' : 'async',
msg: errorMessage
});
//</debug>
},
/**
* @private
*/
addOptionalRequires: function(requires) {
var optionalRequires = this.optionalRequires,
i, ln, require;
requires = Ext.Array.from(requires);
for (i = 0, ln = requires.length; i < ln; i++) {
require = requires[i];
Ext.Array.include(optionalRequires, require);
}
return this;
},
/**
* @private
*/
triggerReady: function(force) {
var readyListeners = this.readyListeners,
optionalRequires, listener;
if (this.isLoading || force) {
this.isLoading = false;
if (this.optionalRequires.length) {
// Clone then empty the array to eliminate potential recursive loop issue
optionalRequires = Ext.Array.clone(this.optionalRequires);
// Empty the original array
this.optionalRequires.length = 0;
this.require(optionalRequires, Ext.Function.pass(this.triggerReady, [true], this), this);
return this;
}
while (readyListeners.length) {
listener = readyListeners.shift();
listener.fn.call(listener.scope);
if (this.isLoading) {
return this;
}
}
}
return this;
},
/**
* Add a new listener to be executed when all required scripts are fully loaded
*
* @param {Function} fn The function callback to be executed
* @param {Object} scope The execution scope (<code>this</code>) of the callback function
* @param {Boolean} withDomReady Whether or not to wait for document dom ready as well
*/
onReady: function(fn, scope, withDomReady, options) {
var oldFn;
if (withDomReady !== false && Ext.onDocumentReady) {
oldFn = fn;
fn = function() {
Ext.onDocumentReady(oldFn, scope, options);
};
}
if (!this.isLoading) {
fn.call(scope);
}
else {
this.readyListeners.push({
fn: fn,
scope: scope
});
}
},
/**
* @private
* @param {String} className
*/
historyPush: function(className) {
if (className && this.isFileLoaded.hasOwnProperty(className)) {
Ext.Array.include(this.history, className);
}
return this;
}
};
/**
* Convenient alias of {@link Ext.Loader#require}. Please see the introduction documentation of
* {@link Ext.Loader} for examples.
* @member Ext
* @method require
*/
Ext.require = alias(Loader, 'require');
/**
* Synchronous version of {@link Ext#require}, convenient alias of {@link Ext.Loader#syncRequire}.
*
* @member Ext
* @method syncRequire
*/
Ext.syncRequire = alias(Loader, 'syncRequire');
/**
* Convenient shortcut to {@link Ext.Loader#exclude}
* @member Ext
* @method exclude
*/
Ext.exclude = alias(Loader, 'exclude');
/**
* @member Ext
* @method onReady
*/
Ext.onReady = function(fn, scope, options) {
Loader.onReady(fn, scope, true, options);
};
Class.registerPreprocessor('loader', function(cls, data, continueFn) {
var me = this,
dependencies = [],
className = Manager.getName(cls),
i, j, ln, subLn, value, propertyName, propertyValue;
/*
Basically loop through the dependencyProperties, look for string class names and push
them into a stack, regardless of whether the property's value is a string, array or object. For example:
{
extend: 'Ext.MyClass',
requires: ['Ext.some.OtherClass'],
mixins: {
observable: 'Ext.util.Observable';
}
}
which will later be transformed into:
{
extend: Ext.MyClass,
requires: [Ext.some.OtherClass],
mixins: {
observable: Ext.util.Observable;
}
}
*/
for (i = 0, ln = dependencyProperties.length; i < ln; i++) {
propertyName = dependencyProperties[i];
if (data.hasOwnProperty(propertyName)) {
propertyValue = data[propertyName];
if (typeof propertyValue === 'string') {
dependencies.push(propertyValue);
}
else if (propertyValue instanceof Array) {
for (j = 0, subLn = propertyValue.length; j < subLn; j++) {
value = propertyValue[j];
if (typeof value === 'string') {
dependencies.push(value);
}
}
}
else {
for (j in propertyValue) {
if (propertyValue.hasOwnProperty(j)) {
value = propertyValue[j];
if (typeof value === 'string') {
dependencies.push(value);
}
}
}
}
}
}
if (dependencies.length === 0) {
// Loader.historyPush(className);
return;
}
//<debug error>
var deadlockPath = [],
requiresMap = Loader.requiresMap,
detectDeadlock;
/*
Automatically detect deadlocks before-hand,
will throw an error with detailed path for ease of debugging. Examples of deadlock cases:
- A extends B, then B extends A
- A requires B, B requires C, then C requires A
The detectDeadlock function will recursively transverse till the leaf, hence it can detect deadlocks
no matter how deep the path is.
*/
if (className) {
requiresMap[className] = dependencies;
detectDeadlock = function(cls) {
deadlockPath.push(cls);
if (requiresMap[cls]) {
if (Ext.Array.contains(requiresMap[cls], className)) {
Ext.Error.raise({
sourceClass: "Ext.Loader",
msg: "Deadlock detected while loading dependencies! '" + className + "' and '" +
deadlockPath[1] + "' " + "mutually require each other. Path: " +
deadlockPath.join(' -> ') + " -> " + deadlockPath[0]
});
}
for (i = 0, ln = requiresMap[cls].length; i < ln; i++) {
detectDeadlock(requiresMap[cls][i]);
}
}
};
detectDeadlock(className);
}
//</debug>
Loader.require(dependencies, function() {
for (i = 0, ln = dependencyProperties.length; i < ln; i++) {
propertyName = dependencyProperties[i];
if (data.hasOwnProperty(propertyName)) {
propertyValue = data[propertyName];
if (typeof propertyValue === 'string') {
data[propertyName] = Manager.get(propertyValue);
}
else if (propertyValue instanceof Array) {
for (j = 0, subLn = propertyValue.length; j < subLn; j++) {
value = propertyValue[j];
if (typeof value === 'string') {
data[propertyName][j] = Manager.get(value);
}
}
}
else {
for (var k in propertyValue) {
if (propertyValue.hasOwnProperty(k)) {
value = propertyValue[k];
if (typeof value === 'string') {
data[propertyName][k] = Manager.get(value);
}
}
}
}
}
}
continueFn.call(me, cls, data);
});
return false;
}, true);
Class.setDefaultPreprocessorPosition('loader', 'after', 'className');
Manager.registerPostprocessor('uses', function(name, cls, data) {
var uses = Ext.Array.from(data.uses),
items = [],
i, ln, item;
for (i = 0, ln = uses.length; i < ln; i++) {
item = uses[i];
if (typeof item === 'string') {
items.push(item);
}
}
Loader.addOptionalRequires(items);
});
Manager.setDefaultPostprocessorPosition('uses', 'last');
})(Ext.ClassManager, Ext.Class, Ext.Function.flexSetter, Ext.Function.alias);
/**
* @class Ext.Error
* @private
* @extends Error
A wrapper class for the native JavaScript Error object that adds a few useful capabilities for handling
errors in an Ext application. When you use Ext.Error to {@link #raise} an error from within any class that
uses the Ext 4 class system, the Error class can automatically add the source class and method from which
the error was raised. It also includes logic to automatically log the eroor to the console, if available,
with additional metadata about the error. In all cases, the error will always be thrown at the end so that
execution will halt.
Ext.Error also offers a global error {@link #handle handling} method that can be overridden in order to
handle application-wide errors in a single spot. You can optionally {@link #ignore} errors altogether,
although in a real application it's usually a better idea to override the handling function and perform
logging or some other method of reporting the errors in a way that is meaningful to the application.
At its simplest you can simply raise an error as a simple string from within any code:
#Example usage:#
Ext.Error.raise('Something bad happened!');
If raised from plain JavaScript code, the error will be logged to the console (if available) and the message
displayed. In most cases however you'll be raising errors from within a class, and it may often be useful to add
additional metadata about the error being raised. The {@link #raise} method can also take a config object.
In this form the `msg` attribute becomes the error description, and any other data added to the config gets
added to the error object and, if the console is available, logged to the console for inspection.
#Example usage:#
Ext.define('Ext.Foo', {
doSomething: function(option){
if (someCondition === false) {
Ext.Error.raise({
msg: 'You cannot do that!',
option: option, // whatever was passed into the method
'error code': 100 // other arbitrary info
});
}
}
});
If a console is available (that supports the `console.dir` function) you'll see console output like:
An error was raised with the following data:
option: Object { foo: "bar"}
foo: "bar"
error code: 100
msg: "You cannot do that!"
sourceClass: "Ext.Foo"
sourceMethod: "doSomething"
uncaught exception: You cannot do that!
As you can see, the error will report exactly where it was raised and will include as much information as the
raising code can usefully provide.
If you want to handle all application errors globally you can simply override the static {@link handle} method
and provide whatever handling logic you need. If the method returns true then the error is considered handled
and will not be thrown to the browser. If anything but true is returned then the error will be thrown normally.
#Example usage:#
Ext.Error.handle = function(err) {
if (err.someProperty == 'NotReallyAnError') {
// maybe log something to the application here if applicable
return true;
}
// any non-true return value (including none) will cause the error to be thrown
}
* Create a new Error object
* @param {Object} config The config object
* @markdown
* @author Brian Moeskau <brian@sencha.com>
* @docauthor Brian Moeskau <brian@sencha.com>
*/
Ext.Error = Ext.extend(Error, {
statics: {
/**
* @property ignore
Static flag that can be used to globally disable error reporting to the browser if set to true
(defaults to false). Note that if you ignore Ext errors it's likely that some other code may fail
and throw a native JavaScript error thereafter, so use with caution. In most cases it will probably
be preferable to supply a custom error {@link #handle handling} function instead.
#Example usage:#
Ext.Error.ignore = true;
* @markdown
* @static
*/
ignore: false,
/**
Raise an error that can include additional data and supports automatic console logging if available.
You can pass a string error message or an object with the `msg` attribute which will be used as the
error message. The object can contain any other name-value attributes (or objects) to be logged
along with the error.
Note that after displaying the error message a JavaScript error will ultimately be thrown so that
execution will halt.
#Example usage:#
Ext.Error.raise('A simple string error message');
// or...
Ext.define('Ext.Foo', {
doSomething: function(option){
if (someCondition === false) {
Ext.Error.raise({
msg: 'You cannot do that!',
option: option, // whatever was passed into the method
'error code': 100 // other arbitrary info
});
}
}
});
* @param {String/Object} err The error message string, or an object containing the
* attribute "msg" that will be used as the error message. Any other data included in
* the object will also be logged to the browser console, if available.
* @static
* @markdown
*/
raise: function(err){
err = err || {};
if (Ext.isString(err)) {
err = { msg: err };
}
var method = this.raise.caller;
if (method) {
if (method.$name) {
err.sourceMethod = method.$name;
}
if (method.$owner) {
err.sourceClass = method.$owner.$className;
}
}
if (Ext.Error.handle(err) !== true) {
var global = Ext.global,
con = global.console,
msg = Ext.Error.prototype.toString.call(err),
noConsoleMsg = 'An uncaught error was raised: "' + msg +
'". Use Firebug or Webkit console for additional details.';
if (con) {
if (con.dir) {
con.warn('An uncaught error was raised with the following data:');
con.dir(err);
}
else {
con.warn(noConsoleMsg);
}
if (con.error) {
con.error(msg);
}
}
else if (global.alert){
global.alert(noConsoleMsg);
}
throw new Ext.Error(err);
}
},
/**
Globally handle any Ext errors that may be raised, optionally providing custom logic to
handle different errors individually. Return true from the function to bypass throwing the
error to the browser, otherwise the error will be thrown and execution will halt.
#Example usage:#
Ext.Error.handle = function(err) {
if (err.someProperty == 'NotReallyAnError') {
// maybe log something to the application here if applicable
return true;
}
// any non-true return value (including none) will cause the error to be thrown
}
* @param {Ext.Error} err The Ext.Error object being raised. It will contain any attributes
* that were originally raised with it, plus properties about the method and class from which
* the error originated (if raised from a class that uses the Ext 4 class system).
* @static
* @markdown
*/
handle: function(){
return Ext.Error.ignore;
}
},
/**
* @constructor
* @param {String/Object} config The error message string, or an object containing the
* attribute "msg" that will be used as the error message. Any other data included in
* the object will be applied to the error instance and logged to the browser console, if available.
*/
constructor: function(config){
if (Ext.isString(config)) {
config = { msg: config };
}
Ext.apply(this, config);
},
/**
Provides a custom string representation of the error object. This is an override of the base JavaScript
`Object.toString` method, which is useful so that when logged to the browser console, an error object will
be displayed with a useful message instead of `[object Object]`, the default `toString` result.
The default implementation will include the error message along with the raising class and method, if available,
but this can be overridden with a custom implementation either at the prototype level (for all errors) or on
a particular error instance, if you want to provide a custom description that will show up in the console.
* @markdown
* @return {String} The error message. If raised from within the Ext 4 class system, the error message
* will also include the raising class and method names, if available.
*/
toString: function(){
var me = this,
className = me.className ? me.className : '',
methodName = me.methodName ? '.' + me.methodName + '(): ' : '',
msg = me.msg || '(No description provided)';
return className + methodName + msg;
}
});
| bibryam/lazyplanner | webapp/lazyplanner/ext-4.0.0/pkgs/foundation.js | JavaScript | lgpl-2.1 | 273,154 |
/*
* Copyright 2014 Apereo Foundation (AF) Licensed under the
* Educational Community 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://opensource.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS IS"
* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
var assert = require('assert');
var fs = require('fs');
var IO = require('oae-util/lib/io');
var datadir = __dirname + '/data/';
describe('IO', function() {
describe('#copyFile()', function(callback) {
/**
* Test that verifies that copyFiles creates a new file with the same contents as the original
*/
it('verify a new file is created with duplicate content', function(callback) {
var sourceFile = datadir + 'banditos.txt';
var destFile = datadir + 'refreshments.txt';
// Verify that the dest file doesn't already exist
fs.stat(destFile, function(err) {
assert.ok(err);
assert.equal(err.code, 'ENOENT');
IO.copyFile(sourceFile, destFile, function(err) {
assert.ok(!err);
// Verify that the source and dest files contain the same data
fs.readFile(sourceFile, 'utf8', function(err, sourceText) {
assert.ok(!err);
fs.readFile(destFile, 'utf8', function(err, destText){
assert.ok(!err);
assert.equal(sourceText, destText);
callback();
});
});
});
});
});
});
describe('#moveFile()', function(callback) {
/**
* Test that verifies that moveFile renames a file
*/
it('verify a file is renamed', function(callback) {
var sourceFile = datadir + 'refreshments.txt';
var destFile = datadir + 'refreshments-banditos.txt';
IO.moveFile(sourceFile, destFile, function(err) {
assert.ok(!err);
// Verify that the source file is removed
fs.stat(sourceFile, function(err){
assert.equal(err.code, 'ENOENT');
// Verify that the source and dest files contain the same data
fs.readFile(datadir + 'banditos.txt', 'utf8', function(err, sourceText) {
assert.ok(!err);
fs.readFile(destFile, 'utf8', function(err, destText){
assert.ok(!err);
assert.equal(sourceText, destText);
fs.unlink(destFile, callback);
});
});
});
});
});
});
describe('#destroyStream()', function() {
/**
* Test that verifies that a stream is fully destroyed.
*/
it('verify a stream is properly destroyed.', function() {
var stream = fs.createReadStream('.');
// Register our pre-destroy listener.
stream.on('error', function(err) {
assert.fail('This listener should have been removed.');
});
stream.on('close', function() {
assert.fail('This listener should have been removed.');
});
// Destroy the stream, the above listeners should NOT be called.
IO.destroyStream(stream);
// Register a new error listener as the the test would otherwise fail.
stream.on('error', function(err) {});
stream.emit('error');
stream.emit('close');
});
});
});
| timdegroote/Hilary | node_modules/oae-util/tests/test-io.js | JavaScript | apache-2.0 | 4,053 |
CKEDITOR.plugins.add('bbcodeselector',
{
requires: ['dialog'],
lang: ['en'],
init: function(editor) {
window["arrayTest"] = [];
$.getJSON(CKEDITOR.basePath.replace('Scripts/ckeditor/', '') + "resource.ashx?bbcodelist=json", function (json) {
$.each(json, function(idx, obj) {
window["arrayTest"].push([obj.Name, obj.Name.toLowerCase()]);
});
});
var b = "bbcodeselector";
var c = editor.addCommand(b, new CKEDITOR.dialogCommand(b));
c.modes = { wysiwyg: 1, source: 0 };
c.canUndo = false;
editor.ui.addButton("bbcodeselector", {
label: editor.lang.bbcodeselector.title,
command: b,
icon: this.path + "images/yafbbcode.gif"
});
CKEDITOR.dialog.add(b, this.path + "dialogs/bbcodeselector.js");
}
}); | Pathfinder-Fr/YAFNET | yafsrc/YetAnotherForum.NET/Scripts/ckeditor/plugins/bbcodeselector/plugin.js | JavaScript | apache-2.0 | 872 |
/*global ArangoServerState*/
'use strict';
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014 triAGENS GmbH, Cologne, Germany
/// Copyright 2016 ArangoDB 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 ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Alan Plum
////////////////////////////////////////////////////////////////////////////////
const internal = require('internal');
const cluster = require('@arangodb/cluster');
const db = require('@arangodb').db;
const _ = require('lodash');
const STATISTICS_INTERVAL = 10; // seconds
const STATISTICS_HISTORY_INTERVAL = 15 * 60; // seconds
const joi = require('joi');
const httperr = require('http-errors');
const createRouter = require('@arangodb/foxx/router');
const { MergeStatisticSamples } = require('@arangodb/statistics-helper');
const router = createRouter();
module.exports = router;
const startOffsetSchema = joi.number().default(
() => internal.time() - STATISTICS_INTERVAL * 10,
'Default offset'
);
const clusterIdSchema = joi.string().default(
() => cluster.isCluster() ? ArangoServerState.id() : undefined,
'Default DB server'
);
function percentChange (current, prev, section, src) {
if (prev === null) {
return 0;
}
const p = prev[section][src];
if (p !== 0) {
return (current[section][src] - p) / p;
}
return 0;
}
function percentChange2 (current, prev, section, src1, src2) {
if (prev === null) {
return 0;
}
const p = prev[section][src1] - prev[section][src2];
if (p !== 0) {
return (current[section][src1] - current[section][src2] - p) / p;
}
return 0;
}
const STAT_SERIES = {
avgTotalTime: [ "client", "avgTotalTime" ],
avgRequestTime: [ "client", "avgRequestTime" ],
avgQueueTime: [ "client", "avgQueueTime" ],
avgIoTime: [ "client", "avgIoTime" ],
bytesSentPerSecond: [ "client", "bytesSentPerSecond" ],
bytesReceivedPerSecond: [ "client", "bytesReceivedPerSecond" ],
asyncPerSecond: [ "http", "requestsAsyncPerSecond" ],
optionsPerSecond: [ "http", "requestsOptionsPerSecond" ],
putsPerSecond: [ "http", "requestsPutPerSecond" ],
headsPerSecond: [ "http", "requestsHeadPerSecond" ],
postsPerSecond: [ "http", "requestsPostPerSecond" ],
getsPerSecond: [ "http", "requestsGetPerSecond" ],
deletesPerSecond: [ "http", "requestsDeletePerSecond" ],
othersPerSecond: [ "http", "requestsOptionsPerSecond" ],
patchesPerSecond: [ "http", "requestsPatchPerSecond" ],
systemTimePerSecond: [ "system", "systemTimePerSecond" ],
userTimePerSecond: [ "system", "userTimePerSecond" ],
majorPageFaultsPerSecond: [ "system", "majorPageFaultsPerSecond" ],
minorPageFaultsPerSecond: [ "system", "minorPageFaultsPerSecond" ]
};
const STAT_DISTRIBUTION = {
totalTimeDistributionPercent: [ "client", "totalTimePercent" ],
requestTimeDistributionPercent: [ "client", "requestTimePercent" ],
queueTimeDistributionPercent: [ "client", "queueTimePercent" ],
bytesSentDistributionPercent: [ "client", "bytesSentPercent" ],
bytesReceivedDistributionPercent: [ "client", "bytesReceivedPercent" ]
};
function computeStatisticsRaw (result, start, clusterId) {
let filter = "";
if (clusterId !== undefined) {
filter = " FILTER s.clusterId == @clusterId ";
}
const values = db._query(
"FOR s IN _statistics "
+ " FILTER s.time > @start "
+ filter
+ " SORT s.time "
+ " return s",
{ start: start - 2 * STATISTICS_INTERVAL, clusterId: clusterId });
result.enabled = internal.enabledStatistics();
result.times = [];
for (let key in STAT_SERIES) {
if (STAT_SERIES.hasOwnProperty(key)) {
result[key] = [];
}
}
let lastRaw = null;
let lastRaw2 = null;
let path;
// read the last entries
while (values.hasNext()) {
const stat = values.next();
lastRaw2 = lastRaw;
lastRaw = stat;
if (stat.time <= start) {
continue;
}
result.times.push(stat.time);
for (let key in STAT_SERIES) {
if (STAT_SERIES.hasOwnProperty(key)) {
path = STAT_SERIES[key];
result[key].push(stat[path[0]][path[1]]);
}
}
}
// have at least one entry, use it
if (lastRaw !== null) {
for (let key in STAT_DISTRIBUTION) {
if (STAT_DISTRIBUTION.hasOwnProperty(key)) {
path = STAT_DISTRIBUTION[key];
result[key] = lastRaw[path[0]][path[1]];
}
}
result.numberOfThreadsCurrent = lastRaw.system.numberOfThreads;
result.numberOfThreadsPercentChange = percentChange(lastRaw, lastRaw2, 'system', 'numberOfThreads');
result.virtualSizeCurrent = lastRaw.system.virtualSize;
result.virtualSizePercentChange = percentChange(lastRaw, lastRaw2, 'system', 'virtualSize');
result.residentSizeCurrent = lastRaw.system.residentSize;
result.residentSizePercent = lastRaw.system.residentSizePercent;
result.asyncPerSecondCurrent = lastRaw.http.requestsAsyncPerSecond;
result.asyncPerSecondPercentChange = percentChange(lastRaw, lastRaw2, 'http', 'requestsAsyncPerSecond');
result.syncPerSecondCurrent = lastRaw.http.requestsTotalPerSecond - lastRaw.http.requestsAsyncPerSecond;
result.syncPerSecondPercentChange
= percentChange2(lastRaw, lastRaw2, 'http', 'requestsTotalPerSecond', 'requestsAsyncPerSecond');
result.clientConnectionsCurrent = lastRaw.client.httpConnections;
result.clientConnectionsPercentChange = percentChange(lastRaw, lastRaw2, 'client', 'httpConnections');
}
// have no entry, add nulls
else {
for (let key in STAT_DISTRIBUTION) {
if (STAT_DISTRIBUTION.hasOwnProperty(key)) {
result[key] = { values: [0,0,0,0,0,0,0], cuts: [0,0,0,0,0,0] };
}
}
const ps = internal.processStatistics();
result.numberOfThreadsCurrent = ps.numberOfThreads;
result.numberOfThreadsPercentChange = 0;
result.virtualSizeCurrent = ps.virtualSize;
result.virtualSizePercentChange = 0;
result.residentSizeCurrent = ps.residentSize;
result.residentSizePercent = ps.residentSizePercent;
result.asyncPerSecondCurrent = 0;
result.asyncPerSecondPercentChange = 0;
result.syncPerSecondCurrent = 0;
result.syncPerSecondPercentChange = 0;
result.clientConnectionsCurrent = 0;
result.clientConnectionsPercentChange = 0;
}
// add physical memory
const ss = internal.serverStatistics();
result.physicalMemory = ss.physicalMemory;
// add next start time
if (lastRaw === null) {
result.nextStart = internal.time();
result.waitFor = STATISTICS_INTERVAL;
}
else {
result.nextStart = lastRaw.time;
result.waitFor = (lastRaw.time + STATISTICS_INTERVAL) - internal.time();
}
}
function computeStatisticsRaw15M (result, start, clusterId) {
let filter = "";
if (clusterId !== undefined) {
filter = " FILTER s.clusterId == @clusterId ";
}
const values = db._query(
"FOR s IN _statistics15 "
+ " FILTER s.time > @start "
+ filter
+ " SORT s.time "
+ " return s",
{ start: start - 2 * STATISTICS_HISTORY_INTERVAL, clusterId: clusterId });
let lastRaw = null;
let lastRaw2 = null;
// read the last entries
while (values.hasNext()) {
const stat = values.next();
lastRaw2 = lastRaw;
lastRaw = stat;
}
// have at least one entry, use it
if (lastRaw !== null) {
result.numberOfThreads15M = lastRaw.system.numberOfThreads;
result.numberOfThreads15MPercentChange = percentChange(lastRaw, lastRaw2, 'system', 'numberOfThreads');
result.virtualSize15M = lastRaw.system.virtualSize;
result.virtualSize15MPercentChange = percentChange(lastRaw, lastRaw2, 'system', 'virtualSize');
result.asyncPerSecond15M = lastRaw.http.requestsAsyncPerSecond;
result.asyncPerSecond15MPercentChange = percentChange(lastRaw, lastRaw2, 'http', 'requestsAsyncPerSecond');
result.syncPerSecond15M = lastRaw.http.requestsTotalPerSecond - lastRaw.http.requestsAsyncPerSecond;
result.syncPerSecond15MPercentChange
= percentChange2(lastRaw, lastRaw2, 'http', 'requestsTotalPerSecond', 'requestsAsyncPerSecond');
result.clientConnections15M = lastRaw.client.httpConnections;
result.clientConnections15MPercentChange = percentChange(lastRaw, lastRaw2, 'client', 'httpConnections');
}
// have no entry, add nulls
else {
const ps = internal.processStatistics();
result.numberOfThreads15M = ps.numberOfThreads;
result.numberOfThreads15MPercentChange = 0;
result.virtualSize15M = ps.virtualSize;
result.virtualSize15MPercentChange = 0;
result.asyncPerSecond15M = 0;
result.asyncPerSecond15MPercentChange = 0;
result.syncPerSecond15M = 0;
result.syncPerSecond15MPercentChange = 0;
result.clientConnections15M = 0;
result.clientConnections15MPercentChange = 0;
}
}
function computeStatisticsShort (start, clusterId) {
const result = {};
computeStatisticsRaw(result, start, clusterId);
computeStatisticsRaw15M(result, start, clusterId);
return result;
}
function computeStatisticsValues (result, values, attrs) {
for (let key in attrs) {
if (attrs.hasOwnProperty(key)) {
result[key] = [];
}
}
while (values.hasNext()) {
const stat = values.next();
result.times.push(stat.time);
for (let key in attrs) {
if (attrs.hasOwnProperty(key) && STAT_SERIES.hasOwnProperty(key)) {
const path = STAT_SERIES[key];
result[key].push(stat[path[0]][path[1]]);
}
}
}
}
function computeStatisticsLong (attrs, clusterId) {
const short = { times: [] };
let filter = "";
if (clusterId !== undefined) {
filter = " FILTER s.clusterId == @clusterId ";
}
const values = db._query(
"FOR s IN _statistics "
+ filter
+ " SORT s.time "
+ " return s",
{ clusterId: clusterId });
computeStatisticsValues(short, values, attrs);
let filter2 = "";
let end = 0;
if (short.times.length !== 0) {
filter2 = " FILTER s.time < @end ";
end = short.times[0];
}
const values2 = db._query(
"FOR s IN _statistics15 "
+ filter
+ filter2
+ " SORT s.time "
+ " return s",
{ end: end, clusterId: clusterId });
const long = { times: [] };
computeStatisticsValues(long, values2, attrs);
for (let key in attrs) {
if (attrs.hasOwnProperty(key) && long.hasOwnProperty(key)) {
long[key] = long[key].concat(short[key]);
}
}
if (!attrs.times) {
delete long.times;
}
return long;
}
router.use((req, res, next) => {
if (internal.authenticationEnabled()) {
if (!req.authorized) {
throw new httperr.Unauthorized();
}
}
next();
});
router.get('/coordshort', function (req, res) {
let merged = { };
try {
let start = internal.time() - 12 * STATISTICS_INTERVAL;
let { stats15, statsSamples } = SYSTEM_STATISTICS(start || 0);
if (statsSamples.length !== 0) {
// we have no samples -> either statistics are disabled, or the server has just been started
merged = MergeStatisticSamples(statsSamples);
merged.clientConnections15M = stats15.length === 0 ? 0 : stats15[0].clientConnections15M;
}
} catch (e) {
// ignore exceptions, because throwing here will render the entire web UI cluster stats broken
}
res.json({'enabled': internal.enabledStatistics(), 'data': merged});
})
.summary('Short term history for all coordinators')
.description('This function is used to get the statistics history.');
router.get("/short", function (req, res) {
const start = req.queryParams.start;
const clusterId = req.queryParams.DBserver;
const series = computeStatisticsShort(start, clusterId);
res.json(series);
})
.queryParam("start", startOffsetSchema)
.queryParam("DBserver", clusterIdSchema)
.summary("Short term history")
.description("This function is used to get the statistics history.");
| wiltonlazary/arangodb | js/apps/system/_admin/aardvark/APP/statistics.js | JavaScript | apache-2.0 | 12,516 |
/**
* Copyright 2012 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author benvanik@google.com (Ben Vanik)
*/
goog.provide('blk.game.server.ServerController');
goog.require('blk.assets.models.BaseDataLibrary');
goog.require('blk.env.MapParameters');
goog.require('blk.env.server.ServerMap');
goog.require('blk.game.server.SimulationObserver');
goog.require('blk.net.packets.ReadyPlayer');
goog.require('blk.sim.Root');
goog.require('blk.sim.commands');
goog.require('blk.sim.entities');
goog.require('gf.log');
goog.require('gf.net.INetworkService');
goog.require('gf.net.SessionState');
goog.require('gf.net.chat.ServerChatService');
goog.require('gf.sim.EntityFlag');
goog.require('gf.sim.ServerSimulator');
goog.require('goog.Disposable');
goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.async.Deferred');
goog.require('goog.reflect');
goog.require('wtfapi.trace');
/**
* Abstract server game controller.
* @constructor
* @extends {goog.Disposable}
* @implements {gf.net.INetworkService}
* @param {!blk.game.server.ServerGame} game Server game.
* @param {!gf.net.ServerSession} session Network session.
* @param {!blk.io.MapStore} mapStore Map storage provider, ownership
* transferred.
*/
blk.game.server.ServerController = function(game, session, mapStore) {
goog.base(this);
// Reset runtime clock
game.clock = session.clock;
/**
* Server game this instance is controlling.
* @protected
* @type {!blk.game.server.ServerGame}
*/
this.game = game;
/**
* Network session.
* @type {!gf.net.ServerSession}
*/
this.session = session;
this.session.registerService(this);
/**
* Chat server.
* @private
* @type {!gf.net.chat.ServerChatService}
*/
this.chatService_ = new gf.net.chat.ServerChatService(session);
this.session.registerService(this.chatService_);
// TODO(benvanik): store in map info
var launchOptions =
/** @type {!blk.server.LaunchOptions} */ (game.launchOptions);
var mapParams = new blk.env.MapParameters();
mapParams.generator = launchOptions.mapGenerator;
mapParams.seed = launchOptions.mapSeed;
/**
* Map.
* @private
* @type {!blk.env.server.ServerMap}
*/
this.map_ = new blk.env.server.ServerMap(mapParams, mapStore);
this.registerDisposable(this.map_);
/**
* Server-side simulation.
* @private
* @type {!gf.sim.ServerSimulator}
*/
this.simulator_ = new gf.sim.ServerSimulator(game, this.session,
blk.game.server.SimulationObserver);
this.registerDisposable(this.simulator_);
blk.sim.commands.registerCommands(this.simulator_);
blk.sim.entities.registerEntities(this.simulator_);
/**
* Root entity.
* @private
* @type {blk.sim.Root}
*/
this.root_ = null;
/**
* Player listing.
* @private
* @type {!Array.<!blk.sim.Player>}
*/
this.players_ = [];
/**
* Data model library.
* @private
* @type {!gf.mdl.Library}
*/
this.modelLibrary_ = new blk.assets.models.BaseDataLibrary(
this.game.getAssetManager());
this.registerDisposable(this.modelLibrary_);
};
goog.inherits(blk.game.server.ServerController, goog.Disposable);
/**
* Gets the server simulator.
* @return {!gf.sim.ServerSimulator} Server-side simulation.
*/
blk.game.server.ServerController.prototype.getSimulator = function() {
return this.simulator_;
};
/**
* @return {!blk.env.server.ServerMap} Game map.
*/
blk.game.server.ServerController.prototype.getMap = function() {
return this.map_;
};
/**
* @return {!blk.sim.Root} Root entity.
*/
blk.game.server.ServerController.prototype.getRoot = function() {
goog.asserts.assert(this.root_);
return this.root_;
};
/**
* Gets a list of all currently connected players.
* Do not modify the results. The results may change at any time.
* @return {!Array.<!blk.sim.Player>} A list of players.
*/
blk.game.server.ServerController.prototype.getPlayerList = function() {
return this.players_;
};
/**
* Gets a player by session ID.
* @param {string} sessionId User session ID.
* @return {blk.sim.Player} Player, if found.
*/
blk.game.server.ServerController.prototype.getPlayerBySessionId =
function(sessionId) {
var user = this.session.getUserBySessionId(sessionId);
if (user) {
return /** @type {blk.sim.Player} */ (user.data);
}
return null;
};
/**
* Gets a player by wire ID.
* @param {number} wireId User wire ID.
* @return {blk.sim.Player} Player, if found.
*/
blk.game.server.ServerController.prototype.getPlayerByWireId =
function(wireId) {
var user = this.session.getUserByWireId(wireId);
if (user) {
return /** @type {blk.sim.Player} */ (user.data);
}
return null;
};
/**
* Handles player change events.
* Called when a player joins, leaves, or updates their metadata.
* @protected
*/
blk.game.server.ServerController.prototype.handlePlayersChanged =
goog.nullFunction;
/**
* @return {!gf.mdl.Library} Render model library.
*/
blk.game.server.ServerController.prototype.getModelLibrary = function() {
return this.modelLibrary_;
};
/**
* Loads any resources required by the controller before the game can start.
* @return {!goog.async.Deferred} A deferred fulfilled when the server is ready.
*/
blk.game.server.ServerController.prototype.load = function() {
var deferred = new goog.async.Deferred();
// TODO(benvanik): wait on initial map load?
var simulator = this.getSimulator();
// Root sim entity
this.root_ = /** @type {!blk.sim.Root} */ (
this.simulator_.createEntity(
blk.sim.Root.ID,
gf.sim.EntityFlag.ROOT));
this.root_.setGameController(this);
// Create initial simulation state
this.setupSimulation();
// Start accepting connections
this.session.ready();
deferred.callback(null);
return deferred;
};
/**
* Sets up the simulation on initial load.
* @protected
*/
blk.game.server.ServerController.prototype.setupSimulation =
goog.abstractMethod;
/**
* Handles a new user.
* @protected
* @param {!gf.net.User} user User that connected.
*/
blk.game.server.ServerController.prototype.userConnected = function(user) {
var map = this.map_;
gf.log.write('client connected', user.sessionId, user.info, user.agent);
// Add to chat channels
this.chatService_.join(user, 'main');
// Create player entity
var player = this.createPlayer(user);
user.data = player;
this.players_.push(player);
// Signal player ready
this.session.send(blk.net.packets.ReadyPlayer.createData(), user);
this.handlePlayersChanged();
};
/**
* Creates a player entity for the given user and adds it to the simulation.
* @protected
* @param {!gf.net.User} user User the player represents.
* @return {!blk.sim.Player} Player entity.
*/
blk.game.server.ServerController.prototype.createPlayer = goog.abstractMethod;
/**
* Handles a dead user.
* @protected
* @param {!gf.net.User} user User that disconnected.
*/
blk.game.server.ServerController.prototype.userDisconnected = function(user) {
var map = this.map_;
gf.log.write('client disconnected', user.sessionId);
var player = /** @type {blk.sim.Player} */ (user.data);
if (!player) {
return;
}
// Delete player entity
this.deletePlayer(player);
// Remove from roster
goog.array.remove(this.players_, player);
goog.dispose(player);
};
/**
* Deletes a player entity and removes it from the simulation.
* @protected
* @param {!blk.sim.Player} player Player entity.
*/
blk.game.server.ServerController.prototype.deletePlayer = goog.abstractMethod;
/**
* @override
*/
blk.game.server.ServerController.prototype.userUpdated = goog.nullFunction;
/**
* Handles game-ending errors.
* @protected
* @param {string} message Error message.
* @param {*=} opt_arg Optional argument.
*/
blk.game.server.ServerController.prototype.handleError =
function(message, opt_arg) {
// Log the error
gf.log.write('Error: ' + message, opt_arg);
// Graceful disconnect
// TODO(benvanik): log with server?
this.session.unready();
// TODO(benvanik): die?
};
/**
* Maximum amount of time, in ms, the network poll is allowed to take.
* @private
* @const
* @type {number}
*/
blk.game.server.ServerController.MAX_NETWORK_POLL_TIME_ = 5;
/**
* Updates the game contents.
* @param {!gf.UpdateFrame} frame Current update frame.
*/
blk.game.server.ServerController.prototype.update = function(frame) {
// Ignore updating when disconnected/stopped
if (this.session.state == gf.net.SessionState.DISCONNECTED) {
return;
}
// Poll for network activity
this.session.poll(blk.game.server.ServerController.MAX_NETWORK_POLL_TIME_);
// Check for new disconnection
if (this.session.state == gf.net.SessionState.DISCONNECTED) {
// TODO(benvanik): sys exit?
gf.log.write('Server disconnected!?');
return;
}
// Update game state
this.map_.update(frame);
// Update simulation
this.simulator_.update(frame);
};
/**
* Renders the screen contents.
* @param {!gf.RenderFrame} frame Current render frame.
*/
blk.game.server.ServerController.prototype.render = function(frame) {
};
/**
* @override
*/
blk.game.server.ServerController.prototype.connected = goog.nullFunction;
/**
* @override
*/
blk.game.server.ServerController.prototype.disconnected = goog.nullFunction;
blk.game.server.ServerController = wtfapi.trace.instrumentType(
blk.game.server.ServerController, 'blk.game.server.ServerController',
goog.reflect.object(blk.game.server.ServerController, {
load: 'load',
update: 'update',
render: 'render'
}));
| baumicon/blk-game | src/blk/game/server/servercontroller.js | JavaScript | apache-2.0 | 10,159 |
module.exports={"dependencies":{},"theme":"corporate_theme"}; | titanium-forks/appcelerator-se.DemoApp | Resources/iphone/alloy/CFG.js | JavaScript | apache-2.0 | 61 |
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A combo box control that allows user input with
* auto-suggestion from a limited set of options.
*
* @see ../demos/combobox.html
*/
goog.provide('goog.ui.ComboBox');
goog.provide('goog.ui.ComboBoxItem');
goog.require('goog.Timer');
goog.require('goog.asserts');
goog.require('goog.dom');
goog.require('goog.dom.classlist');
goog.require('goog.events.EventType');
goog.require('goog.events.InputHandler');
goog.require('goog.events.KeyCodes');
goog.require('goog.events.KeyHandler');
goog.require('goog.log');
goog.require('goog.positioning.Corner');
goog.require('goog.positioning.MenuAnchoredPosition');
goog.require('goog.string');
goog.require('goog.style');
goog.require('goog.ui.Component');
goog.require('goog.ui.ItemEvent');
goog.require('goog.ui.LabelInput');
goog.require('goog.ui.Menu');
goog.require('goog.ui.MenuItem');
goog.require('goog.ui.MenuSeparator');
goog.require('goog.ui.registry');
goog.require('goog.userAgent');
/**
* A ComboBox control.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper.
* @param {goog.ui.Menu=} opt_menu Optional menu component.
* This menu is disposed of by this control.
* @param {goog.ui.LabelInput=} opt_labelInput Optional label input.
* This label input is disposed of by this control.
* @extends {goog.ui.Component}
* @constructor
*/
goog.ui.ComboBox = function(opt_domHelper, opt_menu, opt_labelInput) {
goog.ui.Component.call(this, opt_domHelper);
this.labelInput_ = opt_labelInput || new goog.ui.LabelInput();
this.enabled_ = true;
// TODO(user): Allow lazy creation of menus/menu items
this.menu_ = opt_menu || new goog.ui.Menu(this.getDomHelper());
this.setupMenu_();
};
goog.inherits(goog.ui.ComboBox, goog.ui.Component);
/**
* Number of milliseconds to wait before dismissing combobox after blur.
* @type {number}
*/
goog.ui.ComboBox.BLUR_DISMISS_TIMER_MS = 250;
/**
* A logger to help debugging of combo box behavior.
* @type {goog.log.Logger}
* @private
*/
goog.ui.ComboBox.prototype.logger_ =
goog.log.getLogger('goog.ui.ComboBox');
/**
* Whether the combo box is enabled.
* @type {boolean}
* @private
*/
goog.ui.ComboBox.prototype.enabled_;
/**
* Keyboard event handler to manage key events dispatched by the input element.
* @type {goog.events.KeyHandler}
* @private
*/
goog.ui.ComboBox.prototype.keyHandler_;
/**
* Input handler to take care of firing events when the user inputs text in
* the input.
* @type {goog.events.InputHandler?}
* @private
*/
goog.ui.ComboBox.prototype.inputHandler_ = null;
/**
* The last input token.
* @type {?string}
* @private
*/
goog.ui.ComboBox.prototype.lastToken_ = null;
/**
* A LabelInput control that manages the focus/blur state of the input box.
* @type {goog.ui.LabelInput?}
* @private
*/
goog.ui.ComboBox.prototype.labelInput_ = null;
/**
* Drop down menu for the combo box. Will be created at construction time.
* @type {goog.ui.Menu?}
* @private
*/
goog.ui.ComboBox.prototype.menu_ = null;
/**
* The cached visible count.
* @type {number}
* @private
*/
goog.ui.ComboBox.prototype.visibleCount_ = -1;
/**
* The input element.
* @type {Element}
* @private
*/
goog.ui.ComboBox.prototype.input_ = null;
/**
* The match function. The first argument for the match function will be
* a MenuItem's caption and the second will be the token to evaluate.
* @type {Function}
* @private
*/
goog.ui.ComboBox.prototype.matchFunction_ = goog.string.startsWith;
/**
* Element used as the combo boxes button.
* @type {Element}
* @private
*/
goog.ui.ComboBox.prototype.button_ = null;
/**
* Default text content for the input box when it is unchanged and unfocussed.
* @type {string}
* @private
*/
goog.ui.ComboBox.prototype.defaultText_ = '';
/**
* Name for the input box created
* @type {string}
* @private
*/
goog.ui.ComboBox.prototype.fieldName_ = '';
/**
* Timer identifier for delaying the dismissal of the combo menu.
* @type {?number}
* @private
*/
goog.ui.ComboBox.prototype.dismissTimer_ = null;
/**
* True if the unicode inverted triangle should be displayed in the dropdown
* button. Defaults to false.
* @type {boolean} useDropdownArrow
* @private
*/
goog.ui.ComboBox.prototype.useDropdownArrow_ = false;
/**
* Create the DOM objects needed for the combo box. A span and text input.
* @override
*/
goog.ui.ComboBox.prototype.createDom = function() {
this.input_ = this.getDomHelper().createDom(
'input', {name: this.fieldName_, type: 'text', autocomplete: 'off'});
this.button_ = this.getDomHelper().createDom('span',
goog.getCssName('goog-combobox-button'));
this.setElementInternal(this.getDomHelper().createDom('span',
goog.getCssName('goog-combobox'), this.input_, this.button_));
if (this.useDropdownArrow_) {
this.button_.innerHTML = '▼';
goog.style.setUnselectable(this.button_, true /* unselectable */);
}
this.input_.setAttribute('label', this.defaultText_);
this.labelInput_.decorate(this.input_);
this.menu_.setFocusable(false);
if (!this.menu_.isInDocument()) {
this.addChild(this.menu_, true);
}
};
/**
* Enables/Disables the combo box.
* @param {boolean} enabled Whether to enable (true) or disable (false) the
* combo box.
*/
goog.ui.ComboBox.prototype.setEnabled = function(enabled) {
this.enabled_ = enabled;
this.labelInput_.setEnabled(enabled);
goog.dom.classlist.enable(
goog.asserts.assert(this.getElement()),
goog.getCssName('goog-combobox-disabled'), !enabled);
};
/** @override */
goog.ui.ComboBox.prototype.enterDocument = function() {
goog.ui.ComboBox.superClass_.enterDocument.call(this);
var handler = this.getHandler();
handler.listen(this.getElement(),
goog.events.EventType.MOUSEDOWN, this.onComboMouseDown_);
handler.listen(this.getDomHelper().getDocument(),
goog.events.EventType.MOUSEDOWN, this.onDocClicked_);
handler.listen(this.input_,
goog.events.EventType.BLUR, this.onInputBlur_);
this.keyHandler_ = new goog.events.KeyHandler(this.input_);
handler.listen(this.keyHandler_,
goog.events.KeyHandler.EventType.KEY, this.handleKeyEvent);
this.inputHandler_ = new goog.events.InputHandler(this.input_);
handler.listen(this.inputHandler_,
goog.events.InputHandler.EventType.INPUT, this.onInputEvent_);
handler.listen(this.menu_,
goog.ui.Component.EventType.ACTION, this.onMenuSelected_);
};
/** @override */
goog.ui.ComboBox.prototype.exitDocument = function() {
this.keyHandler_.dispose();
delete this.keyHandler_;
this.inputHandler_.dispose();
this.inputHandler_ = null;
goog.ui.ComboBox.superClass_.exitDocument.call(this);
};
/**
* Combo box currently can't decorate elements.
* @return {boolean} The value false.
* @override
*/
goog.ui.ComboBox.prototype.canDecorate = function() {
return false;
};
/** @override */
goog.ui.ComboBox.prototype.disposeInternal = function() {
goog.ui.ComboBox.superClass_.disposeInternal.call(this);
this.clearDismissTimer_();
this.labelInput_.dispose();
this.menu_.dispose();
this.labelInput_ = null;
this.menu_ = null;
this.input_ = null;
this.button_ = null;
};
/**
* Dismisses the menu and resets the value of the edit field.
*/
goog.ui.ComboBox.prototype.dismiss = function() {
this.clearDismissTimer_();
this.hideMenu_();
this.menu_.setHighlightedIndex(-1);
};
/**
* Adds a new menu item at the end of the menu.
* @param {goog.ui.MenuItem} item Menu item to add to the menu.
*/
goog.ui.ComboBox.prototype.addItem = function(item) {
this.menu_.addChild(item, true);
this.visibleCount_ = -1;
};
/**
* Adds a new menu item at a specific index in the menu.
* @param {goog.ui.MenuItem} item Menu item to add to the menu.
* @param {number} n Index at which to insert the menu item.
*/
goog.ui.ComboBox.prototype.addItemAt = function(item, n) {
this.menu_.addChildAt(item, n, true);
this.visibleCount_ = -1;
};
/**
* Removes an item from the menu and disposes it.
* @param {goog.ui.MenuItem} item The menu item to remove.
*/
goog.ui.ComboBox.prototype.removeItem = function(item) {
var child = this.menu_.removeChild(item, true);
if (child) {
child.dispose();
this.visibleCount_ = -1;
}
};
/**
* Remove all of the items from the ComboBox menu
*/
goog.ui.ComboBox.prototype.removeAllItems = function() {
for (var i = this.getItemCount() - 1; i >= 0; --i) {
this.removeItem(this.getItemAt(i));
}
};
/**
* Removes a menu item at a given index in the menu.
* @param {number} n Index of item.
*/
goog.ui.ComboBox.prototype.removeItemAt = function(n) {
var child = this.menu_.removeChildAt(n, true);
if (child) {
child.dispose();
this.visibleCount_ = -1;
}
};
/**
* Returns a reference to the menu item at a given index.
* @param {number} n Index of menu item.
* @return {goog.ui.MenuItem?} Reference to the menu item.
*/
goog.ui.ComboBox.prototype.getItemAt = function(n) {
return /** @type {goog.ui.MenuItem?} */(this.menu_.getChildAt(n));
};
/**
* Returns the number of items in the list, including non-visible items,
* such as separators.
* @return {number} Number of items in the menu for this combobox.
*/
goog.ui.ComboBox.prototype.getItemCount = function() {
return this.menu_.getChildCount();
};
/**
* @return {goog.ui.Menu} The menu that pops up.
*/
goog.ui.ComboBox.prototype.getMenu = function() {
return this.menu_;
};
/**
* @return {Element} The input element.
*/
goog.ui.ComboBox.prototype.getInputElement = function() {
return this.input_;
};
/**
* @return {goog.ui.LabelInput} A LabelInput control that manages the
* focus/blur state of the input box.
*/
goog.ui.ComboBox.prototype.getLabelInput = function() {
return this.labelInput_;
};
/**
* @return {number} The number of visible items in the menu.
* @private
*/
goog.ui.ComboBox.prototype.getNumberOfVisibleItems_ = function() {
if (this.visibleCount_ == -1) {
var count = 0;
for (var i = 0, n = this.menu_.getChildCount(); i < n; i++) {
var item = this.menu_.getChildAt(i);
if (!(item instanceof goog.ui.MenuSeparator) && item.isVisible()) {
count++;
}
}
this.visibleCount_ = count;
}
goog.log.info(this.logger_,
'getNumberOfVisibleItems() - ' + this.visibleCount_);
return this.visibleCount_;
};
/**
* Sets the match function to be used when filtering the combo box menu.
* @param {Function} matchFunction The match function to be used when filtering
* the combo box menu.
*/
goog.ui.ComboBox.prototype.setMatchFunction = function(matchFunction) {
this.matchFunction_ = matchFunction;
};
/**
* @return {Function} The match function for the combox box.
*/
goog.ui.ComboBox.prototype.getMatchFunction = function() {
return this.matchFunction_;
};
/**
* Sets the default text for the combo box.
* @param {string} text The default text for the combo box.
*/
goog.ui.ComboBox.prototype.setDefaultText = function(text) {
this.defaultText_ = text;
if (this.labelInput_) {
this.labelInput_.setLabel(this.defaultText_);
}
};
/**
* @return {string} text The default text for the combox box.
*/
goog.ui.ComboBox.prototype.getDefaultText = function() {
return this.defaultText_;
};
/**
* Sets the field name for the combo box.
* @param {string} fieldName The field name for the combo box.
*/
goog.ui.ComboBox.prototype.setFieldName = function(fieldName) {
this.fieldName_ = fieldName;
};
/**
* @return {string} The field name for the combo box.
*/
goog.ui.ComboBox.prototype.getFieldName = function() {
return this.fieldName_;
};
/**
* Set to true if a unicode inverted triangle should be displayed in the
* dropdown button.
* This option defaults to false for backwards compatibility.
* @param {boolean} useDropdownArrow True to use the dropdown arrow.
*/
goog.ui.ComboBox.prototype.setUseDropdownArrow = function(useDropdownArrow) {
this.useDropdownArrow_ = !!useDropdownArrow;
};
/**
* Sets the current value of the combo box.
* @param {string} value The new value.
*/
goog.ui.ComboBox.prototype.setValue = function(value) {
goog.log.info(this.logger_, 'setValue() - ' + value);
if (this.labelInput_.getValue() != value) {
this.labelInput_.setValue(value);
this.handleInputChange_();
}
};
/**
* @return {string} The current value of the combo box.
*/
goog.ui.ComboBox.prototype.getValue = function() {
return this.labelInput_.getValue();
};
/**
* @return {string} HTML escaped token.
*/
goog.ui.ComboBox.prototype.getToken = function() {
// TODO(user): Remove HTML escaping and fix the existing calls.
return goog.string.htmlEscape(this.getTokenText_());
};
/**
* @return {string} The token for the current cursor position in the
* input box, when multi-input is disabled it will be the full input value.
* @private
*/
goog.ui.ComboBox.prototype.getTokenText_ = function() {
// TODO(user): Implement multi-input such that getToken returns a substring
// of the whole input delimited by commas.
return goog.string.trim(this.labelInput_.getValue().toLowerCase());
};
/**
* @private
*/
goog.ui.ComboBox.prototype.setupMenu_ = function() {
var sm = this.menu_;
sm.setVisible(false);
sm.setAllowAutoFocus(false);
sm.setAllowHighlightDisabled(true);
};
/**
* Shows the menu if it isn't already showing. Also positions the menu
* correctly, resets the menu item visibilities and highlights the relevent
* item.
* @param {boolean} showAll Whether to show all items, with the first matching
* item highlighted.
* @private
*/
goog.ui.ComboBox.prototype.maybeShowMenu_ = function(showAll) {
var isVisible = this.menu_.isVisible();
var numVisibleItems = this.getNumberOfVisibleItems_();
if (isVisible && numVisibleItems == 0) {
goog.log.fine(this.logger_, 'no matching items, hiding');
this.hideMenu_();
} else if (!isVisible && numVisibleItems > 0) {
if (showAll) {
goog.log.fine(this.logger_, 'showing menu');
this.setItemVisibilityFromToken_('');
this.setItemHighlightFromToken_(this.getTokenText_());
}
// In Safari 2.0, when clicking on the combox box, the blur event is
// received after the click event that invokes this function. Since we want
// to cancel the dismissal after the blur event is processed, we have to
// wait for all event processing to happen.
goog.Timer.callOnce(this.clearDismissTimer_, 1, this);
this.showMenu_();
}
this.positionMenu();
};
/**
* Positions the menu.
* @protected
*/
goog.ui.ComboBox.prototype.positionMenu = function() {
if (this.menu_ && this.menu_.isVisible()) {
var position = new goog.positioning.MenuAnchoredPosition(this.getElement(),
goog.positioning.Corner.BOTTOM_START, true);
position.reposition(this.menu_.getElement(),
goog.positioning.Corner.TOP_START);
}
};
/**
* Show the menu and add an active class to the combo box's element.
* @private
*/
goog.ui.ComboBox.prototype.showMenu_ = function() {
this.menu_.setVisible(true);
goog.dom.classlist.add(
goog.asserts.assert(this.getElement()),
goog.getCssName('goog-combobox-active'));
};
/**
* Hide the menu and remove the active class from the combo box's element.
* @private
*/
goog.ui.ComboBox.prototype.hideMenu_ = function() {
this.menu_.setVisible(false);
goog.dom.classlist.remove(
goog.asserts.assert(this.getElement()),
goog.getCssName('goog-combobox-active'));
};
/**
* Clears the dismiss timer if it's active.
* @private
*/
goog.ui.ComboBox.prototype.clearDismissTimer_ = function() {
if (this.dismissTimer_) {
goog.Timer.clear(this.dismissTimer_);
this.dismissTimer_ = null;
}
};
/**
* Event handler for when the combo box area has been clicked.
* @param {goog.events.BrowserEvent} e The browser event.
* @private
*/
goog.ui.ComboBox.prototype.onComboMouseDown_ = function(e) {
// We only want this event on the element itself or the input or the button.
if (this.enabled_ &&
(e.target == this.getElement() || e.target == this.input_ ||
goog.dom.contains(this.button_, /** @type {Node} */ (e.target)))) {
if (this.menu_.isVisible()) {
goog.log.fine(this.logger_, 'Menu is visible, dismissing');
this.dismiss();
} else {
goog.log.fine(this.logger_, 'Opening dropdown');
this.maybeShowMenu_(true);
if (goog.userAgent.OPERA) {
// select() doesn't focus <input> elements in Opera.
this.input_.focus();
}
this.input_.select();
this.menu_.setMouseButtonPressed(true);
// Stop the click event from stealing focus
e.preventDefault();
}
}
// Stop the event from propagating outside of the combo box
e.stopPropagation();
};
/**
* Event handler for when the document is clicked.
* @param {goog.events.BrowserEvent} e The browser event.
* @private
*/
goog.ui.ComboBox.prototype.onDocClicked_ = function(e) {
if (!goog.dom.contains(
this.menu_.getElement(), /** @type {Node} */ (e.target))) {
goog.log.info(this.logger_, 'onDocClicked_() - dismissing immediately');
this.dismiss();
}
};
/**
* Handle the menu's select event.
* @param {goog.events.Event} e The event.
* @private
*/
goog.ui.ComboBox.prototype.onMenuSelected_ = function(e) {
goog.log.info(this.logger_, 'onMenuSelected_()');
var item = /** @type {!goog.ui.MenuItem} */ (e.target);
// Stop propagation of the original event and redispatch to allow the menu
// select to be cancelled at this level. i.e. if a menu item should cause
// some behavior such as a user prompt instead of assigning the caption as
// the value.
if (this.dispatchEvent(new goog.ui.ItemEvent(
goog.ui.Component.EventType.ACTION, this, item))) {
var caption = item.getCaption();
goog.log.fine(this.logger_,
'Menu selection: ' + caption + '. Dismissing menu');
if (this.labelInput_.getValue() != caption) {
this.labelInput_.setValue(caption);
this.dispatchEvent(goog.ui.Component.EventType.CHANGE);
}
this.dismiss();
}
e.stopPropagation();
};
/**
* Event handler for when the input box looses focus -- hide the menu
* @param {goog.events.BrowserEvent} e The browser event.
* @private
*/
goog.ui.ComboBox.prototype.onInputBlur_ = function(e) {
goog.log.info(this.logger_, 'onInputBlur_() - delayed dismiss');
this.clearDismissTimer_();
this.dismissTimer_ = goog.Timer.callOnce(
this.dismiss, goog.ui.ComboBox.BLUR_DISMISS_TIMER_MS, this);
};
/**
* Handles keyboard events from the input box. Returns true if the combo box
* was able to handle the event, false otherwise.
* @param {goog.events.KeyEvent} e Key event to handle.
* @return {boolean} Whether the event was handled by the combo box.
* @protected
* @suppress {visibility} performActionInternal
*/
goog.ui.ComboBox.prototype.handleKeyEvent = function(e) {
var isMenuVisible = this.menu_.isVisible();
// Give the menu a chance to handle the event.
if (isMenuVisible && this.menu_.handleKeyEvent(e)) {
return true;
}
// The menu is either hidden or didn't handle the event.
var handled = false;
switch (e.keyCode) {
case goog.events.KeyCodes.ESC:
// If the menu is visible and the user hit Esc, dismiss the menu.
if (isMenuVisible) {
goog.log.fine(this.logger_,
'Dismiss on Esc: ' + this.labelInput_.getValue());
this.dismiss();
handled = true;
}
break;
case goog.events.KeyCodes.TAB:
// If the menu is open and an option is highlighted, activate it.
if (isMenuVisible) {
var highlighted = this.menu_.getHighlighted();
if (highlighted) {
goog.log.fine(this.logger_,
'Select on Tab: ' + this.labelInput_.getValue());
highlighted.performActionInternal(e);
handled = true;
}
}
break;
case goog.events.KeyCodes.UP:
case goog.events.KeyCodes.DOWN:
// If the menu is hidden and the user hit the up/down arrow, show it.
if (!isMenuVisible) {
goog.log.fine(this.logger_, 'Up/Down - maybe show menu');
this.maybeShowMenu_(true);
handled = true;
}
break;
}
if (handled) {
e.preventDefault();
}
return handled;
};
/**
* Handles the content of the input box changing.
* @param {goog.events.Event} e The INPUT event to handle.
* @private
*/
goog.ui.ComboBox.prototype.onInputEvent_ = function(e) {
// If the key event is text-modifying, update the menu.
goog.log.fine(this.logger_,
'Key is modifying: ' + this.labelInput_.getValue());
this.handleInputChange_();
};
/**
* Handles the content of the input box changing, either because of user
* interaction or programmatic changes.
* @private
*/
goog.ui.ComboBox.prototype.handleInputChange_ = function() {
var token = this.getTokenText_();
this.setItemVisibilityFromToken_(token);
if (goog.dom.getActiveElement(this.getDomHelper().getDocument()) ==
this.input_) {
// Do not alter menu visibility unless the user focus is currently on the
// combobox (otherwise programmatic changes may cause the menu to become
// visible).
this.maybeShowMenu_(false);
}
var highlighted = this.menu_.getHighlighted();
if (token == '' || !highlighted || !highlighted.isVisible()) {
this.setItemHighlightFromToken_(token);
}
this.lastToken_ = token;
this.dispatchEvent(goog.ui.Component.EventType.CHANGE);
};
/**
* Loops through all menu items setting their visibility according to a token.
* @param {string} token The token.
* @private
*/
goog.ui.ComboBox.prototype.setItemVisibilityFromToken_ = function(token) {
goog.log.info(this.logger_, 'setItemVisibilityFromToken_() - ' + token);
var isVisibleItem = false;
var count = 0;
var recheckHidden = !this.matchFunction_(token, this.lastToken_);
for (var i = 0, n = this.menu_.getChildCount(); i < n; i++) {
var item = this.menu_.getChildAt(i);
if (item instanceof goog.ui.MenuSeparator) {
// Ensure that separators are only shown if there is at least one visible
// item before them.
item.setVisible(isVisibleItem);
isVisibleItem = false;
} else if (item instanceof goog.ui.MenuItem) {
if (!item.isVisible() && !recheckHidden) continue;
var caption = item.getCaption();
var visible = this.isItemSticky_(item) ||
caption && this.matchFunction_(caption.toLowerCase(), token);
if (typeof item.setFormatFromToken == 'function') {
item.setFormatFromToken(token);
}
item.setVisible(!!visible);
isVisibleItem = visible || isVisibleItem;
} else {
// Assume all other items are correctly using their visibility.
isVisibleItem = item.isVisible() || isVisibleItem;
}
if (!(item instanceof goog.ui.MenuSeparator) && item.isVisible()) {
count++;
}
}
this.visibleCount_ = count;
};
/**
* Highlights the first token that matches the given token.
* @param {string} token The token.
* @private
*/
goog.ui.ComboBox.prototype.setItemHighlightFromToken_ = function(token) {
goog.log.info(this.logger_, 'setItemHighlightFromToken_() - ' + token);
if (token == '') {
this.menu_.setHighlightedIndex(-1);
return;
}
for (var i = 0, n = this.menu_.getChildCount(); i < n; i++) {
var item = this.menu_.getChildAt(i);
var caption = item.getCaption();
if (caption && this.matchFunction_(caption.toLowerCase(), token)) {
this.menu_.setHighlightedIndex(i);
if (item.setFormatFromToken) {
item.setFormatFromToken(token);
}
return;
}
}
this.menu_.setHighlightedIndex(-1);
};
/**
* Returns true if the item has an isSticky method and the method returns true.
* @param {goog.ui.MenuItem} item The item.
* @return {boolean} Whether the item has an isSticky method and the method
* returns true.
* @private
*/
goog.ui.ComboBox.prototype.isItemSticky_ = function(item) {
return typeof item.isSticky == 'function' && item.isSticky();
};
/**
* Class for combo box items.
* @param {goog.ui.ControlContent} content Text caption or DOM structure to
* display as the content of the item (use to add icons or styling to
* menus).
* @param {Object=} opt_data Identifying data for the menu item.
* @param {goog.dom.DomHelper=} opt_domHelper Optional dom helper used for dom
* interactions.
* @param {goog.ui.MenuItemRenderer=} opt_renderer Optional renderer.
* @constructor
* @extends {goog.ui.MenuItem}
*/
goog.ui.ComboBoxItem = function(content, opt_data, opt_domHelper,
opt_renderer) {
goog.ui.MenuItem.call(this, content, opt_data, opt_domHelper, opt_renderer);
};
goog.inherits(goog.ui.ComboBoxItem, goog.ui.MenuItem);
// Register a decorator factory function for goog.ui.ComboBoxItems.
goog.ui.registry.setDecoratorByClassName(goog.getCssName('goog-combobox-item'),
function() {
// ComboBoxItem defaults to using MenuItemRenderer.
return new goog.ui.ComboBoxItem(null);
});
/**
* Whether the menu item is sticky, non-sticky items will be hidden as the
* user types.
* @type {boolean}
* @private
*/
goog.ui.ComboBoxItem.prototype.isSticky_ = false;
/**
* Sets the menu item to be sticky or not sticky.
* @param {boolean} sticky Whether the menu item should be sticky.
*/
goog.ui.ComboBoxItem.prototype.setSticky = function(sticky) {
this.isSticky_ = sticky;
};
/**
* @return {boolean} Whether the menu item is sticky.
*/
goog.ui.ComboBoxItem.prototype.isSticky = function() {
return this.isSticky_;
};
/**
* Sets the format for a menu item based on a token, bolding the token.
* @param {string} token The token.
*/
goog.ui.ComboBoxItem.prototype.setFormatFromToken = function(token) {
if (this.isEnabled()) {
var caption = this.getCaption();
var index = caption.toLowerCase().indexOf(token);
if (index >= 0) {
var domHelper = this.getDomHelper();
this.setContent([
domHelper.createTextNode(caption.substr(0, index)),
domHelper.createDom('b', null, caption.substr(index, token.length)),
domHelper.createTextNode(caption.substr(index + token.length))
]);
}
}
};
| chihuahua/beautiful-audio-editor | third_party/closure_library/closure/goog/ui/combobox.js | JavaScript | apache-2.0 | 26,925 |
dojo.provide("dojox.gfx.Moveable");
dojo.require("dojox.gfx.Mover");
dojo.declare("dojox.gfx.Moveable", null, {
constructor: function(shape, params){
// summary: an object, which makes a shape moveable
// shape: dojox.gfx.Shape: a shape object to be moved
// params: Object: an optional object with additional parameters;
// following parameters are recognized:
// delay: Number: delay move by this number of pixels
// mover: Object: a constructor of custom Mover
this.shape = shape;
this.delay = (params && params.delay > 0) ? params.delay : 0;
this.mover = (params && params.mover) ? params.mover : dojox.gfx.Mover;
this.events = [
this.shape.connect("onmousedown", this, "onMouseDown")
// cancel text selection and text dragging
//, dojo.connect(this.handle, "ondragstart", dojo, "stopEvent")
//, dojo.connect(this.handle, "onselectstart", dojo, "stopEvent")
];
},
// methods
destroy: function(){
// summary: stops watching for possible move, deletes all references, so the object can be garbage-collected
dojo.forEach(this.events, this.shape.disconnect, this.shape);
this.events = this.shape = null;
},
// mouse event processors
onMouseDown: function(e){
// summary: event processor for onmousedown, creates a Mover for the shape
// e: Event: mouse event
if(this.delay){
this.events.push(
this.shape.connect("onmousemove", this, "onMouseMove"),
this.shape.connect("onmouseup", this, "onMouseUp"));
this._lastX = e.clientX;
this._lastY = e.clientY;
}else{
new this.mover(this.shape, e, this);
}
dojo.stopEvent(e);
},
onMouseMove: function(e){
// summary: event processor for onmousemove, used only for delayed drags
// e: Event: mouse event
if(Math.abs(e.clientX - this._lastX) > this.delay || Math.abs(e.clientY - this._lastY) > this.delay){
this.onMouseUp(e);
new this.mover(this.shape, e, this);
}
dojo.stopEvent(e);
},
onMouseUp: function(e){
// summary: event processor for onmouseup, used only for delayed delayed drags
// e: Event: mouse event
this.shape.disconnect(this.events.pop());
this.shape.disconnect(this.events.pop());
},
// local events
onMoveStart: function(/* dojox.gfx.Mover */ mover){
// summary: called before every move operation
dojo.publish("/gfx/move/start", [mover]);
dojo.addClass(dojo.body(), "dojoMove");
},
onMoveStop: function(/* dojox.gfx.Mover */ mover){
// summary: called after every move operation
dojo.publish("/gfx/move/stop", [mover]);
dojo.removeClass(dojo.body(), "dojoMove");
},
onFirstMove: function(/* dojox.gfx.Mover */ mover){
// summary: called during the very first move notification,
// can be used to initialize coordinates, can be overwritten.
// default implementation does nothing
},
onMove: function(/* dojox.gfx.Mover */ mover, /* Object */ shift){
// summary: called during every move notification,
// should actually move the node, can be overwritten.
this.onMoving(mover, shift);
this.shape.applyLeftTransform(shift);
this.onMoved(mover, shift);
},
onMoving: function(/* dojox.gfx.Mover */ mover, /* Object */ shift){
// summary: called before every incremental move,
// can be overwritten.
// default implementation does nothing
},
onMoved: function(/* dojox.gfx.Mover */ mover, /* Object */ shift){
// summary: called after every incremental move,
// can be overwritten.
// default implementation does nothing
}
});
| sulistionoadi/belajar-springmvc-dojo | training-web/src/main/webapp/js/dojotoolkit/dojox/gfx/Moveable.js | JavaScript | apache-2.0 | 3,453 |
// This file was procedurally generated from the following sources:
// - src/dstr-binding/obj-ptrn-prop-obj-value-null.case
// - src/dstr-binding/error/async-gen-meth.template
/*---
description: Object binding pattern with "nested" object binding pattern taking the `null` value (async generator method)
esid: sec-asyncgenerator-definitions-propertydefinitionevaluation
features: [async-iteration]
flags: [generated]
info: |
AsyncGeneratorMethod :
async [no LineTerminator here] * PropertyName ( UniqueFormalParameters )
{ AsyncGeneratorBody }
1. Let propKey be the result of evaluating PropertyName.
2. ReturnIfAbrupt(propKey).
3. If the function code for this AsyncGeneratorMethod is strict mode code, let strict be true.
Otherwise let strict be false.
4. Let scope be the running execution context's LexicalEnvironment.
5. Let closure be ! AsyncGeneratorFunctionCreate(Method, UniqueFormalParameters,
AsyncGeneratorBody, scope, strict).
[...]
13.3.3.7 Runtime Semantics: KeyedBindingInitialization
[...]
3. If Initializer is present and v is undefined, then
[...]
4. Return the result of performing BindingInitialization for BindingPattern
passing v and environment as arguments.
---*/
var obj = {
async *method({ w: { x, y, z } = { x: 4, y: 5, z: 6 } }) {
}
};
assert.throws(TypeError, function() {
obj.method({ w: null });
});
| sebastienros/jint | Jint.Tests.Test262/test/language/expressions/object/dstr-async-gen-meth-obj-ptrn-prop-obj-value-null.js | JavaScript | bsd-2-clause | 1,441 |
/*!
* SAP UI development toolkit for HTML5 (SAPUI5/OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
sap.ui.define(['jquery.sap.global','sap/ui/core/Element','sap/ui/core/library'],function(q,E,l){"use strict";var S=E.extend("sap.ui.core.search.SearchProvider",{metadata:{library:"sap.ui.core",properties:{icon:{type:"string",group:"Misc",defaultValue:null}}}});S.prototype.suggest=function(v,c){q.sap.log.warning("sap.ui.core.search.SearchProvider is the abstract base class for all SearchProviders. Do not create instances of this class, but use a concrete sub class instead.");};return S;},true);
| mindmill/open-cmis-explorer | resources/sap/ui/core/search/SearchProvider.js | JavaScript | bsd-2-clause | 696 |
// Copyright (C) 2015 André Bargull. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es6id: 22.2.2.4
description: >
get %TypedArray% [ @@species ].length is 0.
info: |
get %TypedArray% [ @@species ]
17 ECMAScript Standard Built-in Objects:
Every built-in Function object, including constructors, has a length
property whose value is an integer. Unless otherwise specified, this
value is equal to the largest number of named arguments shown in the
subclause headings for the function description, including optional
parameters. However, rest parameters shown using the form “...name”
are not included in the default argument count.
Unless otherwise specified, the length property of a built-in Function
object has the attributes { [[Writable]]: false, [[Enumerable]]: false,
[[Configurable]]: true }.
includes: [propertyHelper.js, testTypedArray.js]
features: [Symbol.species]
---*/
var desc = Object.getOwnPropertyDescriptor(TypedArray, Symbol.species);
assert.sameValue(desc.get.length, 0);
verifyNotEnumerable(desc.get, "length");
verifyNotWritable(desc.get, "length");
verifyConfigurable(desc.get, "length");
| sebastienros/jint | Jint.Tests.Test262/test/built-ins/TypedArray/Symbol.species/length.js | JavaScript | bsd-2-clause | 1,215 |
'use strict';
var mergeTrees = require('broccoli-merge-trees'),
unwatchedTree = require('broccoli-unwatched-tree'),
compileModules = require('./lib/compile-modules'),
graphModules = require('./lib/graph'),
cssWithMQs = require('./lib/css-with-mqs'),
stripMQs = require('./lib/css-strip-mqs'),
mapFiles = require('./lib/map-files');
var bower_components = unwatchedTree('bower_components/'),
node_modules = unwatchedTree('node_modules/');
var vendor = mergeTrees([
mapFiles(bower_components, {
'rainbow/js/': 'vendor/rainbow/'
}),
mapFiles(node_modules, {
'css-mediaquery/index.js' : 'vendor/css-mediaquery.js',
'handlebars/dist/handlebars.runtime.js': 'vendor/handlebars.runtime.js'
})
]);
var pub = 'public/';
// Calculate the ES6 module dependency graph.
var modGraph = graphModules(pub, {
basePath : 'js/',
resolveImports: true
});
// Compile ES6 Modules in `pub`.
pub = compileModules(pub, {
basePath: 'js/',
type : 'yui'
});
// Strip Media Queries from CSS files and save copy as "-old-ie.css".
var oldIECSS = stripMQs(cssWithMQs(pub), {suffix: '-old-ie'});
// Export merged trees.
module.exports = mergeTrees([vendor, pub, oldIECSS, modGraph]);
| igorstefurak/pushcourse | Brocfile.js | JavaScript | bsd-3-clause | 1,292 |
/**
* 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 diffRelayQuery
* @flow
* @typechecks
*/
'use strict';
var GraphQLStoreDataHandler = require('GraphQLStoreDataHandler');
var RelayConnectionInterface = require('RelayConnectionInterface');
var RelayNodeInterface = require('RelayNodeInterface');
var RelayProfiler = require('RelayProfiler');
var RelayQuery = require('RelayQuery');
var RelayQueryPath = require('RelayQueryPath');
import type RelayQueryTracker from 'RelayQueryTracker';
import type RelayRecordStore from 'RelayRecordStore';
import type {RangeInfo} from 'RelayRecordStore';
var forEachRootCallArg = require('forEachRootCallArg');
var invariant = require('invariant');
var warning = require('warning');
var {EDGES, NODE, PAGE_INFO} = RelayConnectionInterface;
var idField = RelayQuery.Node.buildField('id', null, null, {
parentType: RelayNodeInterface.NODE_TYPE,
requisite: true,
});
var nodeWithID = RelayQuery.Node.buildField(
RelayNodeInterface.NODE,
null,
[idField],
);
import type {DataID} from 'RelayInternalTypes';
type DiffScope = {
connectionField: ?RelayQuery.Field;
dataID: DataID,
edgeID: ?DataID,
rangeInfo: ?RangeInfo;
};
type DiffOutput = {
diffNode: ?RelayQuery.Node;
trackedNode: ?RelayQuery.Node;
};
/**
* @internal
*
* Computes the difference between the data requested in `root` and the data
* available in `store`. It returns a minimal set of queries that will fulfill
* the difference, or an empty array if the query can be resolved locally.
*/
function diffRelayQuery(
root: RelayQuery.Root,
store: RelayRecordStore,
tracker: RelayQueryTracker
): Array<RelayQuery.Root> {
var path = new RelayQueryPath(root);
var queries = [];
var visitor = new RelayDiffQueryBuilder(store, tracker);
var rootCallValue = root.getRootCall().value;
var isPluralCall = Array.isArray(rootCallValue) && rootCallValue.length > 1;
forEachRootCallArg(root, (rootCallArg, rootCallName) => {
var nodeRoot;
if (isPluralCall) {
invariant(
rootCallArg != null,
'diffRelayQuery(): Unexpected null or undefined value in root call ' +
'argument array for query, `%s(...).',
rootCallName
);
nodeRoot = RelayQuery.Node.buildRoot(
rootCallName,
rootCallArg,
root.getChildren(),
{
rootArg: root.getRootCallArgument(),
rootCallType: root.getCallType(),
},
root.getName()
);
} else {
// Reuse `root` if it only maps to one result.
nodeRoot = root;
}
// The whole query must be fetched if the root dataID is unknown.
var dataID = store.getRootCallID(rootCallName, rootCallArg);
if (dataID == null) {
queries.push(nodeRoot);
return;
}
// Diff the current dataID
var scope = makeScope(dataID);
var diffOutput = visitor.visit(nodeRoot, path, scope);
var diffNode = diffOutput ? diffOutput.diffNode : null;
if (diffNode) {
invariant(
diffNode instanceof RelayQuery.Root,
'diffRelayQuery(): Expected result to be a root query.'
);
queries.push(diffNode);
}
});
return queries.concat(visitor.getSplitQueries());
}
/**
* @internal
*
* A transform for (node + store) -> (diff + tracked queries). It is analagous
* to `RelayQueryTransform` with the main differences as follows:
* - there is no `state` (which allowed for passing data up and down the tree).
* - data is passed down via `scope`, which flows from a parent field down
* through intermediary fragments to the nearest child field.
* - data is passed up via the return type `{diffNode, trackedNode}`, where:
* - `diffNode`: subset of the input that could not diffed out
* - `trackedNode`: subset of the input that must be tracked
*
* The provided `tracker` is updated whenever the traversal of a node results
* in a `trackedNode` being created. New top-level queries are not returned
* up the tree, and instead are available via `getSplitQueries()`.
*/
class RelayDiffQueryBuilder {
_store: RelayRecordStore;
_splitQueries: Array<RelayQuery.Root>;
_tracker: RelayQueryTracker;
constructor(store: RelayRecordStore, tracker: RelayQueryTracker) {
this._store = store;
this._splitQueries = [];
this._tracker = tracker;
}
splitQuery(
root: RelayQuery.Root
): void {
this._splitQueries.push(root);
}
getSplitQueries(): Array<RelayQuery.Root> {
return this._splitQueries;
}
visit(
node: RelayQuery.Node,
path: RelayQueryPath,
scope: DiffScope
): ?DiffOutput {
if (node instanceof RelayQuery.Field) {
return this.visitField(node, path, scope);
} else if (node instanceof RelayQuery.Fragment) {
return this.visitFragment(node, path, scope);
} else if (node instanceof RelayQuery.Root) {
return this.visitRoot(node, path, scope);
}
}
visitRoot(
node: RelayQuery.Root,
path: RelayQueryPath,
scope: DiffScope
): ?DiffOutput {
return this.traverse(node, path, scope);
}
visitFragment(
node: RelayQuery.Fragment,
path: RelayQueryPath,
scope: DiffScope
): ?DiffOutput {
return this.traverse(node, path, scope);
}
/**
* Diffs the field conditionally based on the `scope` from the nearest
* ancestor field.
*/
visitField(
node: RelayQuery.Field,
path: RelayQueryPath,
{connectionField, dataID, edgeID, rangeInfo}: DiffScope
): ?DiffOutput {
// special case when inside a connection traversal
if (connectionField && rangeInfo) {
if (edgeID) {
// When traversing a specific connection edge only look at `edges`
if (node.getSchemaName() === EDGES) {
return this.diffConnectionEdge(
connectionField,
node, // edge field
path.getPath(node, edgeID),
edgeID,
rangeInfo
);
} else {
return null;
}
} else {
// When traversing connection metadata fields, edges/page_info are
// only kept if there are range extension calls. Other fields fall
// through to regular diffing.
if (
node.getSchemaName() === EDGES ||
node.getSchemaName() === PAGE_INFO
) {
return rangeInfo.diffCalls.length > 0 ?
{
diffNode: node,
trackedNode: null
} :
null;
}
}
}
// default field diffing algorithm
if (node.isScalar()) {
return this.diffScalar(node, dataID);
} else if (node.isGenerated()) {
return {
diffNode: node,
trackedNode: null,
};
} else if (node.isConnection()) {
return this.diffConnection(node, path, dataID);
} else if (node.isPlural()) {
return this.diffPluralLink(node, path, dataID);
} else {
return this.diffLink(node, path, dataID);
}
}
/**
* Visit all the children of the given `node` and merge their results.
*/
traverse(
node: RelayQuery.Node,
path: RelayQueryPath,
scope: DiffScope
): ?DiffOutput {
var diffNode;
var diffChildren;
var trackedNode;
var trackedChildren;
var hasDiffField = false;
var hasTrackedField = false;
node.getChildren().forEach(child => {
var diffOutput = this.visit(child, path, scope);
var diffChild = diffOutput ? diffOutput.diffNode : null;
var trackedChild = diffOutput ? diffOutput.trackedNode : null;
// Diff uses child nodes and keeps requisite fields
if (diffChild) {
diffChildren = diffChildren || [];
diffChildren.push(diffChild);
hasDiffField = hasDiffField || !diffChild.isGenerated();
} else if (child.isRequisite() && !scope.rangeInfo) {
// The presence of `rangeInfo` indicates that we are traversing
// connection metadata fields, in which case `visitField` will ensure
// that `edges` and `page_info` are kept when necessary. The requisite
// check alone could cause these fields to be added back when not
// needed.
//
// Example: `friends.first(3) {count, edges {...}, page_info {...} }
// If all `edges` were fetched but `count` is unfetched, the diff
// should be `friends.first(3) {count}` and not include `page_info`.
diffChildren = diffChildren || [];
diffChildren.push(child);
}
// Tracker uses tracked children and keeps requisite fields
if (trackedChild) {
trackedChildren = trackedChildren || [];
trackedChildren.push(trackedChild);
hasTrackedField = hasTrackedField || !trackedChild.isGenerated();
} else if (child.isRequisite()) {
trackedChildren = trackedChildren || [];
trackedChildren.push(child);
}
});
// Only return diff/tracked node if there are non-generated fields
if (diffChildren && hasDiffField) {
diffNode = node.clone(diffChildren);
}
if (trackedChildren && hasTrackedField) {
trackedNode = node.clone(trackedChildren);
}
// Record tracked nodes. Fragments can be skipped because these will
// always be composed into, and therefore tracked by, their nearest
// non-fragment parent.
if (trackedNode && !(trackedNode instanceof RelayQuery.Fragment)) {
this._tracker.trackNodeForID(trackedNode, scope.dataID, path);
}
return {
diffNode,
trackedNode,
};
}
/**
* Diff a scalar field such as `name` or `id`.
*/
diffScalar(
field: RelayQuery.Field,
dataID: DataID,
): ?DiffOutput {
if (this._store.getField(dataID, field.getStorageKey()) === undefined) {
return {
diffNode: field,
trackedNode: null,
};
}
return null;
}
/**
* Diff a field-of-fields such as `profile_picture {...}`. Returns early if
* the field has not been fetched, otherwise the result of traversal.
*/
diffLink(
field: RelayQuery.Field,
path: RelayQueryPath,
dataID: DataID,
): ?DiffOutput {
var nextDataID =
this._store.getLinkedRecordID(dataID, field.getStorageKey());
if (nextDataID === undefined) {
return {
diffNode: field,
trackedNode: null,
};
}
if (nextDataID === null) {
return null;
}
return this.traverse(
field,
path.getPath(field, nextDataID),
makeScope(nextDataID)
);
}
/**
* Diffs a non-connection plural field against each of the fetched items.
* Note that scalar plural fields are handled by `_diffScalar`.
*/
diffPluralLink(
field: RelayQuery.Field,
path: RelayQueryPath,
dataID: DataID
): ?DiffOutput {
var linkedIDs =
this._store.getLinkedRecordIDs(dataID, field.getStorageKey());
if (linkedIDs === undefined) {
// not fetched
return {
diffNode: field,
trackedNode: null,
};
} else if (linkedIDs === null || linkedIDs.length === 0) {
// empty array means nothing to fetch
return null;
} else if (field.getInferredRootCallName() === NODE) {
// The items in this array are fetchable and may have been filled in
// from other sources, so check them all. For example, `Story{actors}`
// is an array (but not a range), and the Actors in that array likely
// had data fetched for them elsewhere (like `viewer(){actor}`).
var hasSplitQueries = false;
linkedIDs.forEach(itemID => {
var itemState = this.traverse(
field,
path.getPath(field, itemID),
makeScope(itemID)
);
if (itemState) {
// If any child was tracked then `field` will also be tracked
hasSplitQueries =
hasSplitQueries || !!itemState.trackedNode || !!itemState.diffNode;
// split diff nodes into root queries
if (itemState.diffNode) {
this.splitQuery(buildRoot(
itemID,
itemState.diffNode.getChildren(),
path.getName()
));
}
}
});
// if sub-queries are split then this *entire* field will be tracked,
// therefore we don't need to merge the `trackedNode` from each item
if (hasSplitQueries) {
return {
diffNode: null,
trackedNode: field,
};
}
} else {
// The items in this array are not fetchable by ID, so nothing else
// could have fetched additional data for individual items. Therefore,
// we only need to diff the first record to figure out which fields have
// previously been fetched.
var sampleItemID = linkedIDs[0];
return this.traverse(
field,
path.getPath(field, sampleItemID),
makeScope(sampleItemID)
);
}
return null;
}
/**
* Diff a connection field such as `news_feed.first(3)`. Returns early if
* the range has not been fetched or the entire range has already been
* fetched. Otherwise the diff output is a clone of `field` with updated
* after/first and before/last calls.
*/
diffConnection(
field: RelayQuery.Field,
path: RelayQueryPath,
dataID: DataID,
): ?DiffOutput {
var store: RelayRecordStore = this._store;
var connectionID = store.getLinkedRecordID(dataID, field.getStorageKey());
var rangeInfo = store.getRangeMetadata(
connectionID,
field.getCallsWithValues()
);
// Keep the field if the connection is unfetched
if (connectionID === undefined) {
return {
diffNode: field,
trackedNode: null,
};
}
// Skip if the connection is deleted.
if (connectionID === null) {
return null;
}
// If metadata fields but not edges are fetched, diff as a normal field.
// In practice, `rangeInfo` is `undefined` if unfetched, `null` if the
// connection was deleted (in which case `connectionID` is null too).
if (rangeInfo == null) {
return this.traverse(
field,
path.getPath(field, connectionID),
makeScope(connectionID)
);
}
var {diffCalls, requestedEdges} = rangeInfo;
// check existing edges for missing fields
var hasSplitQueries = false;
requestedEdges.forEach(edge => {
// Flow loses type information in closures
if (rangeInfo && connectionID) {
var scope = {
connectionField: field,
dataID: connectionID,
edgeID: edge.edgeID,
rangeInfo,
};
var diffOutput = this.traverse(
field,
path.getPath(field, edge.edgeID),
scope
);
// If any edges were missing data (resulting in a split query),
// then the entire original connection field must be tracked.
if (diffOutput) {
hasSplitQueries = hasSplitQueries || !!diffOutput.trackedNode;
}
}
});
// Scope has null `edgeID` to skip looking at `edges` fields.
var scope = {
connectionField: field,
dataID: connectionID,
edgeID: null,
rangeInfo,
};
// diff non-`edges` fields such as `count`
var diffOutput = this.traverse(
field,
path.getPath(field, connectionID),
scope
);
var diffNode = diffOutput ? diffOutput.diffNode : null;
var trackedNode = diffOutput ? diffOutput.trackedNode : null;
if (diffCalls.length && diffNode instanceof RelayQuery.Field) {
diffNode = diffNode.cloneFieldWithCalls(
diffNode.getChildren(),
diffCalls
);
}
// if a sub-query was split, then we must track the entire field, which will
// be a superset of the `trackedNode` from traversing any metadata fields.
// Example:
// dataID: `4`
// node: `friends.first(3)`
// diffNode: null
// splitQueries: `node(friend1) {...}`, `node(friend2) {...}`
//
// In this case the two fetched `node` queries do not reflect the fact that
// `friends.first(3)` were fetched for item `4`, so `friends.first(3)` has
// to be tracked as-is.
if (hasSplitQueries) {
trackedNode = field;
}
return {
diffNode,
trackedNode
};
}
/**
* Diff an `edges` field for the edge rooted at `edgeID`, splitting a new
* root query to fetch any missing data (via a `node(id)` root if the
* field is refetchable or a `...{connection.find(id){}}` query if the
* field is not refetchable).
*/
diffConnectionEdge(
connectionField: RelayQuery.Field,
edgeField: RelayQuery.Field,
path: RelayQueryPath,
edgeID: DataID,
rangeInfo: RangeInfo
): ?DiffOutput {
var nodeID = this._store.getLinkedRecordID(edgeID, NODE);
if (!nodeID || GraphQLStoreDataHandler.isClientID(nodeID)) {
warning(
false,
'RelayDiffQueryBuilder: connection `node{*}` can only be refetched ' +
'if the node is refetchable by `id`. Cannot refetch data for field ' +
'`%s`.',
connectionField.getStorageKey()
);
return;
}
var hasSplitQueries = false;
var diffOutput = this.traverse(
edgeField,
path.getPath(edgeField, edgeID),
makeScope(edgeID)
);
var diffNode = diffOutput ? diffOutput.diffNode : null;
var trackedNode = diffOutput ? diffOutput.trackedNode : null;
if (diffNode) {
var {
edges: diffEdgesField,
node: diffNodeField
} = splitNodeAndEdgesFields(diffNode);
// split missing `node` fields into a `node(id)` root query
if (diffNodeField) {
hasSplitQueries = true;
this.splitQuery(buildRoot(
nodeID,
diffNodeField.getChildren(),
path.getName()
));
}
// split missing `edges` fields into a `connection.find(id)` query
// if `find` is supported, otherwise warn
if (diffEdgesField) {
if (connectionField.isFindable()) {
diffEdgesField = diffEdgesField
.clone(diffEdgesField.getChildren().concat(nodeWithID));
var connectionFind = connectionField.cloneFieldWithCalls(
[diffEdgesField],
rangeInfo.filterCalls.concat({name: 'find', value: nodeID})
);
if (connectionFind) {
hasSplitQueries = true;
// current path has `parent`, `connection`, `edges`; pop to parent
var connectionParent = path.getParent().getParent();
this.splitQuery(connectionParent.getQuery(connectionFind));
}
} else {
warning(
false,
'RelayDiffQueryBuilder: connection `edges{*}` fields can only be ' +
'refetched if the connection supports the `find` call. Cannot ' +
'refetch data for field `%s`.',
connectionField.getStorageKey()
);
}
}
}
// Connection edges will never return diff nodes; instead missing fields
// are fetched by new root queries. Tracked nodes are returned if either
// a child field was tracked or missing fields were split into a new query.
// The returned `trackedNode` is never tracked directly: instead it serves
// as an indicator to `diffConnection` that the entire connection field must
// be tracked.
return {
diffNode: null,
trackedNode: hasSplitQueries ? edgeField : trackedNode,
};
}
}
/**
* Helper to construct a plain scope for the given `dataID`.
*/
function makeScope(dataID: DataID): DiffScope {
return {
connectionField: null,
dataID,
edgeID: null,
rangeInfo: null,
};
}
/**
* Returns a clone of the input with `edges` and `node` sub-fields split into
* separate `edges` and `node` roots. Example:
*
* Input:
* edges {
* edge_field,
* node {
* a,
* b
* },
* ${
* Fragment {
* edge_field_2,
* node {
* c
* }
* }
* }
* }
*
* Output:
* node:
* edges {
* a, // flattened
* b, // flattend
* ${
* Fragment {
* c // flattened
* }
* }
* }
* edges:
* edges {
* edge_field,
* ${
* Fragment {
* edge_field_2
* }
* }
* }
*/
function splitNodeAndEdgesFields(
edgeOrFragment: RelayQuery.Node
): {
edges: ?RelayQuery.Node,
node: ?RelayQuery.Node
} {
var children = edgeOrFragment.getChildren();
var edgeChildren = [];
var hasNodeChild = false;
var nodeChildren = [];
var hasEdgeChild = false;
for (var ii = 0; ii < children.length; ii++) {
var child = children[ii];
if (child instanceof RelayQuery.Field) {
if (child.getSchemaName() === NODE) {
var subFields = child.getChildren();
nodeChildren = nodeChildren.concat(subFields);
// can skip if `node` only has an `id` field
hasNodeChild = (
hasNodeChild ||
subFields.length !== 1 ||
!(subFields[0] instanceof RelayQuery.Field) ||
/* $FlowFixMe(>=0.13.0) - subFields[0] needs to be in a local for Flow to
* narrow its type, otherwise Flow thinks its a RelayQueryNode without
* method `getSchemaName`
*/
subFields[0].getSchemaName() !== 'id'
);
} else {
edgeChildren.push(child);
hasEdgeChild = hasEdgeChild || !child.isRequisite();
}
} else if (child instanceof RelayQuery.Fragment) {
var {edges, node} = splitNodeAndEdgesFields(child);
if (edges) {
edgeChildren.push(edges);
hasEdgeChild = true;
}
if (node) {
nodeChildren.push(node);
hasNodeChild = true;
}
}
}
return {
edges: hasEdgeChild ? edgeOrFragment.clone(edgeChildren) : null,
node: hasNodeChild ? edgeOrFragment.clone(nodeChildren) : null,
};
}
function buildRoot(
rootID: DataID,
children: Array<RelayQuery.Node>,
name: string
): RelayQuery.Root {
// Child fields are always collapsed into fragments so a root `id` field
// must be added.
var fragments = [idField];
var childTypes = {};
children.forEach(child => {
if (child instanceof RelayQuery.Field) {
var parentType = child.getParentType();
childTypes[parentType] = childTypes[parentType] || [];
childTypes[parentType].push(child);
} else {
fragments.push(child);
}
});
Object.keys(childTypes).map(type => {
fragments.push(RelayQuery.Node.buildFragment(
'diffRelayQuery',
type,
childTypes[type]
));
});
return RelayQuery.Node.buildRoot(
NODE,
rootID,
fragments,
{rootArg: RelayNodeInterface.ID},
name
);
}
module.exports = RelayProfiler.instrument('diffRelayQuery', diffRelayQuery);
| xymostech/relay | src/traversal/diffRelayQuery.js | JavaScript | bsd-3-clause | 22,986 |
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule Geolocation
* @flow
*/
'use strict';
const NativeEventEmitter = require('NativeEventEmitter');
const RCTLocationObserver = require('NativeModules').LocationObserver;
const invariant = require('fbjs/lib/invariant');
const logError = require('logError');
/* $FlowFixMe(>=0.54.0 site=react_native_oss) This comment suppresses an error
* found when Flow v0.54 was deployed. To see the error delete this comment and
* run Flow. */
const warning = require('fbjs/lib/warning');
const LocationEventEmitter = new NativeEventEmitter(RCTLocationObserver);
const Platform = require('Platform');
const PermissionsAndroid = require('PermissionsAndroid');
var subscriptions = [];
var updatesEnabled = false;
type GeoConfiguration = {
skipPermissionRequests: bool;
}
type GeoOptions = {
timeout?: number,
maximumAge?: number,
enableHighAccuracy?: bool,
distanceFilter: number,
useSignificantChanges?: bool,
}
/**
* The Geolocation API extends the web spec:
* https://developer.mozilla.org/en-US/docs/Web/API/Geolocation
*
* See https://facebook.github.io/react-native/docs/geolocation.html
*/
var Geolocation = {
/*
* Sets configuration options that will be used in all location requests.
*
* See https://facebook.github.io/react-native/docs/geolocation.html#setrnconfiguration
*
*/
setRNConfiguration: function(
config: GeoConfiguration
) {
if (RCTLocationObserver.setConfiguration) {
RCTLocationObserver.setConfiguration(config);
}
},
/*
* Request suitable Location permission based on the key configured on pList.
*
* See https://facebook.github.io/react-native/docs/geolocation.html#requestauthorization
*/
requestAuthorization: function() {
RCTLocationObserver.requestAuthorization();
},
/*
* Invokes the success callback once with the latest location info.
*
* See https://facebook.github.io/react-native/docs/geolocation.html#getcurrentposition
*/
getCurrentPosition: async function(
geo_success: Function,
geo_error?: Function,
geo_options?: GeoOptions
) {
invariant(
typeof geo_success === 'function',
'Must provide a valid geo_success callback.'
);
let hasPermission = true;
// Supports Android's new permission model. For Android older devices,
// it's always on.
if (Platform.OS === 'android' && Platform.Version >= 23) {
hasPermission = await PermissionsAndroid.check(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
);
if (!hasPermission) {
const status = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
);
hasPermission = status === PermissionsAndroid.RESULTS.GRANTED;
}
}
if (hasPermission) {
RCTLocationObserver.getCurrentPosition(
geo_options || {},
geo_success,
geo_error || logError,
);
}
},
/*
* Invokes the success callback whenever the location changes.
*
* See https://facebook.github.io/react-native/docs/geolocation.html#watchposition
*/
watchPosition: function(success: Function, error?: Function, options?: GeoOptions): number {
if (!updatesEnabled) {
RCTLocationObserver.startObserving(options || {});
updatesEnabled = true;
}
var watchID = subscriptions.length;
subscriptions.push([
LocationEventEmitter.addListener(
'geolocationDidChange',
success
),
error ? LocationEventEmitter.addListener(
'geolocationError',
error
) : null,
]);
return watchID;
},
clearWatch: function(watchID: number) {
var sub = subscriptions[watchID];
if (!sub) {
// Silently exit when the watchID is invalid or already cleared
// This is consistent with timers
return;
}
sub[0].remove();
// array element refinements not yet enabled in Flow
var sub1 = sub[1]; sub1 && sub1.remove();
subscriptions[watchID] = undefined;
var noWatchers = true;
for (var ii = 0; ii < subscriptions.length; ii++) {
if (subscriptions[ii]) {
noWatchers = false; // still valid subscriptions
}
}
if (noWatchers) {
Geolocation.stopObserving();
}
},
stopObserving: function() {
if (updatesEnabled) {
RCTLocationObserver.stopObserving();
updatesEnabled = false;
for (var ii = 0; ii < subscriptions.length; ii++) {
var sub = subscriptions[ii];
if (sub) {
warning(false, 'Called stopObserving with existing subscriptions.');
sub[0].remove();
// array element refinements not yet enabled in Flow
var sub1 = sub[1]; sub1 && sub1.remove();
}
}
subscriptions = [];
}
}
};
module.exports = Geolocation;
| hoastoolshop/react-native | Libraries/Geolocation/Geolocation.js | JavaScript | bsd-3-clause | 5,003 |
/**
* Copyright (c) 2015-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.
*
* @flow
*/
'use strict';
exports.assetExts = [
'bmp', 'gif', 'jpg', 'jpeg', 'png', 'psd', 'svg', 'webp', // Image formats
'm4v', 'mov', 'mp4', 'mpeg', 'mpg', 'webm', // Video formats
'aac', 'aiff', 'caf', 'm4a', 'mp3', 'wav', // Audio formats
'html', 'pdf', // Document formats
];
exports.sourceExts = ['js', 'json'];
exports.moduleSystem = require.resolve('./Resolver/polyfills/require.js');
exports.platforms = ['ios', 'android', 'windows', 'web'];
exports.polyfills = [
require.resolve('./Resolver/polyfills/Object.es6.js'),
require.resolve('./Resolver/polyfills/console.js'),
require.resolve('./Resolver/polyfills/error-guard.js'),
require.resolve('./Resolver/polyfills/Number.es6.js'),
require.resolve('./Resolver/polyfills/String.prototype.es6.js'),
require.resolve('./Resolver/polyfills/Array.prototype.es6.js'),
require.resolve('./Resolver/polyfills/Array.es6.js'),
require.resolve('./Resolver/polyfills/Object.es7.js'),
require.resolve('./Resolver/polyfills/babelHelpers.js'),
];
exports.providesModuleNodeModules = [
'react-native',
'react-native-windows',
];
exports.runBeforeMainModule = [
// Ensures essential globals are available and are patched correctly.
'InitializeCore',
];
| peterp/react-native | packager/src/defaults.js | JavaScript | bsd-3-clause | 1,544 |
(function() {
module('Arrays');
test('first', function() {
equal(_.first([1, 2, 3]), 1, 'can pull out the first element of an array');
equal(_([1, 2, 3]).first(), 1, 'can perform OO-style "first()"');
deepEqual(_.first([1, 2, 3], 0), [], 'can pass an index to first');
deepEqual(_.first([1, 2, 3], 2), [1, 2], 'can pass an index to first');
deepEqual(_.first([1, 2, 3], 5), [1, 2, 3], 'can pass an index to first');
var result = (function(){ return _.first(arguments); }(4, 3, 2, 1));
equal(result, 4, 'works on an arguments object.');
result = _.map([[1, 2, 3], [1, 2, 3]], _.first);
deepEqual(result, [1, 1], 'works well with _.map');
result = (function() { return _.first([1, 2, 3], 2); }());
deepEqual(result, [1, 2]);
equal(_.first(null), undefined, 'handles nulls');
strictEqual(_.first([1, 2, 3], -1).length, 0);
});
test('head', function() {
strictEqual(_.first, _.head, 'alias for first');
});
test('take', function() {
strictEqual(_.first, _.take, 'alias for first');
});
test('rest', function() {
var numbers = [1, 2, 3, 4];
deepEqual(_.rest(numbers), [2, 3, 4], 'working rest()');
deepEqual(_.rest(numbers, 0), [1, 2, 3, 4], 'working rest(0)');
deepEqual(_.rest(numbers, 2), [3, 4], 'rest can take an index');
var result = (function(){ return _(arguments).rest(); }(1, 2, 3, 4));
deepEqual(result, [2, 3, 4], 'works on arguments object');
result = _.map([[1, 2, 3], [1, 2, 3]], _.rest);
deepEqual(_.flatten(result), [2, 3, 2, 3], 'works well with _.map');
result = (function(){ return _(arguments).rest(); }(1, 2, 3, 4));
deepEqual(result, [2, 3, 4], 'works on arguments object');
});
test('tail', function() {
strictEqual(_.rest, _.tail, 'alias for rest');
});
test('drop', function() {
strictEqual(_.rest, _.drop, 'alias for rest');
});
test('initial', function() {
deepEqual(_.initial([1, 2, 3, 4, 5]), [1, 2, 3, 4], 'working initial()');
deepEqual(_.initial([1, 2, 3, 4], 2), [1, 2], 'initial can take an index');
deepEqual(_.initial([1, 2, 3, 4], 6), [], 'initial can take a large index');
var result = (function(){ return _(arguments).initial(); }(1, 2, 3, 4));
deepEqual(result, [1, 2, 3], 'initial works on arguments object');
result = _.map([[1, 2, 3], [1, 2, 3]], _.initial);
deepEqual(_.flatten(result), [1, 2, 1, 2], 'initial works with _.map');
});
test('last', function() {
equal(_.last([1, 2, 3]), 3, 'can pull out the last element of an array');
deepEqual(_.last([1, 2, 3], 0), [], 'can pass an index to last');
deepEqual(_.last([1, 2, 3], 2), [2, 3], 'can pass an index to last');
deepEqual(_.last([1, 2, 3], 5), [1, 2, 3], 'can pass an index to last');
var result = (function(){ return _(arguments).last(); }(1, 2, 3, 4));
equal(result, 4, 'works on an arguments object');
result = _.map([[1, 2, 3], [1, 2, 3]], _.last);
deepEqual(result, [3, 3], 'works well with _.map');
equal(_.last(null), undefined, 'handles nulls');
strictEqual(_.last([1, 2, 3], -1).length, 0);
});
test('compact', function() {
equal(_.compact([0, 1, false, 2, false, 3]).length, 3, 'can trim out all falsy values');
var result = (function(){ return _.compact(arguments).length; }(0, 1, false, 2, false, 3));
equal(result, 3, 'works on an arguments object');
});
test('flatten', function() {
deepEqual(_.flatten(null), [], 'Flattens supports null');
deepEqual(_.flatten(void 0), [], 'Flattens supports undefined');
deepEqual(_.flatten([[], [[]], []]), [], 'Flattens empty arrays');
deepEqual(_.flatten([[], [[]], []], true), [[]], 'Flattens empty arrays');
var list = [1, [2], [3, [[[4]]]]];
deepEqual(_.flatten(list), [1, 2, 3, 4], 'can flatten nested arrays');
deepEqual(_.flatten(list, true), [1, 2, 3, [[[4]]]], 'can shallowly flatten nested arrays');
var result = (function(){ return _.flatten(arguments); }(1, [2], [3, [[[4]]]]));
deepEqual(result, [1, 2, 3, 4], 'works on an arguments object');
list = [[1], [2], [3], [[4]]];
deepEqual(_.flatten(list, true), [1, 2, 3, [4]], 'can shallowly flatten arrays containing only other arrays');
equal(_.flatten([_.range(10), _.range(10), 5, 1, 3], true).length, 23);
equal(_.flatten([_.range(10), _.range(10), 5, 1, 3]).length, 23);
equal(_.flatten([new Array(1000000), _.range(56000), 5, 1, 3]).length, 1056003, 'Flatten can handle massive collections');
equal(_.flatten([new Array(1000000), _.range(56000), 5, 1, 3], true).length, 1056003, 'Flatten can handle massive collections');
});
test('without', function() {
var list = [1, 2, 1, 0, 3, 1, 4];
deepEqual(_.without(list, 0, 1), [2, 3, 4], 'can remove all instances of an object');
var result = (function(){ return _.without(arguments, 0, 1); }(1, 2, 1, 0, 3, 1, 4));
deepEqual(result, [2, 3, 4], 'works on an arguments object');
list = [{one : 1}, {two : 2}];
equal(_.without(list, {one : 1}).length, 2, 'uses real object identity for comparisons.');
equal(_.without(list, list[0]).length, 1, 'ditto.');
});
test('uniq', function() {
var list = [1, 2, 1, 3, 1, 4];
deepEqual(_.uniq(list), [1, 2, 3, 4], 'can find the unique values of an unsorted array');
list = [1, 1, 1, 2, 2, 3];
deepEqual(_.uniq(list, true), [1, 2, 3], 'can find the unique values of a sorted array faster');
list = [{name: 'moe'}, {name: 'curly'}, {name: 'larry'}, {name: 'curly'}];
var iterator = function(value) { return value.name; };
deepEqual(_.map(_.uniq(list, false, iterator), iterator), ['moe', 'curly', 'larry'], 'can find the unique values of an array using a custom iterator');
deepEqual(_.map(_.uniq(list, iterator), iterator), ['moe', 'curly', 'larry'], 'can find the unique values of an array using a custom iterator without specifying whether array is sorted');
iterator = function(value) { return value + 1; };
list = [1, 2, 2, 3, 4, 4];
deepEqual(_.uniq(list, true, iterator), [1, 2, 3, 4], 'iterator works with sorted array');
var kittens = [
{kitten: 'Celery', cuteness: 8},
{kitten: 'Juniper', cuteness: 10},
{kitten: 'Spottis', cuteness: 10}
];
var expected = [
{kitten: 'Celery', cuteness: 8},
{kitten: 'Juniper', cuteness: 10}
];
deepEqual(_.uniq(kittens, true, 'cuteness'), expected, 'string iterator works with sorted array');
var result = (function(){ return _.uniq(arguments); }(1, 2, 1, 3, 1, 4));
deepEqual(result, [1, 2, 3, 4], 'works on an arguments object');
var a = {}, b = {}, c = {};
deepEqual(_.uniq([a, b, a, b, c]), [a, b, c], 'works on values that can be tested for equivalency but not ordered');
deepEqual(_.uniq(null), []);
var context = {};
list = [3];
_.uniq(list, function(value, index, array) {
strictEqual(this, context);
strictEqual(value, 3);
strictEqual(index, 0);
strictEqual(array, list);
}, context);
deepEqual(_.uniq([{a: 1, b: 1}, {a: 1, b: 2}, {a: 1, b: 3}, {a: 2, b: 1}], 'a'), [{a: 1, b: 1}, {a: 2, b: 1}], 'can use pluck like iterator');
deepEqual(_.uniq([{0: 1, b: 1}, {0: 1, b: 2}, {0: 1, b: 3}, {0: 2, b: 1}], 0), [{0: 1, b: 1}, {0: 2, b: 1}], 'can use falsey pluck like iterator');
});
test('unique', function() {
strictEqual(_.uniq, _.unique, 'alias for uniq');
});
test('intersection', function() {
var stooges = ['moe', 'curly', 'larry'], leaders = ['moe', 'groucho'];
deepEqual(_.intersection(stooges, leaders), ['moe'], 'can take the set intersection of two arrays');
deepEqual(_(stooges).intersection(leaders), ['moe'], 'can perform an OO-style intersection');
var result = (function(){ return _.intersection(arguments, leaders); }('moe', 'curly', 'larry'));
deepEqual(result, ['moe'], 'works on an arguments object');
var theSixStooges = ['moe', 'moe', 'curly', 'curly', 'larry', 'larry'];
deepEqual(_.intersection(theSixStooges, leaders), ['moe'], 'returns a duplicate-free array');
result = _.intersection([2, 4, 3, 1], [1, 2, 3]);
deepEqual(result, [2, 3, 1], 'preserves order of first array');
result = _.intersection(null, [1, 2, 3]);
equal(Object.prototype.toString.call(result), '[object Array]', 'returns an empty array when passed null as first argument');
equal(result.length, 0, 'returns an empty array when passed null as first argument');
result = _.intersection([1, 2, 3], null);
equal(Object.prototype.toString.call(result), '[object Array]', 'returns an empty array when passed null as argument beyond the first');
equal(result.length, 0, 'returns an empty array when passed null as argument beyond the first');
});
test('union', function() {
var result = _.union([1, 2, 3], [2, 30, 1], [1, 40]);
deepEqual(result, [1, 2, 3, 30, 40], 'takes the union of a list of arrays');
result = _.union([1, 2, 3], [2, 30, 1], [1, 40, [1]]);
deepEqual(result, [1, 2, 3, 30, 40, [1]], 'takes the union of a list of nested arrays');
var args = null;
(function(){ args = arguments; }(1, 2, 3));
result = _.union(args, [2, 30, 1], [1, 40]);
deepEqual(result, [1, 2, 3, 30, 40], 'takes the union of a list of arrays');
result = _.union([1, 2, 3], 4);
deepEqual(result, [1, 2, 3], 'restrict the union to arrays only');
});
test('difference', function() {
var result = _.difference([1, 2, 3], [2, 30, 40]);
deepEqual(result, [1, 3], 'takes the difference of two arrays');
result = _.difference([1, 2, 3, 4], [2, 30, 40], [1, 11, 111]);
deepEqual(result, [3, 4], 'takes the difference of three arrays');
result = _.difference([1, 2, 3], 1);
deepEqual(result, [1, 2, 3], 'restrict the difference to arrays only');
});
test('zip', function() {
var names = ['moe', 'larry', 'curly'], ages = [30, 40, 50], leaders = [true];
deepEqual(_.zip(names, ages, leaders), [
['moe', 30, true],
['larry', 40, undefined],
['curly', 50, undefined]
], 'zipped together arrays of different lengths');
var stooges = _.zip(['moe', 30, 'stooge 1'], ['larry', 40, 'stooge 2'], ['curly', 50, 'stooge 3']);
deepEqual(stooges, [['moe', 'larry', 'curly'], [30, 40, 50], ['stooge 1', 'stooge 2', 'stooge 3']], 'zipped pairs');
// In the case of difference lengths of the tuples undefineds
// should be used as placeholder
stooges = _.zip(['moe', 30], ['larry', 40], ['curly', 50, 'extra data']);
deepEqual(stooges, [['moe', 'larry', 'curly'], [30, 40, 50], [undefined, undefined, 'extra data']], 'zipped pairs with empties');
var empty = _.zip([]);
deepEqual(empty, [], 'unzipped empty');
deepEqual(_.zip(null), [], 'handles null');
deepEqual(_.zip(), [], '_.zip() returns []');
});
test('unzip', function() {
deepEqual(_.unzip([['a', 'b'], [1, 2]]), [['a', 1], ['b', 2]]);
// complements zip
var zipped = _.zip(['fred', 'barney'], [30, 40], [true, false]);
deepEqual(_.unzip(zipped), [['fred', 'barney'], [30, 40], [true, false]]);
zipped = _.zip(['moe', 30], ['larry', 40], ['curly', 50, 'extra data']);
deepEqual(_.unzip(zipped), [['moe', 30, void 0], ['larry', 40, void 0], ['curly', 50, 'extra data']], 'Uses length of largest array');
});
test('object', function() {
var result = _.object(['moe', 'larry', 'curly'], [30, 40, 50]);
var shouldBe = {moe: 30, larry: 40, curly: 50};
deepEqual(result, shouldBe, 'two arrays zipped together into an object');
result = _.object([['one', 1], ['two', 2], ['three', 3]]);
shouldBe = {one: 1, two: 2, three: 3};
deepEqual(result, shouldBe, 'an array of pairs zipped together into an object');
var stooges = {moe: 30, larry: 40, curly: 50};
deepEqual(_.object(_.pairs(stooges)), stooges, 'an object converted to pairs and back to an object');
deepEqual(_.object(null), {}, 'handles nulls');
});
test('indexOf', function() {
var numbers = [1, 2, 3];
equal(_.indexOf(numbers, 2), 1, 'can compute indexOf');
var result = (function(){ return _.indexOf(arguments, 2); }(1, 2, 3));
equal(result, 1, 'works on an arguments object');
_.each([null, void 0, [], false], function(val) {
var msg = 'Handles: ' + (_.isArray(val) ? '[]' : val);
equal(_.indexOf(val, 2), -1, msg);
equal(_.indexOf(val, 2, -1), -1, msg);
equal(_.indexOf(val, 2, -20), -1, msg);
equal(_.indexOf(val, 2, 15), -1, msg);
});
var num = 35;
numbers = [10, 20, 30, 40, 50];
var index = _.indexOf(numbers, num, true);
equal(index, -1, '35 is not in the list');
numbers = [10, 20, 30, 40, 50]; num = 40;
index = _.indexOf(numbers, num, true);
equal(index, 3, '40 is in the list');
numbers = [1, 40, 40, 40, 40, 40, 40, 40, 50, 60, 70]; num = 40;
equal(_.indexOf(numbers, num, true), 1, '40 is in the list');
equal(_.indexOf(numbers, 6, true), -1, '6 isnt in the list');
equal(_.indexOf([1, 2, 5, 4, 6, 7], 5, true), -1, 'sorted indexOf doesn\'t uses binary search');
ok(_.every(['1', [], {}, null], function() {
return _.indexOf(numbers, num, {}) === 1;
}), 'non-nums as fromIndex make indexOf assume sorted');
numbers = [1, 2, 3, 1, 2, 3, 1, 2, 3];
index = _.indexOf(numbers, 2, 5);
equal(index, 7, 'supports the fromIndex argument');
index = _.indexOf([,,,], undefined);
equal(index, 0, 'treats sparse arrays as if they were dense');
var array = [1, 2, 3, 1, 2, 3];
strictEqual(_.indexOf(array, 1, -3), 3, 'neg `fromIndex` starts at the right index');
strictEqual(_.indexOf(array, 1, -2), -1, 'neg `fromIndex` starts at the right index');
strictEqual(_.indexOf(array, 2, -3), 4);
_.each([-6, -8, -Infinity], function(fromIndex) {
strictEqual(_.indexOf(array, 1, fromIndex), 0);
});
strictEqual(_.indexOf([1, 2, 3], 1, true), 0);
});
test('lastIndexOf', function() {
var numbers = [1, 0, 1];
var falsey = [void 0, '', 0, false, NaN, null, undefined];
equal(_.lastIndexOf(numbers, 1), 2);
numbers = [1, 0, 1, 0, 0, 1, 0, 0, 0];
numbers.lastIndexOf = null;
equal(_.lastIndexOf(numbers, 1), 5, 'can compute lastIndexOf, even without the native function');
equal(_.lastIndexOf(numbers, 0), 8, 'lastIndexOf the other element');
var result = (function(){ return _.lastIndexOf(arguments, 1); }(1, 0, 1, 0, 0, 1, 0, 0, 0));
equal(result, 5, 'works on an arguments object');
_.each([null, void 0, [], false], function(val) {
var msg = 'Handles: ' + (_.isArray(val) ? '[]' : val);
equal(_.lastIndexOf(val, 2), -1, msg);
equal(_.lastIndexOf(val, 2, -1), -1, msg);
equal(_.lastIndexOf(val, 2, -20), -1, msg);
equal(_.lastIndexOf(val, 2, 15), -1, msg);
});
numbers = [1, 2, 3, 1, 2, 3, 1, 2, 3];
var index = _.lastIndexOf(numbers, 2, 2);
equal(index, 1, 'supports the fromIndex argument');
var array = [1, 2, 3, 1, 2, 3];
strictEqual(_.lastIndexOf(array, 1, 0), 0, 'starts at the correct from idx');
strictEqual(_.lastIndexOf(array, 3), 5, 'should return the index of the last matched value');
strictEqual(_.lastIndexOf(array, 4), -1, 'should return `-1` for an unmatched value');
strictEqual(_.lastIndexOf(array, 1, 2), 0, 'should work with a positive `fromIndex`');
_.each([6, 8, Math.pow(2, 32), Infinity], function(fromIndex) {
strictEqual(_.lastIndexOf(array, undefined, fromIndex), -1);
strictEqual(_.lastIndexOf(array, 1, fromIndex), 3);
strictEqual(_.lastIndexOf(array, '', fromIndex), -1);
});
var expected = _.map(falsey, function(value) {
return typeof value == 'number' ? -1 : 5;
});
var actual = _.map(falsey, function(fromIndex) {
return _.lastIndexOf(array, 3, fromIndex);
});
deepEqual(actual, expected, 'should treat falsey `fromIndex` values, except `0` and `NaN`, as `array.length`');
strictEqual(_.lastIndexOf(array, 3, '1'), 5, 'should treat non-number `fromIndex` values as `array.length`');
strictEqual(_.lastIndexOf(array, 3, true), 5, 'should treat non-number `fromIndex` values as `array.length`');
strictEqual(_.lastIndexOf(array, 2, -3), 1, 'should work with a negative `fromIndex`');
strictEqual(_.lastIndexOf(array, 1, -3), 3, 'neg `fromIndex` starts at the right index');
deepEqual(_.map([-6, -8, -Infinity], function(fromIndex) {
return _.lastIndexOf(array, 1, fromIndex);
}), [0, -1, -1]);
});
test('range', function() {
deepEqual(_.range(0), [], 'range with 0 as a first argument generates an empty array');
deepEqual(_.range(4), [0, 1, 2, 3], 'range with a single positive argument generates an array of elements 0,1,2,...,n-1');
deepEqual(_.range(5, 8), [5, 6, 7], 'range with two arguments a & b, a<b generates an array of elements a,a+1,a+2,...,b-2,b-1');
deepEqual(_.range(8, 5), [], 'range with two arguments a & b, b<a generates an empty array');
deepEqual(_.range(3, 10, 3), [3, 6, 9], 'range with three arguments a & b & c, c < b-a, a < b generates an array of elements a,a+c,a+2c,...,b - (multiplier of a) < c');
deepEqual(_.range(3, 10, 15), [3], 'range with three arguments a & b & c, c > b-a, a < b generates an array with a single element, equal to a');
deepEqual(_.range(12, 7, -2), [12, 10, 8], 'range with three arguments a & b & c, a > b, c < 0 generates an array of elements a,a-c,a-2c and ends with the number not less than b');
deepEqual(_.range(0, -10, -1), [0, -1, -2, -3, -4, -5, -6, -7, -8, -9], 'final example in the Python docs');
});
}());
| dimitriwalters/underscore | test/arrays.js | JavaScript | mit | 17,722 |
describe('fg-edit-palette', function () {
var $controller, $scope, fgConfigMock, $compile, $templateCache, FgField;
beforeEach(function () {
module('fg');
fgConfigMock = {
fields: {
templates: [],
categories: []
}
};
module(function ($provide) {
$provide.constant('fgConfig', fgConfigMock);
});
inject(function (_$controller_, _$rootScope_, _$compile_, _$templateCache_, _FgField_) {
$controller = _$controller_;
$scope = _$rootScope_.$new();
$compile = _$compile_;
$templateCache = _$templateCache_;
FgField = _FgField_;
});
});
describe('controller', function () {
describe('template copy from configuration', function () {
it('should create a copy of the templates found in the configuration', function () {
// Arrange
var templates = fgConfigMock.fields.templates = [
new FgField('myType'), new FgField('myOtherType')
];
// Act
$controller('fgEditPaletteController', {
$scope: $scope,
fgConfig: fgConfigMock
});
// Assert
expect($scope.templates).toBeDefined();
expect($scope.templates).not.toBe(templates);
expect($scope.templates.length).toEqual(templates.length);
_.forEach($scope.templates, function (copyTemplate) {
var origTemplate = _.find(templates, {
type: copyTemplate.type
});
expect(origTemplate).toBeDefined();
expect(origTemplate).not.toBe(copyTemplate);
_.forEach(origTemplate, function (value, key) {
if (key !== 'id') {
expect(value).toEqual(copyTemplate[key]);
}
});
});
});
it('copy should not contain templates marked editor.visible == false', function () {
// Arrange
var templates = fgConfigMock.fields.templates = [
new FgField('myVisibleType'),
new FgField('myInvisibleType', {
editor: {
visible: false
}
})
];
// Act
$controller('fgEditPaletteController', {
$scope: $scope,
fgConfig: fgConfigMock
});
// Assert
expect($scope.templates).toBeDefined();
expect($scope.templates.length).toEqual(1);
expect($scope.templates[0].type).toBe('myVisibleType');
});
});
describe('templateFilter', function () {
it('should include all templates when no category has been selected', function () {
// Arrange
$controller('fgEditPaletteController', {
$scope: $scope,
fgConfig: fgConfigMock
});
$scope.selectedCategory = null;
// Act
var result = $scope.templateFilter({});
// Assert
expect(result).toBe(true);
});
it('should not include templates on category mismatch', function () {
// Arrange
var templates = fgConfigMock.fields.templates = [
new FgField('myType'), new FgField('myOtherType')
];
var categories = fgConfigMock.fields.categories = {
'myCategory': {
'myType': true
},
'myOtherCategory': {
'myOtherType': true
}
};
$controller('fgEditPaletteController', {
$scope: $scope,
fgConfig: fgConfigMock
});
$scope.selectedCategory = categories['myOtherCategory'];
// Act
var result = $scope.templateFilter(templates[0]);
// Assert
expect(result).toBeFalsy();
});
it('should include templates on category match', function () {
// Arrange
var templates = fgConfigMock.fields.templates = [
new FgField('myType'), new FgField('myOtherType')
];
var categories = fgConfigMock.fields.categories = {
'myCategory': {
'myType': true
},
'myOtherCategory': {
'myOtherType': true
}
};
$controller('fgEditPaletteController', {
$scope: $scope,
fgConfig: fgConfigMock
});
$scope.selectedCategory = categories['myCategory'];
// Act
var result = $scope.templateFilter(templates[0]);
// Assert
expect(result).toBe(true);
});
})
});
}); | yujj/angular-form-gen | src/angular-form-gen/edit/palette/palette-controller.test.js | JavaScript | mit | 4,452 |
(async function() { aw\u0061it x })
| jridgewell/babel | packages/babel-parser/test/fixtures/es2017/async-functions/invalid-escape-await/input.js | JavaScript | mit | 36 |
/*!
* Module dependencies.
*/
var util = require('util'),
utils = require('keystone-utils'),
super_ = require('../field');
/**
* TextArray FieldType Constructor
* @extends Field
* @api public
*/
function textarray(list, path, options) {
this._nativeType = [String];
this._underscoreMethods = ['crop'];
textarray.super_.call(this, list, path, options);
}
/*!
* Inherit from Field
*/
util.inherits(textarray, super_);
/**
* Crops the string to the specifed length.
*
* @api public
*/
textarray.prototype.crop = function(item, length, append, preserveWords) {
return utils.cropString(item.get(this.path), length, append, preserveWords);
};
/**
* Updates the value for this field in the item from a data object
*
* @api public
*/
textarray.prototype.updateItem = function(item, data) {
if ( data[this.path] === undefined ) {
item.set(this.path, []);
} else {
item.set(this.path, data[this.path]);
}
};
/*!
* Export class
*/
exports = module.exports = textarray;
| gyiang/advdb-exp | node_modules/keystone/lib/fieldTypes/textarray.js | JavaScript | mit | 1,002 |
module.exports = require("github:angular/bower-material@master/index"); | jagdeepak123/meanapp | app/jspm_packages/github/angular/bower-material@master.js | JavaScript | mit | 71 |
'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; }; }();
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _createHelper = require('./createHelper');
var _createHelper2 = _interopRequireDefault(_createHelper);
var _createElement = require('./createElement');
var _createElement2 = _interopRequireDefault(_createElement);
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 _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var branch = function branch(test, left, right) {
return function (BaseComponent) {
return function (_React$Component) {
_inherits(_class2, _React$Component);
function _class2(props, context) {
_classCallCheck(this, _class2);
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(_class2).call(this, props, context));
_this.LeftComponent = null;
_this.RightComponent = null;
_this.computeChildComponent(_this.props);
return _this;
}
_createClass(_class2, [{
key: 'computeChildComponent',
value: function computeChildComponent(props) {
if (test(props)) {
this.LeftComponent = this.LeftComponent || left(BaseComponent);
this.Component = this.LeftComponent;
} else {
this.RightComponent = this.RightComponent || right(BaseComponent);
this.Component = this.RightComponent;
}
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
this.computeChildComponent(nextProps);
}
}, {
key: 'render',
value: function render() {
var Component = this.Component;
return (0, _createElement2.default)(Component, this.props);
}
}]);
return _class2;
}(_react2.default.Component);
};
};
exports.default = (0, _createHelper2.default)(branch, 'branch'); | xzzw9987/Memos | project/LearnReact/node_modules/recompose/branch.js | JavaScript | mit | 3,417 |
'use strict';
require('../common');
console.trace('foo');
| enclose-io/compiler | lts/test/message/console.js | JavaScript | mit | 60 |
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const WebpackError = require("../WebpackError");
const {
evaluateToString,
toConstantDependency
} = require("../javascript/JavascriptParserHelpers");
const makeSerializable = require("../util/makeSerializable");
const RequireIncludeDependency = require("./RequireIncludeDependency");
module.exports = class RequireIncludeDependencyParserPlugin {
constructor(warn) {
this.warn = warn;
}
apply(parser) {
const { warn } = this;
parser.hooks.call
.for("require.include")
.tap("RequireIncludeDependencyParserPlugin", expr => {
if (expr.arguments.length !== 1) return;
const param = parser.evaluateExpression(expr.arguments[0]);
if (!param.isString()) return;
if (warn) {
parser.state.module.addWarning(
new RequireIncludeDeprecationWarning(expr.loc)
);
}
const dep = new RequireIncludeDependency(param.string, expr.range);
dep.loc = expr.loc;
parser.state.current.addDependency(dep);
return true;
});
parser.hooks.evaluateTypeof
.for("require.include")
.tap("RequireIncludePlugin", expr => {
if (warn) {
parser.state.module.addWarning(
new RequireIncludeDeprecationWarning(expr.loc)
);
}
return evaluateToString("function")(expr);
});
parser.hooks.typeof
.for("require.include")
.tap("RequireIncludePlugin", expr => {
if (warn) {
parser.state.module.addWarning(
new RequireIncludeDeprecationWarning(expr.loc)
);
}
return toConstantDependency(parser, JSON.stringify("function"))(expr);
});
}
};
class RequireIncludeDeprecationWarning extends WebpackError {
constructor(loc) {
super("require.include() is deprecated and will be removed soon.");
this.name = "RequireIncludeDeprecationWarning";
this.loc = loc;
}
}
makeSerializable(
RequireIncludeDeprecationWarning,
"webpack/lib/dependencies/RequireIncludeDependencyParserPlugin",
"RequireIncludeDeprecationWarning"
);
| webpack/webpack | lib/dependencies/RequireIncludeDependencyParserPlugin.js | JavaScript | mit | 2,046 |
exports.BattleMovedex = {
acupressure: {
inherit: true,
desc: "Raises a random stat by 2 stages as long as the stat is not already at stage 6. The user can choose to use this move on itself or an ally. Fails if no stat stage can be raised or if the user or ally has a Substitute. This move ignores Protect and Detect.",
flags: {snatch: 1},
onHit: function (target) {
if (target.volatiles['substitute']) {
return false;
}
var stats = [];
for (var i in target.boosts) {
if (target.boosts[i] < 6) {
stats.push(i);
}
}
if (stats.length) {
var i = stats[this.random(stats.length)];
var boost = {};
boost[i] = 2;
this.boost(boost);
} else {
return false;
}
}
},
assist: {
inherit: true,
desc: "The user performs a random move from any of the Pokemon on its team. Assist cannot generate itself, Chatter, Copycat, Counter, Covet, Destiny Bond, Detect, Endure, Feint, Focus Punch, Follow Me, Helping Hand, Me First, Metronome, Mimic, Mirror Coat, Mirror Move, Protect, Sketch, Sleep Talk, Snatch, Struggle, Switcheroo, Thief or Trick.",
onHit: function (target) {
var moves = [];
for (var j = 0; j < target.side.pokemon.length; j++) {
var pokemon = target.side.pokemon[j];
if (pokemon === target) continue;
for (var i = 0; i < pokemon.moves.length; i++) {
var move = pokemon.moves[i];
var noAssist = {
assist:1, chatter:1, copycat:1, counter:1, covet:1, destinybond:1, detect:1, endure:1, feint:1, focuspunch:1, followme:1, helpinghand:1, mefirst:1, metronome:1, mimic:1, mirrorcoat:1, mirrormove:1, protect:1, sketch:1, sleeptalk:1, snatch:1, struggle:1, switcheroo:1, thief:1, trick:1
};
if (move && !noAssist[move]) {
moves.push(move);
}
}
}
var move = '';
if (moves.length) move = moves[this.random(moves.length)];
if (!move) {
return false;
}
this.useMove(move, target);
}
},
aquaring: {
inherit: true,
flags: {}
},
beatup: {
inherit: true,
basePower: 10,
basePowerCallback: function (pokemon, target) {
pokemon.addVolatile('beatup');
if (!pokemon.side.pokemon[pokemon.volatiles.beatup.index]) return null;
return 10;
},
desc: "Does one hit for the user and each other unfainted non-egg active and non-active Pokemon on the user's side without a status problem.",
effect: {
duration: 1,
onStart: function (pokemon) {
this.effectData.index = 0;
while (!pokemon.side.pokemon[this.effectData.index] || pokemon.side.pokemon[this.effectData.index].fainted || pokemon.side.pokemon[this.effectData.index].status) {
this.effectData.index++;
}
},
onRestart: function (pokemon) {
do {
this.effectData.index++;
if (this.effectData.index >= 6) break;
} while (!pokemon.side.pokemon[this.effectData.index] || pokemon.side.pokemon[this.effectData.index].fainted || pokemon.side.pokemon[this.effectData.index].status);
},
onModifyAtkPriority: 5,
onModifyAtk: function (atk, pokemon) {
this.add('-activate', pokemon, 'move: Beat Up', '[of] ' + pokemon.side.pokemon[this.effectData.index].name);
return pokemon.side.pokemon[this.effectData.index].template.baseStats.atk;
},
onFoeModifyDefPriority: 5,
onFoeModifyDef: function (def, pokemon) {
return pokemon.template.baseStats.def;
}
}
},
bide: {
inherit: true,
effect: {
duration: 3,
onLockMove: 'bide',
onStart: function (pokemon) {
this.effectData.totalDamage = 0;
this.add('-start', pokemon, 'Bide');
},
onDamagePriority: -101,
onDamage: function (damage, target, source, move) {
if (!move || move.effectType !== 'Move') return;
if (!source || source.side === target.side) return;
this.effectData.totalDamage += damage;
this.effectData.sourcePosition = source.position;
this.effectData.sourceSide = source.side;
},
onAfterSetStatus: function (status, pokemon) {
if (status.id === 'slp') {
pokemon.removeVolatile('bide');
}
},
onBeforeMove: function (pokemon) {
if (this.effectData.duration === 1) {
if (!this.effectData.totalDamage) {
this.add('-end', pokemon, 'Bide');
this.add('-fail', pokemon);
return false;
}
this.add('-end', pokemon, 'Bide');
var target = this.effectData.sourceSide.active[this.effectData.sourcePosition];
this.moveHit(target, pokemon, 'bide', {damage: this.effectData.totalDamage * 2});
return false;
}
this.add('-activate', pokemon, 'Bide');
return false;
}
}
},
bind: {
inherit: true,
accuracy: 75
},
bonerush: {
inherit: true,
accuracy: 80
},
brickbreak: {
inherit: true,
desc: "Reflect and Light Screen are removed from the target's field even if the attack misses or the target is a Ghost-type.",
onTryHit: function (pokemon) {
pokemon.side.removeSideCondition('reflect');
pokemon.side.removeSideCondition('lightscreen');
}
},
bulletseed: {
inherit: true,
basePower: 10
},
chatter: {
inherit: true,
desc: "Deals damage to one adjacent target. This move has an X% chance to confuse the target, where X is 0 unless the user is a Chatot that hasn't Transformed. If the user is a Chatot, X is 1, 11, or 31 depending on the volume of Chatot's recorded cry, if any; 1 for no recording or low volume, 11 for medium volume, and 31 for high volume. Pokemon with the Ability Soundproof are immune. (Field: Can be used to record a sound to replace Chatot's cry. The cry is reset if Chatot is deposited in a PC.)",
shortDesc: "31% chance to confuse the target.",
secondary: {
chance: 31,
volatileStatus: 'confusion'
}
},
clamp: {
inherit: true,
accuracy: 75,
pp: 10
},
conversion: {
inherit: true,
flags: {}
},
copycat: {
inherit: true,
onHit: function (pokemon) {
var noCopycat = {assist:1, chatter:1, copycat:1, counter:1, covet:1, destinybond:1, detect:1, endure:1, feint:1, focuspunch:1, followme:1, helpinghand:1, mefirst:1, metronome:1, mimic:1, mirrorcoat:1, mirrormove:1, protect:1, sketch:1, sleeptalk:1, snatch:1, struggle:1, switcheroo:1, thief:1, trick:1};
if (!this.lastMove || noCopycat[this.lastMove]) {
return false;
}
this.useMove(this.lastMove, pokemon);
}
},
cottonspore: {
inherit: true,
accuracy: 85
},
covet: {
inherit: true,
basePower: 40
},
crabhammer: {
inherit: true,
accuracy: 85
},
crushgrip: {
inherit: true,
basePowerCallback: function (pokemon) {
return Math.floor(pokemon.hp * 120 / pokemon.maxhp) + 1;
}
},
curse: {
inherit: true,
desc: "If the user is not a Ghost-type, lowers the user's Speed by 1 stage and raises the user's Attack and Defense by 1 stage. If the user is a Ghost-type, the user loses 1/2 of its maximum HP, rounded down and even if it would cause fainting, in exchange for one adjacent target losing 1/4 of its maximum HP, rounded down, at the end of each turn while it is active. If the target uses Baton Pass, the replacement will continue to be affected. Fails if there is no target or if the target is already affected or has a Substitute.",
onModifyMove: function (move, source, target) {
if (!source.hasType('Ghost')) {
delete move.volatileStatus;
delete move.onHit;
move.self = {boosts: {atk:1, def:1, spe:-1}};
move.target = move.nonGhostTarget;
} else if (target.volatiles['substitute']) {
delete move.volatileStatus;
delete move.onHit;
}
},
type: "???"
},
defog: {
inherit: true,
flags: {protect: 1, mirror: 1, authentic: 1}
},
detect: {
inherit: true,
priority: 3,
effect: {
duration: 1,
onStart: function (target) {
this.add('-singleturn', target, 'Protect');
},
onTryHitPriority: 3,
onTryHit: function (target, source, move) {
if (!move.flags['protect']) return;
if (move.breaksProtect) {
target.removeVolatile('Protect');
return;
}
this.add('-activate', target, 'Protect');
var lockedmove = source.getVolatile('lockedmove');
if (lockedmove) {
// Outrage counter is NOT reset
if (source.volatiles['lockedmove'].trueDuration >= 2) {
source.volatiles['lockedmove'].duration = 2;
}
}
return null;
}
}
},
disable: {
inherit: true,
accuracy: 80,
desc: "The target cannot choose its last move for 4-7 turns. Disable only works on one move at a time and fails if the target has not yet used a move or if its move has run out of PP. The target does nothing if it is about to use a move that becomes disabled.",
flags: {protect: 1, mirror: 1, authentic: 1},
volatileStatus: 'disable',
effect: {
durationCallback: function () {
return this.random(4, 8);
},
noCopy: true,
onStart: function (pokemon) {
if (!this.willMove(pokemon)) {
this.effectData.duration++;
}
if (!pokemon.lastMove) {
return false;
}
var moves = pokemon.moveset;
for (var i = 0; i < moves.length; i++) {
if (moves[i].id === pokemon.lastMove) {
if (!moves[i].pp) {
return false;
} else {
this.add('-start', pokemon, 'Disable', moves[i].move);
this.effectData.move = pokemon.lastMove;
return;
}
}
}
return false;
},
onEnd: function (pokemon) {
this.add('-end', pokemon, 'move: Disable');
},
onBeforeMovePriority: 7,
onBeforeMove: function (attacker, defender, move) {
if (move.id === this.effectData.move) {
this.add('cant', attacker, 'Disable', move);
return false;
}
},
onDisableMove: function (pokemon) {
var moves = pokemon.moveset;
for (var i = 0; i < moves.length; i++) {
if (moves[i].id === this.effectData.move) {
pokemon.disableMove(moves[i].id);
}
}
}
}
},
doomdesire: {
inherit: true,
accuracy: 85,
basePower: 120
},
drainpunch: {
inherit: true,
basePower: 60,
pp: 5
},
dreameater: {
inherit: true,
desc: "Deals damage to one adjacent target, if it is asleep and does not have a Substitute. The user recovers half of the HP lost by the target, rounded up. If Big Root is held by the user, the HP recovered is 1.3x normal, rounded half down.",
onTryHit: function (target) {
if (target.status !== 'slp' || target.volatiles['substitute']) {
this.add('-immune', target, '[msg]');
return null;
}
}
},
embargo: {
inherit: true,
flags: {protect: 1, mirror: 1},
onTryHit: function (pokemon) {
if (pokemon.ability === 'multitype' || pokemon.item === 'griseousorb') {
return false;
}
}
},
encore: {
inherit: true,
flags: {protect: 1, mirror: 1, authentic: 1},
volatileStatus: 'encore',
effect: {
durationCallback: function () {
return this.random(4, 9);
},
onStart: function (target) {
var noEncore = {encore:1, mimic:1, mirrormove:1, sketch:1, struggle:1, transform:1};
var moveIndex = target.moves.indexOf(target.lastMove);
if (!target.lastMove || noEncore[target.lastMove] || (target.moveset[moveIndex] && target.moveset[moveIndex].pp <= 0)) {
// it failed
this.add('-fail', target);
delete target.volatiles['encore'];
return;
}
this.effectData.move = target.lastMove;
this.add('-start', target, 'Encore');
if (!this.willMove(target)) {
this.effectData.duration++;
}
},
onOverrideDecision: function (pokemon) {
return this.effectData.move;
},
onResidualOrder: 13,
onResidual: function (target) {
if (target.moves.indexOf(target.lastMove) >= 0 && target.moveset[target.moves.indexOf(target.lastMove)].pp <= 0) {
// early termination if you run out of PP
delete target.volatiles.encore;
this.add('-end', target, 'Encore');
}
},
onEnd: function (target) {
this.add('-end', target, 'Encore');
},
onModifyPokemon: function (pokemon) {
if (!this.effectData.move || !pokemon.hasMove(this.effectData.move)) {
return;
}
for (var i = 0; i < pokemon.moveset.length; i++) {
if (pokemon.moveset[i].id !== this.effectData.move) {
pokemon.moveset[i].disabled = true;
}
}
}
}
},
endeavor: {
inherit: true,
damageCallback: function (pokemon, target) {
if (target.hp > pokemon.hp) {
return target.hp - pokemon.hp;
}
this.add('-fail', pokemon);
return false;
}
},
explosion: {
inherit: true,
basePower: 500
},
extremespeed: {
inherit: true,
shortDesc: "Usually goes first.",
priority: 1
},
fakeout: {
inherit: true,
shortDesc: "Usually hits first; first turn out only; target flinch.",
priority: 1
},
feint: {
inherit: true,
basePower: 50,
onTryHit: function (target) {
if (!target.volatiles['protect']) {
return false;
}
}
},
firespin: {
inherit: true,
accuracy: 70,
basePower: 15
},
flail: {
inherit: true,
basePowerCallback: function (pokemon, target) {
var ratio = pokemon.hp * 64 / pokemon.maxhp;
if (ratio < 2) {
return 200;
}
if (ratio < 6) {
return 150;
}
if (ratio < 13) {
return 100;
}
if (ratio < 22) {
return 80;
}
if (ratio < 43) {
return 40;
}
return 20;
}
},
focuspunch: {
inherit: true,
beforeMoveCallback: function () { },
onTry: function (pokemon) {
if (!pokemon.removeVolatile('focuspunch')) {
return;
}
if (pokemon.lastAttackedBy && pokemon.lastAttackedBy.damage && pokemon.lastAttackedBy.thisTurn) {
this.attrLastMove('[still]');
this.add('cant', pokemon, 'Focus Punch', 'Focus Punch');
return false;
}
}
},
foresight: {
inherit: true,
flags: {protect: 1, mirror: 1, authentic: 1}
},
furycutter: {
inherit: true,
basePower: 10
},
futuresight: {
inherit: true,
accuracy: 90,
basePower: 80,
pp: 15
},
gigadrain: {
inherit: true,
basePower: 60
},
glare: {
inherit: true,
accuracy: 75
},
growth: {
inherit: true,
desc: "Raises the user's Special Attack by 1 stage.",
shortDesc: "Boosts the user's Sp. Atk by 1.",
onModifyMove: function () { },
boosts: {
spa: 1
}
},
healblock: {
inherit: true,
flags: {protect: 1, mirror: 1},
effect: {
duration: 5,
durationCallback: function (target, source, effect) {
if (source && source.hasAbility('persistent')) {
return 7;
}
return 5;
},
onStart: function (pokemon) {
this.add('-start', pokemon, 'move: Heal Block');
},
onDisableMove: function (pokemon) {
var disabledMoves = {healingwish:1, lunardance:1, rest:1, swallow:1, wish:1};
var moves = pokemon.moveset;
for (var i = 0; i < moves.length; i++) {
if (disabledMoves[moves[i].id] || this.getMove(moves[i].id).heal) {
pokemon.disableMove(moves[i].id);
}
}
},
onBeforeMovePriority: 6,
onBeforeMove: function (pokemon, target, move) {
var disabledMoves = {healingwish:1, lunardance:1, rest:1, swallow:1, wish:1};
if (disabledMoves[move.id] || move.heal) {
this.add('cant', pokemon, 'move: Heal Block', move);
return false;
}
},
onResidualOrder: 17,
onEnd: function (pokemon) {
this.add('-end', pokemon, 'move: Heal Block');
},
onTryHeal: function (damage, pokemon, source, effect) {
if (effect && (effect.id === 'drain' || effect.id === 'leechseed' || effect.id === 'wish')) {
return false;
}
}
}
},
healingwish: {
inherit: true,
flags: {heal: 1},
onAfterMove: function (pokemon) {
pokemon.switchFlag = true;
},
effect: {
duration: 1,
onStart: function (side) {
this.debug('Healing Wish started on ' + side.name);
},
onSwitchInPriority: -1,
onSwitchIn: function (target) {
if (target.position !== this.effectData.sourcePosition) {
return;
}
if (target.hp > 0) {
var source = this.effectData.source;
var damage = target.heal(target.maxhp);
target.setStatus('');
this.add('-heal', target, target.getHealth, '[from] move: Healing Wish');
target.side.removeSideCondition('healingwish');
} else {
target.switchFlag = true;
}
}
}
},
hiddenpower: {
inherit: true,
basePower: 0,
basePowerCallback: function (pokemon) {
return pokemon.hpPower || 70;
},
desc: "Deals damage to one adjacent target. This move's type and power depend on the user's individual values (IVs). Power varies between 30 and 70, and type can be any but Normal.",
shortDesc: "Varies in power and type based on the user's IVs."
},
hiddenpowerbug: {
inherit: true,
basePower: 70
},
hiddenpowerdark: {
inherit: true,
basePower: 70
},
hiddenpowerdragon: {
inherit: true,
basePower: 70
},
hiddenpowerelectric: {
inherit: true,
basePower: 70
},
hiddenpowerfighting: {
inherit: true,
basePower: 70
},
hiddenpowerfire: {
inherit: true,
basePower: 70
},
hiddenpowerflying: {
inherit: true,
basePower: 70
},
hiddenpowerghost: {
inherit: true,
basePower: 70
},
hiddenpowergrass: {
inherit: true,
basePower: 70
},
hiddenpowerground: {
inherit: true,
basePower: 70
},
hiddenpowerice: {
inherit: true,
basePower: 70
},
hiddenpowerpoison: {
inherit: true,
basePower: 70
},
hiddenpowerpsychic: {
inherit: true,
basePower: 70
},
hiddenpowerrock: {
inherit: true,
basePower: 70
},
hiddenpowersteel: {
inherit: true,
basePower: 70
},
hiddenpowerwater: {
inherit: true,
basePower: 70
},
highjumpkick: {
inherit: true,
basePower: 100,
desc: "If this attack misses the target, the user takes half of the damage it would have dealt in recoil damage.",
shortDesc: "User takes half damage it would have dealt if miss.",
pp: 20,
onMoveFail: function (target, source, move) {
var damage = this.getDamage(source, target, move, true);
if (!damage) damage = target.maxhp;
this.damage(this.clampIntRange(damage / 2, 1, Math.floor(target.maxhp / 2)), source, source, 'highjumpkick');
}
},
iciclespear: {
inherit: true,
basePower: 10
},
imprison: {
inherit: true,
flags: {authentic: 1},
onTryHit: function (pokemon) {
var targets = pokemon.side.foe.active;
for (var i = 0; i < targets.length; i++) {
if (!targets[i] || targets[i].fainted) continue;
for (var j = 0; j < pokemon.moves.length; j++) {
if (targets[i].moves.indexOf(pokemon.moves[j]) >= 0) return;
}
}
return false;
}
},
jumpkick: {
inherit: true,
basePower: 85,
desc: "If this attack misses the target, the user takes half of the damage it would have dealt in recoil damage.",
shortDesc: "User takes half damage it would have dealt if miss.",
pp: 25,
onMoveFail: function (target, source, move) {
var damage = this.getDamage(source, target, move, true);
if (!damage) damage = target.maxhp;
this.damage(this.clampIntRange(damage / 2, 1, Math.floor(target.maxhp / 2)), source, source, 'jumpkick');
}
},
lastresort: {
inherit: true,
basePower: 130
},
luckychant: {
inherit: true,
flags: {}
},
lunardance: {
inherit: true,
flags: {heal: 1},
onAfterMove: function (pokemon) {
pokemon.switchFlag = true;
},
effect: {
duration: 1,
onStart: function (side) {
this.debug('Lunar Dance started on ' + side.name);
},
onSwitchInPriority: -1,
onSwitchIn: function (target) {
if (target.position !== this.effectData.sourcePosition) {
return;
}
if (target.hp > 0) {
var source = this.effectData.source;
var damage = target.heal(target.maxhp);
target.setStatus('');
for (var m in target.moveset) {
target.moveset[m].pp = target.moveset[m].maxpp;
}
this.add('-heal', target, target.getHealth, '[from] move: Lunar Dance');
target.side.removeSideCondition('lunardance');
} else {
target.switchFlag = true;
}
}
}
},
magiccoat: {
inherit: true,
effect: {
duration: 1,
onTryHitPriority: 2,
onTryHit: function (target, source, move) {
if (target === source || move.hasBounced || !move.flags['reflectable']) {
return;
}
target.removeVolatile('magiccoat');
var newMove = this.getMoveCopy(move.id);
newMove.hasBounced = true;
this.useMove(newMove, target, source);
return null;
}
}
},
magmastorm: {
inherit: true,
accuracy: 70
},
magnetrise: {
inherit: true,
flags: {gravity: 1},
volatileStatus: 'magnetrise',
effect: {
duration: 5,
onStart: function (target) {
if (target.volatiles['ingrain'] || target.ability === 'levitate') return false;
this.add('-start', target, 'Magnet Rise');
},
onImmunity: function (type) {
if (type === 'Ground') return false;
},
onResidualOrder: 6,
onResidualSubOrder: 9,
onEnd: function (target) {
this.add('-end', target, 'Magnet Rise');
}
}
},
metronome: {
inherit: true,
onHit: function (target) {
var moves = [];
for (var i in exports.BattleMovedex) {
var move = exports.BattleMovedex[i];
if (i !== move.id) continue;
if (move.isNonstandard) continue;
var noMetronome = {
assist:1, chatter:1, copycat:1, counter:1, covet:1, destinybond:1, detect:1, endure:1, feint:1, focuspunch:1, followme:1, helpinghand:1, mefirst:1, metronome:1, mimic:1, mirrorcoat:1, mirrormove:1, protect:1, sketch:1, sleeptalk:1, snatch:1, struggle:1, switcheroo:1, thief:1, trick:1
};
if (!noMetronome[move.id] && move.num < 468) {
moves.push(move.id);
}
}
var move = '';
if (moves.length) move = moves[this.random(moves.length)];
if (!move) return false;
this.useMove(move, target);
}
},
mimic: {
inherit: true,
onHit: function (target, source) {
var disallowedMoves = {chatter:1, metronome:1, mimic:1, sketch:1, struggle:1, transform:1};
if (source.transformed || !target.lastMove || disallowedMoves[target.lastMove] || source.moves.indexOf(target.lastMove) !== -1 || target.volatiles['substitute']) return false;
var moveslot = source.moves.indexOf('mimic');
if (moveslot < 0) return false;
var move = Tools.getMove(target.lastMove);
source.moveset[moveslot] = {
move: move.name,
id: move.id,
pp: 5,
maxpp: move.pp * 8 / 5,
disabled: false,
used: false
};
source.moves[moveslot] = toId(move.name);
this.add('-activate', source, 'move: Mimic', move.name);
}
},
minimize: {
inherit: true,
desc: "Raises the user's evasion by 1 stage. After using this move, Stomp will have its power doubled if used against the user while it is active.",
shortDesc: "Boosts the user's evasion by 1.",
boosts: {
evasion: 1
}
},
miracleeye: {
inherit: true,
flags: {protect: 1, mirror: 1, authentic: 1}
},
mirrormove: {
inherit: true,
onTryHit: function () { },
onHit: function (pokemon) {
var noMirror = {acupressure:1, aromatherapy:1, assist:1, chatter:1, copycat:1, counter:1, curse:1, doomdesire:1, feint:1, focuspunch:1, futuresight:1, gravity:1, hail:1, haze:1, healbell:1, helpinghand:1, lightscreen:1, luckychant:1, magiccoat:1, mefirst:1, metronome:1, mimic:1, mirrorcoat:1, mirrormove:1, mist:1, mudsport:1, naturepower:1, perishsong:1, psychup:1, raindance:1, reflect:1, roleplay:1, safeguard:1, sandstorm:1, sketch:1, sleeptalk:1, snatch:1, spikes:1, spitup:1, stealthrock:1, struggle:1, sunnyday:1, tailwind:1, toxicspikes:1, transform:1, watersport:1};
if (!pokemon.lastAttackedBy || !pokemon.lastAttackedBy.pokemon.lastMove || noMirror[pokemon.lastAttackedBy.move] || !pokemon.lastAttackedBy.pokemon.hasMove(pokemon.lastAttackedBy.move)) {
return false;
}
this.useMove(pokemon.lastAttackedBy.move, pokemon);
},
target: "self"
},
moonlight: {
inherit: true,
onHit: function (pokemon) {
if (this.isWeather(['sunnyday', 'desolateland'])) {
this.heal(pokemon.maxhp * 2 / 3);
} else if (this.isWeather(['raindance', 'primordialsea', 'sandstorm', 'hail'])) {
this.heal(pokemon.maxhp / 4);
} else {
this.heal(pokemon.maxhp / 2);
}
}
},
morningsun: {
inherit: true,
onHit: function (pokemon) {
if (this.isWeather(['sunnyday', 'desolateland'])) {
this.heal(pokemon.maxhp * 2 / 3);
} else if (this.isWeather(['raindance', 'primordialsea', 'sandstorm', 'hail'])) {
this.heal(pokemon.maxhp / 4);
} else {
this.heal(pokemon.maxhp / 2);
}
}
},
odorsleuth: {
inherit: true,
flags: {protect: 1, mirror: 1, authentic: 1}
},
outrage: {
inherit: true,
pp: 15,
onAfterMove: function () {}
},
payback: {
inherit: true,
basePowerCallback: function (pokemon, target) {
if (this.willMove(target)) {
return 50;
}
return 100;
}
},
petaldance: {
inherit: true,
basePower: 90,
pp: 20,
onAfterMove: function () {}
},
poisongas: {
inherit: true,
accuracy: 55,
target: "normal"
},
powertrick: {
inherit: true,
flags: {}
},
protect: {
inherit: true,
priority: 3,
effect: {
duration: 1,
onStart: function (target) {
this.add('-singleturn', target, 'Protect');
},
onTryHitPriority: 3,
onTryHit: function (target, source, move) {
if (!move.flags['protect']) return;
if (move.breaksProtect) {
target.removeVolatile('Protect');
return;
}
this.add('-activate', target, 'Protect');
var lockedmove = source.getVolatile('lockedmove');
if (lockedmove) {
// Outrage counter is NOT reset
if (source.volatiles['lockedmove'].trueDuration >= 2) {
source.volatiles['lockedmove'].duration = 2;
}
}
return null;
}
}
},
psychup: {
inherit: true,
flags: {snatch:1, authentic: 1}
},
recycle: {
inherit: true,
flags: {}
},
reversal: {
inherit: true,
basePowerCallback: function (pokemon, target) {
var ratio = pokemon.hp * 64 / pokemon.maxhp;
if (ratio < 2) {
return 200;
}
if (ratio < 6) {
return 150;
}
if (ratio < 13) {
return 100;
}
if (ratio < 22) {
return 80;
}
if (ratio < 43) {
return 40;
}
return 20;
}
},
roar: {
inherit: true,
flags: {protect: 1, mirror: 1, sound: 1, authentic: 1}
},
rockblast: {
inherit: true,
accuracy: 80
},
sandtomb: {
inherit: true,
accuracy: 70,
basePower: 15
},
scaryface: {
inherit: true,
accuracy: 90
},
selfdestruct: {
inherit: true,
basePower: 400
},
sketch: {
inherit: true,
onHit: function (target, source) {
var disallowedMoves = {chatter:1, sketch:1, struggle:1};
if (source.transformed || !target.lastMove || disallowedMoves[target.lastMove] || source.moves.indexOf(target.lastMove) >= 0 || target.volatiles['substitute']) return false;
var moveslot = source.moves.indexOf('sketch');
if (moveslot < 0) return false;
var move = Tools.getMove(target.lastMove);
var sketchedMove = {
move: move.name,
id: move.id,
pp: move.pp,
maxpp: move.pp,
disabled: false,
used: false
};
source.moveset[moveslot] = sketchedMove;
source.baseMoveset[moveslot] = sketchedMove;
source.moves[moveslot] = toId(move.name);
this.add('-activate', source, 'move: Mimic', move.name);
}
},
skillswap: {
inherit: true,
onHit: function (target, source) {
var targetAbility = target.ability;
var sourceAbility = source.ability;
if (targetAbility === sourceAbility) {
return false;
}
this.add('-activate', source, 'move: Skill Swap');
source.setAbility(targetAbility);
target.setAbility(sourceAbility);
}
},
sleeptalk: {
inherit: true,
beforeMoveCallback: function (pokemon) {
if (pokemon.volatiles['choicelock'] || pokemon.volatiles['encore']) {
this.addMove('move', pokemon, 'Sleep Talk');
this.add('-fail', pokemon);
return true;
}
}
},
spikes: {
inherit: true,
flags: {}
},
spite: {
inherit: true,
flags: {protect: 1, mirror: 1, authentic: 1}
},
stealthrock: {
inherit: true,
flags: {}
},
struggle: {
inherit: true,
onModifyMove: function (move) {
move.type = '???';
}
},
suckerpunch: {
inherit: true,
onTry: function (source, target) {
var decision = this.willMove(target);
if (!decision || decision.choice !== 'move' || decision.move.category === 'Status' || target.volatiles.mustrecharge) {
this.add('-fail', source);
return null;
}
}
},
synthesis: {
inherit: true,
onHit: function (pokemon) {
if (this.isWeather(['sunnyday', 'desolateland'])) {
this.heal(pokemon.maxhp * 2 / 3);
} else if (this.isWeather(['raindance', 'primordialsea', 'sandstorm', 'hail'])) {
this.heal(pokemon.maxhp / 4);
} else {
this.heal(pokemon.maxhp / 2);
}
}
},
tackle: {
inherit: true,
accuracy: 95,
basePower: 35
},
tailglow: {
inherit: true,
desc: "Raises the user's Special Attack by 2 stages.",
shortDesc: "Boosts the user's Sp. Atk by 2.",
boosts: {
spa: 2
}
},
tailwind: {
inherit: true,
desc: "For 3 turns, the user and its party members have their Speed doubled. Fails if this move is already in effect for the user's side.",
shortDesc: "For 3 turns, allies' Speed is doubled.",
effect: {
duration: 3,
durationCallback: function (target, source, effect) {
if (source && source.ability === 'persistent') {
return 5;
}
return 3;
},
onStart: function (side) {
this.add('-sidestart', side, 'move: Tailwind');
},
onModifySpe: function (spe) {
return spe * 2;
},
onResidualOrder: 21,
onResidualSubOrder: 4,
onEnd: function (side) {
this.add('-sideend', side, 'move: Tailwind');
}
}
},
taunt: {
inherit: true,
flags: {protect: 1, mirror: 1, authentic: 1},
effect: {
durationCallback: function () {
return this.random(3, 6);
},
onStart: function (target) {
this.add('-start', target, 'move: Taunt');
},
onResidualOrder: 12,
onEnd: function (target) {
this.add('-end', target, 'move: Taunt');
},
onDisableMove: function (pokemon) {
var moves = pokemon.moveset;
for (var i = 0; i < moves.length; i++) {
if (this.getMove(moves[i].move).category === 'Status') {
pokemon.disableMove(moves[i].id);
}
}
},
onBeforeMovePriority: 5,
onBeforeMove: function (attacker, defender, move) {
if (move.category === 'Status') {
this.add('cant', attacker, 'move: Taunt', move);
return false;
}
}
}
},
thrash: {
inherit: true,
basePower: 90,
pp: 20,
onAfterMove: function () {}
},
torment: {
inherit: true,
flags: {protect: 1, mirror: 1, authentic: 1}
},
toxic: {
inherit: true,
accuracy: 85
},
toxicspikes: {
inherit: true,
flags: {},
effect: {
// this is a side condition
onStart: function (side) {
this.add('-sidestart', side, 'move: Toxic Spikes');
this.effectData.layers = 1;
},
onRestart: function (side) {
if (this.effectData.layers >= 2) return false;
this.add('-sidestart', side, 'move: Toxic Spikes');
this.effectData.layers++;
},
onSwitchIn: function (pokemon) {
if (!pokemon.runImmunity('Ground')) return;
if (!pokemon.runImmunity('Poison')) return;
if (pokemon.hasType('Poison')) {
this.add('-sideend', pokemon.side, 'move: Toxic Spikes', '[of] ' + pokemon);
pokemon.side.removeSideCondition('toxicspikes');
}
if (pokemon.volatiles['substitute']) {
return;
} else if (this.effectData.layers >= 2) {
pokemon.trySetStatus('tox');
} else {
pokemon.trySetStatus('psn');
}
}
}
},
transform: {
inherit: true,
flags: {authentic: 1}
},
uproar: {
inherit: true,
basePower: 50
},
whirlpool: {
inherit: true,
accuracy: 70,
basePower: 15
},
whirlwind: {
inherit: true,
flags: {protect: 1, mirror: 1, authentic: 1}
},
wish: {
inherit: true,
shortDesc: "Next turn, heals 50% of the recipient's max HP.",
flags: {heal: 1},
sideCondition: 'Wish',
effect: {
duration: 2,
onResidualOrder: 0,
onEnd: function (side) {
var target = side.active[this.effectData.sourcePosition];
if (!target.fainted) {
var source = this.effectData.source;
var damage = this.heal(target.maxhp / 2, target, target);
if (damage) this.add('-heal', target, target.getHealth, '[from] move: Wish', '[wisher] ' + source.name);
}
}
}
},
worryseed: {
inherit: true,
onTryHit: function (pokemon) {
var bannedAbilities = {multitype:1, truant:1};
if (bannedAbilities[pokemon.ability]) {
return false;
}
}
},
wrap: {
inherit: true,
accuracy: 85
},
wringout: {
inherit: true,
basePowerCallback: function (pokemon) {
return Math.floor(pokemon.hp * 120 / pokemon.maxhp) + 1;
}
},
magikarpsrevenge: null
};
| BuzzyOG/Pokemon-Showdown | mods/gen4/moves.js | JavaScript | mit | 32,423 |
window.addEventListener('DOMContentLoaded', webGLStart, false);
function webGLStart() {
var numSites = 1,
sites = [0, 0, 1],
siteColors = [0.5, 0.5, 0.7],
width = 800,
height = 600,
R = 200,
vs = [],
weight = [1],
fullscreen = false,
dragStart = [],
matStart = null,
mat = new PhiloGL.Mat4(),
imat = mat.clone(),
weighted = false;
mat.id();
imat.id();
function toggleFullscreen() {
document.body.classList.toggle('fullscreen');
resize();
}
function toggleWeighted() {
weighted = !weighted;
this.app && this.app.update();
}
window.toggleFullscreen = toggleFullscreen;
window.toggleWeighted = toggleWeighted;
function resize() {
var canvas = document.getElementById('voronoi'),
style = window.getComputedStyle(canvas);
height = parseFloat(style.getPropertyValue('height'));
canvas.height = height;
width = parseFloat(style.getPropertyValue('width'));
canvas.width = width;
this.app && this.app.update();
}
window.addEventListener('resize', resize);
resize();
function calcXYZ(e) {
var x = e.x / R,
y = e.y / R,
z = 1.0 - x * x - y * y;
if (z < 0) {
while (z < 0) {
x *= Math.exp(z);
y *= Math.exp(z);
z = 1.0 - x * x - y * y;
}
z = -Math.sqrt(z);
} else {
z = Math.sqrt(z);
}
var v3 = new PhiloGL.Vec3(x, y, z, 1);
imat.$mulVec3(v3);
return v3;
}
PhiloGL('voronoi', {
program: {
id: 'voronoi',
from: 'uris',
vs: 'sph-shader.vs.glsl',
fs: 'sph-shader.fs.glsl'
},
onError: function (e) {
alert(e);
},
events: {
cachePosition: false,
onDragStart: function (e) {
matStart = mat.clone();
dragStart = [e.x, e.y];
},
onMouseWheel: function (e) {
var id = new PhiloGL.Mat4();
id.id();
id.$rotateAxis(('wheelDeltaX' in e.event ? e.event.wheelDeltaX : 0) / 5 / R, [0, 1, 0])
.$rotateAxis(('wheelDeltaY' in e.event ? e.event.wheelDeltaY : e.wheel * 120) / 5 / R, [1, 0, 0]);
mat = id.mulMat4(mat);
imat = mat.invert();
var v3 = calcXYZ(e);
sites[0] = v3[0];
sites[1] = v3[1];
sites[2] = v3[2];
this.update();
e.event.preventDefault();
e.event.stopPropagation();
},
onDragMove: function (e) {
var id = new PhiloGL.Mat4();
id.id();
id.$rotateAxis((e.x - dragStart[0]) / R, [0, 1, 0])
.$rotateAxis((e.y - dragStart[1]) / R, [-1, 0, 0]);
mat = id.mulMat4(matStart);
imat = mat.invert();
var v3 = calcXYZ(e);
sites[0] = v3[0];
sites[1] = v3[1];
sites[2] = v3[2];
this.update();
},
onDragEnd: function (e) {
var id = new PhiloGL.Mat4();
id.id();
id.$rotateAxis((e.x - dragStart[0]) / R, [0, 1, 0])
.$rotateAxis((e.y - dragStart[1]) / R, [-1, 0, 0]);
mat = id.mulMat4(matStart);
imat = mat.invert();
var v3 = calcXYZ(e);
sites[0] = v3[0];
sites[1] = v3[1];
sites[2] = v3[2];
this.update();
},
onMouseMove: function (e) {
var v3 = calcXYZ(e);
sites[0] = v3[0];
sites[1] = v3[1];
sites[2] = v3[2];
this.update();
},
onClick: function (e) {
var v3 = calcXYZ(e);
sites.push(v3[0], v3[1], v3[2]);
siteColors.push(Math.random(), Math.random(), Math.random());
weight.push(Math.random() * 2 + 1);
numSites++;
this.update();
}
},
onLoad: function (app) {
var gl = app.gl,
program = app.program;
window.app = app;
app.update = function () {
draw();
}
function draw() {
gl.clearColor(0, 0, 0, 1);
gl.clearDepth(1);
gl.viewport(0, 0, width, height);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
PhiloGL.Media.Image.postProcess({
program: 'voronoi',
width: width,
height: height,
toScreen: true,
uniforms: {
'numberSites': numSites,
'sites': sites,
'ws': weight,
'siteColors': siteColors,
'p': 2,
'modelMat': mat,
'weighted': weighted,
'width': width,
'height': height,
'R': R
}
});
}
app.update();
}
});
}
| Drakesinger/philogl | examples/voronoi/index.js | JavaScript | mit | 4,533 |
/* eslint-disable */
var webpack = require('webpack');
module.exports = {
debug: true,
devtool: 'source-map',
entry: {
app: __dirname + '/index.js'
},
module: {
loaders: [
{
test: /\.js$/, exclude: /node_modules/, loader: 'babel'
}
]
},
output: {
path: __dirname + '/build/',
filename: '[name].js',
publicPath: 'http://localhost:8000/build'
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': '"development"'
}
}),
new webpack.NoErrorsPlugin(),
new webpack.HotModuleReplacementPlugin()
],
devServer: {
colors: true,
contentBase: __dirname,
historyApiFallback: true,
hot: true,
inline: true,
port: 8000,
progress: true,
stats: {
cached: false
}
}
}; | Charmatzis/react-leaflet-google | example/webpack.config.js | JavaScript | mit | 816 |
const fs = require('fs');
const path = require('path');
const p = path.join(
path.dirname(process.mainModule.filename),
'data',
'products.json'
);
const getProductsFromFile = cb => {
fs.readFile(p, (err, fileContent) => {
if (err) {
cb([]);
} else {
cb(JSON.parse(fileContent));
}
});
};
module.exports = class Product {
constructor(title, imageUrl, description, price) {
this.title = title;
this.imageUrl = imageUrl;
this.description = description;
this.price = price;
}
save() {
getProductsFromFile(products => {
products.push(this);
fs.writeFile(p, JSON.stringify(products), err => {
console.log(err);
});
});
}
static fetchAll(cb) {
getProductsFromFile(cb);
}
};
| tarsoqueiroz/NodeJS | Udemy/NodeJS - The Complete Guide/Recursos/09/00-starting-setup-b/models/product.js | JavaScript | mit | 772 |
/*
* Copyright (c) 2015-2016 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*/
'use strict';
/**
* Test of the CheSvn
*/
describe('CheSvn', function () {
/**
* User Factory for the test
*/
var factory;
/**
* API builder.
*/
var apiBuilder;
/**
* Backend for handling http operations
*/
var httpBackend;
/**
* Che backend
*/
var cheBackend;
/**
* setup module
*/
beforeEach(angular.mock.module('userDashboard'));
/**
* Inject factory and http backend
*/
beforeEach(inject(function (cheSvn, cheAPIBuilder, cheHttpBackend) {
factory = cheSvn;
apiBuilder = cheAPIBuilder;
cheBackend = cheHttpBackend;
httpBackend = cheHttpBackend.getHttpBackend();
}));
/**
* Check assertion after the test
*/
afterEach(function () {
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
});
/**
* Check that we're able to fetch remote svn url
*/
it('Fetch remote svn url', function () {
// setup tests objects
var workspaceId = 'workspace456test';
var projectPath = '/testSvnProject';
var remoteSvnUrl = 'https://svn.apache.org' + projectPath;
// providing request
// add test remote svn url on http backend
cheBackend.addRemoteSvnUrl(workspaceId, encodeURIComponent(projectPath), remoteSvnUrl);
// setup backend
cheBackend.setup();
cheBackend.getRemoteSvnUrl(workspaceId, encodeURIComponent(projectPath));
// fetch remote url
factory.fetchRemoteUrl(workspaceId, projectPath);
// expecting POST
httpBackend.expectPOST('/api/svn/' + workspaceId + '/info');
// flush command
httpBackend.flush();
// now, check
var url = factory.getRemoteUrlByKey(workspaceId, projectPath);
// check local url
expect(remoteSvnUrl).toEqual(url);
}
);
});
| dhuebner/che | dashboard/src/components/api/che-svn.spec.js | JavaScript | epl-1.0 | 2,191 |
// This file is part of the jQuery formatCurrency Plugin.
//
// The jQuery formatCurrency Plugin is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// The jQuery formatCurrency Plugin 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License along with
// the jQuery formatCurrency Plugin. If not, see <http://www.gnu.org/licenses/>.
// formatCurrency i18n
(function($) {
$.formatCurrency.regions['fr'] = {
symbol: '€',
positiveFormat: '%n %s',
negativeFormat: '-%n %s',
decimalSymbol: ',',
digitGroupSymbol: ' ',
groupDigits: true
};
})(jQuery); | wulanrahayu/jquery-formatcurrency | i18n/jquery.formatCurrency.fr.js | JavaScript | gpl-3.0 | 1,081 |
Ext.ns('QNAP.QOS.QPKG.EyeFiServerController');
QNAP.QOS.QPKG.EyeFiServerController = function () {
return {
init: function (cmp) {
Ext.apply(cmp, this);
},
ajaxFunction: function (paramsData, callbackFunction) {
var me = this;
QNAP.QOS.ajax({
url: QNAP.QOS.lib.getCgiUrl('/cgi-bin/qpkg/EyeFiServer/' + 'api.cgi'),
params: paramsData,
method: 'GET',
success: function (response, opts) {
if( callbackFunction ) callbackFunction(response.responseText.trim());
}
});
},
daemon: function(name)
{
var me = this;
me.ajaxFunction({'act':name}, function(data){ me.showEyeFiServerStatusWindow(data); me.refreshLog(); });
},
apply: function(name)
{
var me = this;
me.ajaxFunction(
{
'act':'save',
'mac_0':Ext.getCmp(me.compIDs.MAC_0_FIELD).getValue().replace(new RegExp("[^0-9A-F]",'gi'),""),
'upload_key_0':Ext.getCmp(me.compIDs.UPLOAD_KEY_0_FIELD).getValue(),
'mac_1':Ext.getCmp(me.compIDs.MAC_1_FIELD).getValue().replace(new RegExp("[^0-9A-F]",'gi'),""),
'upload_key_1':Ext.getCmp(me.compIDs.UPLOAD_KEY_1_FIELD).getValue(),
'upload_dir':Ext.getCmp(me.compIDs.UPLOAD_DIR_FIELD).getValue(),
'upload_uid':Ext.getCmp(me.compIDs.UPLOAD_UID_FIELD).getValue(),
'upload_gid':Ext.getCmp(me.compIDs.UPLOAD_GID_FIELD).getValue(),
'upload_file_mode':me.getCheckBoxes(me.compIDs.UPLOAD_FILE_MODE_FIELD),
'upload_dir_mode':me.getCheckBoxes(me.compIDs.UPLOAD_DIR_MODE_FIELD),
'geotag_enable':Ext.getCmp(me.compIDs.GEOTAG_ENABLE_FIELD).getValue()?'1':'0',
'geotag_lag':Ext.getCmp(me.compIDs.GEOTAG_LAG_FIELD).getValue(),
'geotag_accuracy':Ext.getCmp(me.compIDs.GEOTAG_ACCURACY_FIELD).getValue()
},
function(data){
me.showEyeFiServerStatusWindow(data); me.refreshLog();
}
);
},
revert: function()
{
var me = this;
me.refreshFields();
me.showEyeFiServerStatusWindow('configuration reverted');
},
refreshField: function(name, id){
var me = this;
me.ajaxFunction({'act':'getval','name':name}, function(data){ Ext.getCmp(id).setValue(data); });
},
refreshMacField: function(name, id){
var me = this;
me.ajaxFunction({'act':'getval','name':name}, function(data){
Ext.getCmp(id).setValue(data.replace(new RegExp("[0-9A-F]{2}",'gi'),"$&:").substring(0,17));
});
},
fillSelect: function(name, id){
var me = this;
me.ajaxFunction({'act':'getuids','name':name}, function(data){
var store = new Ext.data.ArrayStore({
fields: ['uid', 'name']
});
var rows = data.split('\n');
for(var i=0; i<rows.length; i++){
var cell = rows[i].split(':');
store.add(new store.recordType({ uid: cell[1], name: cell[0]}));
}
Ext.getCmp(id).bindStore(store);
});
},
refreshSelect: function(name, id){
var me = this;
me.ajaxFunction({'act':'getval','name':name}, function(data){
Ext.getCmp(id).setValue(data);
});
},
refreshCheckBoxes: function(name, id){
var me = this;
me.ajaxFunction({'act':'getval','name':name}, function(data){
for(i=0; i<=8; i++){
Ext.getCmp(id + '_' + i).setValue(data&1);
data>>=1;
}
});
},
getCheckBoxes: function(id){
var val;
for(i=8; i>=0; i--){
val<<=1;
if(Ext.getCmp(id + '_' + i).getValue()){
val++;
}
}
return val;
},
updateGeotag: function(){
var me = this;
Ext.getCmp((me.compIDs.GEOTAG_OPTIONS_CONTAINER)).setDisabled(! Ext.getCmp(me.compIDs.GEOTAG_ENABLE_FIELD).getValue());
},
refreshLog: function() {
var me = this;
me.ajaxFunction({'act':'status'}, function(data){Ext.getCmp(me.compIDs.STATUS_FIELD).setValue(data);});
me.ajaxFunction({'act':'getlog'}, function(data){Ext.getCmp(me.compIDs.LOG_FIELD).setValue(data); Ext.getCmp(me.compIDs.LOG_FIELD).getEl().dom.scrollTop = 99999;});
// Ext.getCmp(me.compIDs.LOG_FIELD).getElement().getFirtChildElement().setScrollTop( Ext.getCmp(me.compIDs.LOG_FIELD).getElement().getFirtChildElement().getScrollHeight() );
// log.scrollTop(log[0].scrollHeight - log.height());
},
refreshFields: function() {
var me = this;
me.refreshMacField('mac_0',me.compIDs.MAC_0_FIELD);
me.refreshField('upload_key_0',me.compIDs.UPLOAD_KEY_0_FIELD);
me.refreshMacField('mac_1',me.compIDs.MAC_1_FIELD);
me.refreshField('upload_key_1',me.compIDs.UPLOAD_KEY_1_FIELD);
me.refreshField('upload_dir',me.compIDs.UPLOAD_DIR_FIELD);
me.refreshSelect('upload_uid',me.compIDs.UPLOAD_UID_FIELD);
me.refreshSelect('upload_gid',me.compIDs.UPLOAD_GID_FIELD);
me.refreshCheckBoxes('upload_file_mode',me.compIDs.UPLOAD_FILE_MODE_FIELD);
me.refreshCheckBoxes('upload_dir_mode',me.compIDs.UPLOAD_DIR_MODE_FIELD);
me.refreshField('geotag_enable',me.compIDs.GEOTAG_ENABLE_FIELD);
me.refreshField('geotag_lag',me.compIDs.GEOTAG_LAG_FIELD);
me.refreshField('geotag_accuracy',me.compIDs.GEOTAG_ACCURACY_FIELD);
me.updateGeotag();
}
}
};
| dgrant/eyefiserver2 | qpkg/ui/eyefiserver_controller.js | JavaScript | gpl-3.0 | 4,927 |
/*
YUI 3.8.0 (build 5744)
Copyright 2012 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('yql', function (Y, NAME) {
/**
* This class adds a sugar class to allow access to YQL (http://developer.yahoo.com/yql/).
* @module yql
*/
/**
* Utility Class used under the hood my the YQL class
* @class YQLRequest
* @constructor
* @param {String} sql The SQL statement to execute
* @param {Function/Object} callback The callback to execute after the query (Falls through to JSONP).
* @param {Object} params An object literal of extra parameters to pass along (optional).
* @param {Object} opts An object literal of configuration options (optional): proto (http|https), base (url)
*/
var YQLRequest = function (sql, callback, params, opts) {
if (!params) {
params = {};
}
params.q = sql;
//Allow format override.. JSON-P-X
if (!params.format) {
params.format = Y.YQLRequest.FORMAT;
}
if (!params.env) {
params.env = Y.YQLRequest.ENV;
}
this._context = this;
if (opts && opts.context) {
this._context = opts.context;
delete opts.context;
}
if (params && params.context) {
this._context = params.context;
delete params.context;
}
this._params = params;
this._opts = opts;
this._callback = callback;
};
YQLRequest.prototype = {
/**
* @private
* @property _jsonp
* @description Reference to the JSONP instance used to make the queries
*/
_jsonp: null,
/**
* @private
* @property _opts
* @description Holder for the opts argument
*/
_opts: null,
/**
* @private
* @property _callback
* @description Holder for the callback argument
*/
_callback: null,
/**
* @private
* @property _params
* @description Holder for the params argument
*/
_params: null,
/**
* @private
* @property _context
* @description The context to execute the callback in
*/
_context: null,
/**
* @private
* @method _internal
* @description Internal Callback Handler
*/
_internal: function () {
this._callback.apply(this._context, arguments);
},
/**
* @method send
* @description The method that executes the YQL Request.
* @chainable
* @return {YQLRequest}
*/
send: function () {
var qs = [], url = ((this._opts && this._opts.proto) ? this._opts.proto : Y.YQLRequest.PROTO), o;
Y.each(this._params, function (v, k) {
qs.push(k + '=' + encodeURIComponent(v));
});
qs = qs.join('&');
url += ((this._opts && this._opts.base) ? this._opts.base : Y.YQLRequest.BASE_URL) + qs;
o = (!Y.Lang.isFunction(this._callback)) ? this._callback : { on: { success: this._callback } };
o.on = o.on || {};
this._callback = o.on.success;
o.on.success = Y.bind(this._internal, this);
Y.log('URL: ' + url, 'info', 'yql');
this._send(url, o);
return this;
},
/**
* Private method to send the request, overwritten in plugins
* @method _send
* @private
* @param {String} url The URL to request
* @param {Object} o The config object
*/
_send: function(url, o) {
if (o.allowCache !== false) {
o.allowCache = true;
}
if (!this._jsonp) {
this._jsonp = Y.jsonp(url, o);
} else {
this._jsonp.url = url;
if (o.on && o.on.success) {
this._jsonp._config.on.success = o.on.success;
}
this._jsonp.send();
}
}
};
/**
* @static
* @property FORMAT
* @description Default format to use: json
*/
YQLRequest.FORMAT = 'json';
/**
* @static
* @property PROTO
* @description Default protocol to use: http
*/
YQLRequest.PROTO = 'http';
/**
* @static
* @property BASE_URL
* @description The base URL to query: query.yahooapis.com/v1/public/yql?
*/
YQLRequest.BASE_URL = ':/' + '/query.yahooapis.com/v1/public/yql?';
/**
* @static
* @property ENV
* @description The environment file to load: http://datatables.org/alltables.env
*/
YQLRequest.ENV = 'http:/' + '/datatables.org/alltables.env';
Y.YQLRequest = YQLRequest;
/**
* This class adds a sugar class to allow access to YQL (http://developer.yahoo.com/yql/).
* @class YQL
* @constructor
* @param {String} sql The SQL statement to execute
* @param {Function} callback The callback to execute after the query (optional).
* @param {Object} params An object literal of extra parameters to pass along (optional).
* @param {Object} opts An object literal of configuration options (optional): proto (http|https), base (url)
*/
Y.YQL = function (sql, callback, params, opts) {
return new Y.YQLRequest(sql, callback, params, opts).send();
};
}, '3.8.0', {"requires": ["jsonp", "jsonp-url"]});
| relipse/cworklog | public_html/js/yui/3.8.0/build/yql/yql-debug.js | JavaScript | gpl-3.0 | 4,926 |
function _iterableToArrayLimitLoose(arr, i) {
if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) {
return;
}
var _arr = [];
for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) {
_arr.push(_step.value);
if (i && _arr.length === i) break;
}
return _arr;
}
module.exports = _iterableToArrayLimitLoose; | mdranger/mytest | node_modules/@babel/runtime/helpers/iterableToArrayLimitLoose.js | JavaScript | mpl-2.0 | 414 |
'use strict';
var openUrl = require('./utils').open;
module.exports = new Dashboard();
function Dashboard() {
/**
* Open dashboard for current selected desk/custom workspace.
*/
this.openDashboard = function() {
openUrl('/#/workspace');
};
/**
* Open the dashboard setting. The dashboard page should be already opened.
*/
this.showDashboardSettings = function() {
element.all(by.className('svg-icon-plus')).first().click();
};
/**
* Get the list of available widgets on dashboard settings.
*
* @return {promise} list of widgets
*/
this.getSettingsWidgets = function() {
return element.all(by.repeater('widget in dashboard.availableWidgets'));
};
/**
* Get the widget at index 'index' from the list of available widgets on
* dashboard settings.
*
* @param {number} index
* @return {promise} widget element
*/
this.getSettingsWidget = function(index) {
return this.getSettingsWidgets().get(index);
};
/**
* Add to current dashboard the widget at index 'index' from the list
* of available widgets on dashboard settings.
*
* @param {number} index
*/
this.addWidget = function(index) {
this.getSettingsWidget(index).click();
element.all(by.css('[ng-click="dashboard.addWidget(dashboard.selectedWidget)"]')).first().click();
};
/**
* Close the dashboard settings.
*/
this.doneAction = function() {
element.all(by.css('[ng-click="dashboard.add = false"]')).first().click();
};
/**
* Get the list of widgets from current dashboard
*
* @return {promise} widgets list
**/
this.getWidgets = function() {
return element.all(by.repeater('widget in widgets'));
};
/**
* Get the widget at index 'index' from the current dashboard.
*
* @param {number} index
* @return {promise} widget element
*/
this.getWidget = function(index) {
return this.getWidgets().get(index);
};
/**
* Get the label for widget at index 'index'
* from the current dashboard.
*
* @param {number} index
* @return {text} label
*/
this.getWidgetLabel = function(index) {
return this.getWidget(index).all(by.css('.widget-title')).first().getText();
};
/**
* Show the monitoring settings for 'index' widget
*
* @param {number} index
*/
this.showMonitoringSettings = function(index) {
this.getWidget(index).all(by.css('[ng-click="openConfiguration()"]')).first().click();
browser.wait(function() {
return element.all(by.css('.aggregate-widget-config')).isDisplayed();
});
};
/**
* Get groups for widget
*
* @param {number} widget index
* @return {promise} list of groups elements
*/
this.getGroups = function(widget) {
return this.getWidget(widget).all(by.repeater('group in agg.cards'));
};
/**
* Get a group for a widget
*
* @param {number} widget index
* @param {number} group index
* @return {promise} group element
*/
this.getGroup = function(widget, group) {
return this.getGroups(widget).get(group);
};
/**
* Get the list of items from a group for a widget
*
* @param {number} widget index
* @param {number} group index
* @return {promise} items element list
*/
this.getGroupItems = function(widget, group) {
return this.getGroup(widget, group).all(by.repeater('item in items'));
};
/**
* Get an item from a group for a widget
*
* @param {number} widget index
* @param {number} group index
* @param {number} item index
* @return {promise} item element
*/
this.getItem = function(widget, group, item) {
return this.getGroupItems(widget, group).get(item);
};
/**
* Get an item from a group for a widget
*
* @param {number} widget index
* @param {number} group index
* @param {number} item index
* @return {promise} item element
*/
this.getTextItem = function(widget, group, item) {
return this.getItem(widget, group, item).element(by.id('title')).getText();
};
/**
* Get an search text box widget
*
* @param {number} widget index
* @return {promise} item element
*/
this.getSearchTextBox = function(widget) {
return this.getWidget(widget).element(by.css('.search-box input'));
};
/**
* Get an search text box widget
*
* @param {number} widget index
* @param {string} searchText search string
*/
this.doSearch = function(widget, searchText) {
this.getSearchTextBox(widget).sendKeys(searchText);
};
}
| sivakuna-aap/superdesk | client/spec/helpers/dashboard.js | JavaScript | agpl-3.0 | 4,857 |
var b = require('bonescript');
// setup starting conditions
var awValue = 0.01;
var awDirection = 1;
var awPin = "P9_14";
// configure pin
b.pinMode(awPin, b.ANALOG_OUTPUT);
// call function to update brightness every 10ms
setInterval(fade, 10);
// function to update brightness
function fade() {
b.analogWrite(awPin, awValue);
awValue = awValue + (awDirection*0.01);
if(awValue > 1.0) { awValue = 1.0; awDirection = -1; }
else if(awValue <= 0.01) { awValue = 0.01; awDirection = 1; }
}
| MIC00L/bone101 | examples/fade.js | JavaScript | lgpl-3.0 | 496 |
var locations = [
];
var states = [
];
var countries = [
]; | cnsde/lforum | webapp/javascript/locations.js | JavaScript | apache-2.0 | 74 |
//// [optionalPropertyAssignableToStringIndexSignature.ts]
declare let optionalProperties: { k1?: string };
declare let undefinedProperties: { k1: string | undefined };
declare let stringDictionary: { [key: string]: string };
stringDictionary = optionalProperties; // ok
stringDictionary = undefinedProperties; // error
declare let probablyArray: { [key: number]: string };
declare let numberLiteralKeys: { 1?: string };
probablyArray = numberLiteralKeys; // error
declare let optionalUndefined: { k1?: undefined };
let dict: { [key: string]: string } = optionalUndefined; // error
function f<T>() {
let optional: { k1?: T } = undefined!;
let dict: { [key: string]: T | number } = optional; // ok
}
//// [optionalPropertyAssignableToStringIndexSignature.js]
"use strict";
stringDictionary = optionalProperties; // ok
stringDictionary = undefinedProperties; // error
probablyArray = numberLiteralKeys; // error
var dict = optionalUndefined; // error
function f() {
var optional = undefined;
var dict = optional; // ok
}
| Microsoft/TypeScript | tests/baselines/reference/optionalPropertyAssignableToStringIndexSignature.js | JavaScript | apache-2.0 | 1,050 |
class CacheClassification {
constructor() {
this.state = {
cachedClassification: null,
};
}
create() {
const cachedClassification = { annotations: [] };
this.state = { cachedClassification };
return this.state.cachedClassification;
}
update(newAnnotation) {
let cachedClassification;
const taskKey = newAnnotation.task;
if (this.state.cachedClassification === null) {
cachedClassification = this.create();
} else {
cachedClassification = this.state.cachedClassification;
}
const cachedAnnotation = this.isAnnotationCached(taskKey);
if (cachedAnnotation) {
const index = cachedClassification.annotations.findIndex(
(annotation) => annotation.task === taskKey);
if (index > -1) {
cachedClassification.annotations.splice(index, 1);
}
}
cachedClassification.annotations.push(newAnnotation);
}
delete() {
this.state = { cachedClassification: null };
}
isAnnotationCached(taskKey) {
let annotationToReturn = null;
if (this.state.cachedClassification !== null) {
const annotations = this.state.cachedClassification.annotations;
annotations.forEach((annotation) => {
if (annotation.task === taskKey) {
annotationToReturn = annotation;
}
});
}
return annotationToReturn;
}
}
const cachedClassification = new CacheClassification;
export default cachedClassification;
| jelliotartz/Panoptes-Front-End | app/components/cache-classification.js | JavaScript | apache-2.0 | 1,460 |
module.exports={A:{A:{"2":"K C G E A B EB"},B:{"1":"I M H","2":"D w","322":"Z"},C:{"2":"0 1 XB AB F J K C G E A B D w Z I M H N O P Q R S T U V W X Y y a b c d e f L h i j k l m n o p q r s t u v VB PB","4162":"3 5 6 7 8 z x"},D:{"1":"8 BB JB DB FB ZB GB HB","2":"F J K C G E A B D w Z I M H N O P Q R S T U V W X Y y a b c d e f L h i j k l m n o p q r s t u v","194":"0 1 3 5 z x","1090":"6 7"},E:{"1":"g QB","2":"F J K C G E IB CB KB LB MB NB","514":"A B OB"},F:{"1":"r s t u v","2":"4 9 E B D I M H N O P Q R S T U V W X Y y a b c d e f L h i RB SB TB UB g WB","194":"j k l m n o p q"},G:{"1":"jB","2":"2 G CB YB aB bB cB dB eB fB","514":"gB hB iB"},H:{"2":"kB"},I:{"2":"2 AB F BB lB mB nB oB pB qB"},J:{"2":"C A"},K:{"2":"4 9 A B D L g"},L:{"2049":"DB"},M:{"2":"x"},N:{"2":"A B"},O:{"2":"rB"},P:{"1":"J sB","2":"F"},Q:{"194":"tB"},R:{"2":"uB"}},B:5,C:"Payment Request API"};
| arschles/go-in-5-minutes | episode24/node_modules/caniuse-lite/data/features/payment-request.js | JavaScript | apache-2.0 | 880 |
// Need the following side-effect import because in actual production code,
// Fast Fetch impls are always loaded via an AmpAd tag, which means AmpAd is
// always available for them. However, when we test an impl in isolation,
// AmpAd is not loaded already, so we need to load it separately.
import '../../../amp-ad/0.1/amp-ad';
import {AMP_EXPERIMENT_ATTRIBUTE, QQID_HEADER} from '#ads/google/a4a/utils';
import {
CONSENT_POLICY_STATE,
CONSENT_STRING_TYPE,
} from '#core/constants/consent-state';
import {Deferred} from '#core/data-structures/promise';
import {createElementWithAttributes} from '#core/dom';
import {Layout_Enum} from '#core/dom/layout';
import * as bytesUtils from '#core/types/string/bytes';
import {toggleExperiment} from '#experiments';
import {Services} from '#service';
import {FriendlyIframeEmbed} from '../../../../src/friendly-iframe-embed';
import {
AmpA4A,
CREATIVE_SIZE_HEADER,
XORIGIN_MODE,
signatureVerifierFor,
} from '../../../amp-a4a/0.1/amp-a4a';
import {
AMP_SIGNATURE_HEADER,
VerificationStatus,
} from '../../../amp-a4a/0.1/signature-verifier';
import {AmpAd} from '../../../amp-ad/0.1/amp-ad';
import {
AmpAdNetworkDoubleclickImpl,
getNetworkId,
getPageviewStateTokensForAdRequest,
resetLocationQueryParametersForTesting,
resetTokensToInstancesMap,
} from '../amp-ad-network-doubleclick-impl';
import {SafeframeHostApi} from '../safeframe-host';
/**
* We're allowing external resources because otherwise using realWin causes
* strange behavior with iframes, as it doesn't load resources that we
* normally load in prod.
* We're turning on ampAdCss because using realWin means that we don't
* inherit that CSS from the parent page anymore.
*/
const realWinConfig = {
amp: {
extensions: ['amp-ad-network-doubleclick-impl'],
},
ampAdCss: true,
allowExternalResources: true,
};
const shadowRealWinConfig = {
amp: {
extensions: ['amp-ad-network-doubleclick-impl'],
},
ampdoc: 'shadow',
ampAdCss: true,
allowExternalResources: true,
};
/**
* Creates an iframe promise, and instantiates element and impl, adding the
* former to the document of the iframe.
* @param {{width, height, type}} config
* @param {!Element} element
* @param {!AmpAdNetworkDoubleclickImpl} impl
* @param {!Object} env
* @return {!Array} The iframe promise.
*/
function createImplTag(config, element, impl, env) {
config.type = 'doubleclick';
element = createElementWithAttributes(env.win.document, 'amp-ad', config);
// To trigger CSS styling.
element.setAttribute(
'data-a4a-upgrade-type',
'amp-ad-network-doubleclick-impl'
);
// Used to test styling which is targetted at first iframe child of
// amp-ad.
const iframe = env.win.document.createElement('iframe');
element.appendChild(iframe);
env.win.document.body.appendChild(element);
impl = new AmpAdNetworkDoubleclickImpl(element);
impl.iframe = iframe;
impl.win['goog_identity_prom'] = Promise.resolve({});
return [element, impl, env];
}
for (const {config, name} of [
{
name: 'regular',
config: realWinConfig,
},
{
name: 'shadow',
config: shadowRealWinConfig,
},
]) {
describes.realWin(
'amp-ad-network-doubleclick-impl - ' + name,
config,
(env) => {
let win, doc, ampdoc;
let element;
let impl;
beforeEach(() => {
resetLocationQueryParametersForTesting();
win = env.win;
doc = win.document;
ampdoc = env.ampdoc;
});
afterEach(() => resetLocationQueryParametersForTesting);
describe('#isValidElement', () => {
beforeEach(() => {
element = doc.createElement('amp-ad');
element.setAttribute('type', 'doubleclick');
element.setAttribute('data-ad-client', 'doubleclick');
impl = new AmpAdNetworkDoubleclickImpl(element);
});
it('should be valid', () => {
expect(impl.isValidElement()).to.be.true;
});
it('should NOT be valid (impl tag name)', () => {
element = doc.createElement('amp-ad-network-doubleclick-impl');
element.setAttribute('type', 'doubleclick');
element.setAttribute('data-ad-client', 'doubleclick');
impl = new AmpAdNetworkDoubleclickImpl(element);
expect(impl.isValidElement()).to.be.false;
});
it.skip('should be NOT valid (missing ad client)', () => {
// TODO(taymonbeal): reenable this test after clarifying validation
element.setAttribute('data-ad-client', '');
element.setAttribute('type', 'doubleclick');
expect(impl.isValidElement()).to.be.false;
});
it('should be valid (amp-embed)', () => {
element = doc.createElement('amp-embed');
element.setAttribute('type', 'doubleclick');
element.setAttribute('data-ad-client', 'doubleclick');
impl = new AmpAdNetworkDoubleclickImpl(element);
expect(impl.isValidElement()).to.be.true;
});
});
describe('#extractSize', () => {
let preloadExtensionSpy;
const size = {width: 200, height: 50};
beforeEach(() => {
element = createElementWithAttributes(doc, 'amp-ad', {
'width': '200',
'height': '50',
'type': 'doubleclick',
'layout': 'fixed',
});
impl = new AmpAdNetworkDoubleclickImpl(element);
env.sandbox.stub(impl, 'getAmpDoc').callsFake(() => ampdoc);
impl.size_ = size;
const extensions = Services.extensionsFor(impl.win);
preloadExtensionSpy = env.sandbox.spy(extensions, 'preloadExtension');
});
afterEach(() => {
resetTokensToInstancesMap();
});
it('should ignore creative-size header for fluid response', () => {
impl.isFluid_ = true;
impl.element.setAttribute('height', 'fluid');
const resizeSpy = env.sandbox.spy(impl, 'attemptChangeSize');
expect(
impl.extractSize({
get(name) {
return name == CREATIVE_SIZE_HEADER ? '0x0' : undefined;
},
has(name) {
return name == CREATIVE_SIZE_HEADER;
},
})
).to.deep.equal({width: 0, height: 0});
expect(resizeSpy).to.not.be.called;
});
it('should not load amp-analytics without an analytics header', () => {
expect(
impl.extractSize({
get() {
return undefined;
},
has() {
return false;
},
})
).to.deep.equal(size);
expect(preloadExtensionSpy.withArgs('amp-analytics')).to.not.be
.called;
});
it('should load amp-analytics with an analytics header', () => {
const url = [
'https://foo.com?a=b',
'https://blah.com?lsk=sdk&sld=vj',
];
expect(
impl.extractSize({
get(name) {
switch (name) {
case 'X-AmpAnalytics':
return JSON.stringify({url});
default:
return undefined;
}
},
has(name) {
return !!this.get(name);
},
})
).to.deep.equal(size);
expect(preloadExtensionSpy.withArgs('amp-analytics')).to.be.called;
// exact value of ampAnalyticsConfig covered in
// ads/google/test/test-utils.js
});
it('should load delayed impression amp-pixels with fluid', () => {
impl.isFluidRequest_ = true;
expect(
impl.extractSize({
get(name) {
switch (name) {
case 'X-AmpImps':
return 'https://a.com?a=b,https://b.com?c=d';
default:
return undefined;
}
},
has(name) {
return !!this.get(name);
},
})
).to.deep.equal(size);
expect(impl.fluidImpressionUrl_).to.equal(
'https://a.com?a=b,https://b.com?c=d'
);
});
it('should not load delayed impression amp-pixels with fluid + multi-size', () => {
env.sandbox.stub(impl, 'handleResize_');
impl.isFluid_ = true;
expect(
impl.extractSize({
get(name) {
switch (name) {
case 'X-AmpImps':
return 'https://a.com?a=b,https://b.com?c=d';
case 'X-CreativeSize':
return '200x50';
default:
return undefined;
}
},
has(name) {
return !!this.get(name);
},
})
).to.deep.equal(size);
expect(impl.fluidImpressionUrl_).to.not.be.ok;
});
it('should consume pageview state tokens when header is present', () => {
const removePageviewStateTokenSpy = env.sandbox.spy(
impl,
'removePageviewStateToken'
);
const setPageviewStateTokenSpy = env.sandbox.spy(
impl,
'setPageviewStateToken'
);
expect(
impl.extractSize({
get(name) {
switch (name) {
case 'amp-ff-pageview-tokens':
return 'DUMMY_TOKEN';
default:
return undefined;
}
},
has(name) {
return !!this.get(name);
},
})
).to.deep.equal(size);
expect(removePageviewStateTokenSpy).to.be.calledOnce;
expect(setPageviewStateTokenSpy.withArgs('DUMMY_TOKEN')).to.be
.calledOnce;
});
it('should consume sandbox header', () => {
impl.extractSize({
get(name) {
switch (name) {
case 'amp-ff-sandbox':
return 'true';
default:
return undefined;
}
},
has(name) {
return !!this.get(name);
},
});
expect(impl.sandboxHTMLCreativeFrame()).to.be.true;
});
[
{
direction: 'ltr',
parentWidth: 300,
newWidth: 250,
margin: '-25px',
},
{
direction: 'rtl',
parentWidth: 300,
newWidth: 250,
margin: '-25px',
},
{
direction: 'ltr',
parentWidth: 300,
newWidth: 300,
margin: '-50px',
},
{
direction: 'rtl',
parentWidth: 300,
newWidth: 300,
margin: '-50px',
},
{
direction: 'ltr',
parentWidth: 300,
newWidth: 380,
margin: '-15px',
},
{
direction: 'rtl',
parentWidth: 300,
newWidth: 380,
margin: '-365px',
},
{
direction: 'ltr',
parentWidth: 300,
newWidth: 400,
margin: '-25px',
},
{
direction: 'rtl',
parentWidth: 300,
newWidth: 400,
margin: '-375px',
},
{
direction: 'ltr',
parentWidth: 300,
newWidth: 200,
margin: '',
isMultiSizeResponse: true,
},
{
direction: 'ltr',
parentWidth: 300,
newWidth: 300,
margin: '',
isAlreadyCentered: true,
},
{
direction: 'rtl',
parentWidth: 300,
newWidth: 300,
margin: '',
isAlreadyCentered: true,
},
{
direction: 'ltr',
parentWidth: 300,
newWidth: 250,
margin: '-25px',
inZIndexHoldBack: true,
},
].forEach((testCase, testNum) => {
it(`should adjust slot CSS after expanding width #${testNum}`, () => {
if (testCase.isMultiSizeResponse) {
impl.parameterSize = '320x50,200x50';
impl.isFluidPrimaryRequest_ = true;
} else {
impl.paramterSize = '200x50';
}
env.sandbox
.stub(impl, 'attemptChangeSize')
.callsFake((height, width) => {
impl.element.style.width = `${width}px`;
return {
catch: () => {},
};
});
env.sandbox.stub(impl, 'getViewport').callsFake(() => ({
getRect: () => ({width: 400}),
}));
env.sandbox.stub(impl.element, 'offsetLeft').value(25);
env.sandbox.stub(impl.element, 'offsetTop').value(25);
const dirStr = testCase.direction == 'ltr' ? 'Left' : 'Right';
impl.flexibleAdSlotData_ = {
parentWidth: testCase.parentWidth,
parentStyle: {
[`padding${dirStr}`]: '50px',
['textAlign']: testCase.isAlreadyCentered ? 'center' : 'start',
},
};
impl.win.document.body.dir = testCase.direction;
impl.inZIndexHoldBack_ = testCase.inZIndexHoldBack;
impl.extractSize({
get(name) {
switch (name) {
case 'X-CreativeSize':
return `${testCase.newWidth}x50`;
}
},
has(name) {
return !!this.get(name);
},
});
expect(impl.element.style[`margin${dirStr}`]).to.equal(
testCase.margin
);
if (!testCase.isMultiSizeResponse && testCase.inZIndexHoldBack) {
// We use a fixed '11' value for z-index.
expect(impl.element.style.zIndex).to.equal('11');
}
});
});
});
describe('#onCreativeRender', () => {
beforeEach(() => {
doc.win = env.win;
element = createElementWithAttributes(doc, 'amp-ad', {
'width': '200',
'height': '50',
'type': 'doubleclick',
});
doc.body.appendChild(element);
impl = new AmpAdNetworkDoubleclickImpl(element);
impl.getA4aAnalyticsConfig = () => {};
impl.buildCallback();
env.sandbox.stub(impl, 'getAmpDoc').callsFake(() => ampdoc);
env.sandbox
.stub(env.ampdocService, 'getAmpDoc')
.callsFake(() => ampdoc);
// Next two lines are to ensure that internal parts not relevant for this
// test are properly set.
impl.size_ = {width: 200, height: 50};
impl.iframe = impl.win.document.createElement('iframe');
// Temporary fix for local test failure.
env.sandbox
.stub(impl, 'getIntersectionElementLayoutBox')
.callsFake(() => {
return {
top: 0,
bottom: 0,
left: 0,
right: 0,
width: 320,
height: 50,
};
});
});
[true, false].forEach((exp) => {
it(
'injects amp analytics' +
(exp ? ', trigger immediate disable exp' : ''),
() => {
impl.ampAnalyticsConfig_ = {
transport: {beacon: false, xhrpost: false},
requests: {
visibility1: 'https://foo.com?hello=world',
visibility2: 'https://bar.com?a=b',
},
triggers: {
continuousVisible: {
on: 'visible',
request: ['visibility1', 'visibility2'],
visibilitySpec: {
selector: 'amp-ad',
selectionMethod: 'closest',
visiblePercentageMin: 50,
continuousTimeMin: 1000,
},
},
continuousVisibleIniLoad: {
on: 'ini-load',
selector: 'amp-ad',
selectionMethod: 'closest',
},
continuousVisibleRenderStart: {
on: 'render-start',
selector: 'amp-ad',
selectionMethod: 'closest',
},
},
};
// To placate assertion.
impl.responseHeaders_ = {
get: function (name) {
if (name == 'X-QQID') {
return 'qqid_string';
}
},
has: function (name) {
if (name == 'X-QQID') {
return true;
}
},
};
if (exp) {
impl.postAdResponseExperimentFeatures['avr_disable_immediate'] =
'1';
}
impl.onCreativeRender(false);
const ampAnalyticsElement =
impl.element.querySelector('amp-analytics');
expect(ampAnalyticsElement).to.be.ok;
expect(ampAnalyticsElement.CONFIG).jsonEqual(
impl.ampAnalyticsConfig_
);
expect(ampAnalyticsElement.getAttribute('sandbox')).to.equal(
'true'
);
expect(ampAnalyticsElement.getAttribute('trigger')).to.equal(
exp ? '' : 'immediate'
);
expect(impl.ampAnalyticsElement_).to.be.ok;
// Exact format of amp-analytics element covered in
// test/unit/test-analytics.js.
// Just ensure extensions is loaded, and analytics element appended.
}
);
});
it('should register click listener', () => {
impl.iframe = impl.win.document.createElement('iframe');
impl.win.document.body.appendChild(impl.iframe);
const adBody = impl.iframe.contentDocument.body;
let clickHandlerCalled = 0;
adBody.onclick = function (e) {
expect(e.defaultPrevented).to.be.false;
e.preventDefault(); // Make the test not actually navigate.
clickHandlerCalled++;
};
adBody.innerHTML =
'<a ' +
'href="https://f.co?CLICK_X,CLICK_Y,RANDOM">' +
'<button id="target"><button></div>';
const button = adBody.querySelector('#target');
const a = adBody.querySelector('a');
const ev1 = new Event('click', {bubbles: true});
ev1.pageX = 10;
ev1.pageY = 20;
env.sandbox.stub(impl, 'getResource').returns({
getUpgradeDelayMs: () => 1,
});
// Make sure the ad iframe (FIE) has a local URL replacements service.
const urlReplacements = Services.urlReplacementsForDoc(element);
env.sandbox
.stub(Services, 'urlReplacementsForDoc')
.withArgs(a)
.returns(urlReplacements);
impl.buildCallback();
impl.size_ = {width: 123, height: 456};
impl.onCreativeRender({customElementExtensions: []});
button.dispatchEvent(ev1);
expect(a.href).to.equal('https://f.co/?10,20,RANDOM');
expect(clickHandlerCalled).to.equal(1);
});
it('should not register click listener is amp-ad-exit', () => {
impl.iframe = impl.win.document.createElement('iframe');
impl.win.document.body.appendChild(impl.iframe);
const adBody = impl.iframe.contentDocument.body;
let clickHandlerCalled = 0;
adBody.onclick = function (e) {
expect(e.defaultPrevented).to.be.false;
e.preventDefault(); // Make the test not actually navigate.
clickHandlerCalled++;
};
adBody.innerHTML =
'<a ' +
'href="https://f.co?CLICK_X,CLICK_Y,RANDOM">' +
'<button id="target"><button></div>';
const button = adBody.querySelector('#target');
const a = adBody.querySelector('a');
const ev1 = new Event('click', {bubbles: true});
ev1.pageX = 10;
ev1.pageY = 20;
env.sandbox.stub(impl, 'getResource').returns({
getUpgradeDelayMs: () => 1,
});
impl.buildCallback();
impl.size_ = {width: 123, height: 456};
impl.onCreativeRender({customElementExtensions: ['amp-ad-exit']});
button.dispatchEvent(ev1);
expect(a.href).to.equal('https://f.co/?CLICK_X,CLICK_Y,RANDOM');
expect(clickHandlerCalled).to.equal(1);
});
it('should set iframe id and data-google-query-id attribute', () => {
impl.buildCallback();
impl.ifi_ = 3;
impl.qqid_ = 'abc';
impl.iframe = impl.win.document.createElement('iframe');
impl.size_ = {width: 123, height: 456};
impl.onCreativeRender(null);
expect(impl.element.getAttribute('data-google-query-id')).to.equal(
'abc'
);
expect(impl.iframe.id).to.equal('google_ads_iframe_3');
});
});
describe('#getAdUrl', () => {
beforeEach(() => {
element = doc.createElement('amp-ad');
element.setAttribute('type', 'doubleclick');
element.setAttribute('data-ad-client', 'doubleclick');
element.setAttribute('width', '320');
element.setAttribute('height', '50');
doc.body.appendChild(element);
impl = new AmpAdNetworkDoubleclickImpl(element);
// Temporary fix for local test failure.
env.sandbox
.stub(impl, 'getIntersectionElementLayoutBox')
.callsFake(() => {
return {
top: 0,
bottom: 0,
left: 0,
right: 0,
width: 320,
height: 50,
};
});
});
afterEach(() => {
toggleExperiment(env.win, 'dc-use-attr-for-format', false);
doc.body.removeChild(element);
env.win['ampAdGoogleIfiCounter'] = 0;
resetTokensToInstancesMap();
});
it('returns the right URL', () => {
const viewer = Services.viewerForDoc(element);
// inabox-viewer.getReferrerUrl() returns Promise<string>.
env.sandbox
.stub(viewer, 'getReferrerUrl')
.returns(Promise.resolve('http://fake.example/?foo=bar'));
const impl = new AmpAdNetworkDoubleclickImpl(element);
impl.uiHandler = {isStickyAd: () => false};
const impl2 = new AmpAdNetworkDoubleclickImpl(element);
impl.setPageviewStateToken('abc');
impl2.setPageviewStateToken('def');
impl.experimentIds = ['12345678'];
return impl.getAdUrl().then((url) => {
[
/^https:\/\/securepubads\.g\.doubleclick\.net\/gampad\/ads/,
/(\?|&)adk=\d+(&|$)/,
/(\?|&)gdfp_req=1(&|$)/,
/(\?|&)impl=ifr(&|$)/,
/(\?|&)sfv=\d+-\d+-\d+(&|$)/,
/(\?|&)sz=320x50(&|$)/,
/(\?|&)u_sd=[0-9]+(&|$)/,
/(\?|&)is_amp=3(&|$)/,
/(\?|&)amp_v=%24internalRuntimeVersion%24(&|$)/,
/(\?|&)d_imp=1(&|$)/,
/(\?|&)dt=[0-9]+(&|$)/,
/(\?|&)ifi=[0-9]+(&|$)/,
/(\?|&)adf=[0-9]+(&|$)/,
/(\?|&)c=[0-9]+(&|$)/,
/(\?|&)output=html(&|$)/,
/(\?|&)nhd=\d+(&|$)/,
/(\?|&)biw=[0-9]+(&|$)/,
/(\?|&)bih=[0-9]+(&|$)/,
/(\?|&)adx=-?[0-9]+(&|$)/,
/(\?|&)ady=-?[0-9]+(&|$)/,
/(\?|&)u_aw=[0-9]+(&|$)/,
/(\?|&)u_ah=[0-9]+(&|$)/,
/(\?|&)u_cd=(24|30)(&|$)/,
/(\?|&)u_w=[0-9]+(&|$)/,
/(\?|&)u_h=[0-9]+(&|$)/,
/(\?|&)u_tz=-?[0-9]+(&|$)/,
/(\?|&)u_his=[0-9]+(&|$)/,
/(\?|&)oid=2(&|$)/,
/(\?|&)isw=[0-9]+(&|$)/,
/(\?|&)ish=[0-9]+(&|$)/,
/(\?|&)eid=([^&]+%2C)*12345678(%2C[^&]+)*(&|$)/,
/(\?|&)url=https?%3A%2F%2F[a-zA-Z0-9.:%-]+(&|$)/,
/(\?|&)top=localhost(&|$)/,
/(\?|&)ref=http%3A%2F%2Ffake.example%2F%3Ffoo%3Dbar/,
/(\?|&)dtd=[0-9]+(&|$)/,
/(\?|&)vis=[0-5]+(&|$)/,
/(\?|&)psts=([^&]+%2C)*def(%2C[^&]+)*(&|$)/,
/(\?|&)bdt=[1-9][0-9]*(&|$)/,
].forEach((regexp) => expect(url).to.match(regexp));
});
});
it('includes psts param when there are pageview tokens', () => {
const impl = new AmpAdNetworkDoubleclickImpl(element);
const impl2 = new AmpAdNetworkDoubleclickImpl(element);
impl.uiHandler = {isStickyAd: () => false};
impl.setPageviewStateToken('abc');
impl2.setPageviewStateToken('def');
return impl.getAdUrl().then((url) => {
expect(url).to.match(/(\?|&)psts=([^&]+%2C)*def(%2C[^&]+)*(&|$)/);
expect(url).to.not.match(
/(\?|&)psts=([^&]+%2C)*abc(%2C[^&]+)*(&|$)/
);
});
});
it('does not include psts param when there are no pageview tokens', () => {
const impl = new AmpAdNetworkDoubleclickImpl(element);
new AmpAdNetworkDoubleclickImpl(element);
impl.uiHandler = {isStickyAd: () => false};
impl.setPageviewStateToken('abc');
return impl.getAdUrl().then((url) => {
expect(url).to.not.match(
/(\?|&)psts=([^&]+%2C)*abc(%2C[^&]+)*(&|$)/
);
});
});
it('handles Single Page Story Ad parameter', () => {
const impl = new AmpAdNetworkDoubleclickImpl(element);
impl.isSinglePageStoryAd_ = true;
const urlPromise = impl.getAdUrl();
expect(urlPromise).to.eventually.match(/(\?|&)spsa=\d+x\d+(&|$)/);
expect(urlPromise).to.eventually.match(/(\?|&)sz=1x1(&|$)/);
});
it('handles tagForChildDirectedTreatment', () => {
element.setAttribute('json', '{"tagForChildDirectedTreatment": 1}');
new AmpAd(element).upgradeCallback();
impl.uiHandler = {isStickyAd: () => false};
return impl.getAdUrl().then((url) => {
expect(url).to.match(/&tfcd=1&/);
});
});
describe('data-force-safeframe', () => {
const fsfRegexp = /(\?|&)fsf=1(&|$)/;
it('handles default', () => {
const impl = new AmpAdNetworkDoubleclickImpl(element);
impl.uiHandler = {isStickyAd: () => false};
return expect(impl.getAdUrl()).to.eventually.not.match(fsfRegexp);
});
it('case insensitive attribute name', () => {
element.setAttribute('data-FORCE-SafeFraMe', '1');
const impl = new AmpAdNetworkDoubleclickImpl(element);
impl.uiHandler = {isStickyAd: () => false};
return expect(impl.getAdUrl()).to.eventually.match(fsfRegexp);
});
['tRuE', 'true', 'TRUE', '1'].forEach((val) => {
it(`valid attribute: ${val}`, () => {
element.setAttribute('data-force-safeframe', val);
const impl = new AmpAdNetworkDoubleclickImpl(element);
impl.uiHandler = {isStickyAd: () => false};
return expect(impl.getAdUrl()).to.eventually.match(fsfRegexp);
});
});
[
'aTrUe',
'trueB',
'0',
'01',
'10',
'false',
'',
' true',
'true ',
' true ',
].forEach((val) => {
it(`invalid attribute: ${val}`, () => {
element.setAttribute('data-force-safeframe', val);
const impl = new AmpAdNetworkDoubleclickImpl(element);
impl.uiHandler = {isStickyAd: () => false};
return expect(impl.getAdUrl()).to.eventually.not.match(fsfRegexp);
});
});
});
it('handles categoryExclusions without targeting', () => {
element.setAttribute('json', '{"categoryExclusions": "sports"}');
new AmpAd(element).upgradeCallback();
impl.uiHandler = {isStickyAd: () => false};
return impl.getAdUrl().then((url) => {
expect(url).to.match(/&scp=excl_cat%3Dsports&/);
});
});
it('expands CLIENT_ID in targeting', () => {
element.setAttribute(
'json',
`{
"targeting": {
"cid": "CLIENT_ID(foo)"
}
}`
);
new AmpAd(element).upgradeCallback();
impl.uiHandler = {isStickyAd: () => false};
return impl.getAdUrl().then((url) => {
expect(url).to.match(/&scp=cid%3Damp-[\w-]+&/);
});
});
it('expands CLIENT_ID in targeting inside array', () => {
element.setAttribute(
'json',
`{
"targeting": {
"arr": ["cats", "CLIENT_ID(foo)"]
}
}`
);
new AmpAd(element).upgradeCallback();
impl.uiHandler = {isStickyAd: () => false};
return impl.getAdUrl().then((url) => {
expect(url).to.match(/&scp=arr%3Dcats%2Camp-[\w-]+&/);
});
});
it('has correct format when height == "auto"', () => {
element.setAttribute('height', 'auto');
new AmpAd(element).upgradeCallback();
expect(impl.element.getAttribute('height')).to.equal('auto');
impl.buildCallback();
impl.onLayoutMeasure();
return impl.getAdUrl().then((url) =>
// With exp dc-use-attr-for-format off, we can't test for specific
// numbers, but we know that the values should be numeric.
expect(url).to.match(/sz=[0-9]+x[0-9]+/)
);
});
it('has correct format when width == "auto"', () => {
element.setAttribute('width', 'auto');
new AmpAd(element).upgradeCallback();
expect(impl.element.getAttribute('width')).to.equal('auto');
impl.buildCallback();
impl.onLayoutMeasure();
return impl.getAdUrl().then((url) =>
// Ensure that "auto" doesn't appear anywhere here:
expect(url).to.match(/sz=[0-9]+x[0-9]+/)
);
});
it('has correct format with height/width override', () => {
element.setAttribute('data-override-width', '123');
element.setAttribute('data-override-height', '456');
new AmpAd(element).upgradeCallback();
impl.buildCallback();
impl.onLayoutMeasure();
return impl
.getAdUrl()
.then((url) => expect(url).to.contain('sz=123x456&'));
});
it('has correct format with height/width override and multiSize', () => {
element.setAttribute('data-override-width', '123');
element.setAttribute('data-override-height', '456');
element.setAttribute('data-multi-size', '1x2,3x4');
element.setAttribute('data-multi-size-validation', 'false');
new AmpAd(element).upgradeCallback();
impl.buildCallback();
impl.onLayoutMeasure();
return impl
.getAdUrl()
.then((url) => expect(url).to.contain('sz=123x456%7C1x2%7C3x4&'));
});
it('has correct format with auto height/width and multiSize', () => {
element.setAttribute('data-override-width', '123');
element.setAttribute('data-override-height', '456');
element.setAttribute('data-multi-size', '1x2,3x4');
element.setAttribute('data-multi-size-validation', 'false');
new AmpAd(element).upgradeCallback();
impl.buildCallback();
impl.onLayoutMeasure();
return impl.getAdUrl().then((url) =>
// Ensure that "auto" doesn't appear anywhere here:
expect(url).to.match(/sz=[0-9]+x[0-9]+%7C1x2%7C3x4&/)
);
});
it('has correct sz with fluid as multi-size', () => {
element.setAttribute('width', '300');
element.setAttribute('height', '250');
element.setAttribute('data-multi-size', 'fluid');
new AmpAd(element).upgradeCallback();
impl.buildCallback();
impl.onLayoutMeasure();
return impl
.getAdUrl()
.then((url) => expect(url).to.match(/sz=320x50%7C300x250&/));
});
it('should have the correct ifi numbers - no refresh', function () {
// When ran locally, this test tends to exceed 2000ms timeout.
this.timeout(5000);
// Reset counter for purpose of this test.
delete env.win['ampAdGoogleIfiCounter'];
new AmpAd(element).upgradeCallback();
env.sandbox
.stub(AmpA4A.prototype, 'tearDownSlot')
.callsFake(() => {});
impl.uiHandler = {isStickyAd: () => false};
return impl.getAdUrl().then((url1) => {
expect(url1).to.match(/ifi=1/);
impl.tearDownSlot();
return impl.getAdUrl().then((url2) => {
expect(url2).to.match(/ifi=2/);
impl.tearDownSlot();
return impl.getAdUrl().then((url3) => {
expect(url3).to.match(/ifi=3/);
});
});
});
});
it('should have google_preview parameter', () => {
env.sandbox
.stub(impl, 'getLocationQueryParameterValue')
.withArgs('google_preview')
.returns('abcdef');
new AmpAd(element).upgradeCallback();
expect(impl.getAdUrl()).to.eventually.contain('&gct=abcdef');
});
it('should cache getLocationQueryParameterValue', () => {
impl.win = {location: {search: '?foo=bar'}};
expect(impl.getLocationQueryParameterValue('foo')).to.equal('bar');
impl.win.location.search = '?foo=bar2';
expect(impl.getLocationQueryParameterValue('foo')).to.equal('bar');
});
// TODO(bradfrizzell, #12476): Make this test work with sinon 4.0.
it.skip('has correct rc and ifi after refresh', () => {
// We don't really care about the behavior of the following methods, so
// we'll just stub them out so that refresh() can run without tripping any
// unrelated errors.
env.sandbox
.stub(AmpA4A.prototype, 'initiateAdRequest')
.callsFake(() => (impl.adPromise_ = Promise.resolve()));
const tearDownSlotMock = env.sandbox.stub(
AmpA4A.prototype,
'tearDownSlot'
);
tearDownSlotMock.returns(undefined);
const destroyFrameMock = env.sandbox.stub(
AmpA4A.prototype,
'destroyFrame'
);
destroyFrameMock.returns(undefined);
impl.mutateElement = (func) => func();
impl.togglePlaceholder = env.sandbox.spy();
impl.win.document.win = impl.win;
impl.getAmpDoc = () => impl.win.document;
impl.getResource = () => {
return {
layoutCanceled: () => {},
};
};
new AmpAd(element).upgradeCallback();
return impl.getAdUrl().then((url1) => {
expect(url1).to.not.match(/(\?|&)rc=[0-9]+(&|$)/);
expect(url1).to.match(/(\?|&)ifi=1(&|$)/);
return impl
.refresh(() => {})
.then(() => {
return impl.getAdUrl().then((url2) => {
expect(url2).to.match(/(\?|&)rc=1(&|$)/);
expect(url1).to.match(/(\?|&)ifi=1(&|$)/);
});
});
});
});
it('should include identity', () => {
// Force get identity result by overloading window variable.
const token =
/**@type {!../../../ads/google/a4a/utils.IdentityToken}*/ ({
token: 'abcdef',
jar: 'some_jar',
pucrd: 'some_pucrd',
});
impl.win['goog_identity_prom'] = Promise.resolve(token);
impl.buildCallback();
return impl.getAdUrl().then((url) => {
[
/(\?|&)adsid=abcdef(&|$)/,
/(\?|&)jar=some_jar(&|$)/,
/(\?|&)pucrd=some_pucrd(&|$)/,
].forEach((regexp) => expect(url).to.match(regexp));
});
});
it('should return empty string if unknown consentState', () =>
impl
.getAdUrl({consentState: CONSENT_POLICY_STATE.UNKNOWN})
.then((url) => {
expect(url).equal('');
return expect(impl.getAdUrlDeferred.promise).to.eventually.equal(
''
);
}));
it('should include npa=1 if unknown consent & explicit npa', () => {
impl.element.setAttribute('data-npa-on-unknown-consent', 'true');
impl.uiHandler = {isStickyAd: () => false};
return impl
.getAdUrl({consentState: CONSENT_POLICY_STATE.UNKNOWN})
.then((url) => {
expect(url).to.match(/(\?|&)npa=1(&|$)/);
});
});
it('should include npa=1 if insufficient consent', () => {
impl.uiHandler = {isStickyAd: () => false};
return impl
.getAdUrl({consentState: CONSENT_POLICY_STATE.INSUFFICIENT})
.then((url) => {
expect(url).to.match(/(\?|&)npa=1(&|$)/);
});
});
it('should not include npa, if sufficient consent', () => {
impl.uiHandler = {isStickyAd: () => false};
return impl
.getAdUrl({consentState: CONSENT_POLICY_STATE.SUFFICIENT})
.then((url) => {
expect(url).to.not.match(/(\?|&)npa=(&|$)/);
});
});
it('should not include npa, if not required consent', () => {
impl.uiHandler = {isStickyAd: () => false};
return impl
.getAdUrl({consentState: CONSENT_POLICY_STATE.UNKNOWN_NOT_REQUIRED})
.then((url) => {
expect(url).to.not.match(/(\?|&)npa=(&|$)/);
});
});
it('should save opt_serveNpaSignal', () => {
impl.uiHandler = {isStickyAd: () => false};
return impl
.getAdUrl(
{consentState: CONSENT_POLICY_STATE.SUFFICIENT},
undefined,
true
)
.then(() => {
expect(impl.serveNpaSignal_).to.be.true;
});
});
it('should include npa=1 if `serveNpaSignal` is found, regardless of consent', () => {
impl.uiHandler = {isStickyAd: () => false};
return impl
.getAdUrl(
{consentState: CONSENT_POLICY_STATE.SUFFICIENT},
undefined,
true
)
.then((url) => {
expect(url).to.match(/(\?|&)npa=1(&|$)/);
});
});
it('should include npa=1 if `serveNpaSignal` is false & insufficient consent', () => {
impl.uiHandler = {isStickyAd: () => false};
return impl
.getAdUrl(
{consentState: CONSENT_POLICY_STATE.INSUFFICIENT},
undefined,
false
)
.then((url) => {
expect(url).to.match(/(\?|&)npa=1(&|$)/);
});
});
it('should include gdpr_consent, if TC String is provided', () => {
impl.uiHandler = {isStickyAd: () => false};
return impl.getAdUrl({consentString: 'tcstring'}).then((url) => {
expect(url).to.match(/(\?|&)gdpr_consent=tcstring(&|$)/);
});
});
it('should include gdpr=1, if gdprApplies is true', () => {
impl.uiHandler = {isStickyAd: () => false};
return impl.getAdUrl({gdprApplies: true}).then((url) => {
expect(url).to.match(/(\?|&)gdpr=1(&|$)/);
});
});
it('should include gdpr=0, if gdprApplies is false', () => {
impl.uiHandler = {isStickyAd: () => false};
return impl.getAdUrl({gdprApplies: false}).then((url) => {
expect(url).to.match(/(\?|&)gdpr=0(&|$)/);
});
});
it('should not include gdpr, if gdprApplies is missing', () => {
impl.uiHandler = {isStickyAd: () => false};
return impl.getAdUrl({}).then((url) => {
expect(url).to.not.match(/(\?|&)gdpr=(&|$)/);
});
});
it('should include addtl_consent', () => {
impl.uiHandler = {isStickyAd: () => false};
return impl.getAdUrl({additionalConsent: 'abc123'}).then((url) => {
expect(url).to.match(/(\?|&)addtl_consent=abc123(&|$)/);
});
});
it('should not include addtl_consent, if additionalConsent is missing', () => {
impl.uiHandler = {isStickyAd: () => false};
return impl.getAdUrl({}).then((url) => {
expect(url).to.not.match(/(\?|&)addtl_consent=/);
});
});
it('should include us_privacy, if consentStringType matches', () => {
impl.uiHandler = {isStickyAd: () => false};
return impl
.getAdUrl({
consentStringType: CONSENT_STRING_TYPE.US_PRIVACY_STRING,
consentString: 'usPrivacyString',
})
.then((url) => {
expect(url).to.match(/(\?|&)us_privacy=usPrivacyString(&|$)/);
expect(url).to.not.match(/(\?|&)gdpr_consent=/);
});
});
it('should include gdpr_consent, if consentStringType is not US_PRIVACY_STRING', () => {
impl.uiHandler = {isStickyAd: () => false};
return impl
.getAdUrl({
consentStringType: CONSENT_STRING_TYPE.TCF_V2,
consentString: 'gdprString',
})
.then((url) => {
expect(url).to.match(/(\?|&)gdpr_consent=gdprString(&|$)/);
expect(url).to.not.match(/(\?|&)us_privacy=/);
});
});
it('should include gdpr_consent, if consentStringType is undefined', () => {
impl.uiHandler = {isStickyAd: () => false};
return impl
.getAdUrl({
consentStringType: undefined,
consentString: 'gdprString',
})
.then((url) => {
expect(url).to.match(/(\?|&)gdpr_consent=gdprString(&|$)/);
expect(url).to.not.match(/(\?|&)us_privacy=/);
});
});
it('should include msz/psz/fws if in holdback control', () => {
env.sandbox
.stub(impl, 'randomlySelectUnsetExperiments_')
.returns({flexAdSlots: '21063173'});
impl.uiHandler = {isStickyAd: () => false};
impl.setPageLevelExperiments();
return impl.getAdUrl().then((url) => {
expect(url).to.match(/(\?|&)msz=[0-9]+x-1(&|$)/);
expect(url).to.match(/(\?|&)psz=[0-9]+x-1(&|$)/);
expect(url).to.match(/(\?|&)fws=[0-9]+(&|$)/);
expect(url).to.match(/(=|%2C)21063173(%2C|&|$)/);
});
});
it('should include msz/psz by default', () => {
impl.uiHandler = {isStickyAd: () => false};
return impl.getAdUrl().then((url) => {
expect(url).to.match(/(\?|&)msz=[0-9]+x-1(&|$)/);
expect(url).to.match(/(\?|&)psz=[0-9]+x-1(&|$)/);
expect(url).to.match(/(\?|&)fws=[0-9]+(&|$)/);
expect(url).to.not.match(/(=|%2C)2106317(3|4)(%2C|&|$)/);
});
});
it('sets ptt parameter', () => {
impl.uiHandler = {isStickyAd: () => false};
return expect(impl.getAdUrl()).to.eventually.match(
/(\?|&)ptt=13(&|$)/
);
});
it('should set ppid parameter if set in json', () => {
impl.uiHandler = {isStickyAd: () => false};
element.setAttribute('json', '{"ppid": "testId"}');
return expect(impl.getAdUrl()).to.eventually.match(
/(\?|&)ppid=testId(&|$)/
);
});
});
describe('#getPageParameters', () => {
it('should include npa=1 for insufficient consent', () => {
const element = createElementWithAttributes(doc, 'amp-ad', {
type: 'doubleclick',
height: 320,
width: 50,
'data-slot': '/1234/abc/def',
});
const impl = new AmpAdNetworkDoubleclickImpl(element);
expect(
impl.getPageParameters({
consentState: CONSENT_POLICY_STATE.INSUFFICIENT,
}).npa
).to.equal(1);
});
it('should include npa=1 when `serveNpaSignal_` is true', () => {
const element = createElementWithAttributes(doc, 'amp-ad', {
type: 'doubleclick',
height: 320,
width: 50,
'data-slot': '/1234/abc/def',
'always-serve-npa': 'gdpr',
});
const impl = new AmpAdNetworkDoubleclickImpl(element);
impl.serveNpaSignal_ = true;
expect(
impl.getPageParameters({
consentState: CONSENT_POLICY_STATE.SUFFICIENT,
}).npa
).to.equal(1);
});
});
describe('#unlayoutCallback', () => {
beforeEach(() => {
const setup = createImplTag(
{
width: '300',
height: '150',
},
element,
impl,
env
);
element = setup[0];
impl = setup[1];
env = setup[2];
impl.buildCallback();
impl.win.ampAdSlotIdCounter = 1;
expect(impl.element.getAttribute('data-amp-slot-index')).to.not.be.ok;
impl.layoutMeasureExecuted_ = true;
impl.uiHandler = {applyUnlayoutUI: () => {}, cleanup: () => {}};
const placeholder = doc.createElement('div');
placeholder.setAttribute('placeholder', '');
const fallback = doc.createElement('div');
fallback.setAttribute('fallback', '');
impl.element.appendChild(placeholder);
impl.element.appendChild(fallback);
impl.size_ = {width: 123, height: 456};
});
afterEach(() => env.sandbox.restore());
it('should reset state to null on non-FIE unlayoutCallback', () => {
impl.onCreativeRender();
expect(impl.unlayoutCallback()).to.be.true;
expect(impl.iframe).is.not.ok;
});
it('should not reset state to null on FIE unlayoutCallback', () => {
impl.onCreativeRender({customElementExtensions: []});
expect(impl.unlayoutCallback()).to.be.false;
expect(impl.iframe).is.ok;
});
it('should call #resetSlot, remove child iframe, but keep other children', () => {
impl.ampAnalyticsConfig_ = {};
impl.ampAnalyticsElement_ = doc.createElement('amp-analytics');
impl.element.appendChild(impl.ampAnalyticsElement_);
expect(impl.iframe).to.be.ok;
expect(impl.element.querySelector('iframe')).to.be.ok;
impl.unlayoutCallback();
expect(impl.element.querySelector('div[placeholder]')).to.be.ok;
expect(impl.element.querySelector('div[fallback]')).to.be.ok;
expect(impl.element.querySelector('iframe')).to.be.null;
expect(
impl.element.querySelectorAll('amp-analytics')
).to.have.lengthOf(1);
expect(impl.element.querySelector('amp-analytics')).to.equal(
impl.a4aAnalyticsElement_
);
expect(impl.iframe).to.be.null;
expect(impl.ampAnalyticsConfig_).to.be.null;
expect(impl.ampAnalyticsElement_).to.be.null;
expect(impl.element.getAttribute('data-amp-slot-index')).to.equal(
'1'
);
});
it('should call #unobserve on refreshManager', () => {
impl.refreshManager_ = {
unobserve: env.sandbox.spy(),
};
impl.unlayoutCallback();
expect(impl.refreshManager_.unobserve).to.be.calledOnce;
});
});
describe('#getNetworkId', () => {
let element;
it('should match expectations', () => {
element = doc.createElement('amp-ad');
const testValues = {
'/1234/abc/def': '1234',
'1234/abc/def': '1234',
'/a1234/abc/def': '',
'a1234/abc/def': '',
'789': '789',
'//789': '',
};
Object.keys(testValues).forEach((slotName) => {
element.setAttribute('data-slot', slotName);
expect(getNetworkId(element)).to.equal(testValues[slotName]);
});
});
});
describe('#delayAdRequestEnabled', () => {
it('should return false', () => {
expect(impl.delayAdRequestEnabled()).to.be.false;
});
it('should not respect loading strategy', () => {
impl.element.setAttribute(
'data-loading-strategy',
'prefer-viewability-over-views'
);
expect(impl.delayAdRequestEnabled()).to.be.false;
});
it('should respect loading strategy if fetch attribute present', () => {
impl.element.setAttribute(
'data-loading-strategy',
'prefer-viewability-over-views'
);
impl.element.setAttribute('data-lazy-fetch', 'true');
expect(impl.delayAdRequestEnabled()).to.equal(1.25);
});
it('should NOT delay due to non-true fetch attribute', () => {
impl.element.setAttribute(
'data-loading-strategy',
'prefer-viewability-over-views'
);
impl.element.setAttribute('data-lazy-fetch', 'false');
expect(impl.delayAdRequestEnabled()).to.be.false;
});
});
describe('#multi-size', () => {
/**
* Calling this function ensures that the enclosing test will behave as if
* it has an AMP creative.
*/
function stubForAmpCreative() {
env.sandbox
.stub(signatureVerifierFor(impl.win), 'verify')
.callsFake(() => Promise.resolve(VerificationStatus.OK));
}
/**
* @param {{width: number, height: number}} size
* @param {boolean} isAmpCreative
*/
function mockSendXhrRequest(size, isAmpCreative) {
return {
arrayBuffer: () =>
Promise.resolve(
bytesUtils.utf8Encode('<html><body>Hello, World!</body></html>')
),
headers: {
get(prop) {
switch (prop) {
case QQID_HEADER:
return 'qqid-header';
case CREATIVE_SIZE_HEADER:
return size;
case AMP_SIGNATURE_HEADER:
return isAmpCreative ? 'fake-sig' : undefined;
default:
return undefined;
}
},
has(prop) {
return !!this.get(prop);
},
},
};
}
beforeEach(() => {
element = createElementWithAttributes(doc, 'amp-ad', {
'width': '200',
'height': '50',
'type': 'doubleclick',
'layout': 'fixed',
});
doc.body.appendChild(element);
impl = new AmpAdNetworkDoubleclickImpl(element);
impl.initialSize_ = {width: 200, height: 50};
impl.uiHandler = {isStickyAd: () => false};
// Boilerplate stubbing
env.sandbox
.stub(impl, 'shouldInitializePromiseChain_')
.callsFake(() => true);
env.sandbox
.stub(impl, 'attemptChangeSize')
.callsFake((height, width) => {
impl.element.style.height = `${height}px`;
impl.element.style.width = `${width}px`;
return Promise.resolve();
});
env.sandbox.stub(impl, 'getAmpAdMetadata').callsFake(() => {
return {
customElementExtensions: [],
minifiedCreative: '<html><body>Hello, World!</body></html>',
};
});
env.sandbox.stub(impl, 'updateLayoutPriority').callsFake(() => {});
const keyResponse = {
body: {'keys': []},
headers: {'Content-Type': 'application/jwk-set+json'},
};
env.expectFetch(
'https://cdn.ampproject.org/amp-ad-verifying-keyset.json',
keyResponse
);
env.expectFetch(
'https://cdn.ampproject.org/amp-ad-verifying-keyset-dev.json',
keyResponse
);
});
it('amp creative - should force iframe to match size of creative', () => {
stubForAmpCreative();
env.sandbox
.stub(impl, 'sendXhrRequest')
.returns(mockSendXhrRequest('150x50', true));
// Stub ini load otherwise FIE could delay test
env.sandbox
./*OK*/ stub(FriendlyIframeEmbed.prototype, 'whenIniLoaded')
.returns(Promise.resolve());
impl.buildCallback();
impl.onLayoutMeasure();
return impl.layoutCallback().then(() => {
const {iframe} = impl;
expect(iframe).to.be.ok;
expect(iframe.getAttribute('style')).to.match(/width: 150/);
expect(iframe.getAttribute('style')).to.match(/height: 50/);
});
});
it('should force iframe to match size of creative', () => {
env.sandbox
.stub(impl, 'sendXhrRequest')
.returns(mockSendXhrRequest('150x50', false));
impl.buildCallback();
impl.onLayoutMeasure();
return impl.layoutCallback().then(() => {
const {iframe} = impl;
expect(iframe).to.be.ok;
expect(iframe.getAttribute('style')).to.match(/width: 150/);
expect(iframe.getAttribute('style')).to.match(/height: 50/);
});
});
it('should center iframe if narrower than ad slot', () => {
env.sandbox
.stub(impl, 'sendXhrRequest')
.returns(mockSendXhrRequest('150x50', false));
impl.buildCallback();
impl.onLayoutMeasure();
return impl.layoutCallback().then(() => {
const {iframe} = impl;
expect(iframe).to.be.ok;
expect(iframe.getAttribute('style')).to.match(/left: 50%/);
expect(iframe.getAttribute('style')).to.match(/top: 50%/);
expect(iframe.getAttribute('style')).to.match(
/transform: translate\(-50%\, -50%\)/
);
});
});
it('should not center iframe if narrower than slot but is fluid', () => {
env.sandbox
.stub(impl, 'sendXhrRequest')
.returns(mockSendXhrRequest('0x0', false));
impl.buildCallback();
impl.onLayoutMeasure();
return impl.layoutCallback().then(() => {
const {iframe} = impl;
expect(iframe).to.be.ok;
expect(iframe.getAttribute('style')).to.not.match(/left: 50%/);
expect(iframe.getAttribute('style')).to.not.match(/top: 50%/);
expect(iframe.getAttribute('style')).to.not.match(
/transform: translate\(-50%\, -50%\)/
);
});
});
it('should not center iframe if same size as ad slot', () => {
env.sandbox
.stub(impl, 'sendXhrRequest')
.returns(mockSendXhrRequest('200x50', false));
impl.buildCallback();
impl.onLayoutMeasure();
return impl.layoutCallback().then(() => {
const {iframe} = impl;
expect(iframe).to.be.ok;
expect(iframe.getAttribute('style')).to.not.match(/left: 50%/);
expect(iframe.getAttribute('style')).to.not.match(/top: 50%/);
expect(iframe.getAttribute('style')).to.not.match(
/transform: translate\(-50%\, -50%\)/
);
});
});
it('amp creative - should force iframe to match size of slot', () => {
stubForAmpCreative();
env.sandbox
.stub(impl, 'sendXhrRequest')
.callsFake(() => mockSendXhrRequest(undefined, true));
env.sandbox
.stub(impl, 'renderViaIframeGet_')
.callsFake(() =>
impl.iframeRenderHelper_({src: impl.adUrl_, name: 'name'})
);
// Stub ini load otherwise FIE could delay test
env.sandbox
./*OK*/ stub(FriendlyIframeEmbed.prototype, 'whenIniLoaded')
.returns(Promise.resolve());
// This would normally be set in AmpA4a#buildCallback.
impl.creativeSize_ = {width: 200, height: 50};
impl.buildCallback();
impl.onLayoutMeasure();
return impl.layoutCallback().then(() => {
const {iframe} = impl;
expect(iframe).to.be.ok;
expect(iframe.getAttribute('style')).to.match(/width: 200/);
expect(iframe.getAttribute('style')).to.match(/height: 50/);
});
});
it('should force iframe to match size of slot', () => {
env.sandbox
.stub(impl, 'sendXhrRequest')
.callsFake(() => mockSendXhrRequest(undefined, false));
env.sandbox
.stub(impl, 'renderViaIframeGet_')
.callsFake(() =>
impl.iframeRenderHelper_({src: impl.adUrl_, name: 'name'})
);
// This would normally be set in AmpA4a#buildCallback.
impl.creativeSize_ = {width: 200, height: 50};
impl.buildCallback();
impl.onLayoutMeasure();
return impl.layoutCallback().then(() => {
const {iframe} = impl;
expect(iframe).to.be.ok;
expect(iframe.getAttribute('style')).to.match(/width: 200/);
expect(iframe.getAttribute('style')).to.match(/height: 50/);
});
});
it('should issue an ad request even with bad multi-size data attr', () => {
stubForAmpCreative();
env.sandbox
.stub(impl, 'sendXhrRequest')
.callsFake(() => mockSendXhrRequest(undefined, true));
impl.element.setAttribute('data-multi-size', '201x50');
// Stub ini load otherwise FIE could delay test
env.sandbox
./*OK*/ stub(FriendlyIframeEmbed.prototype, 'whenIniLoaded')
.returns(Promise.resolve());
impl.buildCallback();
impl.onLayoutMeasure();
return impl.layoutCallback().then(() => {
expect(impl.adUrl_).to.be.ok;
expect(impl.adUrl_.length).to.be.ok;
});
});
it('should attempt resize for fluid request + fixed response case', () => {
impl.isFluidRequest_ = true;
impl.handleResize_(150, 50);
expect(impl.element.getAttribute('style')).to.match(/width: 150/);
expect(impl.element.getAttribute('style')).to.match(/height: 50/);
});
});
describe('Troubleshoot for AMP pages', () => {
beforeEach(() => {
element = doc.createElement('amp-ad');
element.setAttribute('type', 'doubleclick');
doc.body.appendChild(element);
impl = new AmpAdNetworkDoubleclickImpl(element);
impl.troubleshootData_ = {
adUrl: Promise.resolve('http://www.getmesomeads.com'),
creativeId: '123',
lineItemId: '456',
slotId: 'slotId',
slotIndex: '0',
};
});
afterEach(() => {
doc.body.removeChild(element);
});
it('should emit post message', () => {
const slotId = 'slotId';
env.win = {
location: {
href: 'http://localhost:8000/foo?dfpdeb',
search: '?dfpdeb',
},
opener: {
postMessage: (payload) => {
expect(payload).to.be.ok;
expect(payload.userAgent).to.be.ok;
expect(payload.referrer).to.be.ok;
expect(payload.messageType).to.equal('LOAD');
const gutData = JSON.parse(payload.gutData);
expect(gutData).to.be.ok;
expect(gutData.events[0].timestamp).to.be.ok;
expect(gutData.events[0].slotid).to.equal(slotId + '_0');
expect(gutData.events[0].messageId).to.equal(4);
expect(gutData.slots[0].contentUrl).to.equal(
'http://www.getmesomeads.com'
);
expect(gutData.slots[0].id).to.equal(slotId + '_0');
expect(gutData.slots[0].leafAdUnitName).to.equal(slotId);
expect(gutData.slots[0].domId).to.equal(slotId + '_0');
expect(gutData.slots[0].creativeId).to.equal('123');
expect(gutData.slots[0].lineItemId).to.equal('456');
},
},
};
const postMessageSpy = env.sandbox.spy(env.win.opener, 'postMessage');
impl.win = env.win;
return impl
.postTroubleshootMessage()
.then(() => expect(postMessageSpy).to.be.calledOnce);
});
it('should not emit post message', () => {
env.win = {
location: {
href: 'http://localhost:8000/foo',
search: '',
},
opener: {
postMessage: () => {
// should never get here
expect(false).to.be.true;
},
},
};
impl.win = env.win;
expect(impl.postTroubleshootMessage()).to.be.null;
});
});
describe('#getNonAmpCreativeRenderingMethod', () => {
beforeEach(() => {
element = doc.createElement('amp-ad');
element.setAttribute('type', 'doubleclick');
doc.body.appendChild(element);
impl = new AmpAdNetworkDoubleclickImpl(element);
});
afterEach(() => {
doc.body.removeChild(element);
});
it('should return safeframe if fluid', () => {
impl.isLayoutSupported(Layout_Enum.FLUID);
expect(impl.getNonAmpCreativeRenderingMethod()).to.equal(
XORIGIN_MODE.SAFEFRAME
);
});
it('should return safeframe if force safeframe', () => {
element.setAttribute('data-force-safeframe', '1');
expect(
new AmpAdNetworkDoubleclickImpl(
element
).getNonAmpCreativeRenderingMethod()
).to.equal(XORIGIN_MODE.SAFEFRAME);
});
});
describe('#RandomSubdomainSafeFrame', () => {
beforeEach(() => {
element = doc.createElement('amp-ad');
element.setAttribute('type', 'doubleclick');
element.setAttribute('data-ad-client', 'doubleclick');
element.setAttribute('width', '320');
element.setAttribute('height', '50');
doc.body.appendChild(element);
impl = new AmpAdNetworkDoubleclickImpl(element);
});
it('should use random subdomain when experiment is enabled', () => {
const expectedPath =
'^https:\\/\\/[\\w\\d]{32}.safeframe.googlesyndication.com' +
'\\/safeframe\\/\\d+-\\d+-\\d+\\/html\\/container\\.html$';
expect(impl.getSafeframePath()).to.match(new RegExp(expectedPath));
});
it('should use the same random subdomain for every slot on a page', () => {
const first = impl.getSafeframePath();
impl = new AmpAdNetworkDoubleclickImpl(element);
const second = impl.getSafeframePath();
expect(first).to.equal(second);
});
it('uses random subdomain if experiment is on without win.crypto', () => {
env.sandbox
.stub(bytesUtils, 'getCryptoRandomBytesArray')
.returns(null);
const expectedPath =
'^https:\\/\\/[\\w\\d]{32}.safeframe.googlesyndication.com' +
'\\/safeframe\\/\\d+-\\d+-\\d+\\/html\\/container\\.html$';
expect(impl.getSafeframePath()).to.match(new RegExp(expectedPath));
});
});
}
);
describes.realWin(
'additional amp-ad-network-doubleclick-impl - ' + name,
config,
(env) => {
let doc;
let impl;
let element;
beforeEach(() => {
doc = env.win.document;
element = createElementWithAttributes(doc, 'amp-ad', {
'width': '200',
'height': '50',
'type': 'doubleclick',
});
doc.body.appendChild(element);
impl = new AmpAdNetworkDoubleclickImpl(element);
});
describe('#onNetworkFailure', () => {
beforeEach(() => {
element = createElementWithAttributes(doc, 'amp-ad', {
'width': '200',
'height': '50',
'type': 'doubleclick',
});
impl = new AmpAdNetworkDoubleclickImpl(element);
});
it('should append error parameter', () => {
const TEST_URL = 'https://somenetwork.com/foo?hello=world&a=b';
expect(
impl.onNetworkFailure(new Error('xhr failure'), TEST_URL)
).to.jsonEqual({adUrl: TEST_URL + '&aet=n'});
});
});
describe('#fireDelayedImpressions', () => {
let isSecureStub;
beforeEach(() => {
element = createElementWithAttributes(doc, 'amp-ad', {
'width': '200',
'height': '50',
'type': 'doubleclick',
});
impl = new AmpAdNetworkDoubleclickImpl(element);
impl.getAmpDoc = () => env.ampdoc;
isSecureStub = env.sandbox.stub();
env.sandbox
.stub(Services, 'urlForDoc')
.returns({isSecure: isSecureStub});
});
it('should handle null impressions', () => {
impl.fireDelayedImpressions(null);
expect(
env.win.document.querySelectorAll('amp-pixel').length
).to.equal(0);
});
it('should not include non-https', () => {
const urls = ['http://f.com?a=b', 'https://b.net?c=d'];
isSecureStub.withArgs(urls[0]).returns(false);
isSecureStub.withArgs(urls[1]).returns(true);
impl.fireDelayedImpressions(urls.join());
expect(
env.win.document.querySelectorAll('amp-pixel').length
).to.equal(1);
expect(
env.win.document.querySelector(
`amp-pixel[src="${urls[1]}"][referrerpolicy=""]`
)
).to.be.ok;
});
it('should append amp-pixel w/o scrubReferer', () => {
const urls = ['https://f.com?a=b', 'https://b.net?c=d'];
isSecureStub.returns(true);
impl.fireDelayedImpressions(urls.join());
urls.forEach(
(url) =>
expect(
env.win.document.querySelector(
`amp-pixel[src="${url}"][referrerpolicy=""]`
)
).to.be.ok
);
});
it('should append amp-pixel with scrubReferer', () => {
const urls = ['https://f.com?a=b', 'https://b.net?c=d'];
isSecureStub.returns(true);
impl.fireDelayedImpressions(urls.join(), true);
urls.forEach(
(url) =>
expect(
env.win.document.querySelector(
`amp-pixel[src="${url}"][referrerpolicy="no-referrer"]`
)
).to.be.ok
);
});
});
describe('#idleRenderOutsideViewport', () => {
beforeEach(() => {
element = createElementWithAttributes(doc, 'amp-ad', {
'width': '200',
'height': '50',
'type': 'doubleclick',
});
impl = new AmpAdNetworkDoubleclickImpl(element);
env.sandbox
.stub(impl, 'whenWithinViewport')
.returns(Promise.resolve());
});
it('should use experiment value', () => {
impl.postAdResponseExperimentFeatures['render-idle-vp'] = '4';
expect(impl.idleRenderOutsideViewport()).to.equal(4);
expect(impl.isIdleRender_).to.be.true;
});
it('should return false if using loading strategy', () => {
impl.postAdResponseExperimentFeatures['render-idle-vp'] = '4';
impl.element.setAttribute(
'data-loading-strategy',
'prefer-viewability-over-views'
);
expect(impl.idleRenderOutsideViewport()).to.be.false;
expect(impl.isIdleRender_).to.be.false;
});
it('should return false if invalid experiment value', () => {
impl.postAdResponseExperimentFeatures['render-idle-vp'] = 'abc';
expect(impl.idleRenderOutsideViewport()).to.be.false;
});
it('should return 12 if no experiment header', () => {
expect(impl.idleRenderOutsideViewport()).to.equal(12);
});
it('should return renderOutsideViewport boolean', () => {
env.sandbox.stub(impl, 'renderOutsideViewport').returns(false);
expect(impl.idleRenderOutsideViewport()).to.be.false;
});
});
describe('idle renderNonAmpCreative', () => {
beforeEach(() => {
element = createElementWithAttributes(doc, 'amp-ad', {
'width': '200',
'height': '50',
'type': 'doubleclick',
});
impl = new AmpAdNetworkDoubleclickImpl(element);
impl.postAdResponseExperimentFeatures['render-idle-vp'] = '4';
impl.postAdResponseExperimentFeatures['render-idle-throttle'] =
'true';
env.sandbox
.stub(AmpA4A.prototype, 'renderNonAmpCreative')
.returns(Promise.resolve());
});
// TODO(jeffkaufman, #13422): this test was silently failing
it.skip('should throttle if idle render and non-AMP creative', () => {
impl.win['3pla'] = 1;
const startTime = Date.now();
return impl.renderNonAmpCreative().then(() => {
expect(Date.now() - startTime).to.be.at.least(1000);
});
});
it('should NOT throttle if idle experiment not enabled', () => {
impl.win['3pla'] = 1;
delete impl.postAdResponseExperimentFeatures['render-idle-vp'];
const startTime = Date.now();
return impl.renderNonAmpCreative().then(() => {
expect(Date.now() - startTime).to.be.at.most(50);
});
});
it('should NOT throttle if experiment throttle not enabled', () => {
impl.win['3pla'] = 1;
const startTime = Date.now();
return impl.renderNonAmpCreative().then(() => {
expect(Date.now() - startTime).to.be.at.most(50);
});
});
it('should NOT throttle if idle render and no previous', () => {
impl.win['3pla'] = 0;
const startTime = Date.now();
return impl.renderNonAmpCreative().then(() => {
expect(Date.now() - startTime).to.be.at.most(50);
});
});
});
describe('#preconnect', () => {
beforeEach(() => {
element = createElementWithAttributes(doc, 'amp-ad', {
'width': '200',
'height': '50',
'type': 'doubleclick',
});
doc.body.appendChild(element);
impl = new AmpAdNetworkDoubleclickImpl(element);
});
});
describe('#getConsentPolicy', () => {
it('should return null', () =>
expect(AmpAdNetworkDoubleclickImpl.prototype.getConsentPolicy()).to.be
.null);
});
describe('#setPageLevelExperiments', () => {
let randomlySelectUnsetExperimentsStub;
let extractUrlExperimentIdStub;
const ampdocMock = {
whenFirstVisible: () => new Deferred().promise,
getMetaByName: () => null,
};
beforeEach(() => {
randomlySelectUnsetExperimentsStub = env.sandbox.stub(
impl,
'randomlySelectUnsetExperiments_'
);
extractUrlExperimentIdStub = env.sandbox.stub(
impl,
'extractUrlExperimentId_'
);
env.sandbox
.stub(AmpA4A.prototype, 'buildCallback')
.callsFake(() => {});
env.sandbox.stub(impl, 'getAmpDoc').returns(ampdocMock);
});
afterEach(() => {
toggleExperiment(env.win, 'envDfpInvOrigDeprecated', false);
});
it('should have correctly formatted experiment map', () => {
randomlySelectUnsetExperimentsStub.returns({});
impl.buildCallback();
const experimentMap =
randomlySelectUnsetExperimentsStub.firstCall.args[0];
Object.keys(experimentMap).forEach((key) => {
expect(key).to.be.a('string');
const {branches} = experimentMap[key];
expect(branches).to.exist;
expect(branches).to.be.a('array');
branches.forEach((branch) => expect(branch).to.be.a('string'));
});
});
it('should select SRA experiments', () => {
randomlySelectUnsetExperimentsStub.returns({
doubleclickSraExp: '117152667',
});
extractUrlExperimentIdStub.returns(undefined);
impl.buildCallback();
expect(impl.experimentIds).to.include('117152667');
expect(impl.useSra).to.be.true;
});
it('should force-select SRA experiment from URL experiment ID', () => {
randomlySelectUnsetExperimentsStub.returns({});
impl.setPageLevelExperiments('8');
expect(impl.experimentIds).to.include('117152667');
});
describe('should properly limit SRA traffic', () => {
let experimentInfoMap;
beforeEach(() => {
randomlySelectUnsetExperimentsStub.returns({});
impl.setPageLevelExperiments();
// args format is call array followed by parameter array so expect
// first call, first param.
experimentInfoMap =
randomlySelectUnsetExperimentsStub.args[0][0][0];
expect(experimentInfoMap.experimentId).to.equal(
'doubleclickSraExp'
);
expect(impl.useSra).to.be.false;
});
it('should allow by default', () =>
expect(experimentInfoMap.isTrafficEligible()).to.be.true);
it('should not allow if refresh meta', () => {
doc.head.appendChild(
createElementWithAttributes(doc, 'meta', {
name: 'amp-ad-enable-refresh',
})
);
expect(experimentInfoMap.isTrafficEligible()).to.be.false;
});
it('should not allow if sra meta', () => {
doc.head.appendChild(
createElementWithAttributes(doc, 'meta', {
name: 'amp-ad-doubleclick-sra',
})
);
expect(experimentInfoMap.isTrafficEligible()).to.be.false;
});
it('should not allow if block level refresh', () => {
impl.element.setAttribute('data-enable-refresh', '');
expect(experimentInfoMap.isTrafficEligible()).to.be.false;
});
});
describe('SSR experiments', () => {
it('should include SSR experiments', () => {
env.sandbox
.stub(ampdocMock, 'getMetaByName')
.withArgs('amp-usqp')
.returns('5798237482=45,3579282=0');
randomlySelectUnsetExperimentsStub.returns({});
impl.setPageLevelExperiments();
expect(element.getAttribute(AMP_EXPERIMENT_ATTRIBUTE)).to.equal(
'579823748245,357928200'
);
});
it('should pad value to two chars', () => {
env.sandbox
.stub(ampdocMock, 'getMetaByName')
.withArgs('amp-usqp')
.returns('5798237482=1');
randomlySelectUnsetExperimentsStub.returns({});
impl.setPageLevelExperiments();
expect(element.getAttribute(AMP_EXPERIMENT_ATTRIBUTE)).to.equal(
'579823748201'
);
});
it('should ignore excessively large value', () => {
env.sandbox
.stub(ampdocMock, 'getMetaByName')
.withArgs('amp-usqp')
.returns('5798237482=100');
randomlySelectUnsetExperimentsStub.returns({});
impl.setPageLevelExperiments();
expect(element.getAttribute(AMP_EXPERIMENT_ATTRIBUTE)).to.be.null;
});
it('should ignore negative values', () => {
env.sandbox
.stub(ampdocMock, 'getMetaByName')
.withArgs('amp-usqp')
.returns('5798237482=-1');
randomlySelectUnsetExperimentsStub.returns({});
impl.setPageLevelExperiments();
expect(element.getAttribute(AMP_EXPERIMENT_ATTRIBUTE)).to.be.null;
});
it('should ignore non-number values', () => {
env.sandbox
.stub(ampdocMock, 'getMetaByName')
.withArgs('amp-usqp')
.returns('5798237482=testing');
randomlySelectUnsetExperimentsStub.returns({});
impl.setPageLevelExperiments();
expect(element.getAttribute(AMP_EXPERIMENT_ATTRIBUTE)).to.be.null;
});
});
});
describe('#getPageviewStateTokensForAdRequest', () => {
beforeEach(() => {
resetTokensToInstancesMap();
});
it(
'should return the tokens associated with instances that are not ' +
'passed to it as an argument',
() => {
const element1 = doc.createElement('amp-ad');
element1.setAttribute('type', 'doubleclick');
element1.setAttribute('data-ad-client', 'doubleclick');
const impl1 = new AmpAdNetworkDoubleclickImpl(element1);
impl1.setPageviewStateToken('DUMMY_TOKEN_1');
const element2 = doc.createElement('amp-ad');
element2.setAttribute('type', 'doubleclick');
element2.setAttribute('data-ad-client', 'doubleclick');
const impl2 = new AmpAdNetworkDoubleclickImpl(element2);
impl2.setPageviewStateToken('DUMMY_TOKEN_2');
const instances = [impl1];
expect(getPageviewStateTokensForAdRequest(instances)).to.deep.equal(
['DUMMY_TOKEN_2']
);
}
);
});
describe('#checksumVerification', () => {
it('should call super if missing Algorithm header', () => {
env.sandbox
.stub(AmpA4A.prototype, 'maybeValidateAmpCreative')
.returns(Promise.resolve('foo'));
const creative = '<html><body>This is some text</body></html>';
const mockHeaders = {
get: (key) => {
switch (key) {
case 'AMP-Verification-Checksum-Algorithm':
return 'unknown';
case 'AMP-Verification-Checksum':
return '2569076912';
default:
throw new Error(`unexpected header: ${key}`);
}
},
};
expect(
AmpAdNetworkDoubleclickImpl.prototype.maybeValidateAmpCreative(
bytesUtils.utf8Encode(creative),
mockHeaders
)
).to.eventually.equal('foo');
});
it('should properly validate checksum', () => {
const creative = '<html><body>This is some text</body></html>';
const mockHeaders = {
get: (key) => {
switch (key) {
case 'AMP-Verification-Checksum-Algorithm':
return 'djb2a-32';
case 'AMP-Verification-Checksum':
return '2569076912';
default:
throw new Error(`unexpected header: ${key}`);
}
},
};
return AmpAdNetworkDoubleclickImpl.prototype
.maybeValidateAmpCreative(
bytesUtils.utf8Encode(creative),
mockHeaders
)
.then((result) => {
expect(result).to.be.ok;
expect(bytesUtils.utf8Decode(result)).to.equal(creative);
});
});
it('should fail validation if invalid checksum', () => {
const creative = '<html><body>This is some text</body></html>';
const mockHeaders = {
get: (key) => {
switch (key) {
case 'AMP-Verification-Checksum-Algorithm':
return 'djb2a-32';
case 'AMP-Verification-Checksum':
return '12345';
default:
throw new Error(`unexpected header: ${key}`);
}
},
};
expect(
AmpAdNetworkDoubleclickImpl.prototype.maybeValidateAmpCreative(
bytesUtils.utf8Encode(creative),
mockHeaders
)
).to.eventually.not.be.ok;
});
});
describe('#getAdditionalContextMetadata', () => {
const mockSafeFrameApi = {
destroy: () => {},
getSafeframeNameAttr: () => 'sf-name',
};
beforeEach(() => {
element = createElementWithAttributes(doc, 'amp-ad', {
'width': '200',
'height': '50',
'type': 'doubleclick',
});
impl = new AmpAdNetworkDoubleclickImpl(element);
createImplTag({width: 100, height: 100}, element, impl, env);
env.sandbox
.stub(SafeframeHostApi.prototype, 'registerSafeframeHost')
.callsFake(() => {});
env.sandbox
.stub(SafeframeHostApi.prototype, 'getSafeframeNameAttr')
.callsFake(() => 'sf-name');
env.sandbox
.stub(impl, 'getCreativeSize')
.returns({width: 320, height: 50});
env.sandbox.stub(impl, 'getViewport').returns({
getSize: () => ({width: 411, height: 1500}),
getScrollLeft: () => 0,
getScrollTop: () => 0,
});
});
it('should not change safeframeApi value', () => {
impl.safeframeApi_ = mockSafeFrameApi;
impl.getAdditionalContextMetadata(/* isSafeFrame= */ true);
expect(impl.safeframeApi_).to.equal(mockSafeFrameApi);
});
it('should change safeframeApi value', () => {
impl.safeframeApi_ = mockSafeFrameApi;
impl.isRefreshing = true;
impl.getAdditionalContextMetadata(/* isSafeFrame= */ true);
expect(impl.safeframeApi_).to.not.equal(mockSafeFrameApi);
// We just want to make sure the value's changed and is not null.
expect(impl.safeframeApi_).to.be.ok;
});
});
}
);
}
| Gregable/amphtml | extensions/amp-ad-network-doubleclick-impl/0.1/test/test-amp-ad-network-doubleclick-impl.js | JavaScript | apache-2.0 | 84,517 |
DEBUG = true;
CLASS({
name: 'Account',
properties: [
{ name: 'id' },
{ name: 'status' },
{ name: 'balance', defaultValue: 0 }
],
methods: [
{
name: "setStatus",
code: function (status) {
this.status = status;
},
args: [
{ model_: 'Arg', type: 'boolean' }
]
},
{
name: "deposit",
code: function (amount) {
this.balance += amount;
return this.balance;
},
args: [
{ type: 'number' }
],
returnType: 'number',
},
{
name: "withdraw",
code: function (amount) {
this.balance -= amount;
return this.bal;
},
args: [
{ type: 'number' }
],
returnType: 'number'
}
]
});
var a = Account.create();
// Both Pass
a.setStatus(true);
a.deposit(100);
// Both Fail
a.deposit('gold coins');
a.withdraw(50);
| jlhughes/foam | demos/TypeCheck.js | JavaScript | apache-2.0 | 912 |
/**
* Copyright 2021 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// src/polyfills.js must be the first import.
import '../polyfills';
import {draw3p, init} from '../integration-lib';
import {register} from '../3p';
import {sogouad} from '../../ads/vendors/sogouad';
init(window);
register('sogouad', sogouad);
window.draw3p = draw3p;
| prateekbh/amphtml | 3p/vendors/sogouad.js | JavaScript | apache-2.0 | 902 |
if (typeof WeakMap === "undefined") {
(function() {
var defineProperty = Object.defineProperty;
var counter = Date.now() % 1e9;
var WeakMap = function() {
this.name = "__st" + (Math.random() * 1e9 >>> 0) + (counter++ + "__");
};
WeakMap.prototype = {
set: function(key, value) {
var entry = key[this.name];
if (entry && entry[0] === key) entry[1] = value; else defineProperty(key, this.name, {
value: [ key, value ],
writable: true
});
return this;
},
get: function(key) {
var entry;
return (entry = key[this.name]) && entry[0] === key ? entry[1] : undefined;
},
"delete": function(key) {
var entry = key[this.name];
if (!entry) return false;
var hasValue = entry[0] === key;
entry[0] = entry[1] = undefined;
return hasValue;
},
has: function(key) {
var entry = key[this.name];
if (!entry) return false;
return entry[0] === key;
}
};
window.WeakMap = WeakMap;
})();
}
window.ShadowDOMPolyfill = {};
(function(scope) {
"use strict";
var constructorTable = new WeakMap();
var nativePrototypeTable = new WeakMap();
var wrappers = Object.create(null);
function detectEval() {
if (typeof chrome !== "undefined" && chrome.app && chrome.app.runtime) {
return false;
}
if (navigator.getDeviceStorage) {
return false;
}
try {
var f = new Function("return true;");
return f();
} catch (ex) {
return false;
}
}
var hasEval = detectEval();
function assert(b) {
if (!b) throw new Error("Assertion failed");
}
var defineProperty = Object.defineProperty;
var getOwnPropertyNames = Object.getOwnPropertyNames;
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
function mixin(to, from) {
var names = getOwnPropertyNames(from);
for (var i = 0; i < names.length; i++) {
var name = names[i];
defineProperty(to, name, getOwnPropertyDescriptor(from, name));
}
return to;
}
function mixinStatics(to, from) {
var names = getOwnPropertyNames(from);
for (var i = 0; i < names.length; i++) {
var name = names[i];
switch (name) {
case "arguments":
case "caller":
case "length":
case "name":
case "prototype":
case "toString":
continue;
}
defineProperty(to, name, getOwnPropertyDescriptor(from, name));
}
return to;
}
function oneOf(object, propertyNames) {
for (var i = 0; i < propertyNames.length; i++) {
if (propertyNames[i] in object) return propertyNames[i];
}
}
var nonEnumerableDataDescriptor = {
value: undefined,
configurable: true,
enumerable: false,
writable: true
};
function defineNonEnumerableDataProperty(object, name, value) {
nonEnumerableDataDescriptor.value = value;
defineProperty(object, name, nonEnumerableDataDescriptor);
}
getOwnPropertyNames(window);
function getWrapperConstructor(node) {
var nativePrototype = node.__proto__ || Object.getPrototypeOf(node);
var wrapperConstructor = constructorTable.get(nativePrototype);
if (wrapperConstructor) return wrapperConstructor;
var parentWrapperConstructor = getWrapperConstructor(nativePrototype);
var GeneratedWrapper = createWrapperConstructor(parentWrapperConstructor);
registerInternal(nativePrototype, GeneratedWrapper, node);
return GeneratedWrapper;
}
function addForwardingProperties(nativePrototype, wrapperPrototype) {
installProperty(nativePrototype, wrapperPrototype, true);
}
function registerInstanceProperties(wrapperPrototype, instanceObject) {
installProperty(instanceObject, wrapperPrototype, false);
}
var isFirefox = /Firefox/.test(navigator.userAgent);
var dummyDescriptor = {
get: function() {},
set: function(v) {},
configurable: true,
enumerable: true
};
function isEventHandlerName(name) {
return /^on[a-z]+$/.test(name);
}
function isIdentifierName(name) {
return /^\w[a-zA-Z_0-9]*$/.test(name);
}
function getGetter(name) {
return hasEval && isIdentifierName(name) ? new Function("return this.__impl4cf1e782hg__." + name) : function() {
return this.__impl4cf1e782hg__[name];
};
}
function getSetter(name) {
return hasEval && isIdentifierName(name) ? new Function("v", "this.__impl4cf1e782hg__." + name + " = v") : function(v) {
this.__impl4cf1e782hg__[name] = v;
};
}
function getMethod(name) {
return hasEval && isIdentifierName(name) ? new Function("return this.__impl4cf1e782hg__." + name + ".apply(this.__impl4cf1e782hg__, arguments)") : function() {
return this.__impl4cf1e782hg__[name].apply(this.__impl4cf1e782hg__, arguments);
};
}
function getDescriptor(source, name) {
try {
return Object.getOwnPropertyDescriptor(source, name);
} catch (ex) {
return dummyDescriptor;
}
}
var isBrokenSafari = function() {
var descr = Object.getOwnPropertyDescriptor(Node.prototype, "nodeType");
return descr && !descr.get && !descr.set;
}();
function installProperty(source, target, allowMethod, opt_blacklist) {
var names = getOwnPropertyNames(source);
for (var i = 0; i < names.length; i++) {
var name = names[i];
if (name === "polymerBlackList_") continue;
if (name in target) continue;
if (source.polymerBlackList_ && source.polymerBlackList_[name]) continue;
if (isFirefox) {
source.__lookupGetter__(name);
}
var descriptor = getDescriptor(source, name);
var getter, setter;
if (allowMethod && typeof descriptor.value === "function") {
target[name] = getMethod(name);
continue;
}
var isEvent = isEventHandlerName(name);
if (isEvent) getter = scope.getEventHandlerGetter(name); else getter = getGetter(name);
if (descriptor.writable || descriptor.set || isBrokenSafari) {
if (isEvent) setter = scope.getEventHandlerSetter(name); else setter = getSetter(name);
}
defineProperty(target, name, {
get: getter,
set: setter,
configurable: descriptor.configurable,
enumerable: descriptor.enumerable
});
}
}
function register(nativeConstructor, wrapperConstructor, opt_instance) {
var nativePrototype = nativeConstructor.prototype;
registerInternal(nativePrototype, wrapperConstructor, opt_instance);
mixinStatics(wrapperConstructor, nativeConstructor);
}
function registerInternal(nativePrototype, wrapperConstructor, opt_instance) {
var wrapperPrototype = wrapperConstructor.prototype;
assert(constructorTable.get(nativePrototype) === undefined);
constructorTable.set(nativePrototype, wrapperConstructor);
nativePrototypeTable.set(wrapperPrototype, nativePrototype);
addForwardingProperties(nativePrototype, wrapperPrototype);
if (opt_instance) registerInstanceProperties(wrapperPrototype, opt_instance);
defineNonEnumerableDataProperty(wrapperPrototype, "constructor", wrapperConstructor);
wrapperConstructor.prototype = wrapperPrototype;
}
function isWrapperFor(wrapperConstructor, nativeConstructor) {
return constructorTable.get(nativeConstructor.prototype) === wrapperConstructor;
}
function registerObject(object) {
var nativePrototype = Object.getPrototypeOf(object);
var superWrapperConstructor = getWrapperConstructor(nativePrototype);
var GeneratedWrapper = createWrapperConstructor(superWrapperConstructor);
registerInternal(nativePrototype, GeneratedWrapper, object);
return GeneratedWrapper;
}
function createWrapperConstructor(superWrapperConstructor) {
function GeneratedWrapper(node) {
superWrapperConstructor.call(this, node);
}
var p = Object.create(superWrapperConstructor.prototype);
p.constructor = GeneratedWrapper;
GeneratedWrapper.prototype = p;
return GeneratedWrapper;
}
function isWrapper(object) {
return object && object.__impl4cf1e782hg__;
}
function isNative(object) {
return !isWrapper(object);
}
function wrap(impl) {
if (impl === null) return null;
assert(isNative(impl));
return impl.__wrapper8e3dd93a60__ || (impl.__wrapper8e3dd93a60__ = new (getWrapperConstructor(impl))(impl));
}
function unwrap(wrapper) {
if (wrapper === null) return null;
assert(isWrapper(wrapper));
return wrapper.__impl4cf1e782hg__;
}
function unsafeUnwrap(wrapper) {
return wrapper.__impl4cf1e782hg__;
}
function setWrapper(impl, wrapper) {
wrapper.__impl4cf1e782hg__ = impl;
impl.__wrapper8e3dd93a60__ = wrapper;
}
function unwrapIfNeeded(object) {
return object && isWrapper(object) ? unwrap(object) : object;
}
function wrapIfNeeded(object) {
return object && !isWrapper(object) ? wrap(object) : object;
}
function rewrap(node, wrapper) {
if (wrapper === null) return;
assert(isNative(node));
assert(wrapper === undefined || isWrapper(wrapper));
node.__wrapper8e3dd93a60__ = wrapper;
}
var getterDescriptor = {
get: undefined,
configurable: true,
enumerable: true
};
function defineGetter(constructor, name, getter) {
getterDescriptor.get = getter;
defineProperty(constructor.prototype, name, getterDescriptor);
}
function defineWrapGetter(constructor, name) {
defineGetter(constructor, name, function() {
return wrap(this.__impl4cf1e782hg__[name]);
});
}
function forwardMethodsToWrapper(constructors, names) {
constructors.forEach(function(constructor) {
names.forEach(function(name) {
constructor.prototype[name] = function() {
var w = wrapIfNeeded(this);
return w[name].apply(w, arguments);
};
});
});
}
scope.assert = assert;
scope.constructorTable = constructorTable;
scope.defineGetter = defineGetter;
scope.defineWrapGetter = defineWrapGetter;
scope.forwardMethodsToWrapper = forwardMethodsToWrapper;
scope.isWrapper = isWrapper;
scope.isWrapperFor = isWrapperFor;
scope.mixin = mixin;
scope.nativePrototypeTable = nativePrototypeTable;
scope.oneOf = oneOf;
scope.registerObject = registerObject;
scope.registerWrapper = register;
scope.rewrap = rewrap;
scope.setWrapper = setWrapper;
scope.unsafeUnwrap = unsafeUnwrap;
scope.unwrap = unwrap;
scope.unwrapIfNeeded = unwrapIfNeeded;
scope.wrap = wrap;
scope.wrapIfNeeded = wrapIfNeeded;
scope.wrappers = wrappers;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
function newSplice(index, removed, addedCount) {
return {
index: index,
removed: removed,
addedCount: addedCount
};
}
var EDIT_LEAVE = 0;
var EDIT_UPDATE = 1;
var EDIT_ADD = 2;
var EDIT_DELETE = 3;
function ArraySplice() {}
ArraySplice.prototype = {
calcEditDistances: function(current, currentStart, currentEnd, old, oldStart, oldEnd) {
var rowCount = oldEnd - oldStart + 1;
var columnCount = currentEnd - currentStart + 1;
var distances = new Array(rowCount);
for (var i = 0; i < rowCount; i++) {
distances[i] = new Array(columnCount);
distances[i][0] = i;
}
for (var j = 0; j < columnCount; j++) distances[0][j] = j;
for (var i = 1; i < rowCount; i++) {
for (var j = 1; j < columnCount; j++) {
if (this.equals(current[currentStart + j - 1], old[oldStart + i - 1])) distances[i][j] = distances[i - 1][j - 1]; else {
var north = distances[i - 1][j] + 1;
var west = distances[i][j - 1] + 1;
distances[i][j] = north < west ? north : west;
}
}
}
return distances;
},
spliceOperationsFromEditDistances: function(distances) {
var i = distances.length - 1;
var j = distances[0].length - 1;
var current = distances[i][j];
var edits = [];
while (i > 0 || j > 0) {
if (i == 0) {
edits.push(EDIT_ADD);
j--;
continue;
}
if (j == 0) {
edits.push(EDIT_DELETE);
i--;
continue;
}
var northWest = distances[i - 1][j - 1];
var west = distances[i - 1][j];
var north = distances[i][j - 1];
var min;
if (west < north) min = west < northWest ? west : northWest; else min = north < northWest ? north : northWest;
if (min == northWest) {
if (northWest == current) {
edits.push(EDIT_LEAVE);
} else {
edits.push(EDIT_UPDATE);
current = northWest;
}
i--;
j--;
} else if (min == west) {
edits.push(EDIT_DELETE);
i--;
current = west;
} else {
edits.push(EDIT_ADD);
j--;
current = north;
}
}
edits.reverse();
return edits;
},
calcSplices: function(current, currentStart, currentEnd, old, oldStart, oldEnd) {
var prefixCount = 0;
var suffixCount = 0;
var minLength = Math.min(currentEnd - currentStart, oldEnd - oldStart);
if (currentStart == 0 && oldStart == 0) prefixCount = this.sharedPrefix(current, old, minLength);
if (currentEnd == current.length && oldEnd == old.length) suffixCount = this.sharedSuffix(current, old, minLength - prefixCount);
currentStart += prefixCount;
oldStart += prefixCount;
currentEnd -= suffixCount;
oldEnd -= suffixCount;
if (currentEnd - currentStart == 0 && oldEnd - oldStart == 0) return [];
if (currentStart == currentEnd) {
var splice = newSplice(currentStart, [], 0);
while (oldStart < oldEnd) splice.removed.push(old[oldStart++]);
return [ splice ];
} else if (oldStart == oldEnd) return [ newSplice(currentStart, [], currentEnd - currentStart) ];
var ops = this.spliceOperationsFromEditDistances(this.calcEditDistances(current, currentStart, currentEnd, old, oldStart, oldEnd));
var splice = undefined;
var splices = [];
var index = currentStart;
var oldIndex = oldStart;
for (var i = 0; i < ops.length; i++) {
switch (ops[i]) {
case EDIT_LEAVE:
if (splice) {
splices.push(splice);
splice = undefined;
}
index++;
oldIndex++;
break;
case EDIT_UPDATE:
if (!splice) splice = newSplice(index, [], 0);
splice.addedCount++;
index++;
splice.removed.push(old[oldIndex]);
oldIndex++;
break;
case EDIT_ADD:
if (!splice) splice = newSplice(index, [], 0);
splice.addedCount++;
index++;
break;
case EDIT_DELETE:
if (!splice) splice = newSplice(index, [], 0);
splice.removed.push(old[oldIndex]);
oldIndex++;
break;
}
}
if (splice) {
splices.push(splice);
}
return splices;
},
sharedPrefix: function(current, old, searchLength) {
for (var i = 0; i < searchLength; i++) if (!this.equals(current[i], old[i])) return i;
return searchLength;
},
sharedSuffix: function(current, old, searchLength) {
var index1 = current.length;
var index2 = old.length;
var count = 0;
while (count < searchLength && this.equals(current[--index1], old[--index2])) count++;
return count;
},
calculateSplices: function(current, previous) {
return this.calcSplices(current, 0, current.length, previous, 0, previous.length);
},
equals: function(currentValue, previousValue) {
return currentValue === previousValue;
}
};
scope.ArraySplice = ArraySplice;
})(window.ShadowDOMPolyfill);
(function(context) {
"use strict";
var OriginalMutationObserver = window.MutationObserver;
var callbacks = [];
var pending = false;
var timerFunc;
function handle() {
pending = false;
var copies = callbacks.slice(0);
callbacks = [];
for (var i = 0; i < copies.length; i++) {
(0, copies[i])();
}
}
if (OriginalMutationObserver) {
var counter = 1;
var observer = new OriginalMutationObserver(handle);
var textNode = document.createTextNode(counter);
observer.observe(textNode, {
characterData: true
});
timerFunc = function() {
counter = (counter + 1) % 2;
textNode.data = counter;
};
} else {
timerFunc = window.setImmediate || window.setTimeout;
}
function setEndOfMicrotask(func) {
callbacks.push(func);
if (pending) return;
pending = true;
timerFunc(handle, 0);
}
context.setEndOfMicrotask = setEndOfMicrotask;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var setEndOfMicrotask = scope.setEndOfMicrotask;
var wrapIfNeeded = scope.wrapIfNeeded;
var wrappers = scope.wrappers;
var registrationsTable = new WeakMap();
var globalMutationObservers = [];
var isScheduled = false;
function scheduleCallback(observer) {
if (observer.scheduled_) return;
observer.scheduled_ = true;
globalMutationObservers.push(observer);
if (isScheduled) return;
setEndOfMicrotask(notifyObservers);
isScheduled = true;
}
function notifyObservers() {
isScheduled = false;
while (globalMutationObservers.length) {
var notifyList = globalMutationObservers;
globalMutationObservers = [];
notifyList.sort(function(x, y) {
return x.uid_ - y.uid_;
});
for (var i = 0; i < notifyList.length; i++) {
var mo = notifyList[i];
mo.scheduled_ = false;
var queue = mo.takeRecords();
removeTransientObserversFor(mo);
if (queue.length) {
mo.callback_(queue, mo);
}
}
}
}
function MutationRecord(type, target) {
this.type = type;
this.target = target;
this.addedNodes = new wrappers.NodeList();
this.removedNodes = new wrappers.NodeList();
this.previousSibling = null;
this.nextSibling = null;
this.attributeName = null;
this.attributeNamespace = null;
this.oldValue = null;
}
function registerTransientObservers(ancestor, node) {
for (;ancestor; ancestor = ancestor.parentNode) {
var registrations = registrationsTable.get(ancestor);
if (!registrations) continue;
for (var i = 0; i < registrations.length; i++) {
var registration = registrations[i];
if (registration.options.subtree) registration.addTransientObserver(node);
}
}
}
function removeTransientObserversFor(observer) {
for (var i = 0; i < observer.nodes_.length; i++) {
var node = observer.nodes_[i];
var registrations = registrationsTable.get(node);
if (!registrations) return;
for (var j = 0; j < registrations.length; j++) {
var registration = registrations[j];
if (registration.observer === observer) registration.removeTransientObservers();
}
}
}
function enqueueMutation(target, type, data) {
var interestedObservers = Object.create(null);
var associatedStrings = Object.create(null);
for (var node = target; node; node = node.parentNode) {
var registrations = registrationsTable.get(node);
if (!registrations) continue;
for (var j = 0; j < registrations.length; j++) {
var registration = registrations[j];
var options = registration.options;
if (node !== target && !options.subtree) continue;
if (type === "attributes" && !options.attributes) continue;
if (type === "attributes" && options.attributeFilter && (data.namespace !== null || options.attributeFilter.indexOf(data.name) === -1)) {
continue;
}
if (type === "characterData" && !options.characterData) continue;
if (type === "childList" && !options.childList) continue;
var observer = registration.observer;
interestedObservers[observer.uid_] = observer;
if (type === "attributes" && options.attributeOldValue || type === "characterData" && options.characterDataOldValue) {
associatedStrings[observer.uid_] = data.oldValue;
}
}
}
for (var uid in interestedObservers) {
var observer = interestedObservers[uid];
var record = new MutationRecord(type, target);
if ("name" in data && "namespace" in data) {
record.attributeName = data.name;
record.attributeNamespace = data.namespace;
}
if (data.addedNodes) record.addedNodes = data.addedNodes;
if (data.removedNodes) record.removedNodes = data.removedNodes;
if (data.previousSibling) record.previousSibling = data.previousSibling;
if (data.nextSibling) record.nextSibling = data.nextSibling;
if (associatedStrings[uid] !== undefined) record.oldValue = associatedStrings[uid];
scheduleCallback(observer);
observer.records_.push(record);
}
}
var slice = Array.prototype.slice;
function MutationObserverOptions(options) {
this.childList = !!options.childList;
this.subtree = !!options.subtree;
if (!("attributes" in options) && ("attributeOldValue" in options || "attributeFilter" in options)) {
this.attributes = true;
} else {
this.attributes = !!options.attributes;
}
if ("characterDataOldValue" in options && !("characterData" in options)) this.characterData = true; else this.characterData = !!options.characterData;
if (!this.attributes && (options.attributeOldValue || "attributeFilter" in options) || !this.characterData && options.characterDataOldValue) {
throw new TypeError();
}
this.characterData = !!options.characterData;
this.attributeOldValue = !!options.attributeOldValue;
this.characterDataOldValue = !!options.characterDataOldValue;
if ("attributeFilter" in options) {
if (options.attributeFilter == null || typeof options.attributeFilter !== "object") {
throw new TypeError();
}
this.attributeFilter = slice.call(options.attributeFilter);
} else {
this.attributeFilter = null;
}
}
var uidCounter = 0;
function MutationObserver(callback) {
this.callback_ = callback;
this.nodes_ = [];
this.records_ = [];
this.uid_ = ++uidCounter;
this.scheduled_ = false;
}
MutationObserver.prototype = {
constructor: MutationObserver,
observe: function(target, options) {
target = wrapIfNeeded(target);
var newOptions = new MutationObserverOptions(options);
var registration;
var registrations = registrationsTable.get(target);
if (!registrations) registrationsTable.set(target, registrations = []);
for (var i = 0; i < registrations.length; i++) {
if (registrations[i].observer === this) {
registration = registrations[i];
registration.removeTransientObservers();
registration.options = newOptions;
}
}
if (!registration) {
registration = new Registration(this, target, newOptions);
registrations.push(registration);
this.nodes_.push(target);
}
},
disconnect: function() {
this.nodes_.forEach(function(node) {
var registrations = registrationsTable.get(node);
for (var i = 0; i < registrations.length; i++) {
var registration = registrations[i];
if (registration.observer === this) {
registrations.splice(i, 1);
break;
}
}
}, this);
this.records_ = [];
},
takeRecords: function() {
var copyOfRecords = this.records_;
this.records_ = [];
return copyOfRecords;
}
};
function Registration(observer, target, options) {
this.observer = observer;
this.target = target;
this.options = options;
this.transientObservedNodes = [];
}
Registration.prototype = {
addTransientObserver: function(node) {
if (node === this.target) return;
scheduleCallback(this.observer);
this.transientObservedNodes.push(node);
var registrations = registrationsTable.get(node);
if (!registrations) registrationsTable.set(node, registrations = []);
registrations.push(this);
},
removeTransientObservers: function() {
var transientObservedNodes = this.transientObservedNodes;
this.transientObservedNodes = [];
for (var i = 0; i < transientObservedNodes.length; i++) {
var node = transientObservedNodes[i];
var registrations = registrationsTable.get(node);
for (var j = 0; j < registrations.length; j++) {
if (registrations[j] === this) {
registrations.splice(j, 1);
break;
}
}
}
}
};
scope.enqueueMutation = enqueueMutation;
scope.registerTransientObservers = registerTransientObservers;
scope.wrappers.MutationObserver = MutationObserver;
scope.wrappers.MutationRecord = MutationRecord;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
function TreeScope(root, parent) {
this.root = root;
this.parent = parent;
}
TreeScope.prototype = {
get renderer() {
if (this.root instanceof scope.wrappers.ShadowRoot) {
return scope.getRendererForHost(this.root.host);
}
return null;
},
contains: function(treeScope) {
for (;treeScope; treeScope = treeScope.parent) {
if (treeScope === this) return true;
}
return false;
}
};
function setTreeScope(node, treeScope) {
if (node.treeScope_ !== treeScope) {
node.treeScope_ = treeScope;
for (var sr = node.shadowRoot; sr; sr = sr.olderShadowRoot) {
sr.treeScope_.parent = treeScope;
}
for (var child = node.firstChild; child; child = child.nextSibling) {
setTreeScope(child, treeScope);
}
}
}
function getTreeScope(node) {
if (node instanceof scope.wrappers.Window) {
debugger;
}
if (node.treeScope_) return node.treeScope_;
var parent = node.parentNode;
var treeScope;
if (parent) treeScope = getTreeScope(parent); else treeScope = new TreeScope(node, null);
return node.treeScope_ = treeScope;
}
scope.TreeScope = TreeScope;
scope.getTreeScope = getTreeScope;
scope.setTreeScope = setTreeScope;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var forwardMethodsToWrapper = scope.forwardMethodsToWrapper;
var getTreeScope = scope.getTreeScope;
var mixin = scope.mixin;
var registerWrapper = scope.registerWrapper;
var setWrapper = scope.setWrapper;
var unsafeUnwrap = scope.unsafeUnwrap;
var unwrap = scope.unwrap;
var wrap = scope.wrap;
var wrappers = scope.wrappers;
var wrappedFuns = new WeakMap();
var listenersTable = new WeakMap();
var handledEventsTable = new WeakMap();
var currentlyDispatchingEvents = new WeakMap();
var targetTable = new WeakMap();
var currentTargetTable = new WeakMap();
var relatedTargetTable = new WeakMap();
var eventPhaseTable = new WeakMap();
var stopPropagationTable = new WeakMap();
var stopImmediatePropagationTable = new WeakMap();
var eventHandlersTable = new WeakMap();
var eventPathTable = new WeakMap();
function isShadowRoot(node) {
return node instanceof wrappers.ShadowRoot;
}
function rootOfNode(node) {
return getTreeScope(node).root;
}
function getEventPath(node, event) {
var path = [];
var current = node;
path.push(current);
while (current) {
var destinationInsertionPoints = getDestinationInsertionPoints(current);
if (destinationInsertionPoints && destinationInsertionPoints.length > 0) {
for (var i = 0; i < destinationInsertionPoints.length; i++) {
var insertionPoint = destinationInsertionPoints[i];
if (isShadowInsertionPoint(insertionPoint)) {
var shadowRoot = rootOfNode(insertionPoint);
var olderShadowRoot = shadowRoot.olderShadowRoot;
if (olderShadowRoot) path.push(olderShadowRoot);
}
path.push(insertionPoint);
}
current = destinationInsertionPoints[destinationInsertionPoints.length - 1];
} else {
if (isShadowRoot(current)) {
if (inSameTree(node, current) && eventMustBeStopped(event)) {
break;
}
current = current.host;
path.push(current);
} else {
current = current.parentNode;
if (current) path.push(current);
}
}
}
return path;
}
function eventMustBeStopped(event) {
if (!event) return false;
switch (event.type) {
case "abort":
case "error":
case "select":
case "change":
case "load":
case "reset":
case "resize":
case "scroll":
case "selectstart":
return true;
}
return false;
}
function isShadowInsertionPoint(node) {
return node instanceof HTMLShadowElement;
}
function getDestinationInsertionPoints(node) {
return scope.getDestinationInsertionPoints(node);
}
function eventRetargetting(path, currentTarget) {
if (path.length === 0) return currentTarget;
if (currentTarget instanceof wrappers.Window) currentTarget = currentTarget.document;
var currentTargetTree = getTreeScope(currentTarget);
var originalTarget = path[0];
var originalTargetTree = getTreeScope(originalTarget);
var relativeTargetTree = lowestCommonInclusiveAncestor(currentTargetTree, originalTargetTree);
for (var i = 0; i < path.length; i++) {
var node = path[i];
if (getTreeScope(node) === relativeTargetTree) return node;
}
return path[path.length - 1];
}
function getTreeScopeAncestors(treeScope) {
var ancestors = [];
for (;treeScope; treeScope = treeScope.parent) {
ancestors.push(treeScope);
}
return ancestors;
}
function lowestCommonInclusiveAncestor(tsA, tsB) {
var ancestorsA = getTreeScopeAncestors(tsA);
var ancestorsB = getTreeScopeAncestors(tsB);
var result = null;
while (ancestorsA.length > 0 && ancestorsB.length > 0) {
var a = ancestorsA.pop();
var b = ancestorsB.pop();
if (a === b) result = a; else break;
}
return result;
}
function getTreeScopeRoot(ts) {
if (!ts.parent) return ts;
return getTreeScopeRoot(ts.parent);
}
function relatedTargetResolution(event, currentTarget, relatedTarget) {
if (currentTarget instanceof wrappers.Window) currentTarget = currentTarget.document;
var currentTargetTree = getTreeScope(currentTarget);
var relatedTargetTree = getTreeScope(relatedTarget);
var relatedTargetEventPath = getEventPath(relatedTarget, event);
var lowestCommonAncestorTree;
var lowestCommonAncestorTree = lowestCommonInclusiveAncestor(currentTargetTree, relatedTargetTree);
if (!lowestCommonAncestorTree) lowestCommonAncestorTree = relatedTargetTree.root;
for (var commonAncestorTree = lowestCommonAncestorTree; commonAncestorTree; commonAncestorTree = commonAncestorTree.parent) {
var adjustedRelatedTarget;
for (var i = 0; i < relatedTargetEventPath.length; i++) {
var node = relatedTargetEventPath[i];
if (getTreeScope(node) === commonAncestorTree) return node;
}
}
return null;
}
function inSameTree(a, b) {
return getTreeScope(a) === getTreeScope(b);
}
var NONE = 0;
var CAPTURING_PHASE = 1;
var AT_TARGET = 2;
var BUBBLING_PHASE = 3;
var pendingError;
function dispatchOriginalEvent(originalEvent) {
if (handledEventsTable.get(originalEvent)) return;
handledEventsTable.set(originalEvent, true);
dispatchEvent(wrap(originalEvent), wrap(originalEvent.target));
if (pendingError) {
var err = pendingError;
pendingError = null;
throw err;
}
}
function isLoadLikeEvent(event) {
switch (event.type) {
case "load":
case "beforeunload":
case "unload":
return true;
}
return false;
}
function dispatchEvent(event, originalWrapperTarget) {
if (currentlyDispatchingEvents.get(event)) throw new Error("InvalidStateError");
currentlyDispatchingEvents.set(event, true);
scope.renderAllPending();
var eventPath;
var overrideTarget;
var win;
if (isLoadLikeEvent(event) && !event.bubbles) {
var doc = originalWrapperTarget;
if (doc instanceof wrappers.Document && (win = doc.defaultView)) {
overrideTarget = doc;
eventPath = [];
}
}
if (!eventPath) {
if (originalWrapperTarget instanceof wrappers.Window) {
win = originalWrapperTarget;
eventPath = [];
} else {
eventPath = getEventPath(originalWrapperTarget, event);
if (!isLoadLikeEvent(event)) {
var doc = eventPath[eventPath.length - 1];
if (doc instanceof wrappers.Document) win = doc.defaultView;
}
}
}
eventPathTable.set(event, eventPath);
if (dispatchCapturing(event, eventPath, win, overrideTarget)) {
if (dispatchAtTarget(event, eventPath, win, overrideTarget)) {
dispatchBubbling(event, eventPath, win, overrideTarget);
}
}
eventPhaseTable.set(event, NONE);
currentTargetTable.delete(event, null);
currentlyDispatchingEvents.delete(event);
return event.defaultPrevented;
}
function dispatchCapturing(event, eventPath, win, overrideTarget) {
var phase = CAPTURING_PHASE;
if (win) {
if (!invoke(win, event, phase, eventPath, overrideTarget)) return false;
}
for (var i = eventPath.length - 1; i > 0; i--) {
if (!invoke(eventPath[i], event, phase, eventPath, overrideTarget)) return false;
}
return true;
}
function dispatchAtTarget(event, eventPath, win, overrideTarget) {
var phase = AT_TARGET;
var currentTarget = eventPath[0] || win;
return invoke(currentTarget, event, phase, eventPath, overrideTarget);
}
function dispatchBubbling(event, eventPath, win, overrideTarget) {
var phase = BUBBLING_PHASE;
for (var i = 1; i < eventPath.length; i++) {
if (!invoke(eventPath[i], event, phase, eventPath, overrideTarget)) return;
}
if (win && eventPath.length > 0) {
invoke(win, event, phase, eventPath, overrideTarget);
}
}
function invoke(currentTarget, event, phase, eventPath, overrideTarget) {
var listeners = listenersTable.get(currentTarget);
if (!listeners) return true;
var target = overrideTarget || eventRetargetting(eventPath, currentTarget);
if (target === currentTarget) {
if (phase === CAPTURING_PHASE) return true;
if (phase === BUBBLING_PHASE) phase = AT_TARGET;
} else if (phase === BUBBLING_PHASE && !event.bubbles) {
return true;
}
if ("relatedTarget" in event) {
var originalEvent = unwrap(event);
var unwrappedRelatedTarget = originalEvent.relatedTarget;
if (unwrappedRelatedTarget) {
if (unwrappedRelatedTarget instanceof Object && unwrappedRelatedTarget.addEventListener) {
var relatedTarget = wrap(unwrappedRelatedTarget);
var adjusted = relatedTargetResolution(event, currentTarget, relatedTarget);
if (adjusted === target) return true;
} else {
adjusted = null;
}
relatedTargetTable.set(event, adjusted);
}
}
eventPhaseTable.set(event, phase);
var type = event.type;
var anyRemoved = false;
targetTable.set(event, target);
currentTargetTable.set(event, currentTarget);
listeners.depth++;
for (var i = 0, len = listeners.length; i < len; i++) {
var listener = listeners[i];
if (listener.removed) {
anyRemoved = true;
continue;
}
if (listener.type !== type || !listener.capture && phase === CAPTURING_PHASE || listener.capture && phase === BUBBLING_PHASE) {
continue;
}
try {
if (typeof listener.handler === "function") listener.handler.call(currentTarget, event); else listener.handler.handleEvent(event);
if (stopImmediatePropagationTable.get(event)) return false;
} catch (ex) {
if (!pendingError) pendingError = ex;
}
}
listeners.depth--;
if (anyRemoved && listeners.depth === 0) {
var copy = listeners.slice();
listeners.length = 0;
for (var i = 0; i < copy.length; i++) {
if (!copy[i].removed) listeners.push(copy[i]);
}
}
return !stopPropagationTable.get(event);
}
function Listener(type, handler, capture) {
this.type = type;
this.handler = handler;
this.capture = Boolean(capture);
}
Listener.prototype = {
equals: function(that) {
return this.handler === that.handler && this.type === that.type && this.capture === that.capture;
},
get removed() {
return this.handler === null;
},
remove: function() {
this.handler = null;
}
};
var OriginalEvent = window.Event;
OriginalEvent.prototype.polymerBlackList_ = {
returnValue: true,
keyLocation: true
};
function Event(type, options) {
if (type instanceof OriginalEvent) {
var impl = type;
if (!OriginalBeforeUnloadEvent && impl.type === "beforeunload" && !(this instanceof BeforeUnloadEvent)) {
return new BeforeUnloadEvent(impl);
}
setWrapper(impl, this);
} else {
return wrap(constructEvent(OriginalEvent, "Event", type, options));
}
}
Event.prototype = {
get target() {
return targetTable.get(this);
},
get currentTarget() {
return currentTargetTable.get(this);
},
get eventPhase() {
return eventPhaseTable.get(this);
},
get path() {
var eventPath = eventPathTable.get(this);
if (!eventPath) return [];
return eventPath.slice();
},
stopPropagation: function() {
stopPropagationTable.set(this, true);
},
stopImmediatePropagation: function() {
stopPropagationTable.set(this, true);
stopImmediatePropagationTable.set(this, true);
}
};
registerWrapper(OriginalEvent, Event, document.createEvent("Event"));
function unwrapOptions(options) {
if (!options || !options.relatedTarget) return options;
return Object.create(options, {
relatedTarget: {
value: unwrap(options.relatedTarget)
}
});
}
function registerGenericEvent(name, SuperEvent, prototype) {
var OriginalEvent = window[name];
var GenericEvent = function(type, options) {
if (type instanceof OriginalEvent) setWrapper(type, this); else return wrap(constructEvent(OriginalEvent, name, type, options));
};
GenericEvent.prototype = Object.create(SuperEvent.prototype);
if (prototype) mixin(GenericEvent.prototype, prototype);
if (OriginalEvent) {
try {
registerWrapper(OriginalEvent, GenericEvent, new OriginalEvent("temp"));
} catch (ex) {
registerWrapper(OriginalEvent, GenericEvent, document.createEvent(name));
}
}
return GenericEvent;
}
var UIEvent = registerGenericEvent("UIEvent", Event);
var CustomEvent = registerGenericEvent("CustomEvent", Event);
var relatedTargetProto = {
get relatedTarget() {
var relatedTarget = relatedTargetTable.get(this);
if (relatedTarget !== undefined) return relatedTarget;
return wrap(unwrap(this).relatedTarget);
}
};
function getInitFunction(name, relatedTargetIndex) {
return function() {
arguments[relatedTargetIndex] = unwrap(arguments[relatedTargetIndex]);
var impl = unwrap(this);
impl[name].apply(impl, arguments);
};
}
var mouseEventProto = mixin({
initMouseEvent: getInitFunction("initMouseEvent", 14)
}, relatedTargetProto);
var focusEventProto = mixin({
initFocusEvent: getInitFunction("initFocusEvent", 5)
}, relatedTargetProto);
var MouseEvent = registerGenericEvent("MouseEvent", UIEvent, mouseEventProto);
var FocusEvent = registerGenericEvent("FocusEvent", UIEvent, focusEventProto);
var defaultInitDicts = Object.create(null);
var supportsEventConstructors = function() {
try {
new window.FocusEvent("focus");
} catch (ex) {
return false;
}
return true;
}();
function constructEvent(OriginalEvent, name, type, options) {
if (supportsEventConstructors) return new OriginalEvent(type, unwrapOptions(options));
var event = unwrap(document.createEvent(name));
var defaultDict = defaultInitDicts[name];
var args = [ type ];
Object.keys(defaultDict).forEach(function(key) {
var v = options != null && key in options ? options[key] : defaultDict[key];
if (key === "relatedTarget") v = unwrap(v);
args.push(v);
});
event["init" + name].apply(event, args);
return event;
}
if (!supportsEventConstructors) {
var configureEventConstructor = function(name, initDict, superName) {
if (superName) {
var superDict = defaultInitDicts[superName];
initDict = mixin(mixin({}, superDict), initDict);
}
defaultInitDicts[name] = initDict;
};
configureEventConstructor("Event", {
bubbles: false,
cancelable: false
});
configureEventConstructor("CustomEvent", {
detail: null
}, "Event");
configureEventConstructor("UIEvent", {
view: null,
detail: 0
}, "Event");
configureEventConstructor("MouseEvent", {
screenX: 0,
screenY: 0,
clientX: 0,
clientY: 0,
ctrlKey: false,
altKey: false,
shiftKey: false,
metaKey: false,
button: 0,
relatedTarget: null
}, "UIEvent");
configureEventConstructor("FocusEvent", {
relatedTarget: null
}, "UIEvent");
}
var OriginalBeforeUnloadEvent = window.BeforeUnloadEvent;
function BeforeUnloadEvent(impl) {
Event.call(this, impl);
}
BeforeUnloadEvent.prototype = Object.create(Event.prototype);
mixin(BeforeUnloadEvent.prototype, {
get returnValue() {
return unsafeUnwrap(this).returnValue;
},
set returnValue(v) {
unsafeUnwrap(this).returnValue = v;
}
});
if (OriginalBeforeUnloadEvent) registerWrapper(OriginalBeforeUnloadEvent, BeforeUnloadEvent);
function isValidListener(fun) {
if (typeof fun === "function") return true;
return fun && fun.handleEvent;
}
function isMutationEvent(type) {
switch (type) {
case "DOMAttrModified":
case "DOMAttributeNameChanged":
case "DOMCharacterDataModified":
case "DOMElementNameChanged":
case "DOMNodeInserted":
case "DOMNodeInsertedIntoDocument":
case "DOMNodeRemoved":
case "DOMNodeRemovedFromDocument":
case "DOMSubtreeModified":
return true;
}
return false;
}
var OriginalEventTarget = window.EventTarget;
function EventTarget(impl) {
setWrapper(impl, this);
}
var methodNames = [ "addEventListener", "removeEventListener", "dispatchEvent" ];
[ Node, Window ].forEach(function(constructor) {
var p = constructor.prototype;
methodNames.forEach(function(name) {
Object.defineProperty(p, name + "_", {
value: p[name]
});
});
});
function getTargetToListenAt(wrapper) {
if (wrapper instanceof wrappers.ShadowRoot) wrapper = wrapper.host;
return unwrap(wrapper);
}
EventTarget.prototype = {
addEventListener: function(type, fun, capture) {
if (!isValidListener(fun) || isMutationEvent(type)) return;
var listener = new Listener(type, fun, capture);
var listeners = listenersTable.get(this);
if (!listeners) {
listeners = [];
listeners.depth = 0;
listenersTable.set(this, listeners);
} else {
for (var i = 0; i < listeners.length; i++) {
if (listener.equals(listeners[i])) return;
}
}
listeners.push(listener);
var target = getTargetToListenAt(this);
target.addEventListener_(type, dispatchOriginalEvent, true);
},
removeEventListener: function(type, fun, capture) {
capture = Boolean(capture);
var listeners = listenersTable.get(this);
if (!listeners) return;
var count = 0, found = false;
for (var i = 0; i < listeners.length; i++) {
if (listeners[i].type === type && listeners[i].capture === capture) {
count++;
if (listeners[i].handler === fun) {
found = true;
listeners[i].remove();
}
}
}
if (found && count === 1) {
var target = getTargetToListenAt(this);
target.removeEventListener_(type, dispatchOriginalEvent, true);
}
},
dispatchEvent: function(event) {
var nativeEvent = unwrap(event);
var eventType = nativeEvent.type;
handledEventsTable.set(nativeEvent, false);
scope.renderAllPending();
var tempListener;
if (!hasListenerInAncestors(this, eventType)) {
tempListener = function() {};
this.addEventListener(eventType, tempListener, true);
}
try {
return unwrap(this).dispatchEvent_(nativeEvent);
} finally {
if (tempListener) this.removeEventListener(eventType, tempListener, true);
}
}
};
function hasListener(node, type) {
var listeners = listenersTable.get(node);
if (listeners) {
for (var i = 0; i < listeners.length; i++) {
if (!listeners[i].removed && listeners[i].type === type) return true;
}
}
return false;
}
function hasListenerInAncestors(target, type) {
for (var node = unwrap(target); node; node = node.parentNode) {
if (hasListener(wrap(node), type)) return true;
}
return false;
}
if (OriginalEventTarget) registerWrapper(OriginalEventTarget, EventTarget);
function wrapEventTargetMethods(constructors) {
forwardMethodsToWrapper(constructors, methodNames);
}
var originalElementFromPoint = document.elementFromPoint;
function elementFromPoint(self, document, x, y) {
scope.renderAllPending();
var element = wrap(originalElementFromPoint.call(unsafeUnwrap(document), x, y));
if (!element) return null;
var path = getEventPath(element, null);
var idx = path.lastIndexOf(self);
if (idx == -1) return null; else path = path.slice(0, idx);
return eventRetargetting(path, self);
}
function getEventHandlerGetter(name) {
return function() {
var inlineEventHandlers = eventHandlersTable.get(this);
return inlineEventHandlers && inlineEventHandlers[name] && inlineEventHandlers[name].value || null;
};
}
function getEventHandlerSetter(name) {
var eventType = name.slice(2);
return function(value) {
var inlineEventHandlers = eventHandlersTable.get(this);
if (!inlineEventHandlers) {
inlineEventHandlers = Object.create(null);
eventHandlersTable.set(this, inlineEventHandlers);
}
var old = inlineEventHandlers[name];
if (old) this.removeEventListener(eventType, old.wrapped, false);
if (typeof value === "function") {
var wrapped = function(e) {
var rv = value.call(this, e);
if (rv === false) e.preventDefault(); else if (name === "onbeforeunload" && typeof rv === "string") e.returnValue = rv;
};
this.addEventListener(eventType, wrapped, false);
inlineEventHandlers[name] = {
value: value,
wrapped: wrapped
};
}
};
}
scope.elementFromPoint = elementFromPoint;
scope.getEventHandlerGetter = getEventHandlerGetter;
scope.getEventHandlerSetter = getEventHandlerSetter;
scope.wrapEventTargetMethods = wrapEventTargetMethods;
scope.wrappers.BeforeUnloadEvent = BeforeUnloadEvent;
scope.wrappers.CustomEvent = CustomEvent;
scope.wrappers.Event = Event;
scope.wrappers.EventTarget = EventTarget;
scope.wrappers.FocusEvent = FocusEvent;
scope.wrappers.MouseEvent = MouseEvent;
scope.wrappers.UIEvent = UIEvent;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var UIEvent = scope.wrappers.UIEvent;
var mixin = scope.mixin;
var registerWrapper = scope.registerWrapper;
var setWrapper = scope.setWrapper;
var unsafeUnwrap = scope.unsafeUnwrap;
var wrap = scope.wrap;
var OriginalTouchEvent = window.TouchEvent;
if (!OriginalTouchEvent) return;
var nativeEvent;
try {
nativeEvent = document.createEvent("TouchEvent");
} catch (ex) {
return;
}
var nonEnumDescriptor = {
enumerable: false
};
function nonEnum(obj, prop) {
Object.defineProperty(obj, prop, nonEnumDescriptor);
}
function Touch(impl) {
setWrapper(impl, this);
}
Touch.prototype = {
get target() {
return wrap(unsafeUnwrap(this).target);
}
};
var descr = {
configurable: true,
enumerable: true,
get: null
};
[ "clientX", "clientY", "screenX", "screenY", "pageX", "pageY", "identifier", "webkitRadiusX", "webkitRadiusY", "webkitRotationAngle", "webkitForce" ].forEach(function(name) {
descr.get = function() {
return unsafeUnwrap(this)[name];
};
Object.defineProperty(Touch.prototype, name, descr);
});
function TouchList() {
this.length = 0;
nonEnum(this, "length");
}
TouchList.prototype = {
item: function(index) {
return this[index];
}
};
function wrapTouchList(nativeTouchList) {
var list = new TouchList();
for (var i = 0; i < nativeTouchList.length; i++) {
list[i] = new Touch(nativeTouchList[i]);
}
list.length = i;
return list;
}
function TouchEvent(impl) {
UIEvent.call(this, impl);
}
TouchEvent.prototype = Object.create(UIEvent.prototype);
mixin(TouchEvent.prototype, {
get touches() {
return wrapTouchList(unsafeUnwrap(this).touches);
},
get targetTouches() {
return wrapTouchList(unsafeUnwrap(this).targetTouches);
},
get changedTouches() {
return wrapTouchList(unsafeUnwrap(this).changedTouches);
},
initTouchEvent: function() {
throw new Error("Not implemented");
}
});
registerWrapper(OriginalTouchEvent, TouchEvent, nativeEvent);
scope.wrappers.Touch = Touch;
scope.wrappers.TouchEvent = TouchEvent;
scope.wrappers.TouchList = TouchList;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var unsafeUnwrap = scope.unsafeUnwrap;
var wrap = scope.wrap;
var nonEnumDescriptor = {
enumerable: false
};
function nonEnum(obj, prop) {
Object.defineProperty(obj, prop, nonEnumDescriptor);
}
function NodeList() {
this.length = 0;
nonEnum(this, "length");
}
NodeList.prototype = {
item: function(index) {
return this[index];
}
};
nonEnum(NodeList.prototype, "item");
function wrapNodeList(list) {
if (list == null) return list;
var wrapperList = new NodeList();
for (var i = 0, length = list.length; i < length; i++) {
wrapperList[i] = wrap(list[i]);
}
wrapperList.length = length;
return wrapperList;
}
function addWrapNodeListMethod(wrapperConstructor, name) {
wrapperConstructor.prototype[name] = function() {
return wrapNodeList(unsafeUnwrap(this)[name].apply(unsafeUnwrap(this), arguments));
};
}
scope.wrappers.NodeList = NodeList;
scope.addWrapNodeListMethod = addWrapNodeListMethod;
scope.wrapNodeList = wrapNodeList;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
scope.wrapHTMLCollection = scope.wrapNodeList;
scope.wrappers.HTMLCollection = scope.wrappers.NodeList;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var EventTarget = scope.wrappers.EventTarget;
var NodeList = scope.wrappers.NodeList;
var TreeScope = scope.TreeScope;
var assert = scope.assert;
var defineWrapGetter = scope.defineWrapGetter;
var enqueueMutation = scope.enqueueMutation;
var getTreeScope = scope.getTreeScope;
var isWrapper = scope.isWrapper;
var mixin = scope.mixin;
var registerTransientObservers = scope.registerTransientObservers;
var registerWrapper = scope.registerWrapper;
var setTreeScope = scope.setTreeScope;
var unsafeUnwrap = scope.unsafeUnwrap;
var unwrap = scope.unwrap;
var unwrapIfNeeded = scope.unwrapIfNeeded;
var wrap = scope.wrap;
var wrapIfNeeded = scope.wrapIfNeeded;
var wrappers = scope.wrappers;
function assertIsNodeWrapper(node) {
assert(node instanceof Node);
}
function createOneElementNodeList(node) {
var nodes = new NodeList();
nodes[0] = node;
nodes.length = 1;
return nodes;
}
var surpressMutations = false;
function enqueueRemovalForInsertedNodes(node, parent, nodes) {
enqueueMutation(parent, "childList", {
removedNodes: nodes,
previousSibling: node.previousSibling,
nextSibling: node.nextSibling
});
}
function enqueueRemovalForInsertedDocumentFragment(df, nodes) {
enqueueMutation(df, "childList", {
removedNodes: nodes
});
}
function collectNodes(node, parentNode, previousNode, nextNode) {
if (node instanceof DocumentFragment) {
var nodes = collectNodesForDocumentFragment(node);
surpressMutations = true;
for (var i = nodes.length - 1; i >= 0; i--) {
node.removeChild(nodes[i]);
nodes[i].parentNode_ = parentNode;
}
surpressMutations = false;
for (var i = 0; i < nodes.length; i++) {
nodes[i].previousSibling_ = nodes[i - 1] || previousNode;
nodes[i].nextSibling_ = nodes[i + 1] || nextNode;
}
if (previousNode) previousNode.nextSibling_ = nodes[0];
if (nextNode) nextNode.previousSibling_ = nodes[nodes.length - 1];
return nodes;
}
var nodes = createOneElementNodeList(node);
var oldParent = node.parentNode;
if (oldParent) {
oldParent.removeChild(node);
}
node.parentNode_ = parentNode;
node.previousSibling_ = previousNode;
node.nextSibling_ = nextNode;
if (previousNode) previousNode.nextSibling_ = node;
if (nextNode) nextNode.previousSibling_ = node;
return nodes;
}
function collectNodesNative(node) {
if (node instanceof DocumentFragment) return collectNodesForDocumentFragment(node);
var nodes = createOneElementNodeList(node);
var oldParent = node.parentNode;
if (oldParent) enqueueRemovalForInsertedNodes(node, oldParent, nodes);
return nodes;
}
function collectNodesForDocumentFragment(node) {
var nodes = new NodeList();
var i = 0;
for (var child = node.firstChild; child; child = child.nextSibling) {
nodes[i++] = child;
}
nodes.length = i;
enqueueRemovalForInsertedDocumentFragment(node, nodes);
return nodes;
}
function snapshotNodeList(nodeList) {
return nodeList;
}
function nodeWasAdded(node, treeScope) {
setTreeScope(node, treeScope);
node.nodeIsInserted_();
}
function nodesWereAdded(nodes, parent) {
var treeScope = getTreeScope(parent);
for (var i = 0; i < nodes.length; i++) {
nodeWasAdded(nodes[i], treeScope);
}
}
function nodeWasRemoved(node) {
setTreeScope(node, new TreeScope(node, null));
}
function nodesWereRemoved(nodes) {
for (var i = 0; i < nodes.length; i++) {
nodeWasRemoved(nodes[i]);
}
}
function ensureSameOwnerDocument(parent, child) {
var ownerDoc = parent.nodeType === Node.DOCUMENT_NODE ? parent : parent.ownerDocument;
if (ownerDoc !== child.ownerDocument) ownerDoc.adoptNode(child);
}
function adoptNodesIfNeeded(owner, nodes) {
if (!nodes.length) return;
var ownerDoc = owner.ownerDocument;
if (ownerDoc === nodes[0].ownerDocument) return;
for (var i = 0; i < nodes.length; i++) {
scope.adoptNodeNoRemove(nodes[i], ownerDoc);
}
}
function unwrapNodesForInsertion(owner, nodes) {
adoptNodesIfNeeded(owner, nodes);
var length = nodes.length;
if (length === 1) return unwrap(nodes[0]);
var df = unwrap(owner.ownerDocument.createDocumentFragment());
for (var i = 0; i < length; i++) {
df.appendChild(unwrap(nodes[i]));
}
return df;
}
function clearChildNodes(wrapper) {
if (wrapper.firstChild_ !== undefined) {
var child = wrapper.firstChild_;
while (child) {
var tmp = child;
child = child.nextSibling_;
tmp.parentNode_ = tmp.previousSibling_ = tmp.nextSibling_ = undefined;
}
}
wrapper.firstChild_ = wrapper.lastChild_ = undefined;
}
function removeAllChildNodes(wrapper) {
if (wrapper.invalidateShadowRenderer()) {
var childWrapper = wrapper.firstChild;
while (childWrapper) {
assert(childWrapper.parentNode === wrapper);
var nextSibling = childWrapper.nextSibling;
var childNode = unwrap(childWrapper);
var parentNode = childNode.parentNode;
if (parentNode) originalRemoveChild.call(parentNode, childNode);
childWrapper.previousSibling_ = childWrapper.nextSibling_ = childWrapper.parentNode_ = null;
childWrapper = nextSibling;
}
wrapper.firstChild_ = wrapper.lastChild_ = null;
} else {
var node = unwrap(wrapper);
var child = node.firstChild;
var nextSibling;
while (child) {
nextSibling = child.nextSibling;
originalRemoveChild.call(node, child);
child = nextSibling;
}
}
}
function invalidateParent(node) {
var p = node.parentNode;
return p && p.invalidateShadowRenderer();
}
function cleanupNodes(nodes) {
for (var i = 0, n; i < nodes.length; i++) {
n = nodes[i];
n.parentNode.removeChild(n);
}
}
var originalImportNode = document.importNode;
var originalCloneNode = window.Node.prototype.cloneNode;
function cloneNode(node, deep, opt_doc) {
var clone;
if (opt_doc) clone = wrap(originalImportNode.call(opt_doc, unsafeUnwrap(node), false)); else clone = wrap(originalCloneNode.call(unsafeUnwrap(node), false));
if (deep) {
for (var child = node.firstChild; child; child = child.nextSibling) {
clone.appendChild(cloneNode(child, true, opt_doc));
}
if (node instanceof wrappers.HTMLTemplateElement) {
var cloneContent = clone.content;
for (var child = node.content.firstChild; child; child = child.nextSibling) {
cloneContent.appendChild(cloneNode(child, true, opt_doc));
}
}
}
return clone;
}
function contains(self, child) {
if (!child || getTreeScope(self) !== getTreeScope(child)) return false;
for (var node = child; node; node = node.parentNode) {
if (node === self) return true;
}
return false;
}
var OriginalNode = window.Node;
function Node(original) {
assert(original instanceof OriginalNode);
EventTarget.call(this, original);
this.parentNode_ = undefined;
this.firstChild_ = undefined;
this.lastChild_ = undefined;
this.nextSibling_ = undefined;
this.previousSibling_ = undefined;
this.treeScope_ = undefined;
}
var OriginalDocumentFragment = window.DocumentFragment;
var originalAppendChild = OriginalNode.prototype.appendChild;
var originalCompareDocumentPosition = OriginalNode.prototype.compareDocumentPosition;
var originalInsertBefore = OriginalNode.prototype.insertBefore;
var originalRemoveChild = OriginalNode.prototype.removeChild;
var originalReplaceChild = OriginalNode.prototype.replaceChild;
var isIe = /Trident/.test(navigator.userAgent);
var removeChildOriginalHelper = isIe ? function(parent, child) {
try {
originalRemoveChild.call(parent, child);
} catch (ex) {
if (!(parent instanceof OriginalDocumentFragment)) throw ex;
}
} : function(parent, child) {
originalRemoveChild.call(parent, child);
};
Node.prototype = Object.create(EventTarget.prototype);
mixin(Node.prototype, {
appendChild: function(childWrapper) {
return this.insertBefore(childWrapper, null);
},
insertBefore: function(childWrapper, refWrapper) {
assertIsNodeWrapper(childWrapper);
var refNode;
if (refWrapper) {
if (isWrapper(refWrapper)) {
refNode = unwrap(refWrapper);
} else {
refNode = refWrapper;
refWrapper = wrap(refNode);
}
} else {
refWrapper = null;
refNode = null;
}
refWrapper && assert(refWrapper.parentNode === this);
var nodes;
var previousNode = refWrapper ? refWrapper.previousSibling : this.lastChild;
var useNative = !this.invalidateShadowRenderer() && !invalidateParent(childWrapper);
if (useNative) nodes = collectNodesNative(childWrapper); else nodes = collectNodes(childWrapper, this, previousNode, refWrapper);
if (useNative) {
ensureSameOwnerDocument(this, childWrapper);
clearChildNodes(this);
originalInsertBefore.call(unsafeUnwrap(this), unwrap(childWrapper), refNode);
} else {
if (!previousNode) this.firstChild_ = nodes[0];
if (!refWrapper) {
this.lastChild_ = nodes[nodes.length - 1];
if (this.firstChild_ === undefined) this.firstChild_ = this.firstChild;
}
var parentNode = refNode ? refNode.parentNode : unsafeUnwrap(this);
if (parentNode) {
originalInsertBefore.call(parentNode, unwrapNodesForInsertion(this, nodes), refNode);
} else {
adoptNodesIfNeeded(this, nodes);
}
}
enqueueMutation(this, "childList", {
addedNodes: nodes,
nextSibling: refWrapper,
previousSibling: previousNode
});
nodesWereAdded(nodes, this);
return childWrapper;
},
removeChild: function(childWrapper) {
assertIsNodeWrapper(childWrapper);
if (childWrapper.parentNode !== this) {
var found = false;
var childNodes = this.childNodes;
for (var ieChild = this.firstChild; ieChild; ieChild = ieChild.nextSibling) {
if (ieChild === childWrapper) {
found = true;
break;
}
}
if (!found) {
throw new Error("NotFoundError");
}
}
var childNode = unwrap(childWrapper);
var childWrapperNextSibling = childWrapper.nextSibling;
var childWrapperPreviousSibling = childWrapper.previousSibling;
if (this.invalidateShadowRenderer()) {
var thisFirstChild = this.firstChild;
var thisLastChild = this.lastChild;
var parentNode = childNode.parentNode;
if (parentNode) removeChildOriginalHelper(parentNode, childNode);
if (thisFirstChild === childWrapper) this.firstChild_ = childWrapperNextSibling;
if (thisLastChild === childWrapper) this.lastChild_ = childWrapperPreviousSibling;
if (childWrapperPreviousSibling) childWrapperPreviousSibling.nextSibling_ = childWrapperNextSibling;
if (childWrapperNextSibling) {
childWrapperNextSibling.previousSibling_ = childWrapperPreviousSibling;
}
childWrapper.previousSibling_ = childWrapper.nextSibling_ = childWrapper.parentNode_ = undefined;
} else {
clearChildNodes(this);
removeChildOriginalHelper(unsafeUnwrap(this), childNode);
}
if (!surpressMutations) {
enqueueMutation(this, "childList", {
removedNodes: createOneElementNodeList(childWrapper),
nextSibling: childWrapperNextSibling,
previousSibling: childWrapperPreviousSibling
});
}
registerTransientObservers(this, childWrapper);
return childWrapper;
},
replaceChild: function(newChildWrapper, oldChildWrapper) {
assertIsNodeWrapper(newChildWrapper);
var oldChildNode;
if (isWrapper(oldChildWrapper)) {
oldChildNode = unwrap(oldChildWrapper);
} else {
oldChildNode = oldChildWrapper;
oldChildWrapper = wrap(oldChildNode);
}
if (oldChildWrapper.parentNode !== this) {
throw new Error("NotFoundError");
}
var nextNode = oldChildWrapper.nextSibling;
var previousNode = oldChildWrapper.previousSibling;
var nodes;
var useNative = !this.invalidateShadowRenderer() && !invalidateParent(newChildWrapper);
if (useNative) {
nodes = collectNodesNative(newChildWrapper);
} else {
if (nextNode === newChildWrapper) nextNode = newChildWrapper.nextSibling;
nodes = collectNodes(newChildWrapper, this, previousNode, nextNode);
}
if (!useNative) {
if (this.firstChild === oldChildWrapper) this.firstChild_ = nodes[0];
if (this.lastChild === oldChildWrapper) this.lastChild_ = nodes[nodes.length - 1];
oldChildWrapper.previousSibling_ = oldChildWrapper.nextSibling_ = oldChildWrapper.parentNode_ = undefined;
if (oldChildNode.parentNode) {
originalReplaceChild.call(oldChildNode.parentNode, unwrapNodesForInsertion(this, nodes), oldChildNode);
}
} else {
ensureSameOwnerDocument(this, newChildWrapper);
clearChildNodes(this);
originalReplaceChild.call(unsafeUnwrap(this), unwrap(newChildWrapper), oldChildNode);
}
enqueueMutation(this, "childList", {
addedNodes: nodes,
removedNodes: createOneElementNodeList(oldChildWrapper),
nextSibling: nextNode,
previousSibling: previousNode
});
nodeWasRemoved(oldChildWrapper);
nodesWereAdded(nodes, this);
return oldChildWrapper;
},
nodeIsInserted_: function() {
for (var child = this.firstChild; child; child = child.nextSibling) {
child.nodeIsInserted_();
}
},
hasChildNodes: function() {
return this.firstChild !== null;
},
get parentNode() {
return this.parentNode_ !== undefined ? this.parentNode_ : wrap(unsafeUnwrap(this).parentNode);
},
get firstChild() {
return this.firstChild_ !== undefined ? this.firstChild_ : wrap(unsafeUnwrap(this).firstChild);
},
get lastChild() {
return this.lastChild_ !== undefined ? this.lastChild_ : wrap(unsafeUnwrap(this).lastChild);
},
get nextSibling() {
return this.nextSibling_ !== undefined ? this.nextSibling_ : wrap(unsafeUnwrap(this).nextSibling);
},
get previousSibling() {
return this.previousSibling_ !== undefined ? this.previousSibling_ : wrap(unsafeUnwrap(this).previousSibling);
},
get parentElement() {
var p = this.parentNode;
while (p && p.nodeType !== Node.ELEMENT_NODE) {
p = p.parentNode;
}
return p;
},
get textContent() {
var s = "";
for (var child = this.firstChild; child; child = child.nextSibling) {
if (child.nodeType != Node.COMMENT_NODE) {
s += child.textContent;
}
}
return s;
},
set textContent(textContent) {
if (textContent == null) textContent = "";
var removedNodes = snapshotNodeList(this.childNodes);
if (this.invalidateShadowRenderer()) {
removeAllChildNodes(this);
if (textContent !== "") {
var textNode = unsafeUnwrap(this).ownerDocument.createTextNode(textContent);
this.appendChild(textNode);
}
} else {
clearChildNodes(this);
unsafeUnwrap(this).textContent = textContent;
}
var addedNodes = snapshotNodeList(this.childNodes);
enqueueMutation(this, "childList", {
addedNodes: addedNodes,
removedNodes: removedNodes
});
nodesWereRemoved(removedNodes);
nodesWereAdded(addedNodes, this);
},
get childNodes() {
var wrapperList = new NodeList();
var i = 0;
for (var child = this.firstChild; child; child = child.nextSibling) {
wrapperList[i++] = child;
}
wrapperList.length = i;
return wrapperList;
},
cloneNode: function(deep) {
return cloneNode(this, deep);
},
contains: function(child) {
return contains(this, wrapIfNeeded(child));
},
compareDocumentPosition: function(otherNode) {
return originalCompareDocumentPosition.call(unsafeUnwrap(this), unwrapIfNeeded(otherNode));
},
normalize: function() {
var nodes = snapshotNodeList(this.childNodes);
var remNodes = [];
var s = "";
var modNode;
for (var i = 0, n; i < nodes.length; i++) {
n = nodes[i];
if (n.nodeType === Node.TEXT_NODE) {
if (!modNode && !n.data.length) this.removeNode(n); else if (!modNode) modNode = n; else {
s += n.data;
remNodes.push(n);
}
} else {
if (modNode && remNodes.length) {
modNode.data += s;
cleanupNodes(remNodes);
}
remNodes = [];
s = "";
modNode = null;
if (n.childNodes.length) n.normalize();
}
}
if (modNode && remNodes.length) {
modNode.data += s;
cleanupNodes(remNodes);
}
}
});
defineWrapGetter(Node, "ownerDocument");
registerWrapper(OriginalNode, Node, document.createDocumentFragment());
delete Node.prototype.querySelector;
delete Node.prototype.querySelectorAll;
Node.prototype = mixin(Object.create(EventTarget.prototype), Node.prototype);
scope.cloneNode = cloneNode;
scope.nodeWasAdded = nodeWasAdded;
scope.nodeWasRemoved = nodeWasRemoved;
scope.nodesWereAdded = nodesWereAdded;
scope.nodesWereRemoved = nodesWereRemoved;
scope.originalInsertBefore = originalInsertBefore;
scope.originalRemoveChild = originalRemoveChild;
scope.snapshotNodeList = snapshotNodeList;
scope.wrappers.Node = Node;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var HTMLCollection = scope.wrappers.HTMLCollection;
var NodeList = scope.wrappers.NodeList;
var getTreeScope = scope.getTreeScope;
var unsafeUnwrap = scope.unsafeUnwrap;
var wrap = scope.wrap;
var originalDocumentQuerySelector = document.querySelector;
var originalElementQuerySelector = document.documentElement.querySelector;
var originalDocumentQuerySelectorAll = document.querySelectorAll;
var originalElementQuerySelectorAll = document.documentElement.querySelectorAll;
var originalDocumentGetElementsByTagName = document.getElementsByTagName;
var originalElementGetElementsByTagName = document.documentElement.getElementsByTagName;
var originalDocumentGetElementsByTagNameNS = document.getElementsByTagNameNS;
var originalElementGetElementsByTagNameNS = document.documentElement.getElementsByTagNameNS;
var OriginalElement = window.Element;
var OriginalDocument = window.HTMLDocument || window.Document;
function filterNodeList(list, index, result, deep) {
var wrappedItem = null;
var root = null;
for (var i = 0, length = list.length; i < length; i++) {
wrappedItem = wrap(list[i]);
if (!deep && (root = getTreeScope(wrappedItem).root)) {
if (root instanceof scope.wrappers.ShadowRoot) {
continue;
}
}
result[index++] = wrappedItem;
}
return index;
}
function shimSelector(selector) {
return String(selector).replace(/\/deep\//g, " ");
}
function findOne(node, selector) {
var m, el = node.firstElementChild;
while (el) {
if (el.matches(selector)) return el;
m = findOne(el, selector);
if (m) return m;
el = el.nextElementSibling;
}
return null;
}
function matchesSelector(el, selector) {
return el.matches(selector);
}
var XHTML_NS = "http://www.w3.org/1999/xhtml";
function matchesTagName(el, localName, localNameLowerCase) {
var ln = el.localName;
return ln === localName || ln === localNameLowerCase && el.namespaceURI === XHTML_NS;
}
function matchesEveryThing() {
return true;
}
function matchesLocalNameOnly(el, ns, localName) {
return el.localName === localName;
}
function matchesNameSpace(el, ns) {
return el.namespaceURI === ns;
}
function matchesLocalNameNS(el, ns, localName) {
return el.namespaceURI === ns && el.localName === localName;
}
function findElements(node, index, result, p, arg0, arg1) {
var el = node.firstElementChild;
while (el) {
if (p(el, arg0, arg1)) result[index++] = el;
index = findElements(el, index, result, p, arg0, arg1);
el = el.nextElementSibling;
}
return index;
}
function querySelectorAllFiltered(p, index, result, selector, deep) {
var target = unsafeUnwrap(this);
var list;
var root = getTreeScope(this).root;
if (root instanceof scope.wrappers.ShadowRoot) {
return findElements(this, index, result, p, selector, null);
} else if (target instanceof OriginalElement) {
list = originalElementQuerySelectorAll.call(target, selector);
} else if (target instanceof OriginalDocument) {
list = originalDocumentQuerySelectorAll.call(target, selector);
} else {
return findElements(this, index, result, p, selector, null);
}
return filterNodeList(list, index, result, deep);
}
var SelectorsInterface = {
querySelector: function(selector) {
var shimmed = shimSelector(selector);
var deep = shimmed !== selector;
selector = shimmed;
var target = unsafeUnwrap(this);
var wrappedItem;
var root = getTreeScope(this).root;
if (root instanceof scope.wrappers.ShadowRoot) {
return findOne(this, selector);
} else if (target instanceof OriginalElement) {
wrappedItem = wrap(originalElementQuerySelector.call(target, selector));
} else if (target instanceof OriginalDocument) {
wrappedItem = wrap(originalDocumentQuerySelector.call(target, selector));
} else {
return findOne(this, selector);
}
if (!wrappedItem) {
return wrappedItem;
} else if (!deep && (root = getTreeScope(wrappedItem).root)) {
if (root instanceof scope.wrappers.ShadowRoot) {
return findOne(this, selector);
}
}
return wrappedItem;
},
querySelectorAll: function(selector) {
var shimmed = shimSelector(selector);
var deep = shimmed !== selector;
selector = shimmed;
var result = new NodeList();
result.length = querySelectorAllFiltered.call(this, matchesSelector, 0, result, selector, deep);
return result;
}
};
function getElementsByTagNameFiltered(p, index, result, localName, lowercase) {
var target = unsafeUnwrap(this);
var list;
var root = getTreeScope(this).root;
if (root instanceof scope.wrappers.ShadowRoot) {
return findElements(this, index, result, p, localName, lowercase);
} else if (target instanceof OriginalElement) {
list = originalElementGetElementsByTagName.call(target, localName, lowercase);
} else if (target instanceof OriginalDocument) {
list = originalDocumentGetElementsByTagName.call(target, localName, lowercase);
} else {
return findElements(this, index, result, p, localName, lowercase);
}
return filterNodeList(list, index, result, false);
}
function getElementsByTagNameNSFiltered(p, index, result, ns, localName) {
var target = unsafeUnwrap(this);
var list;
var root = getTreeScope(this).root;
if (root instanceof scope.wrappers.ShadowRoot) {
return findElements(this, index, result, p, ns, localName);
} else if (target instanceof OriginalElement) {
list = originalElementGetElementsByTagNameNS.call(target, ns, localName);
} else if (target instanceof OriginalDocument) {
list = originalDocumentGetElementsByTagNameNS.call(target, ns, localName);
} else {
return findElements(this, index, result, p, ns, localName);
}
return filterNodeList(list, index, result, false);
}
var GetElementsByInterface = {
getElementsByTagName: function(localName) {
var result = new HTMLCollection();
var match = localName === "*" ? matchesEveryThing : matchesTagName;
result.length = getElementsByTagNameFiltered.call(this, match, 0, result, localName, localName.toLowerCase());
return result;
},
getElementsByClassName: function(className) {
return this.querySelectorAll("." + className);
},
getElementsByTagNameNS: function(ns, localName) {
var result = new HTMLCollection();
var match = null;
if (ns === "*") {
match = localName === "*" ? matchesEveryThing : matchesLocalNameOnly;
} else {
match = localName === "*" ? matchesNameSpace : matchesLocalNameNS;
}
result.length = getElementsByTagNameNSFiltered.call(this, match, 0, result, ns || null, localName);
return result;
}
};
scope.GetElementsByInterface = GetElementsByInterface;
scope.SelectorsInterface = SelectorsInterface;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var NodeList = scope.wrappers.NodeList;
function forwardElement(node) {
while (node && node.nodeType !== Node.ELEMENT_NODE) {
node = node.nextSibling;
}
return node;
}
function backwardsElement(node) {
while (node && node.nodeType !== Node.ELEMENT_NODE) {
node = node.previousSibling;
}
return node;
}
var ParentNodeInterface = {
get firstElementChild() {
return forwardElement(this.firstChild);
},
get lastElementChild() {
return backwardsElement(this.lastChild);
},
get childElementCount() {
var count = 0;
for (var child = this.firstElementChild; child; child = child.nextElementSibling) {
count++;
}
return count;
},
get children() {
var wrapperList = new NodeList();
var i = 0;
for (var child = this.firstElementChild; child; child = child.nextElementSibling) {
wrapperList[i++] = child;
}
wrapperList.length = i;
return wrapperList;
},
remove: function() {
var p = this.parentNode;
if (p) p.removeChild(this);
}
};
var ChildNodeInterface = {
get nextElementSibling() {
return forwardElement(this.nextSibling);
},
get previousElementSibling() {
return backwardsElement(this.previousSibling);
}
};
scope.ChildNodeInterface = ChildNodeInterface;
scope.ParentNodeInterface = ParentNodeInterface;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var ChildNodeInterface = scope.ChildNodeInterface;
var Node = scope.wrappers.Node;
var enqueueMutation = scope.enqueueMutation;
var mixin = scope.mixin;
var registerWrapper = scope.registerWrapper;
var unsafeUnwrap = scope.unsafeUnwrap;
var OriginalCharacterData = window.CharacterData;
function CharacterData(node) {
Node.call(this, node);
}
CharacterData.prototype = Object.create(Node.prototype);
mixin(CharacterData.prototype, {
get textContent() {
return this.data;
},
set textContent(value) {
this.data = value;
},
get data() {
return unsafeUnwrap(this).data;
},
set data(value) {
var oldValue = unsafeUnwrap(this).data;
enqueueMutation(this, "characterData", {
oldValue: oldValue
});
unsafeUnwrap(this).data = value;
}
});
mixin(CharacterData.prototype, ChildNodeInterface);
registerWrapper(OriginalCharacterData, CharacterData, document.createTextNode(""));
scope.wrappers.CharacterData = CharacterData;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var CharacterData = scope.wrappers.CharacterData;
var enqueueMutation = scope.enqueueMutation;
var mixin = scope.mixin;
var registerWrapper = scope.registerWrapper;
function toUInt32(x) {
return x >>> 0;
}
var OriginalText = window.Text;
function Text(node) {
CharacterData.call(this, node);
}
Text.prototype = Object.create(CharacterData.prototype);
mixin(Text.prototype, {
splitText: function(offset) {
offset = toUInt32(offset);
var s = this.data;
if (offset > s.length) throw new Error("IndexSizeError");
var head = s.slice(0, offset);
var tail = s.slice(offset);
this.data = head;
var newTextNode = this.ownerDocument.createTextNode(tail);
if (this.parentNode) this.parentNode.insertBefore(newTextNode, this.nextSibling);
return newTextNode;
}
});
registerWrapper(OriginalText, Text, document.createTextNode(""));
scope.wrappers.Text = Text;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var setWrapper = scope.setWrapper;
var unsafeUnwrap = scope.unsafeUnwrap;
function invalidateClass(el) {
scope.invalidateRendererBasedOnAttribute(el, "class");
}
function DOMTokenList(impl, ownerElement) {
setWrapper(impl, this);
this.ownerElement_ = ownerElement;
}
DOMTokenList.prototype = {
constructor: DOMTokenList,
get length() {
return unsafeUnwrap(this).length;
},
item: function(index) {
return unsafeUnwrap(this).item(index);
},
contains: function(token) {
return unsafeUnwrap(this).contains(token);
},
add: function() {
unsafeUnwrap(this).add.apply(unsafeUnwrap(this), arguments);
invalidateClass(this.ownerElement_);
},
remove: function() {
unsafeUnwrap(this).remove.apply(unsafeUnwrap(this), arguments);
invalidateClass(this.ownerElement_);
},
toggle: function(token) {
var rv = unsafeUnwrap(this).toggle.apply(unsafeUnwrap(this), arguments);
invalidateClass(this.ownerElement_);
return rv;
},
toString: function() {
return unsafeUnwrap(this).toString();
}
};
scope.wrappers.DOMTokenList = DOMTokenList;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var ChildNodeInterface = scope.ChildNodeInterface;
var GetElementsByInterface = scope.GetElementsByInterface;
var Node = scope.wrappers.Node;
var DOMTokenList = scope.wrappers.DOMTokenList;
var ParentNodeInterface = scope.ParentNodeInterface;
var SelectorsInterface = scope.SelectorsInterface;
var addWrapNodeListMethod = scope.addWrapNodeListMethod;
var enqueueMutation = scope.enqueueMutation;
var mixin = scope.mixin;
var oneOf = scope.oneOf;
var registerWrapper = scope.registerWrapper;
var unsafeUnwrap = scope.unsafeUnwrap;
var wrappers = scope.wrappers;
var OriginalElement = window.Element;
var matchesNames = [ "matches", "mozMatchesSelector", "msMatchesSelector", "webkitMatchesSelector" ].filter(function(name) {
return OriginalElement.prototype[name];
});
var matchesName = matchesNames[0];
var originalMatches = OriginalElement.prototype[matchesName];
function invalidateRendererBasedOnAttribute(element, name) {
var p = element.parentNode;
if (!p || !p.shadowRoot) return;
var renderer = scope.getRendererForHost(p);
if (renderer.dependsOnAttribute(name)) renderer.invalidate();
}
function enqueAttributeChange(element, name, oldValue) {
enqueueMutation(element, "attributes", {
name: name,
namespace: null,
oldValue: oldValue
});
}
var classListTable = new WeakMap();
function Element(node) {
Node.call(this, node);
}
Element.prototype = Object.create(Node.prototype);
mixin(Element.prototype, {
createShadowRoot: function() {
var newShadowRoot = new wrappers.ShadowRoot(this);
unsafeUnwrap(this).polymerShadowRoot_ = newShadowRoot;
var renderer = scope.getRendererForHost(this);
renderer.invalidate();
return newShadowRoot;
},
get shadowRoot() {
return unsafeUnwrap(this).polymerShadowRoot_ || null;
},
setAttribute: function(name, value) {
var oldValue = unsafeUnwrap(this).getAttribute(name);
unsafeUnwrap(this).setAttribute(name, value);
enqueAttributeChange(this, name, oldValue);
invalidateRendererBasedOnAttribute(this, name);
},
removeAttribute: function(name) {
var oldValue = unsafeUnwrap(this).getAttribute(name);
unsafeUnwrap(this).removeAttribute(name);
enqueAttributeChange(this, name, oldValue);
invalidateRendererBasedOnAttribute(this, name);
},
matches: function(selector) {
return originalMatches.call(unsafeUnwrap(this), selector);
},
get classList() {
var list = classListTable.get(this);
if (!list) {
classListTable.set(this, list = new DOMTokenList(unsafeUnwrap(this).classList, this));
}
return list;
},
get className() {
return unsafeUnwrap(this).className;
},
set className(v) {
this.setAttribute("class", v);
},
get id() {
return unsafeUnwrap(this).id;
},
set id(v) {
this.setAttribute("id", v);
}
});
matchesNames.forEach(function(name) {
if (name !== "matches") {
Element.prototype[name] = function(selector) {
return this.matches(selector);
};
}
});
if (OriginalElement.prototype.webkitCreateShadowRoot) {
Element.prototype.webkitCreateShadowRoot = Element.prototype.createShadowRoot;
}
mixin(Element.prototype, ChildNodeInterface);
mixin(Element.prototype, GetElementsByInterface);
mixin(Element.prototype, ParentNodeInterface);
mixin(Element.prototype, SelectorsInterface);
registerWrapper(OriginalElement, Element, document.createElementNS(null, "x"));
scope.invalidateRendererBasedOnAttribute = invalidateRendererBasedOnAttribute;
scope.matchesNames = matchesNames;
scope.wrappers.Element = Element;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var Element = scope.wrappers.Element;
var defineGetter = scope.defineGetter;
var enqueueMutation = scope.enqueueMutation;
var mixin = scope.mixin;
var nodesWereAdded = scope.nodesWereAdded;
var nodesWereRemoved = scope.nodesWereRemoved;
var registerWrapper = scope.registerWrapper;
var snapshotNodeList = scope.snapshotNodeList;
var unsafeUnwrap = scope.unsafeUnwrap;
var unwrap = scope.unwrap;
var wrap = scope.wrap;
var wrappers = scope.wrappers;
var escapeAttrRegExp = /[&\u00A0"]/g;
var escapeDataRegExp = /[&\u00A0<>]/g;
function escapeReplace(c) {
switch (c) {
case "&":
return "&";
case "<":
return "<";
case ">":
return ">";
case '"':
return """;
case " ":
return " ";
}
}
function escapeAttr(s) {
return s.replace(escapeAttrRegExp, escapeReplace);
}
function escapeData(s) {
return s.replace(escapeDataRegExp, escapeReplace);
}
function makeSet(arr) {
var set = {};
for (var i = 0; i < arr.length; i++) {
set[arr[i]] = true;
}
return set;
}
var voidElements = makeSet([ "area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track", "wbr" ]);
var plaintextParents = makeSet([ "style", "script", "xmp", "iframe", "noembed", "noframes", "plaintext", "noscript" ]);
function getOuterHTML(node, parentNode) {
switch (node.nodeType) {
case Node.ELEMENT_NODE:
var tagName = node.tagName.toLowerCase();
var s = "<" + tagName;
var attrs = node.attributes;
for (var i = 0, attr; attr = attrs[i]; i++) {
s += " " + attr.name + '="' + escapeAttr(attr.value) + '"';
}
s += ">";
if (voidElements[tagName]) return s;
return s + getInnerHTML(node) + "</" + tagName + ">";
case Node.TEXT_NODE:
var data = node.data;
if (parentNode && plaintextParents[parentNode.localName]) return data;
return escapeData(data);
case Node.COMMENT_NODE:
return "<!--" + node.data + "-->";
default:
console.error(node);
throw new Error("not implemented");
}
}
function getInnerHTML(node) {
if (node instanceof wrappers.HTMLTemplateElement) node = node.content;
var s = "";
for (var child = node.firstChild; child; child = child.nextSibling) {
s += getOuterHTML(child, node);
}
return s;
}
function setInnerHTML(node, value, opt_tagName) {
var tagName = opt_tagName || "div";
node.textContent = "";
var tempElement = unwrap(node.ownerDocument.createElement(tagName));
tempElement.innerHTML = value;
var firstChild;
while (firstChild = tempElement.firstChild) {
node.appendChild(wrap(firstChild));
}
}
var oldIe = /MSIE/.test(navigator.userAgent);
var OriginalHTMLElement = window.HTMLElement;
var OriginalHTMLTemplateElement = window.HTMLTemplateElement;
function HTMLElement(node) {
Element.call(this, node);
}
HTMLElement.prototype = Object.create(Element.prototype);
mixin(HTMLElement.prototype, {
get innerHTML() {
return getInnerHTML(this);
},
set innerHTML(value) {
if (oldIe && plaintextParents[this.localName]) {
this.textContent = value;
return;
}
var removedNodes = snapshotNodeList(this.childNodes);
if (this.invalidateShadowRenderer()) {
if (this instanceof wrappers.HTMLTemplateElement) setInnerHTML(this.content, value); else setInnerHTML(this, value, this.tagName);
} else if (!OriginalHTMLTemplateElement && this instanceof wrappers.HTMLTemplateElement) {
setInnerHTML(this.content, value);
} else {
unsafeUnwrap(this).innerHTML = value;
}
var addedNodes = snapshotNodeList(this.childNodes);
enqueueMutation(this, "childList", {
addedNodes: addedNodes,
removedNodes: removedNodes
});
nodesWereRemoved(removedNodes);
nodesWereAdded(addedNodes, this);
},
get outerHTML() {
return getOuterHTML(this, this.parentNode);
},
set outerHTML(value) {
var p = this.parentNode;
if (p) {
p.invalidateShadowRenderer();
var df = frag(p, value);
p.replaceChild(df, this);
}
},
insertAdjacentHTML: function(position, text) {
var contextElement, refNode;
switch (String(position).toLowerCase()) {
case "beforebegin":
contextElement = this.parentNode;
refNode = this;
break;
case "afterend":
contextElement = this.parentNode;
refNode = this.nextSibling;
break;
case "afterbegin":
contextElement = this;
refNode = this.firstChild;
break;
case "beforeend":
contextElement = this;
refNode = null;
break;
default:
return;
}
var df = frag(contextElement, text);
contextElement.insertBefore(df, refNode);
},
get hidden() {
return this.hasAttribute("hidden");
},
set hidden(v) {
if (v) {
this.setAttribute("hidden", "");
} else {
this.removeAttribute("hidden");
}
}
});
function frag(contextElement, html) {
var p = unwrap(contextElement.cloneNode(false));
p.innerHTML = html;
var df = unwrap(document.createDocumentFragment());
var c;
while (c = p.firstChild) {
df.appendChild(c);
}
return wrap(df);
}
function getter(name) {
return function() {
scope.renderAllPending();
return unsafeUnwrap(this)[name];
};
}
function getterRequiresRendering(name) {
defineGetter(HTMLElement, name, getter(name));
}
[ "clientHeight", "clientLeft", "clientTop", "clientWidth", "offsetHeight", "offsetLeft", "offsetTop", "offsetWidth", "scrollHeight", "scrollWidth" ].forEach(getterRequiresRendering);
function getterAndSetterRequiresRendering(name) {
Object.defineProperty(HTMLElement.prototype, name, {
get: getter(name),
set: function(v) {
scope.renderAllPending();
unsafeUnwrap(this)[name] = v;
},
configurable: true,
enumerable: true
});
}
[ "scrollLeft", "scrollTop" ].forEach(getterAndSetterRequiresRendering);
function methodRequiresRendering(name) {
Object.defineProperty(HTMLElement.prototype, name, {
value: function() {
scope.renderAllPending();
return unsafeUnwrap(this)[name].apply(unsafeUnwrap(this), arguments);
},
configurable: true,
enumerable: true
});
}
[ "getBoundingClientRect", "getClientRects", "scrollIntoView" ].forEach(methodRequiresRendering);
registerWrapper(OriginalHTMLElement, HTMLElement, document.createElement("b"));
scope.wrappers.HTMLElement = HTMLElement;
scope.getInnerHTML = getInnerHTML;
scope.setInnerHTML = setInnerHTML;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var HTMLElement = scope.wrappers.HTMLElement;
var mixin = scope.mixin;
var registerWrapper = scope.registerWrapper;
var unsafeUnwrap = scope.unsafeUnwrap;
var wrap = scope.wrap;
var OriginalHTMLCanvasElement = window.HTMLCanvasElement;
function HTMLCanvasElement(node) {
HTMLElement.call(this, node);
}
HTMLCanvasElement.prototype = Object.create(HTMLElement.prototype);
mixin(HTMLCanvasElement.prototype, {
getContext: function() {
var context = unsafeUnwrap(this).getContext.apply(unsafeUnwrap(this), arguments);
return context && wrap(context);
}
});
registerWrapper(OriginalHTMLCanvasElement, HTMLCanvasElement, document.createElement("canvas"));
scope.wrappers.HTMLCanvasElement = HTMLCanvasElement;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var HTMLElement = scope.wrappers.HTMLElement;
var mixin = scope.mixin;
var registerWrapper = scope.registerWrapper;
var OriginalHTMLContentElement = window.HTMLContentElement;
function HTMLContentElement(node) {
HTMLElement.call(this, node);
}
HTMLContentElement.prototype = Object.create(HTMLElement.prototype);
mixin(HTMLContentElement.prototype, {
constructor: HTMLContentElement,
get select() {
return this.getAttribute("select");
},
set select(value) {
this.setAttribute("select", value);
},
setAttribute: function(n, v) {
HTMLElement.prototype.setAttribute.call(this, n, v);
if (String(n).toLowerCase() === "select") this.invalidateShadowRenderer(true);
}
});
if (OriginalHTMLContentElement) registerWrapper(OriginalHTMLContentElement, HTMLContentElement);
scope.wrappers.HTMLContentElement = HTMLContentElement;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var HTMLElement = scope.wrappers.HTMLElement;
var mixin = scope.mixin;
var registerWrapper = scope.registerWrapper;
var wrapHTMLCollection = scope.wrapHTMLCollection;
var unwrap = scope.unwrap;
var OriginalHTMLFormElement = window.HTMLFormElement;
function HTMLFormElement(node) {
HTMLElement.call(this, node);
}
HTMLFormElement.prototype = Object.create(HTMLElement.prototype);
mixin(HTMLFormElement.prototype, {
get elements() {
return wrapHTMLCollection(unwrap(this).elements);
}
});
registerWrapper(OriginalHTMLFormElement, HTMLFormElement, document.createElement("form"));
scope.wrappers.HTMLFormElement = HTMLFormElement;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var HTMLElement = scope.wrappers.HTMLElement;
var registerWrapper = scope.registerWrapper;
var unwrap = scope.unwrap;
var rewrap = scope.rewrap;
var OriginalHTMLImageElement = window.HTMLImageElement;
function HTMLImageElement(node) {
HTMLElement.call(this, node);
}
HTMLImageElement.prototype = Object.create(HTMLElement.prototype);
registerWrapper(OriginalHTMLImageElement, HTMLImageElement, document.createElement("img"));
function Image(width, height) {
if (!(this instanceof Image)) {
throw new TypeError("DOM object constructor cannot be called as a function.");
}
var node = unwrap(document.createElement("img"));
HTMLElement.call(this, node);
rewrap(node, this);
if (width !== undefined) node.width = width;
if (height !== undefined) node.height = height;
}
Image.prototype = HTMLImageElement.prototype;
scope.wrappers.HTMLImageElement = HTMLImageElement;
scope.wrappers.Image = Image;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var HTMLElement = scope.wrappers.HTMLElement;
var mixin = scope.mixin;
var NodeList = scope.wrappers.NodeList;
var registerWrapper = scope.registerWrapper;
var OriginalHTMLShadowElement = window.HTMLShadowElement;
function HTMLShadowElement(node) {
HTMLElement.call(this, node);
}
HTMLShadowElement.prototype = Object.create(HTMLElement.prototype);
HTMLShadowElement.prototype.constructor = HTMLShadowElement;
if (OriginalHTMLShadowElement) registerWrapper(OriginalHTMLShadowElement, HTMLShadowElement);
scope.wrappers.HTMLShadowElement = HTMLShadowElement;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var HTMLElement = scope.wrappers.HTMLElement;
var mixin = scope.mixin;
var registerWrapper = scope.registerWrapper;
var unsafeUnwrap = scope.unsafeUnwrap;
var unwrap = scope.unwrap;
var wrap = scope.wrap;
var contentTable = new WeakMap();
var templateContentsOwnerTable = new WeakMap();
function getTemplateContentsOwner(doc) {
if (!doc.defaultView) return doc;
var d = templateContentsOwnerTable.get(doc);
if (!d) {
d = doc.implementation.createHTMLDocument("");
while (d.lastChild) {
d.removeChild(d.lastChild);
}
templateContentsOwnerTable.set(doc, d);
}
return d;
}
function extractContent(templateElement) {
var doc = getTemplateContentsOwner(templateElement.ownerDocument);
var df = unwrap(doc.createDocumentFragment());
var child;
while (child = templateElement.firstChild) {
df.appendChild(child);
}
return df;
}
var OriginalHTMLTemplateElement = window.HTMLTemplateElement;
function HTMLTemplateElement(node) {
HTMLElement.call(this, node);
if (!OriginalHTMLTemplateElement) {
var content = extractContent(node);
contentTable.set(this, wrap(content));
}
}
HTMLTemplateElement.prototype = Object.create(HTMLElement.prototype);
mixin(HTMLTemplateElement.prototype, {
constructor: HTMLTemplateElement,
get content() {
if (OriginalHTMLTemplateElement) return wrap(unsafeUnwrap(this).content);
return contentTable.get(this);
}
});
if (OriginalHTMLTemplateElement) registerWrapper(OriginalHTMLTemplateElement, HTMLTemplateElement);
scope.wrappers.HTMLTemplateElement = HTMLTemplateElement;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var HTMLElement = scope.wrappers.HTMLElement;
var registerWrapper = scope.registerWrapper;
var OriginalHTMLMediaElement = window.HTMLMediaElement;
if (!OriginalHTMLMediaElement) return;
function HTMLMediaElement(node) {
HTMLElement.call(this, node);
}
HTMLMediaElement.prototype = Object.create(HTMLElement.prototype);
registerWrapper(OriginalHTMLMediaElement, HTMLMediaElement, document.createElement("audio"));
scope.wrappers.HTMLMediaElement = HTMLMediaElement;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var HTMLMediaElement = scope.wrappers.HTMLMediaElement;
var registerWrapper = scope.registerWrapper;
var unwrap = scope.unwrap;
var rewrap = scope.rewrap;
var OriginalHTMLAudioElement = window.HTMLAudioElement;
if (!OriginalHTMLAudioElement) return;
function HTMLAudioElement(node) {
HTMLMediaElement.call(this, node);
}
HTMLAudioElement.prototype = Object.create(HTMLMediaElement.prototype);
registerWrapper(OriginalHTMLAudioElement, HTMLAudioElement, document.createElement("audio"));
function Audio(src) {
if (!(this instanceof Audio)) {
throw new TypeError("DOM object constructor cannot be called as a function.");
}
var node = unwrap(document.createElement("audio"));
HTMLMediaElement.call(this, node);
rewrap(node, this);
node.setAttribute("preload", "auto");
if (src !== undefined) node.setAttribute("src", src);
}
Audio.prototype = HTMLAudioElement.prototype;
scope.wrappers.HTMLAudioElement = HTMLAudioElement;
scope.wrappers.Audio = Audio;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var HTMLElement = scope.wrappers.HTMLElement;
var mixin = scope.mixin;
var registerWrapper = scope.registerWrapper;
var rewrap = scope.rewrap;
var unwrap = scope.unwrap;
var wrap = scope.wrap;
var OriginalHTMLOptionElement = window.HTMLOptionElement;
function trimText(s) {
return s.replace(/\s+/g, " ").trim();
}
function HTMLOptionElement(node) {
HTMLElement.call(this, node);
}
HTMLOptionElement.prototype = Object.create(HTMLElement.prototype);
mixin(HTMLOptionElement.prototype, {
get text() {
return trimText(this.textContent);
},
set text(value) {
this.textContent = trimText(String(value));
},
get form() {
return wrap(unwrap(this).form);
}
});
registerWrapper(OriginalHTMLOptionElement, HTMLOptionElement, document.createElement("option"));
function Option(text, value, defaultSelected, selected) {
if (!(this instanceof Option)) {
throw new TypeError("DOM object constructor cannot be called as a function.");
}
var node = unwrap(document.createElement("option"));
HTMLElement.call(this, node);
rewrap(node, this);
if (text !== undefined) node.text = text;
if (value !== undefined) node.setAttribute("value", value);
if (defaultSelected === true) node.setAttribute("selected", "");
node.selected = selected === true;
}
Option.prototype = HTMLOptionElement.prototype;
scope.wrappers.HTMLOptionElement = HTMLOptionElement;
scope.wrappers.Option = Option;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var HTMLElement = scope.wrappers.HTMLElement;
var mixin = scope.mixin;
var registerWrapper = scope.registerWrapper;
var unwrap = scope.unwrap;
var wrap = scope.wrap;
var OriginalHTMLSelectElement = window.HTMLSelectElement;
function HTMLSelectElement(node) {
HTMLElement.call(this, node);
}
HTMLSelectElement.prototype = Object.create(HTMLElement.prototype);
mixin(HTMLSelectElement.prototype, {
add: function(element, before) {
if (typeof before === "object") before = unwrap(before);
unwrap(this).add(unwrap(element), before);
},
remove: function(indexOrNode) {
if (indexOrNode === undefined) {
HTMLElement.prototype.remove.call(this);
return;
}
if (typeof indexOrNode === "object") indexOrNode = unwrap(indexOrNode);
unwrap(this).remove(indexOrNode);
},
get form() {
return wrap(unwrap(this).form);
}
});
registerWrapper(OriginalHTMLSelectElement, HTMLSelectElement, document.createElement("select"));
scope.wrappers.HTMLSelectElement = HTMLSelectElement;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var HTMLElement = scope.wrappers.HTMLElement;
var mixin = scope.mixin;
var registerWrapper = scope.registerWrapper;
var unwrap = scope.unwrap;
var wrap = scope.wrap;
var wrapHTMLCollection = scope.wrapHTMLCollection;
var OriginalHTMLTableElement = window.HTMLTableElement;
function HTMLTableElement(node) {
HTMLElement.call(this, node);
}
HTMLTableElement.prototype = Object.create(HTMLElement.prototype);
mixin(HTMLTableElement.prototype, {
get caption() {
return wrap(unwrap(this).caption);
},
createCaption: function() {
return wrap(unwrap(this).createCaption());
},
get tHead() {
return wrap(unwrap(this).tHead);
},
createTHead: function() {
return wrap(unwrap(this).createTHead());
},
createTFoot: function() {
return wrap(unwrap(this).createTFoot());
},
get tFoot() {
return wrap(unwrap(this).tFoot);
},
get tBodies() {
return wrapHTMLCollection(unwrap(this).tBodies);
},
createTBody: function() {
return wrap(unwrap(this).createTBody());
},
get rows() {
return wrapHTMLCollection(unwrap(this).rows);
},
insertRow: function(index) {
return wrap(unwrap(this).insertRow(index));
}
});
registerWrapper(OriginalHTMLTableElement, HTMLTableElement, document.createElement("table"));
scope.wrappers.HTMLTableElement = HTMLTableElement;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var HTMLElement = scope.wrappers.HTMLElement;
var mixin = scope.mixin;
var registerWrapper = scope.registerWrapper;
var wrapHTMLCollection = scope.wrapHTMLCollection;
var unwrap = scope.unwrap;
var wrap = scope.wrap;
var OriginalHTMLTableSectionElement = window.HTMLTableSectionElement;
function HTMLTableSectionElement(node) {
HTMLElement.call(this, node);
}
HTMLTableSectionElement.prototype = Object.create(HTMLElement.prototype);
mixin(HTMLTableSectionElement.prototype, {
constructor: HTMLTableSectionElement,
get rows() {
return wrapHTMLCollection(unwrap(this).rows);
},
insertRow: function(index) {
return wrap(unwrap(this).insertRow(index));
}
});
registerWrapper(OriginalHTMLTableSectionElement, HTMLTableSectionElement, document.createElement("thead"));
scope.wrappers.HTMLTableSectionElement = HTMLTableSectionElement;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var HTMLElement = scope.wrappers.HTMLElement;
var mixin = scope.mixin;
var registerWrapper = scope.registerWrapper;
var wrapHTMLCollection = scope.wrapHTMLCollection;
var unwrap = scope.unwrap;
var wrap = scope.wrap;
var OriginalHTMLTableRowElement = window.HTMLTableRowElement;
function HTMLTableRowElement(node) {
HTMLElement.call(this, node);
}
HTMLTableRowElement.prototype = Object.create(HTMLElement.prototype);
mixin(HTMLTableRowElement.prototype, {
get cells() {
return wrapHTMLCollection(unwrap(this).cells);
},
insertCell: function(index) {
return wrap(unwrap(this).insertCell(index));
}
});
registerWrapper(OriginalHTMLTableRowElement, HTMLTableRowElement, document.createElement("tr"));
scope.wrappers.HTMLTableRowElement = HTMLTableRowElement;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var HTMLContentElement = scope.wrappers.HTMLContentElement;
var HTMLElement = scope.wrappers.HTMLElement;
var HTMLShadowElement = scope.wrappers.HTMLShadowElement;
var HTMLTemplateElement = scope.wrappers.HTMLTemplateElement;
var mixin = scope.mixin;
var registerWrapper = scope.registerWrapper;
var OriginalHTMLUnknownElement = window.HTMLUnknownElement;
function HTMLUnknownElement(node) {
switch (node.localName) {
case "content":
return new HTMLContentElement(node);
case "shadow":
return new HTMLShadowElement(node);
case "template":
return new HTMLTemplateElement(node);
}
HTMLElement.call(this, node);
}
HTMLUnknownElement.prototype = Object.create(HTMLElement.prototype);
registerWrapper(OriginalHTMLUnknownElement, HTMLUnknownElement);
scope.wrappers.HTMLUnknownElement = HTMLUnknownElement;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var Element = scope.wrappers.Element;
var HTMLElement = scope.wrappers.HTMLElement;
var registerObject = scope.registerObject;
var SVG_NS = "http://www.w3.org/2000/svg";
var svgTitleElement = document.createElementNS(SVG_NS, "title");
var SVGTitleElement = registerObject(svgTitleElement);
var SVGElement = Object.getPrototypeOf(SVGTitleElement.prototype).constructor;
if (!("classList" in svgTitleElement)) {
var descr = Object.getOwnPropertyDescriptor(Element.prototype, "classList");
Object.defineProperty(HTMLElement.prototype, "classList", descr);
delete Element.prototype.classList;
}
scope.wrappers.SVGElement = SVGElement;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var mixin = scope.mixin;
var registerWrapper = scope.registerWrapper;
var unwrap = scope.unwrap;
var wrap = scope.wrap;
var OriginalSVGUseElement = window.SVGUseElement;
var SVG_NS = "http://www.w3.org/2000/svg";
var gWrapper = wrap(document.createElementNS(SVG_NS, "g"));
var useElement = document.createElementNS(SVG_NS, "use");
var SVGGElement = gWrapper.constructor;
var parentInterfacePrototype = Object.getPrototypeOf(SVGGElement.prototype);
var parentInterface = parentInterfacePrototype.constructor;
function SVGUseElement(impl) {
parentInterface.call(this, impl);
}
SVGUseElement.prototype = Object.create(parentInterfacePrototype);
if ("instanceRoot" in useElement) {
mixin(SVGUseElement.prototype, {
get instanceRoot() {
return wrap(unwrap(this).instanceRoot);
},
get animatedInstanceRoot() {
return wrap(unwrap(this).animatedInstanceRoot);
}
});
}
registerWrapper(OriginalSVGUseElement, SVGUseElement, useElement);
scope.wrappers.SVGUseElement = SVGUseElement;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var EventTarget = scope.wrappers.EventTarget;
var mixin = scope.mixin;
var registerWrapper = scope.registerWrapper;
var unsafeUnwrap = scope.unsafeUnwrap;
var wrap = scope.wrap;
var OriginalSVGElementInstance = window.SVGElementInstance;
if (!OriginalSVGElementInstance) return;
function SVGElementInstance(impl) {
EventTarget.call(this, impl);
}
SVGElementInstance.prototype = Object.create(EventTarget.prototype);
mixin(SVGElementInstance.prototype, {
get correspondingElement() {
return wrap(unsafeUnwrap(this).correspondingElement);
},
get correspondingUseElement() {
return wrap(unsafeUnwrap(this).correspondingUseElement);
},
get parentNode() {
return wrap(unsafeUnwrap(this).parentNode);
},
get childNodes() {
throw new Error("Not implemented");
},
get firstChild() {
return wrap(unsafeUnwrap(this).firstChild);
},
get lastChild() {
return wrap(unsafeUnwrap(this).lastChild);
},
get previousSibling() {
return wrap(unsafeUnwrap(this).previousSibling);
},
get nextSibling() {
return wrap(unsafeUnwrap(this).nextSibling);
}
});
registerWrapper(OriginalSVGElementInstance, SVGElementInstance);
scope.wrappers.SVGElementInstance = SVGElementInstance;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var mixin = scope.mixin;
var registerWrapper = scope.registerWrapper;
var setWrapper = scope.setWrapper;
var unsafeUnwrap = scope.unsafeUnwrap;
var unwrap = scope.unwrap;
var unwrapIfNeeded = scope.unwrapIfNeeded;
var wrap = scope.wrap;
var OriginalCanvasRenderingContext2D = window.CanvasRenderingContext2D;
function CanvasRenderingContext2D(impl) {
setWrapper(impl, this);
}
mixin(CanvasRenderingContext2D.prototype, {
get canvas() {
return wrap(unsafeUnwrap(this).canvas);
},
drawImage: function() {
arguments[0] = unwrapIfNeeded(arguments[0]);
unsafeUnwrap(this).drawImage.apply(unsafeUnwrap(this), arguments);
},
createPattern: function() {
arguments[0] = unwrap(arguments[0]);
return unsafeUnwrap(this).createPattern.apply(unsafeUnwrap(this), arguments);
}
});
registerWrapper(OriginalCanvasRenderingContext2D, CanvasRenderingContext2D, document.createElement("canvas").getContext("2d"));
scope.wrappers.CanvasRenderingContext2D = CanvasRenderingContext2D;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var mixin = scope.mixin;
var registerWrapper = scope.registerWrapper;
var setWrapper = scope.setWrapper;
var unsafeUnwrap = scope.unsafeUnwrap;
var unwrapIfNeeded = scope.unwrapIfNeeded;
var wrap = scope.wrap;
var OriginalWebGLRenderingContext = window.WebGLRenderingContext;
if (!OriginalWebGLRenderingContext) return;
function WebGLRenderingContext(impl) {
setWrapper(impl, this);
}
mixin(WebGLRenderingContext.prototype, {
get canvas() {
return wrap(unsafeUnwrap(this).canvas);
},
texImage2D: function() {
arguments[5] = unwrapIfNeeded(arguments[5]);
unsafeUnwrap(this).texImage2D.apply(unsafeUnwrap(this), arguments);
},
texSubImage2D: function() {
arguments[6] = unwrapIfNeeded(arguments[6]);
unsafeUnwrap(this).texSubImage2D.apply(unsafeUnwrap(this), arguments);
}
});
var instanceProperties = /WebKit/.test(navigator.userAgent) ? {
drawingBufferHeight: null,
drawingBufferWidth: null
} : {};
registerWrapper(OriginalWebGLRenderingContext, WebGLRenderingContext, instanceProperties);
scope.wrappers.WebGLRenderingContext = WebGLRenderingContext;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var registerWrapper = scope.registerWrapper;
var setWrapper = scope.setWrapper;
var unsafeUnwrap = scope.unsafeUnwrap;
var unwrap = scope.unwrap;
var unwrapIfNeeded = scope.unwrapIfNeeded;
var wrap = scope.wrap;
var OriginalRange = window.Range;
function Range(impl) {
setWrapper(impl, this);
}
Range.prototype = {
get startContainer() {
return wrap(unsafeUnwrap(this).startContainer);
},
get endContainer() {
return wrap(unsafeUnwrap(this).endContainer);
},
get commonAncestorContainer() {
return wrap(unsafeUnwrap(this).commonAncestorContainer);
},
setStart: function(refNode, offset) {
unsafeUnwrap(this).setStart(unwrapIfNeeded(refNode), offset);
},
setEnd: function(refNode, offset) {
unsafeUnwrap(this).setEnd(unwrapIfNeeded(refNode), offset);
},
setStartBefore: function(refNode) {
unsafeUnwrap(this).setStartBefore(unwrapIfNeeded(refNode));
},
setStartAfter: function(refNode) {
unsafeUnwrap(this).setStartAfter(unwrapIfNeeded(refNode));
},
setEndBefore: function(refNode) {
unsafeUnwrap(this).setEndBefore(unwrapIfNeeded(refNode));
},
setEndAfter: function(refNode) {
unsafeUnwrap(this).setEndAfter(unwrapIfNeeded(refNode));
},
selectNode: function(refNode) {
unsafeUnwrap(this).selectNode(unwrapIfNeeded(refNode));
},
selectNodeContents: function(refNode) {
unsafeUnwrap(this).selectNodeContents(unwrapIfNeeded(refNode));
},
compareBoundaryPoints: function(how, sourceRange) {
return unsafeUnwrap(this).compareBoundaryPoints(how, unwrap(sourceRange));
},
extractContents: function() {
return wrap(unsafeUnwrap(this).extractContents());
},
cloneContents: function() {
return wrap(unsafeUnwrap(this).cloneContents());
},
insertNode: function(node) {
unsafeUnwrap(this).insertNode(unwrapIfNeeded(node));
},
surroundContents: function(newParent) {
unsafeUnwrap(this).surroundContents(unwrapIfNeeded(newParent));
},
cloneRange: function() {
return wrap(unsafeUnwrap(this).cloneRange());
},
isPointInRange: function(node, offset) {
return unsafeUnwrap(this).isPointInRange(unwrapIfNeeded(node), offset);
},
comparePoint: function(node, offset) {
return unsafeUnwrap(this).comparePoint(unwrapIfNeeded(node), offset);
},
intersectsNode: function(node) {
return unsafeUnwrap(this).intersectsNode(unwrapIfNeeded(node));
},
toString: function() {
return unsafeUnwrap(this).toString();
}
};
if (OriginalRange.prototype.createContextualFragment) {
Range.prototype.createContextualFragment = function(html) {
return wrap(unsafeUnwrap(this).createContextualFragment(html));
};
}
registerWrapper(window.Range, Range, document.createRange());
scope.wrappers.Range = Range;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var GetElementsByInterface = scope.GetElementsByInterface;
var ParentNodeInterface = scope.ParentNodeInterface;
var SelectorsInterface = scope.SelectorsInterface;
var mixin = scope.mixin;
var registerObject = scope.registerObject;
var DocumentFragment = registerObject(document.createDocumentFragment());
mixin(DocumentFragment.prototype, ParentNodeInterface);
mixin(DocumentFragment.prototype, SelectorsInterface);
mixin(DocumentFragment.prototype, GetElementsByInterface);
var Comment = registerObject(document.createComment(""));
scope.wrappers.Comment = Comment;
scope.wrappers.DocumentFragment = DocumentFragment;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var DocumentFragment = scope.wrappers.DocumentFragment;
var TreeScope = scope.TreeScope;
var elementFromPoint = scope.elementFromPoint;
var getInnerHTML = scope.getInnerHTML;
var getTreeScope = scope.getTreeScope;
var mixin = scope.mixin;
var rewrap = scope.rewrap;
var setInnerHTML = scope.setInnerHTML;
var unsafeUnwrap = scope.unsafeUnwrap;
var unwrap = scope.unwrap;
var shadowHostTable = new WeakMap();
var nextOlderShadowTreeTable = new WeakMap();
var spaceCharRe = /[ \t\n\r\f]/;
function ShadowRoot(hostWrapper) {
var node = unwrap(unsafeUnwrap(hostWrapper).ownerDocument.createDocumentFragment());
DocumentFragment.call(this, node);
rewrap(node, this);
var oldShadowRoot = hostWrapper.shadowRoot;
nextOlderShadowTreeTable.set(this, oldShadowRoot);
this.treeScope_ = new TreeScope(this, getTreeScope(oldShadowRoot || hostWrapper));
shadowHostTable.set(this, hostWrapper);
}
ShadowRoot.prototype = Object.create(DocumentFragment.prototype);
mixin(ShadowRoot.prototype, {
constructor: ShadowRoot,
get innerHTML() {
return getInnerHTML(this);
},
set innerHTML(value) {
setInnerHTML(this, value);
this.invalidateShadowRenderer();
},
get olderShadowRoot() {
return nextOlderShadowTreeTable.get(this) || null;
},
get host() {
return shadowHostTable.get(this) || null;
},
invalidateShadowRenderer: function() {
return shadowHostTable.get(this).invalidateShadowRenderer();
},
elementFromPoint: function(x, y) {
return elementFromPoint(this, this.ownerDocument, x, y);
},
getElementById: function(id) {
if (spaceCharRe.test(id)) return null;
return this.querySelector('[id="' + id + '"]');
}
});
scope.wrappers.ShadowRoot = ShadowRoot;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var Element = scope.wrappers.Element;
var HTMLContentElement = scope.wrappers.HTMLContentElement;
var HTMLShadowElement = scope.wrappers.HTMLShadowElement;
var Node = scope.wrappers.Node;
var ShadowRoot = scope.wrappers.ShadowRoot;
var assert = scope.assert;
var getTreeScope = scope.getTreeScope;
var mixin = scope.mixin;
var oneOf = scope.oneOf;
var unsafeUnwrap = scope.unsafeUnwrap;
var unwrap = scope.unwrap;
var wrap = scope.wrap;
var ArraySplice = scope.ArraySplice;
function updateWrapperUpAndSideways(wrapper) {
wrapper.previousSibling_ = wrapper.previousSibling;
wrapper.nextSibling_ = wrapper.nextSibling;
wrapper.parentNode_ = wrapper.parentNode;
}
function updateWrapperDown(wrapper) {
wrapper.firstChild_ = wrapper.firstChild;
wrapper.lastChild_ = wrapper.lastChild;
}
function updateAllChildNodes(parentNodeWrapper) {
assert(parentNodeWrapper instanceof Node);
for (var childWrapper = parentNodeWrapper.firstChild; childWrapper; childWrapper = childWrapper.nextSibling) {
updateWrapperUpAndSideways(childWrapper);
}
updateWrapperDown(parentNodeWrapper);
}
function insertBefore(parentNodeWrapper, newChildWrapper, refChildWrapper) {
var parentNode = unwrap(parentNodeWrapper);
var newChild = unwrap(newChildWrapper);
var refChild = refChildWrapper ? unwrap(refChildWrapper) : null;
remove(newChildWrapper);
updateWrapperUpAndSideways(newChildWrapper);
if (!refChildWrapper) {
parentNodeWrapper.lastChild_ = parentNodeWrapper.lastChild;
if (parentNodeWrapper.lastChild === parentNodeWrapper.firstChild) parentNodeWrapper.firstChild_ = parentNodeWrapper.firstChild;
var lastChildWrapper = wrap(parentNode.lastChild);
if (lastChildWrapper) lastChildWrapper.nextSibling_ = lastChildWrapper.nextSibling;
} else {
if (parentNodeWrapper.firstChild === refChildWrapper) parentNodeWrapper.firstChild_ = refChildWrapper;
refChildWrapper.previousSibling_ = refChildWrapper.previousSibling;
}
scope.originalInsertBefore.call(parentNode, newChild, refChild);
}
function remove(nodeWrapper) {
var node = unwrap(nodeWrapper);
var parentNode = node.parentNode;
if (!parentNode) return;
var parentNodeWrapper = wrap(parentNode);
updateWrapperUpAndSideways(nodeWrapper);
if (nodeWrapper.previousSibling) nodeWrapper.previousSibling.nextSibling_ = nodeWrapper;
if (nodeWrapper.nextSibling) nodeWrapper.nextSibling.previousSibling_ = nodeWrapper;
if (parentNodeWrapper.lastChild === nodeWrapper) parentNodeWrapper.lastChild_ = nodeWrapper;
if (parentNodeWrapper.firstChild === nodeWrapper) parentNodeWrapper.firstChild_ = nodeWrapper;
scope.originalRemoveChild.call(parentNode, node);
}
var distributedNodesTable = new WeakMap();
var destinationInsertionPointsTable = new WeakMap();
var rendererForHostTable = new WeakMap();
function resetDistributedNodes(insertionPoint) {
distributedNodesTable.set(insertionPoint, []);
}
function getDistributedNodes(insertionPoint) {
var rv = distributedNodesTable.get(insertionPoint);
if (!rv) distributedNodesTable.set(insertionPoint, rv = []);
return rv;
}
function getChildNodesSnapshot(node) {
var result = [], i = 0;
for (var child = node.firstChild; child; child = child.nextSibling) {
result[i++] = child;
}
return result;
}
var request = oneOf(window, [ "requestAnimationFrame", "mozRequestAnimationFrame", "webkitRequestAnimationFrame", "setTimeout" ]);
var pendingDirtyRenderers = [];
var renderTimer;
function renderAllPending() {
for (var i = 0; i < pendingDirtyRenderers.length; i++) {
var renderer = pendingDirtyRenderers[i];
var parentRenderer = renderer.parentRenderer;
if (parentRenderer && parentRenderer.dirty) continue;
renderer.render();
}
pendingDirtyRenderers = [];
}
function handleRequestAnimationFrame() {
renderTimer = null;
renderAllPending();
}
function getRendererForHost(host) {
var renderer = rendererForHostTable.get(host);
if (!renderer) {
renderer = new ShadowRenderer(host);
rendererForHostTable.set(host, renderer);
}
return renderer;
}
function getShadowRootAncestor(node) {
var root = getTreeScope(node).root;
if (root instanceof ShadowRoot) return root;
return null;
}
function getRendererForShadowRoot(shadowRoot) {
return getRendererForHost(shadowRoot.host);
}
var spliceDiff = new ArraySplice();
spliceDiff.equals = function(renderNode, rawNode) {
return unwrap(renderNode.node) === rawNode;
};
function RenderNode(node) {
this.skip = false;
this.node = node;
this.childNodes = [];
}
RenderNode.prototype = {
append: function(node) {
var rv = new RenderNode(node);
this.childNodes.push(rv);
return rv;
},
sync: function(opt_added) {
if (this.skip) return;
var nodeWrapper = this.node;
var newChildren = this.childNodes;
var oldChildren = getChildNodesSnapshot(unwrap(nodeWrapper));
var added = opt_added || new WeakMap();
var splices = spliceDiff.calculateSplices(newChildren, oldChildren);
var newIndex = 0, oldIndex = 0;
var lastIndex = 0;
for (var i = 0; i < splices.length; i++) {
var splice = splices[i];
for (;lastIndex < splice.index; lastIndex++) {
oldIndex++;
newChildren[newIndex++].sync(added);
}
var removedCount = splice.removed.length;
for (var j = 0; j < removedCount; j++) {
var wrapper = wrap(oldChildren[oldIndex++]);
if (!added.get(wrapper)) remove(wrapper);
}
var addedCount = splice.addedCount;
var refNode = oldChildren[oldIndex] && wrap(oldChildren[oldIndex]);
for (var j = 0; j < addedCount; j++) {
var newChildRenderNode = newChildren[newIndex++];
var newChildWrapper = newChildRenderNode.node;
insertBefore(nodeWrapper, newChildWrapper, refNode);
added.set(newChildWrapper, true);
newChildRenderNode.sync(added);
}
lastIndex += addedCount;
}
for (var i = lastIndex; i < newChildren.length; i++) {
newChildren[i].sync(added);
}
}
};
function ShadowRenderer(host) {
this.host = host;
this.dirty = false;
this.invalidateAttributes();
this.associateNode(host);
}
ShadowRenderer.prototype = {
render: function(opt_renderNode) {
if (!this.dirty) return;
this.invalidateAttributes();
var host = this.host;
this.distribution(host);
var renderNode = opt_renderNode || new RenderNode(host);
this.buildRenderTree(renderNode, host);
var topMostRenderer = !opt_renderNode;
if (topMostRenderer) renderNode.sync();
this.dirty = false;
},
get parentRenderer() {
return getTreeScope(this.host).renderer;
},
invalidate: function() {
if (!this.dirty) {
this.dirty = true;
var parentRenderer = this.parentRenderer;
if (parentRenderer) parentRenderer.invalidate();
pendingDirtyRenderers.push(this);
if (renderTimer) return;
renderTimer = window[request](handleRequestAnimationFrame, 0);
}
},
distribution: function(root) {
this.resetAllSubtrees(root);
this.distributionResolution(root);
},
resetAll: function(node) {
if (isInsertionPoint(node)) resetDistributedNodes(node); else resetDestinationInsertionPoints(node);
this.resetAllSubtrees(node);
},
resetAllSubtrees: function(node) {
for (var child = node.firstChild; child; child = child.nextSibling) {
this.resetAll(child);
}
if (node.shadowRoot) this.resetAll(node.shadowRoot);
if (node.olderShadowRoot) this.resetAll(node.olderShadowRoot);
},
distributionResolution: function(node) {
if (isShadowHost(node)) {
var shadowHost = node;
var pool = poolPopulation(shadowHost);
var shadowTrees = getShadowTrees(shadowHost);
for (var i = 0; i < shadowTrees.length; i++) {
this.poolDistribution(shadowTrees[i], pool);
}
for (var i = shadowTrees.length - 1; i >= 0; i--) {
var shadowTree = shadowTrees[i];
var shadow = getShadowInsertionPoint(shadowTree);
if (shadow) {
var olderShadowRoot = shadowTree.olderShadowRoot;
if (olderShadowRoot) {
pool = poolPopulation(olderShadowRoot);
}
for (var j = 0; j < pool.length; j++) {
destributeNodeInto(pool[j], shadow);
}
}
this.distributionResolution(shadowTree);
}
}
for (var child = node.firstChild; child; child = child.nextSibling) {
this.distributionResolution(child);
}
},
poolDistribution: function(node, pool) {
if (node instanceof HTMLShadowElement) return;
if (node instanceof HTMLContentElement) {
var content = node;
this.updateDependentAttributes(content.getAttribute("select"));
var anyDistributed = false;
for (var i = 0; i < pool.length; i++) {
var node = pool[i];
if (!node) continue;
if (matches(node, content)) {
destributeNodeInto(node, content);
pool[i] = undefined;
anyDistributed = true;
}
}
if (!anyDistributed) {
for (var child = content.firstChild; child; child = child.nextSibling) {
destributeNodeInto(child, content);
}
}
return;
}
for (var child = node.firstChild; child; child = child.nextSibling) {
this.poolDistribution(child, pool);
}
},
buildRenderTree: function(renderNode, node) {
var children = this.compose(node);
for (var i = 0; i < children.length; i++) {
var child = children[i];
var childRenderNode = renderNode.append(child);
this.buildRenderTree(childRenderNode, child);
}
if (isShadowHost(node)) {
var renderer = getRendererForHost(node);
renderer.dirty = false;
}
},
compose: function(node) {
var children = [];
var p = node.shadowRoot || node;
for (var child = p.firstChild; child; child = child.nextSibling) {
if (isInsertionPoint(child)) {
this.associateNode(p);
var distributedNodes = getDistributedNodes(child);
for (var j = 0; j < distributedNodes.length; j++) {
var distributedNode = distributedNodes[j];
if (isFinalDestination(child, distributedNode)) children.push(distributedNode);
}
} else {
children.push(child);
}
}
return children;
},
invalidateAttributes: function() {
this.attributes = Object.create(null);
},
updateDependentAttributes: function(selector) {
if (!selector) return;
var attributes = this.attributes;
if (/\.\w+/.test(selector)) attributes["class"] = true;
if (/#\w+/.test(selector)) attributes["id"] = true;
selector.replace(/\[\s*([^\s=\|~\]]+)/g, function(_, name) {
attributes[name] = true;
});
},
dependsOnAttribute: function(name) {
return this.attributes[name];
},
associateNode: function(node) {
unsafeUnwrap(node).polymerShadowRenderer_ = this;
}
};
function poolPopulation(node) {
var pool = [];
for (var child = node.firstChild; child; child = child.nextSibling) {
if (isInsertionPoint(child)) {
pool.push.apply(pool, getDistributedNodes(child));
} else {
pool.push(child);
}
}
return pool;
}
function getShadowInsertionPoint(node) {
if (node instanceof HTMLShadowElement) return node;
if (node instanceof HTMLContentElement) return null;
for (var child = node.firstChild; child; child = child.nextSibling) {
var res = getShadowInsertionPoint(child);
if (res) return res;
}
return null;
}
function destributeNodeInto(child, insertionPoint) {
getDistributedNodes(insertionPoint).push(child);
var points = destinationInsertionPointsTable.get(child);
if (!points) destinationInsertionPointsTable.set(child, [ insertionPoint ]); else points.push(insertionPoint);
}
function getDestinationInsertionPoints(node) {
return destinationInsertionPointsTable.get(node);
}
function resetDestinationInsertionPoints(node) {
destinationInsertionPointsTable.set(node, undefined);
}
var selectorStartCharRe = /^(:not\()?[*.#[a-zA-Z_|]/;
function matches(node, contentElement) {
var select = contentElement.getAttribute("select");
if (!select) return true;
select = select.trim();
if (!select) return true;
if (!(node instanceof Element)) return false;
if (!selectorStartCharRe.test(select)) return false;
try {
return node.matches(select);
} catch (ex) {
return false;
}
}
function isFinalDestination(insertionPoint, node) {
var points = getDestinationInsertionPoints(node);
return points && points[points.length - 1] === insertionPoint;
}
function isInsertionPoint(node) {
return node instanceof HTMLContentElement || node instanceof HTMLShadowElement;
}
function isShadowHost(shadowHost) {
return shadowHost.shadowRoot;
}
function getShadowTrees(host) {
var trees = [];
for (var tree = host.shadowRoot; tree; tree = tree.olderShadowRoot) {
trees.push(tree);
}
return trees;
}
function render(host) {
new ShadowRenderer(host).render();
}
Node.prototype.invalidateShadowRenderer = function(force) {
var renderer = unsafeUnwrap(this).polymerShadowRenderer_;
if (renderer) {
renderer.invalidate();
return true;
}
return false;
};
HTMLContentElement.prototype.getDistributedNodes = HTMLShadowElement.prototype.getDistributedNodes = function() {
renderAllPending();
return getDistributedNodes(this);
};
Element.prototype.getDestinationInsertionPoints = function() {
renderAllPending();
return getDestinationInsertionPoints(this) || [];
};
HTMLContentElement.prototype.nodeIsInserted_ = HTMLShadowElement.prototype.nodeIsInserted_ = function() {
this.invalidateShadowRenderer();
var shadowRoot = getShadowRootAncestor(this);
var renderer;
if (shadowRoot) renderer = getRendererForShadowRoot(shadowRoot);
unsafeUnwrap(this).polymerShadowRenderer_ = renderer;
if (renderer) renderer.invalidate();
};
scope.getRendererForHost = getRendererForHost;
scope.getShadowTrees = getShadowTrees;
scope.renderAllPending = renderAllPending;
scope.getDestinationInsertionPoints = getDestinationInsertionPoints;
scope.visual = {
insertBefore: insertBefore,
remove: remove
};
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var HTMLElement = scope.wrappers.HTMLElement;
var assert = scope.assert;
var mixin = scope.mixin;
var registerWrapper = scope.registerWrapper;
var unwrap = scope.unwrap;
var wrap = scope.wrap;
var elementsWithFormProperty = [ "HTMLButtonElement", "HTMLFieldSetElement", "HTMLInputElement", "HTMLKeygenElement", "HTMLLabelElement", "HTMLLegendElement", "HTMLObjectElement", "HTMLOutputElement", "HTMLTextAreaElement" ];
function createWrapperConstructor(name) {
if (!window[name]) return;
assert(!scope.wrappers[name]);
var GeneratedWrapper = function(node) {
HTMLElement.call(this, node);
};
GeneratedWrapper.prototype = Object.create(HTMLElement.prototype);
mixin(GeneratedWrapper.prototype, {
get form() {
return wrap(unwrap(this).form);
}
});
registerWrapper(window[name], GeneratedWrapper, document.createElement(name.slice(4, -7)));
scope.wrappers[name] = GeneratedWrapper;
}
elementsWithFormProperty.forEach(createWrapperConstructor);
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var registerWrapper = scope.registerWrapper;
var setWrapper = scope.setWrapper;
var unsafeUnwrap = scope.unsafeUnwrap;
var unwrap = scope.unwrap;
var unwrapIfNeeded = scope.unwrapIfNeeded;
var wrap = scope.wrap;
var OriginalSelection = window.Selection;
function Selection(impl) {
setWrapper(impl, this);
}
Selection.prototype = {
get anchorNode() {
return wrap(unsafeUnwrap(this).anchorNode);
},
get focusNode() {
return wrap(unsafeUnwrap(this).focusNode);
},
addRange: function(range) {
unsafeUnwrap(this).addRange(unwrap(range));
},
collapse: function(node, index) {
unsafeUnwrap(this).collapse(unwrapIfNeeded(node), index);
},
containsNode: function(node, allowPartial) {
return unsafeUnwrap(this).containsNode(unwrapIfNeeded(node), allowPartial);
},
extend: function(node, offset) {
unsafeUnwrap(this).extend(unwrapIfNeeded(node), offset);
},
getRangeAt: function(index) {
return wrap(unsafeUnwrap(this).getRangeAt(index));
},
removeRange: function(range) {
unsafeUnwrap(this).removeRange(unwrap(range));
},
selectAllChildren: function(node) {
unsafeUnwrap(this).selectAllChildren(unwrapIfNeeded(node));
},
toString: function() {
return unsafeUnwrap(this).toString();
}
};
registerWrapper(window.Selection, Selection, window.getSelection());
scope.wrappers.Selection = Selection;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var GetElementsByInterface = scope.GetElementsByInterface;
var Node = scope.wrappers.Node;
var ParentNodeInterface = scope.ParentNodeInterface;
var Selection = scope.wrappers.Selection;
var SelectorsInterface = scope.SelectorsInterface;
var ShadowRoot = scope.wrappers.ShadowRoot;
var TreeScope = scope.TreeScope;
var cloneNode = scope.cloneNode;
var defineWrapGetter = scope.defineWrapGetter;
var elementFromPoint = scope.elementFromPoint;
var forwardMethodsToWrapper = scope.forwardMethodsToWrapper;
var matchesNames = scope.matchesNames;
var mixin = scope.mixin;
var registerWrapper = scope.registerWrapper;
var renderAllPending = scope.renderAllPending;
var rewrap = scope.rewrap;
var setWrapper = scope.setWrapper;
var unsafeUnwrap = scope.unsafeUnwrap;
var unwrap = scope.unwrap;
var wrap = scope.wrap;
var wrapEventTargetMethods = scope.wrapEventTargetMethods;
var wrapNodeList = scope.wrapNodeList;
var implementationTable = new WeakMap();
function Document(node) {
Node.call(this, node);
this.treeScope_ = new TreeScope(this, null);
}
Document.prototype = Object.create(Node.prototype);
defineWrapGetter(Document, "documentElement");
defineWrapGetter(Document, "body");
defineWrapGetter(Document, "head");
function wrapMethod(name) {
var original = document[name];
Document.prototype[name] = function() {
return wrap(original.apply(unsafeUnwrap(this), arguments));
};
}
[ "createComment", "createDocumentFragment", "createElement", "createElementNS", "createEvent", "createEventNS", "createRange", "createTextNode", "getElementById" ].forEach(wrapMethod);
var originalAdoptNode = document.adoptNode;
function adoptNodeNoRemove(node, doc) {
originalAdoptNode.call(unsafeUnwrap(doc), unwrap(node));
adoptSubtree(node, doc);
}
function adoptSubtree(node, doc) {
if (node.shadowRoot) doc.adoptNode(node.shadowRoot);
if (node instanceof ShadowRoot) adoptOlderShadowRoots(node, doc);
for (var child = node.firstChild; child; child = child.nextSibling) {
adoptSubtree(child, doc);
}
}
function adoptOlderShadowRoots(shadowRoot, doc) {
var oldShadowRoot = shadowRoot.olderShadowRoot;
if (oldShadowRoot) doc.adoptNode(oldShadowRoot);
}
var originalGetSelection = document.getSelection;
mixin(Document.prototype, {
adoptNode: function(node) {
if (node.parentNode) node.parentNode.removeChild(node);
adoptNodeNoRemove(node, this);
return node;
},
elementFromPoint: function(x, y) {
return elementFromPoint(this, this, x, y);
},
importNode: function(node, deep) {
return cloneNode(node, deep, unsafeUnwrap(this));
},
getSelection: function() {
renderAllPending();
return new Selection(originalGetSelection.call(unwrap(this)));
},
getElementsByName: function(name) {
return SelectorsInterface.querySelectorAll.call(this, "[name=" + JSON.stringify(String(name)) + "]");
}
});
if (document.registerElement) {
var originalRegisterElement = document.registerElement;
Document.prototype.registerElement = function(tagName, object) {
var prototype, extendsOption;
if (object !== undefined) {
prototype = object.prototype;
extendsOption = object.extends;
}
if (!prototype) prototype = Object.create(HTMLElement.prototype);
if (scope.nativePrototypeTable.get(prototype)) {
throw new Error("NotSupportedError");
}
var proto = Object.getPrototypeOf(prototype);
var nativePrototype;
var prototypes = [];
while (proto) {
nativePrototype = scope.nativePrototypeTable.get(proto);
if (nativePrototype) break;
prototypes.push(proto);
proto = Object.getPrototypeOf(proto);
}
if (!nativePrototype) {
throw new Error("NotSupportedError");
}
var newPrototype = Object.create(nativePrototype);
for (var i = prototypes.length - 1; i >= 0; i--) {
newPrototype = Object.create(newPrototype);
}
[ "createdCallback", "attachedCallback", "detachedCallback", "attributeChangedCallback" ].forEach(function(name) {
var f = prototype[name];
if (!f) return;
newPrototype[name] = function() {
if (!(wrap(this) instanceof CustomElementConstructor)) {
rewrap(this);
}
f.apply(wrap(this), arguments);
};
});
var p = {
prototype: newPrototype
};
if (extendsOption) p.extends = extendsOption;
function CustomElementConstructor(node) {
if (!node) {
if (extendsOption) {
return document.createElement(extendsOption, tagName);
} else {
return document.createElement(tagName);
}
}
setWrapper(node, this);
}
CustomElementConstructor.prototype = prototype;
CustomElementConstructor.prototype.constructor = CustomElementConstructor;
scope.constructorTable.set(newPrototype, CustomElementConstructor);
scope.nativePrototypeTable.set(prototype, newPrototype);
var nativeConstructor = originalRegisterElement.call(unwrap(this), tagName, p);
return CustomElementConstructor;
};
forwardMethodsToWrapper([ window.HTMLDocument || window.Document ], [ "registerElement" ]);
}
forwardMethodsToWrapper([ window.HTMLBodyElement, window.HTMLDocument || window.Document, window.HTMLHeadElement, window.HTMLHtmlElement ], [ "appendChild", "compareDocumentPosition", "contains", "getElementsByClassName", "getElementsByTagName", "getElementsByTagNameNS", "insertBefore", "querySelector", "querySelectorAll", "removeChild", "replaceChild" ].concat(matchesNames));
forwardMethodsToWrapper([ window.HTMLDocument || window.Document ], [ "adoptNode", "importNode", "contains", "createComment", "createDocumentFragment", "createElement", "createElementNS", "createEvent", "createEventNS", "createRange", "createTextNode", "elementFromPoint", "getElementById", "getElementsByName", "getSelection" ]);
mixin(Document.prototype, GetElementsByInterface);
mixin(Document.prototype, ParentNodeInterface);
mixin(Document.prototype, SelectorsInterface);
mixin(Document.prototype, {
get implementation() {
var implementation = implementationTable.get(this);
if (implementation) return implementation;
implementation = new DOMImplementation(unwrap(this).implementation);
implementationTable.set(this, implementation);
return implementation;
},
get defaultView() {
return wrap(unwrap(this).defaultView);
}
});
registerWrapper(window.Document, Document, document.implementation.createHTMLDocument(""));
if (window.HTMLDocument) registerWrapper(window.HTMLDocument, Document);
wrapEventTargetMethods([ window.HTMLBodyElement, window.HTMLDocument || window.Document, window.HTMLHeadElement ]);
function DOMImplementation(impl) {
setWrapper(impl, this);
}
function wrapImplMethod(constructor, name) {
var original = document.implementation[name];
constructor.prototype[name] = function() {
return wrap(original.apply(unsafeUnwrap(this), arguments));
};
}
function forwardImplMethod(constructor, name) {
var original = document.implementation[name];
constructor.prototype[name] = function() {
return original.apply(unsafeUnwrap(this), arguments);
};
}
wrapImplMethod(DOMImplementation, "createDocumentType");
wrapImplMethod(DOMImplementation, "createDocument");
wrapImplMethod(DOMImplementation, "createHTMLDocument");
forwardImplMethod(DOMImplementation, "hasFeature");
registerWrapper(window.DOMImplementation, DOMImplementation);
forwardMethodsToWrapper([ window.DOMImplementation ], [ "createDocumentType", "createDocument", "createHTMLDocument", "hasFeature" ]);
scope.adoptNodeNoRemove = adoptNodeNoRemove;
scope.wrappers.DOMImplementation = DOMImplementation;
scope.wrappers.Document = Document;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var EventTarget = scope.wrappers.EventTarget;
var Selection = scope.wrappers.Selection;
var mixin = scope.mixin;
var registerWrapper = scope.registerWrapper;
var renderAllPending = scope.renderAllPending;
var unwrap = scope.unwrap;
var unwrapIfNeeded = scope.unwrapIfNeeded;
var wrap = scope.wrap;
var OriginalWindow = window.Window;
var originalGetComputedStyle = window.getComputedStyle;
var originalGetDefaultComputedStyle = window.getDefaultComputedStyle;
var originalGetSelection = window.getSelection;
function Window(impl) {
EventTarget.call(this, impl);
}
Window.prototype = Object.create(EventTarget.prototype);
OriginalWindow.prototype.getComputedStyle = function(el, pseudo) {
return wrap(this || window).getComputedStyle(unwrapIfNeeded(el), pseudo);
};
if (originalGetDefaultComputedStyle) {
OriginalWindow.prototype.getDefaultComputedStyle = function(el, pseudo) {
return wrap(this || window).getDefaultComputedStyle(unwrapIfNeeded(el), pseudo);
};
}
OriginalWindow.prototype.getSelection = function() {
return wrap(this || window).getSelection();
};
delete window.getComputedStyle;
delete window.getDefaultComputedStyle;
delete window.getSelection;
[ "addEventListener", "removeEventListener", "dispatchEvent" ].forEach(function(name) {
OriginalWindow.prototype[name] = function() {
var w = wrap(this || window);
return w[name].apply(w, arguments);
};
delete window[name];
});
mixin(Window.prototype, {
getComputedStyle: function(el, pseudo) {
renderAllPending();
return originalGetComputedStyle.call(unwrap(this), unwrapIfNeeded(el), pseudo);
},
getSelection: function() {
renderAllPending();
return new Selection(originalGetSelection.call(unwrap(this)));
},
get document() {
return wrap(unwrap(this).document);
}
});
if (originalGetDefaultComputedStyle) {
Window.prototype.getDefaultComputedStyle = function(el, pseudo) {
renderAllPending();
return originalGetDefaultComputedStyle.call(unwrap(this), unwrapIfNeeded(el), pseudo);
};
}
registerWrapper(OriginalWindow, Window, window);
scope.wrappers.Window = Window;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var unwrap = scope.unwrap;
var OriginalDataTransfer = window.DataTransfer || window.Clipboard;
var OriginalDataTransferSetDragImage = OriginalDataTransfer.prototype.setDragImage;
if (OriginalDataTransferSetDragImage) {
OriginalDataTransfer.prototype.setDragImage = function(image, x, y) {
OriginalDataTransferSetDragImage.call(this, unwrap(image), x, y);
};
}
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var registerWrapper = scope.registerWrapper;
var setWrapper = scope.setWrapper;
var unwrap = scope.unwrap;
var OriginalFormData = window.FormData;
if (!OriginalFormData) return;
function FormData(formElement) {
var impl;
if (formElement instanceof OriginalFormData) {
impl = formElement;
} else {
impl = new OriginalFormData(formElement && unwrap(formElement));
}
setWrapper(impl, this);
}
registerWrapper(OriginalFormData, FormData, new OriginalFormData());
scope.wrappers.FormData = FormData;
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var unwrapIfNeeded = scope.unwrapIfNeeded;
var originalSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function(obj) {
return originalSend.call(this, unwrapIfNeeded(obj));
};
})(window.ShadowDOMPolyfill);
(function(scope) {
"use strict";
var isWrapperFor = scope.isWrapperFor;
var elements = {
a: "HTMLAnchorElement",
area: "HTMLAreaElement",
audio: "HTMLAudioElement",
base: "HTMLBaseElement",
body: "HTMLBodyElement",
br: "HTMLBRElement",
button: "HTMLButtonElement",
canvas: "HTMLCanvasElement",
caption: "HTMLTableCaptionElement",
col: "HTMLTableColElement",
content: "HTMLContentElement",
data: "HTMLDataElement",
datalist: "HTMLDataListElement",
del: "HTMLModElement",
dir: "HTMLDirectoryElement",
div: "HTMLDivElement",
dl: "HTMLDListElement",
embed: "HTMLEmbedElement",
fieldset: "HTMLFieldSetElement",
font: "HTMLFontElement",
form: "HTMLFormElement",
frame: "HTMLFrameElement",
frameset: "HTMLFrameSetElement",
h1: "HTMLHeadingElement",
head: "HTMLHeadElement",
hr: "HTMLHRElement",
html: "HTMLHtmlElement",
iframe: "HTMLIFrameElement",
img: "HTMLImageElement",
input: "HTMLInputElement",
keygen: "HTMLKeygenElement",
label: "HTMLLabelElement",
legend: "HTMLLegendElement",
li: "HTMLLIElement",
link: "HTMLLinkElement",
map: "HTMLMapElement",
marquee: "HTMLMarqueeElement",
menu: "HTMLMenuElement",
menuitem: "HTMLMenuItemElement",
meta: "HTMLMetaElement",
meter: "HTMLMeterElement",
object: "HTMLObjectElement",
ol: "HTMLOListElement",
optgroup: "HTMLOptGroupElement",
option: "HTMLOptionElement",
output: "HTMLOutputElement",
p: "HTMLParagraphElement",
param: "HTMLParamElement",
pre: "HTMLPreElement",
progress: "HTMLProgressElement",
q: "HTMLQuoteElement",
script: "HTMLScriptElement",
select: "HTMLSelectElement",
shadow: "HTMLShadowElement",
source: "HTMLSourceElement",
span: "HTMLSpanElement",
style: "HTMLStyleElement",
table: "HTMLTableElement",
tbody: "HTMLTableSectionElement",
template: "HTMLTemplateElement",
textarea: "HTMLTextAreaElement",
thead: "HTMLTableSectionElement",
time: "HTMLTimeElement",
title: "HTMLTitleElement",
tr: "HTMLTableRowElement",
track: "HTMLTrackElement",
ul: "HTMLUListElement",
video: "HTMLVideoElement"
};
function overrideConstructor(tagName) {
var nativeConstructorName = elements[tagName];
var nativeConstructor = window[nativeConstructorName];
if (!nativeConstructor) return;
var element = document.createElement(tagName);
var wrapperConstructor = element.constructor;
window[nativeConstructorName] = wrapperConstructor;
}
Object.keys(elements).forEach(overrideConstructor);
Object.getOwnPropertyNames(scope.wrappers).forEach(function(name) {
window[name] = scope.wrappers[name];
});
})(window.ShadowDOMPolyfill); | kbwatts/topeka-edu | topeka/components/webcomponentsjs/ShadowDOM.debug.js | JavaScript | bsd-2-clause | 168,342 |
var path = require('path');
module.exports = {
root: path.resolve(__dirname, '../../..'),
suites: ['cli/conf/test'],
};
| Polymer/web-component-tester | test/fixtures/cli/conf/rooted/wct.conf.js | JavaScript | bsd-3-clause | 125 |
/*
YUI 3.6.0 (build 5521)
Copyright 2012 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('loader-rollup', function(Y) {
/**
* Optional automatic rollup logic for reducing http connections
* when not using a combo service.
* @module loader
* @submodule rollup
*/
/**
* Look for rollup packages to determine if all of the modules a
* rollup supersedes are required. If so, include the rollup to
* help reduce the total number of connections required. Called
* by calculate(). This is an optional feature, and requires the
* appropriate submodule to function.
* @method _rollup
* @for Loader
* @private
*/
Y.Loader.prototype._rollup = function() {
var i, j, m, s, r = this.required, roll,
info = this.moduleInfo, rolled, c, smod;
// find and cache rollup modules
if (this.dirty || !this.rollups) {
this.rollups = {};
for (i in info) {
if (info.hasOwnProperty(i)) {
m = this.getModule(i);
// if (m && m.rollup && m.supersedes) {
if (m && m.rollup) {
this.rollups[i] = m;
}
}
}
}
// make as many passes as needed to pick up rollup rollups
for (;;) {
rolled = false;
// go through the rollup candidates
for (i in this.rollups) {
if (this.rollups.hasOwnProperty(i)) {
// there can be only one, unless forced
if (!r[i] && ((!this.loaded[i]) || this.forceMap[i])) {
m = this.getModule(i);
s = m.supersedes || [];
roll = false;
// @TODO remove continue
if (!m.rollup) {
continue;
}
c = 0;
// check the threshold
for (j = 0; j < s.length; j++) {
smod = info[s[j]];
// if the superseded module is loaded, we can't
// load the rollup unless it has been forced.
if (this.loaded[s[j]] && !this.forceMap[s[j]]) {
roll = false;
break;
// increment the counter if this module is required.
// if we are beyond the rollup threshold, we will
// use the rollup module
} else if (r[s[j]] && m.type == smod.type) {
c++;
// Y.log("adding to thresh: " + c + ", " + s[j]);
roll = (c >= m.rollup);
if (roll) {
// Y.log("over thresh " + c + ", " + s[j]);
break;
}
}
}
if (roll) {
// Y.log("adding rollup: " + i);
// add the rollup
r[i] = true;
rolled = true;
// expand the rollup's dependencies
this.getRequires(m);
}
}
}
}
// if we made it here w/o rolling up something, we are done
if (!rolled) {
break;
}
}
};
}, '3.6.0' ,{requires:['loader-base']});
| bretkikehara/wattdepot-visualization | src/main/webapp/yui/3.6.0/build/loader-rollup/loader-rollup-debug.js | JavaScript | bsd-3-clause | 3,508 |
/*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'clipboard', 'ms', {
copy: 'Salin',
copyError: 'Keselamatan perisian browser anda tidak membenarkan operasi salinan text/imej. Sila gunakan papan kekunci (Ctrl/Cmd+C).',
cut: 'Potong',
cutError: 'Keselamatan perisian browser anda tidak membenarkan operasi suntingan text/imej. Sila gunakan papan kekunci (Ctrl/Cmd+X).',
paste: 'Tampal',
pasteArea: 'Paste Area', // MISSING
pasteMsg: 'Please paste inside the following box using the keyboard (<strong>Ctrl/Cmd+V</strong>) and hit OK', // MISSING
securityMsg: 'Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.', // MISSING
title: 'Tampal'
} );
| CCI-MIT/XCoLab | view/src/main/resources/static/js/lib/newckeditorplugins/clipboard/lang/ms.js | JavaScript | mit | 878 |
define(function(require) {
'use strict';
var _ = require('underscore');
var Path = require('oroworkflow/js/tools/path-finder/path');
var Graph = require('oroworkflow/js/tools/path-finder/graph');
var Point2d = require('oroworkflow/js/tools/path-finder/point2d');
var Rectangle = require('oroworkflow/js/tools/path-finder/rectangle');
var directions = require('oroworkflow/js/tools/path-finder/directions');
describe('oroworkflow/js/tools/path-finder/path', function() {
beforeEach(function prepareGraph() {
var graph = new Graph();
graph.rectangles.push(new Rectangle(100, 100, 100, 100));
graph.rectangles.push(new Rectangle(300, 300, 100, 100));
graph.build();
this.graph = graph;
this.node100100 = this.graph.getNodeAt(new Point2d(100, 100));
this.node150100 = this.graph.getNodeAt(new Point2d(150, 100));
this.node150200 = this.graph.getNodeAt(new Point2d(150, 200));
this.node200200 = this.graph.getNodeAt(new Point2d(200, 200));
});
it('should construct', function() {
var path = new Path(this.node100100.connections[directions.LEFT_TO_RIGHT.id], this.node100100, null);
expect(path.connection === this.node100100.connections[directions.LEFT_TO_RIGHT.id]).toBeTruthy();
expect(path.fromNode === this.node100100).toBeTruthy();
expect(path.toNode === this.node150100).toBeTruthy();
expect(path.cost).toBe(50);
});
it('should return uid', function() {
var path1 = new Path(this.node200200.connections[directions.LEFT_TO_RIGHT.id], this.node200200, null);
var path2 = new Path(this.node200200.connections[directions.RIGHT_TO_LEFT.id], this.node200200, null);
var path3 = new Path(this.node200200.connections[directions.TOP_TO_BOTTOM.id], this.node200200, null);
var path4 = new Path(this.node200200.connections[directions.BOTTOM_TO_TOP.id], this.node200200, null);
var uids = [path1.uid, path2.uid, path3.uid, path4.uid];
expect(uids.length).toBe(_.uniq(uids).length);
var path1s = new Path(this.node200200.connections[directions.LEFT_TO_RIGHT.id], this.node200200, null);
var path2s = new Path(this.node200200.connections[directions.RIGHT_TO_LEFT.id], this.node200200, null);
var path3s = new Path(this.node200200.connections[directions.TOP_TO_BOTTOM.id], this.node200200, null);
var path4s = new Path(this.node200200.connections[directions.BOTTOM_TO_TOP.id], this.node200200, null);
var uidsS = [path1s.uid, path2s.uid, path3s.uid, path4s.uid];
expect(uids).toEqual(uidsS);
});
it('should calculate if it can be joined with another path', function() {
var path1 = new Path(this.node200200.connections[directions.LEFT_TO_RIGHT.id], this.node200200, null);
var path2 = new Path(this.node200200.connections[directions.RIGHT_TO_LEFT.id], this.node200200, null);
expect(path1.canJoinWith(path2)).toBeFalsy();
expect(path2.canJoinWith(path1)).toBeFalsy();
var path3 = new Path(this.node150200.connections[directions.LEFT_TO_RIGHT.id], this.node150200, null);
expect(path1.canJoinWith(path3)).toBeFalsy();
expect(path2.canJoinWith(path3)).toBeTruthy();
expect(path3.canJoinWith(path2)).toBeTruthy();
});
it('should calculate allConnections', function() {
var path = new Path(this.node100100.connections[directions.LEFT_TO_RIGHT.id], this.node100100, null);
expect(path.allConnections.length).toBe(1);
expect(path.allConnections[0] === this.node100100.connections[directions.LEFT_TO_RIGHT.id]).toBeTruthy();
var nextPath = new Path(this.node150100.connections[directions.LEFT_TO_RIGHT.id], this.node150100, path);
expect(nextPath.allConnections.length).toBe(2);
expect(nextPath.allConnections[0] === this.node100100.connections[directions.LEFT_TO_RIGHT.id])
.toBeTruthy();
expect(nextPath.allConnections[1] === this.node150100.connections[directions.LEFT_TO_RIGHT.id])
.toBeTruthy();
});
it('should calculate includedConnections', function() {
var path = new Path(this.node100100.connections[directions.LEFT_TO_RIGHT.id], this.node100100, null);
var nextPath = new Path(this.node150100.connections[directions.LEFT_TO_RIGHT.id], this.node150100, path);
this.node150100.vAxis.ensureTraversableSiblings();
expect(nextPath.allConnections.length).toBe(4);
expect(nextPath.includedConnections.length).toBe(2);
});
it('should return all nodes included into it', function() {
var path = new Path(this.node100100.connections[directions.LEFT_TO_RIGHT.id], this.node100100, null);
expect(path.allNodes.length).toBe(2);
expect(path.allNodes[0] === this.node100100).toBeTruthy();
expect(path.allNodes[1] === this.node150100).toBeTruthy();
var nextPath = new Path(this.node150100.connections[directions.LEFT_TO_RIGHT.id], this.node150100, path);
expect(nextPath.allNodes.length).toBe(3);
expect(nextPath.allNodes[0] === this.node100100).toBeTruthy();
expect(nextPath.allNodes[1] === this.node150100).toBeTruthy();
expect(nextPath.allNodes[2] === this.graph.getNodeAt(new Point2d(200, 100))).toBeTruthy();
});
it('should return corner points', function() {
var path = new Path(this.node100100.connections[directions.LEFT_TO_RIGHT.id], this.node100100, null);
expect(path.points.length).toBe(2);
expect(path.points[0].id).toBe((new Point2d(150, 100)).id);
expect(path.points[1].id).toBe((new Point2d(100, 100)).id);
var nextPath = new Path(this.node150100.connections[directions.TOP_TO_BOTTOM.id], this.node150100, path);
expect(nextPath.points.length).toBe(3);
expect(nextPath.points[0].id).toBe((new Point2d(150, 149)).id);
expect(nextPath.points[1].id).toBe((new Point2d(150, 100)).id);
expect(nextPath.points[2].id).toBe((new Point2d(100, 100)).id);
});
it('should return sibling paths', function() {
var path = new Path(this.node100100.connections[directions.LEFT_TO_RIGHT.id], this.node100100, null);
expect(path.getSiblings().length).toBe(1);
expect(path.getSiblings()[0] === path).toBeTruthy();
this.node100100.vAxis.ensureTraversableSiblings();
expect(path.getSiblings().length).toBe(1);
expect(path.getSiblings()[0] === path).toBeTruthy();
this.node100100.hAxis.ensureTraversableSiblings();
expect(path.getSiblings().length).toBe(3);
expect(path.getSiblings()[1] === path).toBeTruthy();
});
});
});
| Djamy/platform | src/Oro/Bundle/WorkflowBundle/Tests/JS/tools/path-finder/pathSpec.js | JavaScript | mit | 7,095 |
define([
'aeris/util',
'aeris/geolocate/html5geolocateservice',
'aeris/geolocate/errors/geolocateserviceerror',
'mocks/window/navigator',
'mocks/window/geolocationresults',
'mocks/window/geolocationerror'
], function(_, HTML5GeolocateService, GeolocateServiceError, MockNavigator, MockGeolocationResults, MockGeolocationError) {
describe('The HTML5 Geolocation Service', function() {
var geolocator, navigator, position;
var onResolve, onReject;
var NAVIGATOR_OPTIONS = {
enableHighAccuracy: false,
maximumAge: 12345,
timeout: 54321
};
var LAT_STUB = 12.345;
var LON_STUB = 54.321;
beforeEach(function() {
var geolocatorOptions;
navigator = new MockNavigator();
geolocatorOptions = _.extend({}, NAVIGATOR_OPTIONS, {
navigator: navigator
});
geolocator = new HTML5GeolocateService(geolocatorOptions);
position = new MockGeolocationResults({
coords: {
latitude: LAT_STUB,
longitude: LON_STUB
}
});
onResolve = jasmine.createSpy('onResolve');
onReject = jasmine.createSpy('onReject');
onResolve.getPosition = _.bind(function() {
if (!this.callCount) { throw new Error('onResolve was never called'); }
return this.mostRecentCall.args[0];
}, onResolve);
onReject.getError = _.bind(function() {
if (!this.callCount) { throw new Error('onReject was never called'); }
return this.mostRecentCall.args[0];
}, onReject);
geolocator.setNavigator(navigator);
});
describe('getCurrentPosition', function() {
it('should request the users current position from the navigator', function() {
geolocator.getCurrentPosition();
expect(navigator.geolocation.getCurrentPosition).toHaveBeenCalled();
expect(navigator.geolocation.getCurrentPosition.getOptions()).toEqual(NAVIGATOR_OPTIONS);
});
it('should resolve with the users current position', function() {
geolocator.getCurrentPosition().done(onResolve);
navigator.geolocation.getCurrentPosition.resolve(position);
expect(onResolve).toHaveBeenCalled();
expect(onResolve.getPosition().latLon).toEqual([LAT_STUB, LON_STUB]);
});
it('should handle errors from the HTML5 geolocator', function() {
geolocator.getCurrentPosition().fail(onReject);
navigator.geolocation.getCurrentPosition.reject(new MockGeolocationError());
expect(onReject).toHaveBeenCalled();
expect(onReject.getError().name).toEqual('GeolocateServiceError');
});
it('should reject the request if HTML5 geolocation is not available', function() {
geolocator.setNavigator(null);
geolocator.getCurrentPosition().
fail(onReject);
expect(onReject).toHaveBeenCalled();
expect(onReject.getError().name).toEqual('GeolocateServiceError');
expect(onReject.getError().code).toEqual(GeolocateServiceError.POSITION_UNAVAILABLE);
});
});
describe('watchPostion', function() {
it('should use the HTML5 geolocation API', function() {
geolocator.watchPosition();
expect(navigator.geolocation.watchPosition).toHaveBeenCalled();
expect(navigator.geolocation.watchPosition.getOptions()).toEqual(NAVIGATOR_OPTIONS);
});
it('should return the user\'s location', function() {
geolocator.watchPosition(onResolve);
navigator.geolocation.watchPosition.resolve(position);
expect(onResolve).toHaveBeenCalled();
expect(onResolve.getPosition().latLon).toEqual([LAT_STUB, LON_STUB]);
});
it('should return the user\'s location multiple times', function() {
var COUNT = 3;
geolocator.watchPosition(onResolve);
_.times(COUNT, function() {
navigator.geolocation.watchPosition.resolve(position);
});
expect(onResolve.callCount).toEqual(COUNT);
});
it('should handle errors', function() {
geolocator.watchPosition(null, onReject);
navigator.geolocation.watchPosition.reject(new MockGeolocationError());
expect(onReject.getError().name).toEqual('GeolocateServiceError');
});
it('should invoke the errback if HTML5 navigation is not supported', function() {
geolocator.setNavigator(null);
geolocator.watchPosition(null, onReject);
expect(onReject).toHaveBeenCalled();
expect(onReject.getError().name).toEqual('GeolocateServiceError');
expect(onReject.getError().code).toEqual(GeolocateServiceError.POSITION_UNAVAILABLE);
});
});
describe('clearWatch', function() {
it('should stop watching for changes in position', function() {
var WATCH_ID_STUB = 12345;
navigator.geolocation.watchPosition.andReturn(WATCH_ID_STUB);
geolocator.watchPosition();
geolocator.clearWatch();
expect(navigator.geolocation.clearWatch).toHaveBeenCalledWith(WATCH_ID_STUB);
});
});
describe('isSupported', function() {
it('should return true if HTML5 geolocation is supported', function() {
expect(HTML5GeolocateService.isSupported(navigator)).toEqual(true);
});
it('should return false if HTML5 geolocation is not supported', function() {
expect(HTML5GeolocateService.isSupported(null)).toEqual(false);
});
});
});
});
| MikeLockz/exit-now-mobile | www/lib/aerisjs/tests/spec/aeris/geolocate/html5geolocateservice.js | JavaScript | mit | 5,453 |
//this page is accessible to all users - authenticated or not.
| feiyue/maven-framework-project | spring3-security-example/src/main/webapp/resources/unprotected.js | JavaScript | mit | 63 |
mocha.setup('bdd');
var expect = chai.expect;
function createRange(min, max) {
var list = [];
for (var i = min; i <= max; i++) {
list.push(i);
}
return list;
}
describe("paged extender", function () {
var emptyObservableArray,
singlePageObservableArray,
smallNumberPagesObservableArray,
largeNumberPagesObservableArray;
beforeEach(function() {
var options = { pageSize: 3 };
// Reset the defaults
ko.paging.defaults.pageNumber = 1;
ko.paging.defaults.pageSize = 50;
// Reset the observable arrays
emptyObservableArray = ko.observableArray([]).extend({ paged: options });
singlePageObservableArray = ko.observableArray([1]).extend({ paged: options });
smallNumberPagesObservableArray = ko.observableArray(createRange(1, 7)).extend({ paged: options });
largeNumberPagesObservableArray = ko.observableArray(createRange(1, 30)).extend({ paged: options });
});
context("on regular observable", function () {
it("throws", function () {
var regularObservable = ko.observable();
expect(regularObservable.extend.bind(regularObservable, { paged: {} })).to.throw(Error);
});
});
context("on empty paged observable array", function () {
it("itemCount is 0", function () {
expect(emptyObservableArray.itemCount()).to.equal(0);
});
it("pageCount is 1", function () {
expect(emptyObservableArray.pageCount()).to.equal(1);
});
it("firstItemOnPage is 1", function () {
expect(emptyObservableArray.firstItemOnPage()).to.equal(1);
});
it("lastItemOnPage is 1", function () {
expect(emptyObservableArray.lastItemOnPage()).to.equal(1);
});
it("hasPreviousPage is false", function () {
expect(emptyObservableArray.hasPreviousPage()).to.be.false;
});
it("hasNextPage is false", function () {
expect(emptyObservableArray.hasNextPage()).to.be.false;
});
it("isFirstPage is true", function () {
expect(emptyObservableArray.isFirstPage()).to.be.true;
});
it("isLastPage is true", function () {
expect(emptyObservableArray.isLastPage()).to.be.true;
});
it("pageItems returns empty array", function () {
expect(emptyObservableArray.pageItems()).to.deep.equal([]);
});
it("toNextPage does not change pageNumber", function () {
var oldPageNumber = emptyObservableArray.pageNumber();
emptyObservableArray.toNextPage();
expect(emptyObservableArray.pageNumber()).to.equal(oldPageNumber);
});
it("toPreviousPage does not change pageNumber", function () {
var oldPageNumber = emptyObservableArray.pageNumber();
emptyObservableArray.toPreviousPage();
expect(emptyObservableArray.pageNumber()).to.equal(oldPageNumber);
});
it("toFirstPage does not change pageNumber", function () {
var oldPageNumber = emptyObservableArray.pageNumber();
emptyObservableArray.toFirstPage();
expect(emptyObservableArray.pageNumber()).to.equal(oldPageNumber);
});
it("toLastPage does not change pageNumber", function () {
var oldPageNumber = emptyObservableArray.pageNumber();
emptyObservableArray.toLastPage();
expect(emptyObservableArray.pageNumber()).to.equal(oldPageNumber);
});
});
context("on single-page paged observable array", function () {
it("itemCount is number of elements in array", function () {
expect(singlePageObservableArray.itemCount()).to.equal(singlePageObservableArray().length);
});
it("pageCount is 1", function () {
expect(singlePageObservableArray.pageCount()).to.equal(1);
});
it("firstItemOnPage is 1", function () {
expect(singlePageObservableArray.firstItemOnPage()).to.equal(1);
});
it("lastItemOnPage is is number of elements in array", function () {
expect(singlePageObservableArray.lastItemOnPage()).to.equal(singlePageObservableArray().length);
});
it("hasPreviousPage is false", function () {
expect(singlePageObservableArray.hasPreviousPage()).to.be.false;
});
it("hasNextPage is false", function () {
expect(singlePageObservableArray.hasNextPage()).to.be.false;
});
it("isFirstPage is true", function () {
expect(singlePageObservableArray.isFirstPage()).to.be.true;
});
it("isLastPage is true", function () {
expect(singlePageObservableArray.isLastPage()).to.be.true;
});
it("pageItems returns all array elements", function () {
expect(singlePageObservableArray.pageItems()).to.deep.equal(singlePageObservableArray());
});
it("toNextPage does not change pageNumber", function () {
var oldPageNumber = singlePageObservableArray.pageNumber();
singlePageObservableArray.toNextPage();
expect(singlePageObservableArray.pageNumber()).to.equal(oldPageNumber);
});
it("toPreviousPage does not change pageNumber", function () {
var oldPageNumber = singlePageObservableArray.pageNumber();
singlePageObservableArray.toPreviousPage();
expect(singlePageObservableArray.pageNumber()).to.equal(oldPageNumber);
});
it("toFirstPage does not change pageNumber", function () {
var oldPageNumber = singlePageObservableArray.pageNumber();
singlePageObservableArray.toFirstPage();
expect(singlePageObservableArray.pageNumber()).to.equal(oldPageNumber);
});
it("toLastPage does not change pageNumber", function () {
var oldPageNumber = singlePageObservableArray.pageNumber();
singlePageObservableArray.toLastPage();
expect(singlePageObservableArray.pageNumber()).to.equal(oldPageNumber);
});
});
context("on multi-page paged observable array", function () {
context("with current page is first page", function () {
beforeEach(function() {
smallNumberPagesObservableArray.pageNumber(1);
});
it("itemCount is number of elements in array", function () {
expect(smallNumberPagesObservableArray.itemCount()).to.equal(smallNumberPagesObservableArray().length);
});
it("pageCount is correct", function () {
expect(smallNumberPagesObservableArray.pageCount()).to.equal(3);
});
it("firstItemOnPage is correct", function () {
expect(smallNumberPagesObservableArray.firstItemOnPage()).to.equal(1);
});
it("lastItemOnPage is correct", function () {
expect(smallNumberPagesObservableArray.lastItemOnPage()).to.equal(3);
});
it("hasPreviousPage is false", function () {
expect(smallNumberPagesObservableArray.hasPreviousPage()).to.be.false;
});
it("hasNextPage is true", function () {
expect(smallNumberPagesObservableArray.hasNextPage()).to.be.true;
});
it("isFirstPage is true", function () {
expect(smallNumberPagesObservableArray.isFirstPage()).to.be.true;
});
it("isLastPage is false", function () {
expect(smallNumberPagesObservableArray.isLastPage()).to.be.false;
});
it("pageItems returns all array elements on page", function () {
expect(smallNumberPagesObservableArray.pageItems()).to.deep.equal([1, 2, 3]);
});
it("toNextPage increments pageNumber", function () {
var oldPageNumber = smallNumberPagesObservableArray.pageNumber();
smallNumberPagesObservableArray.toNextPage();
expect(smallNumberPagesObservableArray.pageNumber()).to.equal(oldPageNumber + 1);
});
it("toPreviousPage does not change pageNumber", function () {
var oldPageNumber = smallNumberPagesObservableArray.pageNumber();
smallNumberPagesObservableArray.toPreviousPage();
expect(smallNumberPagesObservableArray.pageNumber()).to.equal(oldPageNumber);
});
it("toFirstPage does not change pageNumber", function () {
var oldPageNumber = smallNumberPagesObservableArray.pageNumber();
smallNumberPagesObservableArray.toFirstPage();
expect(smallNumberPagesObservableArray.pageNumber()).to.equal(oldPageNumber);
});
it("toLastPage sets pageNumber to last page", function () {
smallNumberPagesObservableArray.toLastPage();
expect(smallNumberPagesObservableArray.pageNumber()).to.equal(smallNumberPagesObservableArray.pageCount());
});
});
context("with current page is middle page", function () {
beforeEach(function() {
smallNumberPagesObservableArray.pageNumber(2);
});
it("itemCount is number of elements in array", function () {
expect(smallNumberPagesObservableArray.itemCount()).to.equal(smallNumberPagesObservableArray().length);
});
it("pageCount is correct", function () {
expect(smallNumberPagesObservableArray.pageCount()).to.equal(3);
});
it("firstItemOnPage is correct", function () {
expect(smallNumberPagesObservableArray.firstItemOnPage()).to.equal(4);
});
it("lastItemOnPage is correct", function () {
expect(smallNumberPagesObservableArray.lastItemOnPage()).to.equal(6);
});
it("hasPreviousPage is true", function () {
expect(smallNumberPagesObservableArray.hasPreviousPage()).to.be.true;
});
it("hasNextPage is true", function () {
expect(smallNumberPagesObservableArray.hasNextPage()).to.be.true;
});
it("isFirstPage is false", function () {
expect(smallNumberPagesObservableArray.isFirstPage()).to.be.false;
});
it("isLastPage is false", function () {
expect(smallNumberPagesObservableArray.isLastPage()).to.be.false;
});
it("pageItems returns all array elements on page", function () {
expect(smallNumberPagesObservableArray.pageItems()).to.deep.equal([4, 5, 6]);
});
it("toNextPage increments pageNumber", function () {
var oldPageNumber = smallNumberPagesObservableArray.pageNumber();
smallNumberPagesObservableArray.toNextPage();
expect(smallNumberPagesObservableArray.pageNumber()).to.equal(oldPageNumber + 1);
});
it("toPreviousPage decrements pageNumber", function () {
var oldPageNumber = smallNumberPagesObservableArray.pageNumber();
smallNumberPagesObservableArray.toPreviousPage();
expect(smallNumberPagesObservableArray.pageNumber()).to.equal(oldPageNumber - 1);
});
it("toFirstPage sets pageNumber to first page", function () {
smallNumberPagesObservableArray.toFirstPage();
expect(smallNumberPagesObservableArray.pageNumber()).to.equal(1);
});
it("toLastPage sets pageNumber to last page", function () {
smallNumberPagesObservableArray.toLastPage();
expect(smallNumberPagesObservableArray.pageNumber()).to.equal(smallNumberPagesObservableArray.pageCount());
});
});
context("with current page is last page", function () {
beforeEach(function() {
smallNumberPagesObservableArray.pageNumber(3);
});
it("itemCount is number of elements in array", function () {
expect(smallNumberPagesObservableArray.itemCount()).to.equal(smallNumberPagesObservableArray().length);
});
it("pageCount is correct", function () {
expect(smallNumberPagesObservableArray.pageCount()).to.equal(3);
});
it("firstItemOnPage is correct", function () {
expect(smallNumberPagesObservableArray.firstItemOnPage()).to.equal(7);
});
it("lastItemOnPage is correct", function () {
expect(smallNumberPagesObservableArray.lastItemOnPage()).to.equal(7);
});
it("hasPreviousPage is true", function () {
expect(smallNumberPagesObservableArray.hasPreviousPage()).to.be.true;
});
it("hasNextPage is false", function () {
expect(smallNumberPagesObservableArray.hasNextPage()).to.be.false;
});
it("isFirstPage is false", function () {
expect(smallNumberPagesObservableArray.isFirstPage()).to.be.false;
});
it("isLastPage is true", function () {
expect(smallNumberPagesObservableArray.isLastPage()).to.be.true;
});
it("pageItems returns all array elements on page", function () {
expect(smallNumberPagesObservableArray.pageItems()).to.deep.equal([7]);
});
it("toNextPage does not change pageNumber", function () {
var oldPageNumber = smallNumberPagesObservableArray.pageNumber();
smallNumberPagesObservableArray.toNextPage();
expect(smallNumberPagesObservableArray.pageNumber()).to.equal(oldPageNumber);
});
it("toPreviousPage decrements pageNumber", function () {
var oldPageNumber = smallNumberPagesObservableArray.pageNumber();
smallNumberPagesObservableArray.toPreviousPage();
expect(smallNumberPagesObservableArray.pageNumber()).to.equal(oldPageNumber - 1);
});
it("toFirstPage sets pageNumber to first page", function () {
smallNumberPagesObservableArray.toFirstPage();
expect(smallNumberPagesObservableArray.pageNumber()).to.equal(1);
});
it("toLastPage does not change pageNumber", function () {
var oldPageNumber = smallNumberPagesObservableArray.pageNumber();
smallNumberPagesObservableArray.toLastPage();
expect(smallNumberPagesObservableArray.pageNumber()).to.equal(oldPageNumber);
});
});
});
context("constructor", function () {
context("without options", function () {
var pagedArrayWithoutOptions,
emptyOptions;
beforeEach(function() {
emptyOptions = {};
pagedArrayWithoutOptions = ko.observableArray([]).extend({ paged: emptyOptions });
});
it("pageNumber is 1", function () {
expect(pagedArrayWithoutOptions.pageNumber()).to.equal(1);
});
it("pageSize is 50", function () {
expect(pagedArrayWithoutOptions.pageSize()).to.equal(50);
});
it("pageGenerator is default", function () {
expect(pagedArrayWithoutOptions.pageGenerator).to.equal(ko.paging.generators['default']);
});
it("pageNumber uses global default", function () {
ko.paging.defaults.pageNumber = 2;
pagedArrayWithoutOptions = ko.observableArray();
pagedArrayWithoutOptions.extend({ paged: emptyOptions });
expect(pagedArrayWithoutOptions.pageNumber()).to.equal(2);
});
it("pageSize uses global default", function () {
ko.paging.defaults.pageSize = 25;
pagedArrayWithoutOptions = ko.observableArray();
pagedArrayWithoutOptions.extend({ paged: emptyOptions });
expect(pagedArrayWithoutOptions.pageSize()).to.equal(25);
});
});
context("with options", function () {
var pagedArrayWithOptions,
options;
beforeEach(function() {
options = { pageNumber: 3, pageSize: 25 };
pagedArrayWithOptions = ko.observableArray(createRange(1, 7)).extend({ paged: options });
});
it("pageNumber is equal to supplied option value", function () {
expect(pagedArrayWithOptions.pageNumber()).to.equal(options.pageNumber);
});
it("pageSize is equal to supplied option value", function () {
expect(pagedArrayWithOptions.pageSize()).to.equal(options.pageSize);
});
var pageGeneratorNames = ['default'];
pageGeneratorNames.forEach(function(pageGeneratorName) {
it("pageGenerator is equal to page generator with supplied option value", function () {
expect(pagedArrayWithOptions.pageGenerator).to.equal(ko.paging.generators[pageGeneratorName]);
});
});
it("pageGenerator is equal to custom page generator with supplied option value", function () {
var customPageGenerator = function (pagedObservable) { return []; }
ko.paging.generators['custom'] = customPageGenerator;
options = { pageGenerator: 'custom' };
pagedArrayWithOptions.extend({ paged: options });
expect(pagedArrayWithOptions.pageGenerator).to.equal(customPageGenerator);
});
var numbersLessThenZero = [0, -1, -3];
numbersLessThenZero.forEach(function(invalidNumber) {
it("pageNumber less than 1 throws", function () {
options = { pageNumber: invalidNumber };
expect(pagedArrayWithOptions.extend.bind(pagedArrayWithOptions, { paged: options })).to.throw(Error);
});
it("pageSize less than 1 throws", function () {
options = { pageSize: invalidNumber };
expect(pagedArrayWithOptions.extend.bind(pagedArrayWithOptions, { paged: options })).to.throw(Error);
});
});
var unknownPageGeneratorNames = [null, '', 'unknown'];
unknownPageGeneratorNames.forEach(function(unknownPageGeneratorName) {
it("pageGenerator with unknown name throws", function () {
options = { pageGenerator: unknownPageGeneratorName };
expect(pagedArrayWithOptions.extend.bind(pagedArrayWithOptions, { paged: options })).to.throw(Error);
});
});
});
context("with initial value is", function() {
it("empty array works", function () {
var pagedArray = ko.observableArray([]).extend({ paged: {} });
expect(pagedArray()).to.deep.equal([]);
});
it("non-empty array works", function () {
var pagedArray = ko.observableArray([1, 2, 3]).extend({ paged: {} });
expect(pagedArray()).to.deep.equal([1, 2, 3]);
});
});
});
context("observable value", function () {
it("pageNumber can be explicitly set", function () {
singlePageObservableArray.pageNumber(2);
expect(singlePageObservableArray.pageNumber()).to.equal(2);
});
it("pageSize can be explicitly set", function () {
singlePageObservableArray.pageSize(10);
expect(singlePageObservableArray.pageSize()).to.equal(10);
});
});
context("page generators", function () {
context("default page generator", function () {
beforeEach(function() {
singlePageObservableArray['pageGenerator'] = ko.paging.generators['default'];
smallNumberPagesObservableArray['pageGenerator'] = ko.paging.generators['default'];
largeNumberPagesObservableArray['pageGenerator'] = ko.paging.generators['default'];
});
it("works for single page", function () {
expect(singlePageObservableArray.pages()).to.deep.equal(createRange(1, 1));
});
it("works for small numbers of pages", function () {
expect(smallNumberPagesObservableArray.pages()).to.deep.equal(createRange(1, 3));
});
it("works for large number of pages", function () {
expect(largeNumberPagesObservableArray.pages()).to.deep.equal(createRange(1, 10));
});
context("responds to change of", function () {
it("pageSize", function () {
var oldPages = smallNumberPagesObservableArray.pages();
smallNumberPagesObservableArray.pageSize(2);
var newPages = smallNumberPagesObservableArray.pages();
expect(oldPages).to.deep.equal(createRange(1, 3));
expect(newPages).to.deep.equal(createRange(1, 4));
});
it("number of items in array", function () {
var oldPages = smallNumberPagesObservableArray.pages();
smallNumberPagesObservableArray(createRange(1, 4))
var newPages = smallNumberPagesObservableArray.pages();
expect(oldPages).to.deep.equal(createRange(1, 3));
expect(newPages).to.deep.equal(createRange(1, 2));
});
});
});
context("sliding page generator", function () {
beforeEach(function() {
ko.paging.generators['sliding'].windowSize(5);
singlePageObservableArray['pageGenerator'] = ko.paging.generators['sliding'];
smallNumberPagesObservableArray['pageGenerator'] = ko.paging.generators['sliding'];
largeNumberPagesObservableArray['pageGenerator'] = ko.paging.generators['sliding'];
});
it("works for single page", function () {
expect(singlePageObservableArray.pages()).to.deep.equal(createRange(1, 1));
});
it("works for small numbers of pages", function () {
expect(smallNumberPagesObservableArray.pages()).to.deep.equal(createRange(1, 3));
});
it("works for large number of pages", function () {
expect(largeNumberPagesObservableArray.pages()).to.deep.equal(createRange(1, 5));
});
it("works when page is first page", function () {
largeNumberPagesObservableArray.pageNumber(1);
expect(largeNumberPagesObservableArray.pages()).to.deep.equal(createRange(1, 5));
});
it("works when page is middle page", function () {
largeNumberPagesObservableArray.pageNumber(5);
expect(largeNumberPagesObservableArray.pages()).to.deep.equal(createRange(3, 7));
});
it("works when page is last page", function () {
largeNumberPagesObservableArray.pageNumber(10);
expect(largeNumberPagesObservableArray.pages()).to.deep.equal(createRange(6, 10));
});
it("works when window size is even", function () {
largeNumberPagesObservableArray.pageGenerator.windowSize(2);
largeNumberPagesObservableArray.pageNumber(6);
expect(largeNumberPagesObservableArray.pages()).to.deep.equal([5, 6]);
});
it("works when window size is odd", function () {
largeNumberPagesObservableArray.pageGenerator.windowSize(3);
largeNumberPagesObservableArray.pageNumber(6);
expect(largeNumberPagesObservableArray.pages()).to.deep.equal([5, 6, 7]);
});
context("responds to change of", function () {
it("pageSize", function () {
var oldPages = smallNumberPagesObservableArray.pages();
smallNumberPagesObservableArray.pageSize(2);
var newPages = smallNumberPagesObservableArray.pages();
expect(oldPages).to.deep.equal(createRange(1, 3));
expect(newPages).to.deep.equal(createRange(1, 4));
});
it("number of items in array", function () {
var oldPages = smallNumberPagesObservableArray.pages();
smallNumberPagesObservableArray(createRange(1, 4))
var newPages = smallNumberPagesObservableArray.pages();
expect(oldPages).to.deep.equal(createRange(1, 3));
expect(newPages).to.deep.equal(createRange(1, 2));
});
it("window size", function () {
var oldPages = smallNumberPagesObservableArray.pages();
smallNumberPagesObservableArray.pageGenerator.windowSize(2);
var newPages = smallNumberPagesObservableArray.pages();
expect(oldPages).to.deep.equal(createRange(1, 3));
expect(newPages).to.deep.equal(createRange(1, 2));
});
});
});
context("custom page generator", function () {
before(function() {
ko.paging.generators['custom'] = {
generate: function(pagedObservable) {
return createRange(0, pagedObservable.pageCount() - 1);
}
}
});
beforeEach(function() {
singlePageObservableArray['pageGenerator'] = ko.paging.generators['custom'];
smallNumberPagesObservableArray['pageGenerator'] = ko.paging.generators['custom'];
largeNumberPagesObservableArray['pageGenerator'] = ko.paging.generators['custom'];
});
it("works for single page", function () {
expect(singlePageObservableArray.pages()).to.deep.equal([0]);
});
it("works for small numbers of pages", function () {
expect(smallNumberPagesObservableArray.pages()).to.deep.equal(createRange(0, 2));
});
it("works for large number of pages", function () {
expect(largeNumberPagesObservableArray.pages()).to.deep.equal(createRange(0, 9));
});
context("responds to change of", function () {
it("pageSize", function () {
var oldPages = smallNumberPagesObservableArray.pages();
smallNumberPagesObservableArray.pageSize(2);
var newPages = smallNumberPagesObservableArray.pages();
expect(oldPages).to.deep.equal(createRange(0, 2));
expect(newPages).to.deep.equal(createRange(0, 3));
});
it("number of items in array", function () {
var oldPages = smallNumberPagesObservableArray.pages();
smallNumberPagesObservableArray(createRange(1, 4))
var newPages = smallNumberPagesObservableArray.pages();
expect(oldPages).to.deep.equal(createRange(0, 2));
expect(newPages).to.deep.equal(createRange(0, 1));
});
});
});
});
context("created using ko.pagedObservableArray", function () {
it("works without parameters", function () {
var pagedObservableArray = ko.pagedObservableArray();
expect(pagedObservableArray()).to.deep.equal([]);
expect(pagedObservableArray.pageNumber()).to.deep.equal(1);
});
it("works with empty array parameter", function () {
var pagedObservableArray = ko.pagedObservableArray([]);
expect(pagedObservableArray()).to.deep.equal([]);
expect(pagedObservableArray.pageNumber()).to.deep.equal(1);
});
it("works with non-empty array parameter", function () {
var pagedObservableArray = ko.pagedObservableArray([1, 2, 3]);
expect(pagedObservableArray()).to.deep.equal([1, 2, 3]);
expect(pagedObservableArray.pageNumber()).to.deep.equal(1);
});
it("works with array and options parameters", function () {
var options = { pageSize: 2 };
var pagedObservableArray = ko.pagedObservableArray([1, 2, 3], options);
expect(pagedObservableArray()).to.deep.equal([1, 2, 3]);
expect(pagedObservableArray.pageSize()).to.deep.equal(2);
});
});
}); | papermache/elmhurst_front_end | newVersion/js/lib/knockout-paging-master/spec/knockout-paged-spec.js | JavaScript | mit | 26,482 |
/**
* Testing of this component is included in the materialize-tabs test cases, since this component
* cannot exist independently
*/
| unmanbearpig/ember-cli-materialize | tests/unit/components/materialize-tabs-tab-test.js | JavaScript | mit | 136 |
// Copyright 2011 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Flags: --harmony-regexp-property
assertThrows("/[\\p]/u");
assertThrows("/[\\p{garbage}]/u");
assertThrows("/[\\p{}]/u");
assertThrows("/[\\p{]/u");
assertThrows("/[\\p}]/u");
assertTrue(/^[\p{Lu}\p{Ll}]+$/u.test("ABCabc"));
assertTrue(/^[\p{Lu}-\p{Ll}]+$/u.test("ABC-abc"));
assertFalse(/^[\P{Lu}\p{Ll}]+$/u.test("ABCabc"));
assertTrue(/^[\P{Lu}\p{Ll}]+$/u.test("abc"));
assertTrue(/^[\P{Lu}]+$/u.test("abc123"));
assertFalse(/^[\P{Lu}]+$/u.test("XYZ"));
assertTrue(/[\p{Math}]/u.test("+"));
assertTrue(/[\P{Bidi_M}]/u.test(" "));
assertTrue(/[\p{Hex}]/u.test("A"));
assertTrue(/^[^\P{Lu}]+$/u.test("XYZ"));
assertFalse(/^[^\p{Lu}\p{Ll}]+$/u.test("abc"));
assertFalse(/^[^\p{Lu}\p{Ll}]+$/u.test("ABC"));
assertTrue(/^[^\p{Lu}\p{Ll}]+$/u.test("123"));
assertTrue(/^[^\p{Lu}\P{Ll}]+$/u.test("abc"));
| hoho/dosido | nodejs/deps/v8/test/mjsunit/harmony/regexp-property-char-class.js | JavaScript | mit | 973 |
angular.module('services.templateRetriever',[])
.factory('templateRetriever', function ($http, $q){
return {
getTemplate: function (templateUrl, tracker) {
var deferred = $q.defer();
$http({
url: templateUrl,
method: 'GET',
headers: {'Content-Type': 'text/html'},
tracker: tracker || 'promiseTracker'
})
.success(function(data){
deferred.resolve(data);
})
.error(function(data, status, headers, config){
deferred.reject({
data: data,
status: status,
headers: headers,
config: config
});
});
return deferred.promise;
}
}
}); | doortracker/doortracker | public/app/lib/angular-ui-form-validation/app/scripts/services/templateretriever/templateRetriever.js | JavaScript | mit | 604 |
/**
@module ember
@submodule ember-htmlbars
*/
/**
Lookup both on root and on window. If the path starts with
a keyword, the corresponding object will be looked up in the
template's data hash and used to resolve the path.
@method get
@for Ember.Handlebars
@param {Object} root The object to look up the property on
@param {String} path The path to be lookedup
@param {Object} options The template's option hash
@deprecated
*/
export default function handlebarsGet(root, path, options) {
Ember.deprecate('Usage of Ember.Handlebars.get is deprecated, use a Component or Ember.Handlebars.makeBoundHelper instead.');
return options.legacyGetPath(path);
}
| Zagorakiss/ember.js | packages/ember-htmlbars/lib/compat/handlebars-get.js | JavaScript | mit | 676 |
(function(){
"use strict;";
var WebDriver = require('sync-webdriver'),
Bacon = require('baconjs').Bacon,
express = require('express'),
http = require("http"),
https = require("https"),
url = require("url"),
path = require("path"),
base64_arraybuffer = require('base64-arraybuffer'),
PNG = require('png-js'),
fs = require("fs"),
googleapis = require('googleapis'),
jwt = require('jwt-sign');
var port = 8080,
app = express(),
colors = {
red: "\x1b[1;31m",
blue: "\x1b[1;36m",
violet: "\x1b[0;35m",
green: "\x1b[0;32m",
clear: "\x1b[0m"
};
var server = app.listen(port);
app.use('/index.html', function(req, res){
res.send("<ul>" + tests.map(function(test) {
return "<li><a href='" + test + "'>" + test + "</a></li>";
}).join("") + "</ul>");
});
app.use('/', express.static(__dirname + "/../"));
function mapStat(item) {
return Bacon.combineTemplate({
stat: Bacon.fromNodeCallback(fs.stat, item),
item: item
});
}
function isDirectory(item) {
return item.stat.isDirectory();
}
function getItem(item) {
return item.item;
}
function isFile(item) {
return !isDirectory(item);
}
function arrayStream(arr) {
return Bacon.fromArray(arr);
}
function getTests(path) {
var items = Bacon.fromNodeCallback(fs.readdir, path).flatMap(arrayStream).map(function(name) {
return path + "/" + name;
}).flatMap(mapStat);
return items.filter(isFile).map(getItem).merge(items.filter(isDirectory).map(getItem).flatMap(getTests));
}
function getPixelArray(base64) {
return Bacon.fromCallback(function(callback) {
var arraybuffer = base64_arraybuffer.decode(base64);
(new PNG(arraybuffer)).decode(callback);
});
}
function calculateDifference(h2cPixels, screenPixels) {
var len = h2cPixels.length, index = 0, diff = 0;
for (; index < len; index++) {
if (screenPixels[index] - h2cPixels[index] !== 0) {
diff++;
}
}
return (100 - (Math.round((diff/h2cPixels.length) * 10000) / 100));
}
function canvasToDataUrl(canvas) {
return canvas.toDataURL("image/png").substring(22);
}
function closeServer() {
server.close();
}
function findResult(testName, tests) {
var item = null;
return tests.some(function(testCase) {
item = testCase;
return testCase.test === testName;
}) ? item : null;
}
function compareResults(oldResults, newResults, browser) {
var improved = [],
regressed = [],
newItems = [];
newResults.forEach(function(testCase){
var testResult = testCase.result,
oldResult = findResult(testCase.test, oldResults),
oldResultValue = oldResult ? oldResult.result : null,
dataObject = {
amount: (Math.abs(testResult - oldResultValue) < 0.01) ? 0 : testResult - oldResultValue,
test: testCase.test
};
if (oldResultValue === null) {
newItems.push(dataObject);
} else if (dataObject.amount > 0) {
improved.push(dataObject);
} else if (dataObject.amount < 0) {
regressed.push(dataObject);
}
});
reportChanges(browser, improved, regressed, newItems);
}
function reportChanges(browser, improved, regressed, newItems) {
if (newItems.length > 0 || improved.length > 0 || regressed.length > 0) {
console.log((regressed.length > 0) ? colors.red : colors.green, browser);
regressed.forEach(function(item) {
console.log(colors.red, item.amount + "%", item.test);
});
improved.forEach(function(item) {
console.log(colors.green, item.amount + "%", item.test);
});
newItems.forEach(function(item) {
console.log(colors.blue, "NEW", item.test);
});
}
}
function httpget(options) {
return Bacon.fromCallback(function(callback) {
https.get(options, function(res){
var data = '';
res.on('data', function (chunk){
data += chunk;
});
res.on('end',function(){
callback(data);
});
});
});
}
function parseJSON(str) {
return JSON.parse(str);
}
function writeResults() {
Object.keys(results).forEach(function(browser) {
var filename = "tests/results/" + browser + ".json";
try {
var oldResults = JSON.parse(fs.readFileSync(filename));
compareResults(oldResults, results[browser], browser);
} catch(e) {}
var date = new Date();
var result = JSON.stringify({
browser: browser,
results: results[browser],
timestamp: date.toISOString()
});
if (process.env.MONGOLAB_APIKEY) {
var options = {
host: "api.mongolab.com",
port: 443,
path: "/api/1/databases/html2canvas/collections/webdriver-results?apiKey=" + process.env.MONGOLAB_APIKEY + '&q={"browser":"' + browser + '"}&fo=true&s={"timestamp":-1}'
};
httpget(options).map(parseJSON).onValue(function(data) {
compareResults(data.results, results[browser], browser);
options.method = 'POST';
options.path = "/api/1/databases/html2canvas/collections/webdriver-results?apiKey=" + process.env.MONGOLAB_APIKEY;
options.headers = {
'Content-Type': 'application/json',
'Content-Length': result.length
};
console.log("Sending results for", browser);
var request = https.request(options, function(res) {
console.log(colors.green, "Results sent for", browser);
});
request.write(result);
request.end();
});
}
console.log(colors.violet, "Writing", browser + ".json");
fs.writeFile(filename, result);
});
}
function webdriverOptions(browserName, version, platform) {
var options = {};
if (process.env.SAUCE_USERNAME && process.env.SAUCE_ACCESS_KEY) {
options = {
port: 4445,
hostname: "localhost",
name: process.env.TRAVIS_JOB_ID || "Manual run",
username: process.env.SAUCE_USERNAME,
password: process.env.SAUCE_ACCESS_KEY,
desiredCapabilities: {
browserName: browserName,
version: version,
platform: platform,
"tunnel-identifier": process.env.TRAVIS_JOB_NUMBER
}
};
}
return options;
}
function mapResults(result) {
if (!results[result.browser]) {
results[result.browser] = [];
}
results[result.browser].push({
test: result.testCase,
result: result.accuracy
});
}
function formatResultName(navigator) {
return (navigator.browser + "-" + ((navigator.version) ? navigator.version : "release") + "-" + navigator.platform).replace(/ /g, "").toLowerCase();
}
function webdriverStream(navigator) {
var drive = Bacon.fromCallback(discover, "drive", "v2").toProperty();
var auth = Bacon.fromCallback(createToken, "95492219822.apps.googleusercontent.com").toProperty();
return Bacon.fromCallback(function(callback) {
new WebDriver.Session(webdriverOptions(navigator.browser, navigator.version, navigator.platform), function() {
var browser = this;
var resultStream = Bacon.fromArray(tests).flatMap(function(testCase) {
console.log(colors.green, "STARTING",formatResultName(navigator), testCase, colors.clear);
browser.url = "http://localhost:" + port + "/" + testCase + "?selenium";
var canvas = browser.element(".html2canvas", 15000);
var dataUrl = Bacon.constant(browser.execute(canvasToDataUrl, canvas));
var screenshot = Bacon.constant(browser.screenshot());
var result = dataUrl.flatMap(getPixelArray).combine(screenshot.flatMap(getPixelArray), calculateDifference);
console.log(colors.green, "COMPLETE", formatResultName(navigator), testCase, colors.clear);
return Bacon.combineTemplate({
browser: formatResultName(navigator),
testCase: testCase,
accuracy: result,
dataUrl: dataUrl,
screenshot: screenshot
});
});
if (fs.existsSync('tests/certificate.pem')) {
Bacon.combineWith(permissionRequest, drive, auth, Bacon.combineWith(uploadRequest, drive, auth, resultStream.doAction(mapResults).flatMap(createImages)).flatMap(executeRequest)).flatMap(executeRequestOriginal).onValue(uploadImages);
}
resultStream.onEnd(callback);
});
});
}
function permissionRequest(client, authClient, images) {
var body = {
value: 'me',
type: 'anyone',
role: 'reader'
};
return images.map(function(data) {
var request = client.drive.permissions.insert({fileId: data.id}).withAuthClient(authClient);
request.body = body;
request.fileData = data;
return request;
});
}
function executeRequest(requests) {
return Bacon.combineAsArray(requests.map(function(request) {
return Bacon.fromCallback(function(callback) {
request.execute(function(err, result) {
if (!err) {
callback(result);
} else {
console.log("Google drive error", err);
}
});
});
}));
}
function executeRequestOriginal(requests) {
return Bacon.combineAsArray(requests.map(function(request) {
return Bacon.fromCallback(function(callback) {
request.execute(function(err, result) {
if (!err) {
callback(request.fileData);
} else {
console.log("Google drive error", err);
}
});
});
}));
}
function createImages(data) {
var dataurlFileName = "tests/results/" + data.browser + "-" + data.testCase.replace(/\//g, "-") + "-html2canvas.png";
var screenshotFileName = "tests/results/" + data.browser + "-" + data.testCase.replace(/\//g, "-") + "-screencapture.png";
return Bacon.combineTemplate({
name: data.testCase,
dataurl: Bacon.fromNodeCallback(fs.writeFile, dataurlFileName, data.dataUrl, "base64").map(function() {
return dataurlFileName;
}),
screenshot: Bacon.fromNodeCallback(fs.writeFile, screenshotFileName, data.screenshot, "base64").map(function() {
return screenshotFileName;
})
});
}
function uploadImages(results) {
results.forEach(function(result) {
console.log(result.webContentLink);
});
}
function discover(api, version, callback) {
googleapis.discover(api, version).execute(function(err, client) {
if (!err) {
callback(client);
}
});
}
function createToken(account, callback) {
var payload = {
"iss": '95492219822@developer.gserviceaccount.com',
"scope": 'https://www.googleapis.com/auth/drive',
"aud":"https://accounts.google.com/o/oauth2/token",
"exp": ~~(new Date().getTime() / 1000) + (30 * 60),
"iat": ~~(new Date().getTime() / 1000 - 60)
},
key = fs.readFileSync('tests/certificate.pem', 'utf8'),
transporterTokenRequest = {
method: 'POST',
uri: 'https://accounts.google.com/o/oauth2/token',
form: {
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
assertion: jwt.sign(payload, key)
},
json: true
},
oauth2Client = new googleapis.OAuth2Client(account, "", "");
oauth2Client.transporter.request(transporterTokenRequest, function(err, result) {
if (!err) {
oauth2Client.credentials = result;
callback(oauth2Client);
}
});
}
function uploadRequest(client, authClient, data) {
return [
client.drive.files.insert({title: data.dataurl, mimeType: 'image/png', description: process.env.TRAVIS_JOB_ID}).withMedia('image/png', fs.readFileSync(data.dataurl)).withAuthClient(authClient),
client.drive.files.insert({title: data.screenshot, mimeType: 'image/png', description: process.env.TRAVIS_JOB_ID}).withMedia('image/png', fs.readFileSync(data.screenshot)).withAuthClient(authClient)
];
}
function runWebDriver() {
var browsers = [
{
browser: "chrome",
platform: "Windows 7"
},{
browser: "firefox",
version: "15",
platform: "Windows 7"
},{
browser: "internet explorer",
version: "9",
platform: "Windows 7"
},{
browser: "internet explorer",
version: "10",
platform: "Windows 8"
},{
browser: "safari",
version: "6",
platform: "OS X 10.8"
},{
browser: "chrome",
platform: "OS X 10.8"
}
];
var testRunnerStream = Bacon.sequentially(1000, browsers).flatMap(webdriverStream);
testRunnerStream.onEnd(writeResults);
testRunnerStream.onEnd(closeServer);
}
var tests = [],
results = {},
testStream = getTests("tests/cases");
testStream.onValue(function(test) {
tests.push(test);
});
exports.tests = function() {
testStream.onEnd(runWebDriver);
};
})(); | ecoder83/html2canvas | tests/selenium.js | JavaScript | mit | 15,207 |
Highcharts.setOptions({
global: {
useUTC: false
}
});
var chart1;
$(document).ready(function() {
chart1 = new Highcharts.Chart({
chart: {
renderTo: 'chart-container-1',
defaultSeriesType: 'scatter',
marginRight: 10,
events: {
load: function() {
}
}
},
title: {
text: 'Altitude'
},
credits: {
enabled: false
},
xAxis: {
title: {
text: 'Time (min)'
}
},
yAxis: {
title: {
text: 'Altitude (ft)'
},
min : 0,
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
Highcharts.numberFormat(this.x,2) +'<br/>'+
Highcharts.numberFormat(this.y, 2);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'altitudeVtime_lig',
data: [],
color: '#E00000'
},{
name: 'altitudeVtime_lhw',
data: [],
color: '#00E000'
},{
name: 'altitudeVtime_sky',
data: [],
color: '#0000E0'
}]
});
});
var chart2;
$(document).ready(function() {
chart2 = new Highcharts.Chart({
chart: {
renderTo: 'chart-container-2',
defaultSeriesType: 'scatter',
marginRight: 10,
events: {
load: function() {
}
}
},
title: {
text: 'Wind Speed'
},
credits: {
enabled: false
},
xAxis: {
title: {
text: 'Wind Speed (mph)'
},
min:0.0001,
},
yAxis: {
title: {
text: 'Altitude (ft)'
},
min: 0,
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
Highcharts.numberFormat(this.x,2) +'<br/>'+
Highcharts.numberFormat(this.y, 2);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'speedValtitude_lig',
data: [],
color: '#E00000'},
{
name: 'speedValtitude_lhw',
data: [],
color: '#00E000'},
{
name: 'speedValtitude_sky',
data: [],
color: '#0000E0'}]});
});
var chart3;
$(document).ready(function() {
chart3 = new Highcharts.Chart({
chart: {
renderTo: 'chart-container-3',
defaultSeriesType: 'scatter',
marginRight: 10,
events: {
load: function() {
}
}
},
title: {
text: 'Other Data'
},
credits: {
enabled: false
},
xAxis: {
title: {
text: 'Wind Speed (mph)'
},
min:0.0001,
},
yAxis: {
title: {
text: 'Altitude (ft)'
},
min: 0,
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
Highcharts.numberFormat(this.x,2) +'<br/>'+
Highcharts.numberFormat(this.y, 2);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'speedValtitude_lig',
data: [],
color: '#E00000'},
{
name: 'speedValtitude_lhw',
data: [],
color: '#00E000'},
{
name: 'speedValtitude_sky',
data: [],
color: '#0000E0'}]});
}); | AdlerFarHorizons/FarHorizonsApp | public/tracking/testChart.js | JavaScript | mit | 3,350 |
var Checker = require('../../../lib/checker');
var assert = require('assert');
describe('rules/disallow-parentheses-around-arrow-param', function() {
var checker;
beforeEach(function() {
checker = new Checker();
checker.registerDefaultRules();
checker.configure({ esnext: true, disallowParenthesesAroundArrowParam: true });
});
it('should not report without parens', function() {
assert(checker.checkString('[1, 2].map(x => x * x);').isEmpty());
});
it('should report with parens around a single parameter', function() {
assert(checker.checkString('[1, 2].map((x) => x * x);').getErrorCount() === 1);
});
it('should not report with parens around multiple parameters', function() {
assert(checker.checkString('[1, 2].map((x, y) => x * x);').isEmpty());
});
it('should not report with parens around a single parameter with a default', function() {
assert(checker.checkString('const a = (x = 1) => x * x;').isEmpty());
});
it('should not report with parens around a multiple parameters with a default', function() {
assert(checker.checkString('const a = (x = 1, y) => x * y;').isEmpty());
});
it('should not report with use of destructuring #1672', function() {
assert(checker.checkString('let func = ({hoge}) => hoge').isEmpty());
});
it('should not report with multiple parameters and destructuring', function() {
assert(checker.checkString('let func = (foo, {hoge}) => hoge').isEmpty());
});
});
| ronkorving/node-jscs | test/specs/rules/disallow-parentheses-around-arrow-param.js | JavaScript | mit | 1,553 |
(function () {
var colorpicker = (function () {
'use strict';
var global = tinymce.util.Tools.resolve('tinymce.PluginManager');
var global$1 = tinymce.util.Tools.resolve('tinymce.util.Color');
var showPreview = function (win, hexColor) {
win.find('#preview')[0].getEl().style.background = hexColor;
};
var setColor = function (win, value) {
var color = global$1(value), rgb = color.toRgb();
win.fromJSON({
r: rgb.r,
g: rgb.g,
b: rgb.b,
hex: color.toHex().substr(1)
});
showPreview(win, color.toHex());
};
var open = function (editor, callback, value) {
var win = editor.windowManager.open({
title: 'Color',
items: {
type: 'container',
layout: 'flex',
direction: 'row',
align: 'stretch',
padding: 5,
spacing: 10,
items: [
{
type: 'colorpicker',
value: value,
onchange: function () {
var rgb = this.rgb();
if (win) {
win.find('#r').value(rgb.r);
win.find('#g').value(rgb.g);
win.find('#b').value(rgb.b);
win.find('#hex').value(this.value().substr(1));
showPreview(win, this.value());
}
}
},
{
type: 'form',
padding: 0,
labelGap: 5,
defaults: {
type: 'textbox',
size: 7,
value: '0',
flex: 1,
spellcheck: false,
onchange: function () {
var colorPickerCtrl = win.find('colorpicker')[0];
var name, value;
name = this.name();
value = this.value();
if (name === 'hex') {
value = '#' + value;
setColor(win, value);
colorPickerCtrl.value(value);
return;
}
value = {
r: win.find('#r').value(),
g: win.find('#g').value(),
b: win.find('#b').value()
};
colorPickerCtrl.value(value);
setColor(win, value);
}
},
items: [
{
name: 'r',
label: 'R',
autofocus: 1
},
{
name: 'g',
label: 'G'
},
{
name: 'b',
label: 'B'
},
{
name: 'hex',
label: '#',
value: '000000'
},
{
name: 'preview',
type: 'container',
border: 1
}
]
}
]
},
onSubmit: function () {
callback('#' + win.toJSON().hex);
}
});
setColor(win, value);
};
var $_bnm4dnanjnlpb0zo = { open: open };
global.add('colorpicker', function (editor) {
if (!editor.settings.color_picker_callback) {
editor.settings.color_picker_callback = function (callback, value) {
$_bnm4dnanjnlpb0zo.open(editor, callback, value);
};
}
});
function Plugin () {
}
return Plugin;
}());
})();
| cityofasheville/coa-converse | plugins/colorpicker/plugin.js | JavaScript | mit | 3,353 |
/**
@license
* @pnp/pnpjs v1.2.2-0 - pnp - rollup library of core functionality (mimics sp-pnp-js)
* 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
*/
import { RuntimeConfig, PnPClientStorage, dateAdd, combine, getCtxCallback, getRandomString, getGUID, isFunc, objectDefinedNotNull, isArray, extend, isUrlAbsolute, stringIsNullOrEmpty, getAttrValueFromString, sanitizeGuid } from '@pnp/common';
export * from '@pnp/common';
import { Logger } from '@pnp/logging';
export * from '@pnp/logging';
import { Settings } from '@pnp/config-store';
export * from '@pnp/config-store';
import { graph } from '@pnp/graph';
export * from '@pnp/graph';
import { sp } from '@pnp/sp-addinhelpers';
export * from '@pnp/sp';
export * from '@pnp/odata';
function setup(config) {
RuntimeConfig.extend(config);
}
/**
* Utility methods
*/
var util = {
combine: combine,
dateAdd: dateAdd,
extend: extend,
getAttrValueFromString: getAttrValueFromString,
getCtxCallback: getCtxCallback,
getGUID: getGUID,
getRandomString: getRandomString,
isArray: isArray,
isFunc: isFunc,
isUrlAbsolute: isUrlAbsolute,
objectDefinedNotNull: objectDefinedNotNull,
sanitizeGuid: sanitizeGuid,
stringIsNullOrEmpty: stringIsNullOrEmpty,
};
/**
* Provides access to the SharePoint REST interface
*/
var sp$1 = sp;
/**
* Provides access to the Microsoft Graph REST interface
*/
var graph$1 = graph;
/**
* Provides access to local and session storage
*/
var storage = new PnPClientStorage();
/**
* Global configuration instance to which providers can be added
*/
var config = new Settings();
/**
* Global logging instance to which subscribers can be registered and messages written
*/
var log = Logger;
/**
* Allows for the configuration of the library
*/
var setup$1 = setup;
// /**
// * Expose a subset of classes from the library for public consumption
// */
// creating this class instead of directly assigning to default fixes issue #116
var Def = {
/**
* Global configuration instance to which providers can be added
*/
config: config,
/**
* Provides access to the Microsoft Graph REST interface
*/
graph: graph$1,
/**
* Global logging instance to which subscribers can be registered and messages written
*/
log: log,
/**
* Provides access to local and session storage
*/
setup: setup$1,
/**
* Provides access to the REST interface
*/
sp: sp$1,
/**
* Provides access to local and session storage
*/
storage: storage,
/**
* Utility methods
*/
util: util,
};
export default Def;
export { util, sp$1 as sp, graph$1 as graph, storage, config, log, setup$1 as setup };
//# sourceMappingURL=pnpjs.es5.js.map
| joeyparrish/cdnjs | ajax/libs/pnp-pnpjs/1.2.2-0/pnpjs.es5.js | JavaScript | mit | 3,001 |
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React, { Component, PropTypes } from 'react';
import emptyFunction from 'fbjs/lib/emptyFunction';
import s from './App.css';
import Header from '../Header';
// import Feedback from '../Feedback';
// import Footer from '../Footer';
class App extends Component {
static propTypes = {
context: PropTypes.shape({
insertCss: PropTypes.func,
setTitle: PropTypes.func,
setMeta: PropTypes.func,
}),
children: PropTypes.element.isRequired,
error: PropTypes.object,
};
static childContextTypes = {
insertCss: PropTypes.func.isRequired,
setTitle: PropTypes.func.isRequired,
setMeta: PropTypes.func.isRequired,
};
getChildContext() {
const context = this.props.context;
return {
insertCss: context.insertCss || emptyFunction,
setTitle: context.setTitle || emptyFunction,
setMeta: context.setMeta || emptyFunction,
};
}
componentWillMount() {
const { insertCss } = this.props.context;
this.removeCss = insertCss(s);
}
componentWillUnmount() {
this.removeCss();
}
render() {
// console.log('\n********\n', this.props, '\n********12334\n');
return this.props.children;
}
}
export default App;
| donal-crotty/fuzzy-telegram | src/components/App/App.js | JavaScript | mit | 1,478 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _concat = require('./internal/concat');
var _concat2 = _interopRequireDefault(_concat);
var _doParallel = require('./internal/doParallel');
var _doParallel2 = _interopRequireDefault(_doParallel);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = (0, _doParallel2.default)(_concat2.default);
module.exports = exports['default']; | fedejoaquin/IAW | serverNode/node_modules/async/concat.js | JavaScript | mit | 481 |
var through = require('through2');
var chunky = require('chunky');
var fs = require('fs');
var path = require('path');
var verify = require('adventure-verify');
var concat = require('concat-stream');
var data = fs.readFileSync(path.join(__dirname, 'finnegans_wake.txt'), 'utf8');
var spawn = require('child_process').spawn;
/*
module.exports = function () {
var tr = through();
var chunks = chunky(data);
var iv = setInterval(function () {
var buf = chunks.shift();
if (!buf) { clearInterval(iv); tr.end() }
else tr.write(buf)
}, 50);
return { args: [], stdin: tr, long: true };
};
*/
exports.problem = fs.createReadStream(path.join(__dirname, 'problem.txt'));
exports.solution = fs.createReadStream(path.join(__dirname, 'solution.js'));
var input = data.split('\n');
exports.verify = verify({ modeReset: true }, function (args, t) {
t.plan(3);
t.equal(args.length, 1, 'stream-adventure verify YOURFILE.js');
var expected = data.split('\n').map(function (line, ix) {
return (ix % 2 ? line.toUpperCase() : line.toLowerCase()) + '\n';
}).join('');
var ps = spawn(process.execPath, args);
ps.stderr.pipe(process.stderr);
ps.stdout.pipe(concat(function (body) {
t.equal(body.toString().trim(), expected.trim());
}));
ps.on('exit', function (code) {
t.equal(code, 0, 'successful exit code');
});
var iv = setInterval(function () {
if (input.length) {
ps.stdin.write(input.shift() + '\n');
}
else {
ps.stdin.end();
clearInterval(iv);
}
}, 50);
});
exports.run = function (args) {
var ps = spawn(process.execPath, args);
ps.stderr.pipe(process.stderr);
ps.stdout.pipe(process.stdout);
ps.once('exit', function (code) {
if (code) process.exit(code)
});
var iv = setInterval(function () {
if (input.length) {
ps.stdin.write(input.shift() + '\n');
}
else {
clearInterval(iv);
ps.stdin.end();
}
}, 50);
};
| Gtskk/stream-adventure | problems/lines/index.js | JavaScript | mit | 2,130 |
import { get } from 'ember-metal';
import { ControllerMixin } from 'ember-runtime';
import { prefixRouteNameArg } from '../utils';
/**
@module ember
@submodule ember-routing
*/
ControllerMixin.reopen({
concatenatedProperties: ['queryParams'],
/**
Defines which query parameters the controller accepts.
If you give the names `['category','page']` it will bind
the values of these query parameters to the variables
`this.category` and `this.page`.
By default, Ember coerces query parameter values using `toggleProperty`.
This behavior may lead to unexpected results.
To explicity configure a query parameter property so it coerces as expected, you must define a type property:
```javascript
queryParams: [{
category: {
type: 'boolean'
}
}]
```
@property queryParams
@public
*/
queryParams: null,
/**
This property is updated to various different callback functions depending on
the current "state" of the backing route. It is used by
`Ember.Controller.prototype._qpChanged`.
The methods backing each state can be found in the `Ember.Route.prototype._qp` computed
property return value (the `.states` property). The current values are listed here for
the sanity of future travelers:
* `inactive` - This state is used when this controller instance is not part of the active
route hierarchy. Set in `Ember.Route.prototype._reset` (a `router.js` microlib hook) and
`Ember.Route.prototype.actions.finalizeQueryParamChange`.
* `active` - This state is used when this controller instance is part of the active
route hierarchy. Set in `Ember.Route.prototype.actions.finalizeQueryParamChange`.
* `allowOverrides` - This state is used in `Ember.Route.prototype.setup` (`route.js` microlib hook).
@method _qpDelegate
@private
*/
_qpDelegate: null, // set by route
/**
During `Ember.Route#setup` observers are created to invoke this method
when any of the query params declared in `Ember.Controller#queryParams` property
are changed.
When invoked this method uses the currently active query param update delegate
(see `Ember.Controller.prototype._qpDelegate` for details) and invokes it with
the QP key/value being changed.
@method _qpChanged
@private
*/
_qpChanged(controller, _prop) {
let prop = _prop.substr(0, _prop.length - 3);
let delegate = controller._qpDelegate;
let value = get(controller, prop);
delegate(prop, value);
},
/**
Transition the application into another route. The route may
be either a single route or route path:
```javascript
aController.transitionToRoute('blogPosts');
aController.transitionToRoute('blogPosts.recentEntries');
```
Optionally supply a model for the route in question. The model
will be serialized into the URL using the `serialize` hook of
the route:
```javascript
aController.transitionToRoute('blogPost', aPost);
```
If a literal is passed (such as a number or a string), it will
be treated as an identifier instead. In this case, the `model`
hook of the route will be triggered:
```javascript
aController.transitionToRoute('blogPost', 1);
```
Multiple models will be applied last to first recursively up the
route tree.
```javascript
App.Router.map(function() {
this.route('blogPost', { path: ':blogPostId' }, function() {
this.route('blogComment', { path: ':blogCommentId', resetNamespace: true });
});
});
aController.transitionToRoute('blogComment', aPost, aComment);
aController.transitionToRoute('blogComment', 1, 13);
```
It is also possible to pass a URL (a string that starts with a
`/`). This is intended for testing and debugging purposes and
should rarely be used in production code.
```javascript
aController.transitionToRoute('/');
aController.transitionToRoute('/blog/post/1/comment/13');
aController.transitionToRoute('/blog/posts?sort=title');
```
An options hash with a `queryParams` property may be provided as
the final argument to add query parameters to the destination URL.
```javascript
aController.transitionToRoute('blogPost', 1, {
queryParams: { showComments: 'true' }
});
// if you just want to transition the query parameters without changing the route
aController.transitionToRoute({ queryParams: { sort: 'date' } });
```
See also [replaceRoute](/api/classes/Ember.ControllerMixin.html#method_replaceRoute).
@param {String} name the name of the route or a URL
@param {...Object} models the model(s) or identifier(s) to be used
while transitioning to the route.
@param {Object} [options] optional hash with a queryParams property
containing a mapping of query parameters
@for Ember.ControllerMixin
@method transitionToRoute
@public
*/
transitionToRoute(...args) {
// target may be either another controller or a router
let target = get(this, 'target');
let method = target.transitionToRoute || target.transitionTo;
return method.apply(target, prefixRouteNameArg(this, args));
},
/**
Transition into another route while replacing the current URL, if possible.
This will replace the current history entry instead of adding a new one.
Beside that, it is identical to `transitionToRoute` in all other respects.
```javascript
aController.replaceRoute('blogPosts');
aController.replaceRoute('blogPosts.recentEntries');
```
Optionally supply a model for the route in question. The model
will be serialized into the URL using the `serialize` hook of
the route:
```javascript
aController.replaceRoute('blogPost', aPost);
```
If a literal is passed (such as a number or a string), it will
be treated as an identifier instead. In this case, the `model`
hook of the route will be triggered:
```javascript
aController.replaceRoute('blogPost', 1);
```
Multiple models will be applied last to first recursively up the
route tree.
```javascript
App.Router.map(function() {
this.route('blogPost', { path: ':blogPostId' }, function() {
this.route('blogComment', { path: ':blogCommentId', resetNamespace: true });
});
});
aController.replaceRoute('blogComment', aPost, aComment);
aController.replaceRoute('blogComment', 1, 13);
```
It is also possible to pass a URL (a string that starts with a
`/`). This is intended for testing and debugging purposes and
should rarely be used in production code.
```javascript
aController.replaceRoute('/');
aController.replaceRoute('/blog/post/1/comment/13');
```
@param {String} name the name of the route or a URL
@param {...Object} models the model(s) or identifier(s) to be used
while transitioning to the route.
@for Ember.ControllerMixin
@method replaceRoute
@public
*/
replaceRoute(...args) {
// target may be either another controller or a router
let target = get(this, 'target');
let method = target.replaceRoute || target.replaceWith;
return method.apply(target, prefixRouteNameArg(target, args));
}
});
export default ControllerMixin;
| cbou/ember.js | packages/ember-routing/lib/ext/controller.js | JavaScript | mit | 7,323 |
void function(exports,$,_,Backbone){Backbone.UndoManager.removeUndoType("add");Backbone.UndoManager.removeUndoType("remove");_(exports).extend({onbeforeunload:function(){},slider:new JSNES_SliderView({el:".jsn-es-app",saveTarget:"#jform_slider_data"})});$(".dropdown-toggle").dropdown()}(this,JSNES_jQuery,JSNES_Underscore,JSNES_Backbone); | DevDean/jissaticket | administrator/components/com_easyslider/assets/slider/js/init.js | JavaScript | gpl-2.0 | 339 |
modules.define('test', ['i-bem__dom'], function(provide, BEMDOM) {
provide(BEMDOM.decl(this.name, {
onSetMod : {
'js' : {
'inited' : function() {
var modal = this.findBlockInside('modal');
this.findBlockInside('link').on('click', function() {
modal.toggleMod('visible');
});
}
}
}
}, {
live : false
}));
});
| just-boris/bem-components | common.blocks/modal/modal.tests/gemini.blocks/test/test.js | JavaScript | mpl-2.0 | 431 |
/**
* Copyright (C) 2005-2016 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* This module was written with the express purpose of working with the [ComboBox]{@link module:alfresco/forms/controls/ComboBox}
* form control. It extends the Dojo JsonRest module to support queries over the Aikau publication/subscription
* communication layer (rather than by direct XHR request).
*
* @module alfresco/forms/controls/utilities/ServiceStore
* @extends external:dojo/store/JsonRest
* @author Dave Draper
*/
define(["dojo/_base/declare",
"dojo/store/JsonRest",
"alfresco/core/Core",
"dojo/Deferred",
"dojo/_base/lang",
"dojo/_base/array",
"dojo/store/util/QueryResults",
"dojo/store/util/SimpleQueryEngine",
"dojo/regexp"],
function(declare, JsonRest, AlfCore, Deferred, lang, array, QueryResults, SimpleQueryEngine, regexp) {
return declare([JsonRest, AlfCore], {
/**
* This is the topic to publish to get the options for.
*
* @instance
* @type {string}
* @default
*/
publishTopic: null,
/**
* The payload to publish on the [publishTopic]{@link module:alfresco/forms/controls/utilities/ServiceStore#publishTopic}
* to assist with retrieving data.
*
* @instance
* @type {object}
* @default
*/
publishPayload: null,
/**
* This is the attribute to use when querying the result data for matching items. This is set to
* "name" by default but can be overridden. When used by a [form control]{@link module:alfresco/forms/controls/BaseFormControl}
* it would be expected that this would be set to be the [name attribute]{@link module:alfresco/forms/controls/BaseFormControl#name}
* of that form control.
*
* @instance
* @type {string}
* @default
*/
queryAttribute: "name",
/**
* Should the results all start with the search query string.
* If set to false, results that contain the string anywhere will match
*
* @instance
* @type {string}
* @default
*/
searchStartsWith: false,
/**
* If this is configured to be an array of fixed options then the query will be run against
* those options without constantly making XHR requests for fresh data.
*
* @instance
* @type {array}
* @default
*/
fixed: null,
/**
* This function is called to retrieve an item from the store. If the store uses fixed options
* then these are checked and if an XHR request is required then a deferred item will be
* returned pending a callback to the
* [onGetOptions function]{@link module:alfresco/forms/controls/utilities/ServiceStore#onGetOptions}.
*
* @instance
* @param {string} id The id of the item to retrieve from the store
* @param {object} options Options for finding the item
* @returns Either the item or a promise of the item
*/
get: function alfresco_forms_controls_utilities_ServiceStore__get(id, /*jshint unused:false*/options){
var response = null;
if (this.publishTopic)
{
// If a publishTopic has been specified then publish on it to request the options
// to search through for the item...
response = new Deferred();
var responseTopic = this.generateUuid();
var payload = lang.clone(this.publishPayload);
if (!payload)
{
payload = {};
}
payload.alfResponseTopic = responseTopic;
var resultsProperty = this.publishPayload.resultsProperty || "response";
this._getOptionsHandle = [];
this._getOptionsHandle.push(this.alfSubscribe(responseTopic + "_SUCCESS", lang.hitch(this, this.onGetOptions, response, resultsProperty, id)));
this._getOptionsHandle.push(this.alfSubscribe(responseTopic, lang.hitch(this, this.onGetOptions, response, resultsProperty, id)));
this.alfPublish(this.publishTopic, payload, this.publishGlobal);
}
else if (this.fixed)
{
// ...otherwise search any fixed options that have been supplied...
response = this.getOption(lang.clone(this.fixed), id);
}
else
{
this.alfLog("warn", "A ServiceStore was set up without 'publishTopic' or 'fixed' attributes to use to retrieve options", this);
response = "";
}
return response;
},
/**
* This is the callback function that is hitched to the request for
*
* @instance
* @param {obejct} dfd The deferred object to resolve.
* @param {string} resultsProperty A dot-notation address in the payload that should contain the list of options.
* @param {string} id The id of the item to retrieve
* @param {object} payload The options to use
*/
onGetOptions: function alfresco_forms_controls_utilities_ServiceStore__onGetOptions(dfd, resultsProperty, id, payload) {
this.alfUnsubscribeSaveHandles([this._getOptionsHandle]);
var results = lang.getObject(resultsProperty, false, payload);
if (results !== null && typeof results !== "undefined")
{
var target = this.getOption(results, id);
dfd.resolve(target);
}
else
{
this.alfLog("warn", "No '" + resultsProperty + "' attribute published in payload for the query options", payload, this);
dfd.resolve("");
}
},
/**
* Iterates over the supplied results array to try and find an item where it's
* valueAttribute matches the supplied id.
*
* @instance
* @param {array} results The results to iterate over
* @param {string} id The id of the item to find
* @returns {object} The found item (or the empty string if the item cannot be found)
*/
getOption: function alfresco_forms_controls_utilities_ServiceStore__getOption(results, id) {
var target = "";
array.forEach(results, function(item) {
if (item[this.valueAttribute] === id)
{
target = item;
}
}, this);
return target;
},
/**
* This function is used to actually query the results (either from a pub/sub request or
* defined in a fixed list of options).
*
* @instance
* @param {array} results The results to query.
*/
queryResults: function alfresco_forms_controls_utilities_ServiceStore__queryResults(results, query) {
/*jshint newcap:false*/
// Clone the original fixed set of options to ensure that we're not
// removing any of the original data...
var queryAttribute = this.queryAttribute || "name";
var labelAttribute = this.labelAttribute || "label";
var valueAttribute = this.valueAttribute || "value";
// Check that all the data is valid, this is done to ensure any data sets that don't contain all the data...
// This is a workaround for an issue with the Dojo query engine that will break when an item doesn't contain
// the query attribute...
array.forEach(results, lang.hitch(this, this.processResult, queryAttribute, labelAttribute, valueAttribute));
// Create an updated query with a sanitised query/regex in it
var updatedQuery = {};
updatedQuery[this.queryAttribute] = this.createSearchRegex(query[this.queryAttribute].toString());
// NOTE: Ignore JSHint warnings on the following 2 lines...
var queryEngine = SimpleQueryEngine(updatedQuery);
var queriedResults = QueryResults(queryEngine(results));
return queriedResults;
},
/**
* Create the regex used for querying
*
* @instance
* @param {string} queryString The supplied query string
* @param {boolean} ignorePostMatch Whether to append ".*$" to the string (defaults to including this)
* @returns {object} The regular expression to use in the query engine
*/
createSearchRegex: function alfresco_forms_controls_utilities_ServiceStore__createSearchRegex(queryString, ignorePostMatch) {
var safeQueryString = regexp.escapeString(queryString),
rePrefix = this.searchStartsWith ? "^" : "",
reSuffix = ignorePostMatch ? "" : ".*$",
reValue = rePrefix + safeQueryString + reSuffix,
reModifiers = "i";
return new RegExp(reValue, reModifiers);
},
/**
* Processes the results to check that all the data is valid, this is done to ensure any
* data sets that don't contain all the data are corrected.This is a workaround for an
* issue with the Dojo query engine that will break when an item doesn't contain
* the query attribute. This function also adds label and value attributes to the item
* if they're not present.
*
* @instance
* @param {array} options The array to add the processed item to
* @param {object} config The configuration to use for processing the option
* @param {object} item The current item to process as an option
* @param {number} index The index of the item in the items list
*/
processResult: function alfresco_forms_controls_utilities_ServiceStore__processResult(queryAttribute, labelAttribute, valueAttribute, item, /*jshint unused:false*/ index) {
// Small helper func to remove JSHint errors but absolutely preserve existing logic
var isValid = function(o) {
return o !== null && typeof o !== "undefined";
};
if (!isValid(item[queryAttribute]))
{
item[queryAttribute] = "";
}
if (!isValid(item.label) && isValid(item[labelAttribute]))
{
item.label = item[labelAttribute];
}
if (!isValid(item.value) && isValid(item[valueAttribute]))
{
item.value = item[valueAttribute];
}
},
/**
* Queries a fixed set of options.
*
* @instance
* @param {object} query The query to use for retrieving objects from the store.
* @param {object} options The optional arguments to apply to the resultset.
* @returns {object} The results of the query, extended with iterative methods.
*/
queryFixedOptions: function alfresco_forms_controls_utilities_ServiceStore__queryFixedOptions(query, /*jshint unused:false*/ options) {
var queriedResults = this.queryResults(lang.clone(this.fixed), query);
return queriedResults;
},
/**
* Makes a request for data by publishing a request on a specific topic. This returns a
* Deferred object which is resolved by the
* [onQueryOptions]{@link module:alfresco/forms/controls/utilities/ServiceStore#onQueryOptions}
* function.
*
* @instance
* @param {object} query The query to use for retrieving objects from the store.
* @param {object} options The optional arguments to apply to the resultset.
* @returns {object} The results of the query, extended with iterative methods.
*/
queryXhrOptions: function alfresco_forms_controls_utilities_ServiceStore__queryXhrOptions(query, /*jshint unused:false*/ options) {
var response = new Deferred();
var responseTopic = this.generateUuid();
var payload = lang.clone(this.publishPayload);
if (!payload)
{
payload = {};
}
payload.alfResponseTopic = responseTopic;
// Set up a dot-notation address to retrieve the results from, this will be set to response if not included
// in the payload...
var resultsProperty = payload.resultsProperty || "response";
// Add in an additional query attribute. Some services (e.g. the TagService) will use this as an additional
// search term request parameter...
payload.query = query[this.queryAttribute || "name"];
var optionsHandle = [];
optionsHandle.push(this.alfSubscribe(responseTopic + "_SUCCESS", lang.hitch(this, this.onQueryOptions, response, query, resultsProperty, optionsHandle)));
optionsHandle.push(this.alfSubscribe(responseTopic, lang.hitch(this, this.onQueryOptions, response, query, resultsProperty, optionsHandle)));
this.alfPublish(this.publishTopic, payload, this.publishGlobal);
return response;
},
/**
* Overrides the inherited function from the JsonRest store to call either the
* [queryXhrOptions]{@link module:alfresco/forms/controls/utilities/ServiceStore#queryXhrOptions}
* or [queryFixedOptions]{@link module:alfresco/forms/controls/utilities/ServiceStore#queryFixedOptions}
* depending upon how this module has been configured.
*
* @instance
* @param {object} query The query to use for retrieving objects from the store.
* @param {object} options The optional arguments to apply to the resultset.
* @returns {object} The r{@link module:alfresco/forms/controls/utilities/ServiceStore#onQueryOptions} esults of the query, extended with iterative methods.
*/
query: function alfresco_forms_controls_utilities_ServiceStore__query(query, options){
var response = null;
if (this.publishTopic)
{
response = this.queryXhrOptions(query, options);
}
else if (this.fixed)
{
response = this.queryFixedOptions(query, options);
}
else
{
this.alfLog("warn", "A ServiceStore was set up without 'publishTopic' or 'fixed' attributes to use to retrieve options", this);
response = {};
}
return response;
},
/**
* This is hitched to a generated topic subscription that is published when the target service has retrieved
* the requested data. It performs a query on the data provided to generate the result set.
*
* @instance
* @param {obejct} dfd The deferred object to resolve.
* @param {object} query The requested query data.
* @param {string} resultsProperty A dot-notation address in the payload that should contain the list of options.
* @param {object} payload The options to use
*/
onQueryOptions: function alfresco_forms_controls_utilities_ServiceStore__onQueryOptions(dfd, query, resultsProperty, optionsHandle, payload) {
this.alfUnsubscribeSaveHandles([optionsHandle]);
var results = lang.getObject(resultsProperty, false, payload);
if (results)
{
var queriedResults = this.queryResults(results, query);
dfd.resolve(queriedResults);
}
else
{
this.alfLog("warn", "No '" + resultsProperty + "' attribute published in payload for the query options", payload, this);
dfd.resolve([]);
}
}
});
}); | davidcognite/Aikau | aikau/src/main/resources/alfresco/forms/controls/utilities/ServiceStore.js | JavaScript | lgpl-3.0 | 15,995 |
var brCore = require("br/Core");
var Fixture = require("br/test/Fixture");
var FixtureFactory = require("br/test/FixtureFactory");
var TestFixtureFactory = function()
{
this.m_mFixtures = {};
};
brCore.implement(TestFixtureFactory, FixtureFactory);
TestFixtureFactory.createMockFixture = function(bCanHandleExactMatch, bApplyTearDownStub)
{
var oMockFixture = mock(Fixture);
oMockFixture.stubs().canHandleProperty(ANYTHING).will(returnValue(false));
oMockFixture.stubs().canHandleProperty("prop").will(returnValue(true));
oMockFixture.stubs().canHandleExactMatch().will(returnValue(bCanHandleExactMatch));
oMockFixture.stubs().addSubFixtures(ANYTHING);
oMockFixture.stubs().setUp();
if(bApplyTearDownStub !== false)
{
oMockFixture.stubs().tearDown();
}
return oMockFixture;
};
TestFixtureFactory.prototype.addFixtures = function(oFixtureRegistry)
{
var ParentTestFixture = require("br/test/ParentTestFixture");
var GrandParentTestFixture = require("br/test/GrandParentTestFixture");
this.addMockFixtureToRegistry(oFixtureRegistry, "fixture", TestFixtureFactory.createMockFixture(false, false));
this.addMockFixtureToRegistry(oFixtureRegistry, "propertyFixture", TestFixtureFactory.createMockFixture(true));
this.addFixtureToRegistry(oFixtureRegistry, "parentFixture", new ParentTestFixture());
this.addFixtureToRegistry(oFixtureRegistry, "grandParentFixture", new GrandParentTestFixture());
this.addMockFixtureToRegistry(oFixtureRegistry, "another=fixture", TestFixtureFactory.createMockFixture(false));
};
TestFixtureFactory.prototype.getFixture = function(sFixtureName)
{
return this.m_mFixtures[sFixtureName];
};
TestFixtureFactory.prototype.addFixtureToRegistry = function(oFixtureRegistry, sFixtureName, oFixture)
{
this.m_mFixtures[sFixtureName] = oFixture;
oFixtureRegistry.addFixture(sFixtureName, oFixture);
};
TestFixtureFactory.prototype.addMockFixtureToRegistry = function(oFixtureRegistry, sFixtureName, oMockFixture)
{
this.m_mFixtures[sFixtureName] = oMockFixture;
oFixtureRegistry.addFixture(sFixtureName, oMockFixture.proxy());
};
module.exports = TestFixtureFactory;
| trueadm/brjs | brjs-sdk/sdk/libs/javascript/br-test/test-unit/src-test/br/test/TestFixtureFactory.js | JavaScript | lgpl-3.0 | 2,121 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _lodash = require('lodash');
var _lodash2 = _interopRequireDefault(_lodash);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var schema = [];
var create = function create(context) {
var regex = /^(Boolean|Number|String)$/;
return {
GenericTypeAnnotation: function GenericTypeAnnotation(node) {
var name = _lodash2.default.get(node, 'id.name');
if (regex.test(name)) {
context.report({
data: {
name
},
loc: node.loc,
message: 'Unexpected use of {{name}} constructor type.',
node
});
}
}
};
};
exports.default = {
create,
schema
};
module.exports = exports.default; | BigBoss424/portfolio | v8/development/node_modules/eslint-plugin-flowtype/dist/rules/noPrimitiveConstructorTypes.js | JavaScript | apache-2.0 | 817 |
var Hat=function(){function t(t){this.greeting=t}return t.prototype.go=function(){return this.greeting},t}();module.exports=Hat; | jimhotchkin-wf/wGulp | test/subtasks/minify/app.min.js | JavaScript | apache-2.0 | 128 |
/**
* Sahi - Web Automation and Test Tool
*
* Copyright 2006 V Narayan Raman
*
* 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.
*/
sahisid = "$sahisid";
function showSteps(s){
var d = top.document.currentForm.debug;
top.document.currentForm.history.value += "\n" + d.value;
d.value = s;
};
var currentActiveTab = null;
TabGroup = function(name, ids, defaultId){
this.name = name;
this.ids = [];
this.defaultId = defaultId;
this.addAll(ids);
var activeTab = getTabVar("controller_active_tab");
if (activeTab != null)
this.show(activeTab);
else
this.show(this.defaultId);
TabGroup.instances[TabGroup.instances.length] = this;
};
TabGroup.instances = [];
TabGroup.prototype.addAll = function(ids){
for ( var i = 0; i < ids.length; i++) {
this.add(ids[i]);
}
};
TabGroup.prototype.add = function(id){
this.ids[this.ids.length] = id;
$(id).onclick_ = $(id).onclick;
$(id).onclick = null;
this.addEvent($(id), "click", this.wrap(this.onclick, this));
};
TabGroup.prototype.addEvent = function (el, ev, fn) {
if (!el) return;
if (el.attachEvent) {
el.attachEvent("on" + ev, fn);
} else if (el.addEventListener) {
el.addEventListener(ev, fn, false);
}
};
TabGroup.prototype.wrap = function (fn, el) {
if (!el) el = this;
return function(){fn.apply(el, arguments);};
};
TabGroup.prototype.onclick = function(e){
var el = getTarget(e);
var thisId = el.id;
this.show(thisId, true);
};
TabGroup.prototype.show = function(thisId, isEvent){
if (!thisId || !$(thisId)) thisId = this.defaultId;
if (!thisId) return;
for ( var i = 0; i < this.ids.length; i++) {
var id = this.ids[i];
if (!$(id)) continue;
$(id+"box").style.display = (id == thisId) ? "block" : "none";
$(id).className = "dimTab";
}
var el = $(thisId);
el.className = "hiTab";
// if (el.onclick && !isEvent) el.onclick();
if (el.onclick_) el.onclick_();
this.selectedTab = thisId;
currentActiveTab = this.selectedTab;
};
function recOnClick(){
doOnPlaybackUnLoad();
doOnRecLoad();
}
function playbackOnClick(){
doOnRecUnLoad();
doOnPlaybackLoad();
}
function infoOnClick(){
sahi().storeDiagnostics();
displayInfoTab();
doOnPlaybackUnLoad();
doOnRecUnLoad();
}
var getTarget = function (e) {
var targ;
if (!e) e = window.event;
if (e.target) targ = e.target;
else if (e.srcElement) targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;
return targ;
};
TabGroup.prototype.getSelectedTab = function (e) {
return this.selectedTab;
};
TabGroup.prototype.showDefault = function (force) {
if (force || this.selectedTab == null) this.show();
};
TabGroup.getState = function(){
var s = [];
for (var i=0; i<TabGroup.instances.length; i++){
var tg = TabGroup.instances[i];
s[s.length] = {id:tg.name, value:tg.getSelectedTab(), type:"tab"};
}
return s;
};
TabGroup.showDefaults = function(){
for (var i=0; i<TabGroup.instances.length; i++){
TabGroup.instances[i].showDefault();
}
};
function $(id){
return document.getElementById(id);
}
function checkOpener() {
try {
var x = window.top.opener.document;
}
catch (e) {
}
}
function sahi(){
return sahiOpener()._sahi;
}
function sahiOpener() {
return window.top.opener._sahi.top();
}
window.onerror = checkOpener;
function trim(s) {
s = s.replace(/^[ \t]/, "", "g");
return s.replace(/[ \t]$/, "", "g");
}
function checkURL(url) {
if (url == null || trim(url) == "") return "";
if (url.indexOf("://") == -1) return "http://" + url;
return url;
}
function resetIfNeeded(){
var nextStep = parseInt($("nextStep").value);
var currentStep = parseInt($("currentStep").innerHTML);
if (nextStep <= currentStep){
resetScript();
}
}
function play() {
resetIfNeeded();
try {
sahi().playManual(parseInt($("nextStep").value))
} catch (e) {
displayLogs("Please open the Controller again. \n(Press CTRL ALT-DblClick on the main window.)");
}
return true;
}
function stepWisePlay() {
resetIfNeeded();
var i = parseInt($("nextStep").value);
sahiOpener().eval("_sahi.skipTill("+i+")");
sahiOpener().eval("_sahi.ex(true)");
}
function pause() {
sahi().pause();
}
function stopPlay() {
sahi().stopPlaying();
}
function resetStep() {
$("currentStep").innerHTML = "0";
$("nextStep").value = 1;
sahiSetServerVar("sahiIx", 0);
sahiSetServerVar("sahiLocalIx", 0);
}
function clearLogs() {
$("talogs").value = "";
}
function stopRec() {
try {
sahi().stopRecording();
enableRecordButton();
} catch(ex) {
alert(ex);
}
}
window.top.isWinOpen = true;
function pageUnLoad(s) {
sendPlaybackSnapshot();
sendRecorderSnapshot();
var s = addVar("controller_active_tab", currentActiveTab);
sahiSetServerVar("tab_state", s);
sahiSendToServer('/_s_/dyn/ControllerUI_closed');
try {
window.top.isWinOpen = false;
} catch(ex) {
sahiHandleException(ex);
}
}
function pageOnLoad(){
Suggest.hideAll();
resizeTAs();
}
function doOnRecUnLoad(s) {
sendRecorderSnapshot();
}
function doOnPlaybackUnLoad(s) {
sendPlaybackSnapshot();
}
function sendPlaybackSnapshot() {
var s = "";
s += addVar("controller_url", $("url").value);
s += addVar("controller_logs", $("talogs").value);
s += addVar("controller_step", $("nextStep").value);
s += addVar("controller_url_starturl", $("url_starturl").value);
s += addVar("controller_pb_dir", $("pbdir").value);
s += addVar("controller_file_starturl", $("script_starturl").value);
s += addVar("controller_file_scriptname", $("filebox").value);
var showUrl = "" + ($("seturl").style.display == "block");
s += addVar("controller_show_url", showUrl);
sahiSetServerVar("playback_state", s);
}
function sendRecorderSnapshot() {
var s = "";
s += addVar("controller_recorder_file", $("recfile").value);
s += addVar("controller_el_value", $("elValue").value);
// s += addVar("controller_comment", $("comment").value);
s += addVar("controller_accessor", $("accessor").value);
// s += addVar("controller_alternative", window.document.currentForm.alternative.value);
s += addVar("controller_debug", $("taDebug").value);
s += addVar("controller_history", $("history").value);
// s += addVar("controller_waitTime", $("waitTime").value);
s += addVar("controller_result", $("taResult").value);
s += addVar("controller_rec_dir", $("recdir").value);
sahiSetServerVar("recorder_state", s);
}
function addVar(n, v) {
return n + "=" + v + "_$sahi$_";
}
_recVars = null;
function getRecVar(name) {
if (_recVars == null || _recVars == "") {
_recVars = loadVars("recorder_state");
}
return blankIfNull(_recVars[name]);
}
_tabVars = null;
function getTabVar(name) {
if (_tabVars == null || _tabVars == "") {
_tabVars = loadVars("tab_state");
}
return blankIfNull(_tabVars[name]);
}
function loadVars(serverVarName) {
var s = sahiGetServerVar(serverVarName);
var a = new Array();
if (s) {
var nv = s.split("_$sahi$_");
for (var i = 0; i < nv.length; i++) {
var ix = nv[i].indexOf("=");
var n = nv[i].substring(0, ix);
var v = nv[i].substring(ix + 1);
a[n] = blankIfNull(v);
}
}
return a;
}
_pbVars = null;
function getPbVar(name) {
if (_pbVars == null || _pbVars == "") {
_pbVars = loadVars("playback_state");
}
return blankIfNull(_pbVars[name]);
}
var _selectedScriptDir = null;
var _selectedScript = null;
var _scriptDirList = null;
var _scriptFileList = null;
function doOnRecLoad() {
_scriptDirList = refreshScriptListDir();
populateOptions($("recdir"), _scriptDirList, _selectedScriptDir);
initRecorderTab();
}
// Returns the number of characters of the longest element in a list
function getLongestListElementSize(p_list) {
var longestSize = 0;
var len = p_list.length;
for (var i = 0; i < len; ++i) {
if (p_list[i].length > longestSize) {
longestSize = p_list[i].length;
}
}
return longestSize;
}
// Changes the width of an element. If more than 1 element has the same name, we resize
// the first one.
function resizeElementWidth(p_elementName, p_size) {
var el = $(p_elementName);
if (!el) {
el = window.document.getElementsByName(p_elementName)[0];
}
if (parseInt(el.style.width) < p_size) el.style.width = p_size;
}
// Resize a dropdown list so we can see its entire content.
function resizeDropdown(p_dropdownContent, p_dropdownName, p_prefix) {
var longest = getLongestListElementSize(p_dropdownContent);
// A caracter is about 7 pixel long
var newDropdownSize = (longest - p_prefix) * 6.2 + 20;
resizeElementWidth(p_dropdownName, newDropdownSize);
}
function populateScripts(dir) {
_scriptFileList = refreshScriptListFile(dir);
setSelectedScriptDir(dir);
$('filebox').value = "";
}
function refreshScriptListDir(){
return eval("(" + sahiSendToServer("/_s_/dyn/ControllerUI_scriptDirsListJSON") + ")");
}
function refreshScriptListFile(dir){
return eval("(" + sahiSendToServer("/_s_/dyn/ControllerUI_scriptsListJSON?dir="+dir) + ")");
}
function populateOptions(el, opts, selectedOpt, defaultOpt, prefix) {
el.options.length = 0;
if (defaultOpt) {
el.options[0] = new Option(defaultOpt, "");
}
var len = opts.length;
for (var i = 0; i < len; i++) {
var ix = el.options.length;
if (prefix) {
if (opts[i].indexOf(prefix) == 0) {
el.options[ix] = new Option(opts[i].substring(prefix.length), opts[i]);
if (opts[i] == selectedOpt) el.options[ix].selected = true;
}
} else {
el.options[ix] = new Option(opts[i], opts[i]);
if (opts[i] == selectedOpt) el.options[ix].selected = true;
}
}
// alert(el.options.length)
}
function doOnPlaybackLoad() {
initPlaybackTab();
var ix = sahiGetCurrentIndex();
if (ix != null) {
displayStepNum(ix);
}
}
function isSameStep(ix) {
try {
return ($("nextStep").value == "" + ix);
} catch(e) {
return false;
}
}
function displayStepNum(ix) {
try {
if (window.document.playform)
$("currentStep").innerHTML = "" + ix;
$("nextStep").value = "" + (ix + 1);
} catch(e) {
sahiHandleException(e);
}
}
function sahiGetCurrentIndex() {
try {
var i = parseInt(sahiGetServerVar("sahiIx"));
return ("" + i != "NaN") ? i : 0;
} catch(e) {
sahiHandleException(e);
}
}
function displayQuery(s) {
// document.currentForm.query.value = forceWrap(s);
}
function displayLogs(s, i) {
if (i == null){ // for stop PlayBack messages
if ($("talogs").value.match(s+"[\r\n]*$")) return;
}
if ((""+i) != $("currentStep").innerHTML) {
$("talogs").value += s + "\n";
$("talogs").scrollTop = $("talogs").scrollHeight;
}
}
function forceWrap(s1) {
var ix = s1.indexOf("\n");
var s = s1;
var rest = "";
if (ix != -1) {
s = s1.substring(0, ix);
rest = s1.substring(ix);
}
var start = 0;
var BR_LEN = 51;
var len = s.length;
var broken = "";
while (true) {
if (start + BR_LEN >= len) {
broken += s.substring(start);
break;
}
else {
broken += s.substring(start, start + BR_LEN) + "\n";
start += BR_LEN;
}
}
return broken + rest;
}
function setSelectedScriptDir(s) {
_selectedScriptDir = s;
}
function setSelectedScript(s) {
_selectedScript = s;
}
var isRecordAll = true;
function recordAll() {
isRecordAll = !isRecordAll;
}
function disableRecordButton(){
$("record").disabled = true;
}
function enableRecordButton(){
$("record").disabled = false;
}
function onRecordStartFormSubmit(f) {
if ($("recfile").value == "") {
alert("Please enter a name for the script");
$("recfile").focus();
return false;
}
if (sahiOpener()) {
var el1 = $("recdir");
var el2 = $("recfile");
var value1 = el1.options[el1.selectedIndex].value.replace(/:/g,'%3A');
var value2 = el2.value;
sahiSendToServer("/_s_/dyn/Recorder_start?dir="+value1+"&file="+value2);
sahi().startRecording(recordAll);
disableRecordButton();
// window.setTimeout("top.location.reload();", 1000);
}
return true;
}
function initRecorderTab() {
$("recfile").value = getRecVar("controller_recorder_file");
$("elValue").value = getRecVar("controller_el_value");
$("accessor").value = getRecVar("controller_accessor");
// window.document.currentForm.alternative.value = getRecVar("controller_alternative");
// $("comment").value = getRecVar("controller_comment");
$("history").value = getRecVar("controller_history");
$("taDebug").value = getRecVar("controller_debug");
// $("waitTime").value = getRecVar("controller_waitTime");
$("taResult").value = getRecVar("controller_result");
var dir = getRecVar("controller_rec_dir");
if (dir && dir != null) $("recdir").value = getRecVar("controller_rec_dir");
if (sahi().isRecording()) disableRecordButton();
}
function showTab(s) {
if (window.top.main.location.href.indexOf(s + '.htm') != -1) return;
hilightTab(s);
window.top.main.location.href = s + '.htm'
}
function listProperties(){
$("taDebug").value = sahi()._eval("sahiList("+addSahi($("accessor").value)+")");
}
function initPlaybackTab() {
//var f = window.document.scriptfileform;
var dir = getPbVar("controller_pb_dir");
_scriptDirList = refreshScriptListDir();
populateOptions($("pbdir"), _scriptDirList, dir);
setSelectedScriptDir($("pbdir").value);
_scriptFileList = refreshScriptListFile($("pbdir").value);
$("filebox").value = getPbVar("controller_file_scriptname");
$("url").value = getPbVar("controller_url");
$("talogs").value = getPbVar("controller_logs");
$("url_starturl").value = getPbVar("controller_url_starturl");
$("script_starturl").value = getPbVar("controller_file_starturl");
$("nextStep").value = getPbVar("controller_step");
byFile(getPbVar("controller_show_url") != "true");
}
function displayInfo(accessors, escapedAccessor, escapedValue, popupName) {
var f = window.document.currentForm;
if (f) {
f.elValue.value = escapedValue ? escapedValue : "";
f.accessor.value = escapedAccessor;
populateOptions(f.alternative, accessors);
//f.alternative.value = info.accessor;
f.winName.value = popupName;
}
}
function resetValue(){
try{
$("elValue").value = getEvaluateExpressionResult($("accessor").value);
}catch(e){}
}
function setAPI(){
var el = $("apiTextbox");
// try{
el.value = $("apiSelect").value;
// }catch(e){}
}
function handleEnterKey(e, el){
if (!e) e = window.event;
if (e.keyCode && e.keyCode == 26){
resetValue();
return false;
}
}
function addWait() {
try {
sahi().addWait($("waitTime").value);
} catch(ex) {
alert("Please enter the number of milliseconds to wait (should be >= 200)");
$("waitTime").value = 3000;
}
}
function mark() {
sahi().mark($("comment").value);
// sahiSendToServer('/_s_/dyn/Recorder_record?event=mark&value='+escape(document.currentForm.comment.value));
}
function getEvaluateExpressionResult(str){
sahiSetServerVar("sahiEvaluateExpr", "true");
var res = "";
try {
res = sahi()._eval(addSahi(str));
} catch(e) {
//throw e;
if (e.exceptionType && e.exceptionType == "SahiAssertionException") {
res = "[Assertion Failed]" + (e.messageText?e.messageText:"");
}
else {
res = "[Exception] " + e;
}
sahiHandleException(e);
}
sahiSetServerVar("sahiEvaluateExpr", "false");
return res;
}
function evaluateExpr(showErr) {
if (!showErr) showErr = false;
$("history").value += "\n" + $("taDebug").value;
var txt = getText();
var res = getEvaluateExpressionResult(txt);
if (showErr) {
$("taResult").value = "" + res;
}
}
function demoClick() {
setDebugValue("_click(" + $("accessor").value + ");");
evaluateExpr();
}
function demoHighlight() {
setDebugValue("_highlight(" + $("accessor").value + ");");
evaluateExpr();
}
function demoHover() {
setDebugValue("_mouseOver(" + $("accessor").value + ");");
evaluateExpr();
}
function demoAction(el) {
if (el.value == "comment1") {
setDebugValue("// Single line comment");
} else if (el.value == "comment2") {
setDebugValue("/* Multiline \n Comment */");
} else {
setDebugValue(el.value + "(" + $("accessor").value + ");");
evaluateExpr();
}
el.options[0].selected = true;
}
function getSelectedText(){
if (sahi().isIE()) return getSel();
var textarea = $("taDebug");
var len = textarea.value.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var sel = textarea.value.substring(start, end);
return sel;
}
function getText(){
var txt = getSelectedText();
if (txt == "") txt = $("taDebug").value;
return txt;
}
function demoHighlight2(){
getEvaluateExpressionResult("_highlight(" + getText() + ");");
}
function demoClick2(){
getEvaluateExpressionResult("_click(" + getText() + ");");
}
function demoSetValue() {
var acc = $("accessor").value;
if (acc.indexOf("_select") == 0 || acc.indexOf('e("select")') != -1) {
setDebugValue("_setSelected(" + acc + ", \"" + $('elValue').value + "\");");
} else
setDebugValue("_setValue(" + acc + ", \"" + $('elValue').value + "\");");
evaluateExpr();
}
function setDebugValue(s) {
$("history").value += "\n" + $('taDebug').value;
$("taDebug").value = s;
}
function append() {
sahiSendToServer('/_s_/dyn/Recorder_record?step=' + fixedEncodeURIComponent($("taDebug").value));
}
function addSahi(s) {
var msg = sahiSendToServer("/_s_/dyn/ControllerUI_getSahiScript?code=" + fixedEncodeURIComponent(s));
//alert(decodeURIComponent(msg))
return fixedDecodeURIComponent(msg);
}
function blankIfNull(s) {
return (s == null || s == "null") ? "" : s;
}
function byFile(showFile) {
$("seturl").style.display = showFile?"none":"block";
$("setfile").style.display = showFile?"block":"none";
}
function checkScript(f) {
if (f.filebox && f.filebox.value == "") {
alert("Please choose a script file");
return false;
}
if (f.url && f.url.value == "") {
alert("Please specify the url to script file");
return false;
}
return true;
}
function replay(){
resetStep();
clearLogs();
resetScript();
}
function resetScript(){
sahiSendToServer("/_s_/dyn/Player_resetScript");
}
function onScriptFormSubmit(f) {
if($('seturl').style.display == "none") f = window.document.scriptfileform;
else f = window.document.scripturlform;
if (!checkScript(f)) return false;
if (f.starturl.value == "") f.starturl.value = sahiOpener().location.href;
var url = checkURL(f.starturl.value);
resetStep();
clearLogs();
sendPlaybackSnapshot();
window.setTimeout("reloadPage('" + url + "')", 100);
var starturl = f.starturl.value.replace(/:/g,'%3A');
if($('seturl').style.display == "none"){
var dirPath = f.dir.options[f.dir.selectedIndex].value.replace(/:/g,'%3A');
var file = trim(f.filebox.value);
sahiSendToServer("_s_/dyn/Player_setScriptFile?dir="+dirPath+"&file="+file+"&starturl="+starturl+"&manual=1");
}
else {
var url = f.url.value.replace(/:/g,'%3A');
sahiSendToServer("_s_/dyn/Player_setScriptUrl?url="+url+"&starturl="+starturl+"&manual=1");
}
}
function reloadPage(u) {
if (u == "" || sahiOpener().location.href == u) {
sahiOpener().location.reload();
} else {
sahiOpener().location.href = u;
}
}
function getSel(){
var txt = '';
if (window.getSelection)
{
txt = window.getSelection();
}
else if (window.document.getSelection)
{
txt = window.document.getSelection();
}
else if (window.document.selection)
{
txt = window.document.selection.createRange().text;
}
return txt;
}
function showHistory() {
var histWin = window.open("history.htm", "sahi_history", "height=500px,width=450px");
}
function findPos(obj){
var x = 0, y = 0;
if (obj.offsetParent)
{
while (obj.offsetParent)
{
//var wasStatic = null;
x += obj.offsetLeft;
y += obj.offsetTop;
//if (wasStatic != null) obj.style.position = wasStatic;
obj = obj.offsetParent;
}
}
else if (obj.x){
x = obj.x;
y = obj.y;
}
return [x, y];
};
function resizeTA2(el, minusRight, minusTop, percent) {
var winH, winW;
if (window.innerWidth){
winW = window.innerWidth;
winH = window.innerHeight;
}else if (document.body.offsetWidth) {
winW = document.body.offsetWidth;
winH = document.body.offsetHeight;
}
el.style.width = winW - minusRight + 'px';
el.style.height = (winH - minusTop)*(percent/100) + 'px';
}
function resizeTAs(){
var t = findPos($('taDebug'))[1];
var delta = 40;
if (t > 10){
resizeTA2($('taDebug'), 40, t + delta, 50);
resizeTA2($('taResult'), 40, t + delta, 50);
}
var taY = findPos($('talogs'))[1];
if (taY > 10)
resizeTA2($('talogs'), 40, taY + 30, 100);
}
function showStack() {
var curIx = $("nextStep").value;
var win = window.open("blank.htm");
var cmds = sahi().cmds;
var s = "";
for (var i = 0; i < cmds.length; i++) {
var sel = (i == curIx - 1);
s += "queue[" + i + "] = " + (sel?"<b>":"") + cmds[i] + (sel?"</b>":"") + "<br>";
}
s += "<br>Size: " + cmds.length;
win.document.write(s);
win.document.close();
}
function xsuggest(){
var selectBox = $("suggestDD");
var accessor = $("accessor").value;
if (accessor.indexOf('.') != -1){
var dot = accessor.lastIndexOf('.');
var elStr = accessor.substring(0, dot);
var prop = accessor.substring(dot + 1);
var el = sahi()._eval(addSahi(elStr));
selectBox.options.length = 0;
for (var i in el){
if (i.indexOf(prop) == 0)
selectBox.options[selectBox.options.length] = new Option(i, i);
}
}
}
function appendToAccessor(){
var accessor = $("accessor").value;
if (accessor.indexOf('.') != -1){
var dot = accessor.lastIndexOf('.');
var elStr = accessor.substring(0, dot);
var prop = accessor.substring(dot + 1);
$("accessor").value = elStr + "." + $("suggestDD").value;
}
}
// Suggest List start
var stripSahi = function (s){
return s.replace(/sahi_/g, "_");
}
function getAccessorProps(str){
var elStr = "window";
var options = [];
var dot = -1;
if (str.indexOf('.') != -1){
dot = str.lastIndexOf('.');
elStr = str.substring(0, dot);
}
var prop = str.substring(dot + 1);
var el = null;
try{
el = sahi()._eval(addSahi(elStr));
}catch(e){}
for (var i in el){
i = stripSahi(i);
if (i.indexOf(prop) == 0 && i != prop)
options[options.length] = new Option(i, i);
}
return options;
}
function getScriptFiles(str){
var options = [];
var fileList = null;
fileList = _scriptFileList;
if(!str) str="";
var fileName = "";
if(fileList){
for (var i=0; i<fileList.length; i++){
fileName = fileList[i].replace(_selectedScriptDir, "");
if (fileName.indexOf(str) != -1)
options[options.length] = new Option(fileName, fileName);
}
}
return options;
}
function getAPIs(str){
var options = [];
var el = null;
try{
el = sahi();
}catch(e){}
if (str == null || str == "") str = "_";
if (str.indexOf("_") != 0) str = "_" + str;
var d = "";
var fns = [];
for (var i in el){
d += i + "<br>";
if (i.indexOf(str) == 0 && el[i]){
var val = i
var fnStr = el[i].toString();
if (fnStr.indexOf("function") == -1) continue;
var args = trim(fnStr.substring(fnStr.indexOf("("), fnStr.indexOf("{")));
if (args == "") continue;
val = i + args;
val = stripSahi(val);
fns[fns.length] = val;
}
}
fns = fns.sort();
for (var i=0; i<fns.length; i++){
options[i] = new Option(fns[i], fns[i]);
}
// alert(d);
return options;
}
// Suggest List end
function xhideAllSuggests(e){
if (!e) e = window.event;
if (e.keyCode == Suggest.KEY_ESCAPE){
Suggest.hideAll();
}
}
function getBrowserName(){
if (sahi().isIE()) return "Microsoft Internet Explorer";
else if (sahi().isFF()) return "Mozilla Firefox";
else if (sahi().isSafari()) return "Safari";
else if (sahi().isChrome()) return "Google Chrome";
else return navigator.appName;
}
function getDiagnostics(name){
return sahi().getDiagnostics(name);
}
function displayInfoTab(){
$("userAgent").innerHTML = getDiagnostics("UserAgent");
//$("browserName").innerHTML = getDiagnostics("Browser Name");
$("browserName").innerHTML = getBrowserName();
$("browserVersion").innerHTML = getDiagnostics("Browser Version");
$("xmlHttpRequest").innerHTML = getDiagnostics("Native XMLHttpRequest");
$("javaEnabled").innerHTML = getDiagnostics("Java Enabled");
$("cookieEnabled").innerHTML = getDiagnostics("Cookie Enabled");
$("osName").innerHTML = getDiagnostics("osname");
$("osVersion").innerHTML = getDiagnostics("osversion");
$("osArchitecture").innerHTML = getDiagnostics("osarch");
$("isTasklistAvailable").innerHTML = getDiagnostics("istasklistavailable");
$("javaDirectory").innerHTML = getDiagnostics("javadir");
$("javaVersion").innerHTML = getDiagnostics("javaversion");
$("isKeytoolAvailable").innerHTML = getDiagnostics("iskeytoolavailable");
}
var _version;
function getVersion(){
if (!_version)
_version = sahi().sendToServer("/_s_/dyn/ControllerUI_getSahiVersion");
return _version;
}
function updateVersion(){
var currentVersion = getVersion();
window.open("http://sahi.co.in/w/version-check?v="+currentVersion, "_blank");
}
function sahiHandleException(e){}
function showProperties(){
$("taDebug").value = sahi().list(sahi()._eval(addSahi($('accessor').value)));
}
function listProperties(str){
return sahi()._eval(addSahi(str))
}
| ketan/functional-tests | tools/sahi/htdocs/spr/controller7.js | JavaScript | apache-2.0 | 27,203 |
// This file was procedurally generated from the following sources:
// - src/async-generators/yield-star-getiter-sync-returns-undefined-throw.case
// - src/async-generators/default/async-class-expr-method.template
/*---
description: Non object returned by [Symbol.iterator]() - undefined (Async generator method as a ClassExpression element)
esid: prod-AsyncGeneratorMethod
features: [Symbol.iterator, async-iteration]
flags: [generated, async]
info: |
ClassElement :
MethodDefinition
MethodDefinition :
AsyncGeneratorMethod
Async Generator Function Definitions
AsyncGeneratorMethod :
async [no LineTerminator here] * PropertyName ( UniqueFormalParameters ) { AsyncGeneratorBody }
YieldExpression: yield * AssignmentExpression
1. Let exprRef be the result of evaluating AssignmentExpression.
2. Let value be ? GetValue(exprRef).
3. Let generatorKind be ! GetGeneratorKind().
4. Let iterator be ? GetIterator(value, generatorKind).
...
GetIterator ( obj [ , hint ] )
...
3. If hint is async,
a. Set method to ? GetMethod(obj, @@asyncIterator).
i. Let syncMethod be ? GetMethod(obj, @@iterator).
ii. Let syncIterator be ? Call(syncMethod, obj).
iii. Return ? CreateAsyncFromSyncIterator(syncIterator).
...
CreateAsyncFromSyncIterator(syncIterator)
1. If Type(syncIterator) is not Object, throw a TypeError exception.
...
---*/
var obj = {
[Symbol.iterator]() {
return undefined;
}
};
var callCount = 0;
var C = class { async *gen() {
callCount += 1;
yield* obj;
throw new Test262Error('abrupt completion closes iter');
}}
var gen = C.prototype.gen;
var iter = gen();
iter.next().then(() => {
throw new Test262Error('Promise incorrectly fulfilled.');
}, v => {
assert.sameValue(v.constructor, TypeError, "TypeError");
iter.next().then(({ done, value }) => {
assert.sameValue(done, true, 'the iterator is completed');
assert.sameValue(value, undefined, 'value is undefined');
}).then($DONE, $DONE);
}).catch($DONE);
assert.sameValue(callCount, 1);
| sebastienros/jint | Jint.Tests.Test262/test/language/expressions/class/async-gen-method-yield-star-getiter-sync-returns-undefined-throw.js | JavaScript | bsd-2-clause | 2,119 |
/**
* Copyright 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 react-core
*/
'use strict';
var React;
var ReactDOM;
var ReactDOMFeatureFlags;
var ReactTestUtils;
var TogglingComponent;
var log;
describe('ReactEmptyComponent', () => {
beforeEach(() => {
jest.resetModules();
React = require('react');
ReactDOM = require('react-dom');
ReactDOMFeatureFlags = require('ReactDOMFeatureFlags');
ReactTestUtils = require('ReactTestUtils');
log = jasmine.createSpy();
TogglingComponent = class extends React.Component {
state = {component: this.props.firstComponent};
componentDidMount() {
log(ReactDOM.findDOMNode(this));
this.setState({component: this.props.secondComponent});
}
componentDidUpdate() {
log(ReactDOM.findDOMNode(this));
}
render() {
var Component = this.state.component;
return Component ? <Component /> : null;
}
};
});
it('should not produce child DOM nodes for null and false', () => {
class Component1 extends React.Component {
render() {
return null;
}
}
class Component2 extends React.Component {
render() {
return false;
}
}
var container1 = document.createElement('div');
ReactDOM.render(<Component1 />, container1);
expect(container1.children.length).toBe(0);
var container2 = document.createElement('div');
ReactDOM.render(<Component2 />, container2);
expect(container2.children.length).toBe(0);
});
it('should still throw when rendering to undefined', () => {
class Component extends React.Component {
render() {}
}
expect(function() {
ReactTestUtils.renderIntoDocument(<Component />);
}).toThrowError(
'Component.render(): A valid React element (or null) must be returned. You may ' +
'have returned undefined, an array or some other invalid object.',
);
});
it('should be able to switch between rendering null and a normal tag', () => {
var instance1 = (
<TogglingComponent firstComponent={null} secondComponent={'div'} />
);
var instance2 = (
<TogglingComponent firstComponent={'div'} secondComponent={null} />
);
ReactTestUtils.renderIntoDocument(instance1);
ReactTestUtils.renderIntoDocument(instance2);
expect(log.calls.count()).toBe(4);
expect(log.calls.argsFor(0)[0]).toBe(null);
expect(log.calls.argsFor(1)[0].tagName).toBe('DIV');
expect(log.calls.argsFor(2)[0].tagName).toBe('DIV');
expect(log.calls.argsFor(3)[0]).toBe(null);
});
it('should be able to switch in a list of children', () => {
var instance1 = (
<TogglingComponent firstComponent={null} secondComponent={'div'} />
);
ReactTestUtils.renderIntoDocument(
<div>
{instance1}
{instance1}
{instance1}
</div>,
);
expect(log.calls.count()).toBe(6);
expect(log.calls.argsFor(0)[0]).toBe(null);
expect(log.calls.argsFor(1)[0]).toBe(null);
expect(log.calls.argsFor(2)[0]).toBe(null);
expect(log.calls.argsFor(3)[0].tagName).toBe('DIV');
expect(log.calls.argsFor(4)[0].tagName).toBe('DIV');
expect(log.calls.argsFor(5)[0].tagName).toBe('DIV');
});
it('should distinguish between a script placeholder and an actual script tag', () => {
var instance1 = (
<TogglingComponent firstComponent={null} secondComponent={'script'} />
);
var instance2 = (
<TogglingComponent firstComponent={'script'} secondComponent={null} />
);
expect(function() {
ReactTestUtils.renderIntoDocument(instance1);
}).not.toThrow();
expect(function() {
ReactTestUtils.renderIntoDocument(instance2);
}).not.toThrow();
expect(log.calls.count()).toBe(4);
expect(log.calls.argsFor(0)[0]).toBe(null);
expect(log.calls.argsFor(1)[0].tagName).toBe('SCRIPT');
expect(log.calls.argsFor(2)[0].tagName).toBe('SCRIPT');
expect(log.calls.argsFor(3)[0]).toBe(null);
});
it(
'should have findDOMNode return null when multiple layers of composite ' +
'components render to the same null placeholder',
() => {
class GrandChild extends React.Component {
render() {
return null;
}
}
class Child extends React.Component {
render() {
return <GrandChild />;
}
}
var instance1 = (
<TogglingComponent firstComponent={'div'} secondComponent={Child} />
);
var instance2 = (
<TogglingComponent firstComponent={Child} secondComponent={'div'} />
);
expect(function() {
ReactTestUtils.renderIntoDocument(instance1);
}).not.toThrow();
expect(function() {
ReactTestUtils.renderIntoDocument(instance2);
}).not.toThrow();
expect(log.calls.count()).toBe(4);
expect(log.calls.argsFor(0)[0].tagName).toBe('DIV');
expect(log.calls.argsFor(1)[0]).toBe(null);
expect(log.calls.argsFor(2)[0]).toBe(null);
expect(log.calls.argsFor(3)[0].tagName).toBe('DIV');
},
);
it('works when switching components', () => {
var assertions = 0;
class Inner extends React.Component {
render() {
return <span />;
}
componentDidMount() {
// Make sure the DOM node resolves properly even if we're replacing a
// `null` component
expect(ReactDOM.findDOMNode(this)).not.toBe(null);
assertions++;
}
componentWillUnmount() {
// Even though we're getting replaced by `null`, we haven't been
// replaced yet!
expect(ReactDOM.findDOMNode(this)).not.toBe(null);
assertions++;
}
}
class Wrapper extends React.Component {
render() {
return this.props.showInner ? <Inner /> : null;
}
}
var el = document.createElement('div');
var component;
// Render the <Inner /> component...
component = ReactDOM.render(<Wrapper showInner={true} />, el);
expect(ReactDOM.findDOMNode(component)).not.toBe(null);
// Switch to null...
component = ReactDOM.render(<Wrapper showInner={false} />, el);
expect(ReactDOM.findDOMNode(component)).toBe(null);
// ...then switch back.
component = ReactDOM.render(<Wrapper showInner={true} />, el);
expect(ReactDOM.findDOMNode(component)).not.toBe(null);
expect(assertions).toBe(3);
});
it('can render null at the top level', () => {
var ReactFeatureFlags = require('ReactFeatureFlags');
ReactFeatureFlags.disableNewFiberFeatures = false;
var div = document.createElement('div');
try {
if (ReactDOMFeatureFlags.useFiber) {
ReactDOM.render(null, div);
expect(div.innerHTML).toBe('');
} else {
// Stack does not implement this.
expect(function() {
ReactDOM.render(null, div);
}).toThrowError('ReactDOM.render(): Invalid component element.');
}
} finally {
ReactFeatureFlags.disableNewFiberFeatures = true;
}
});
it('does not break when updating during mount', () => {
class Child extends React.Component {
componentDidMount() {
if (this.props.onMount) {
this.props.onMount();
}
}
render() {
if (!this.props.visible) {
return null;
}
return <div>hello world</div>;
}
}
class Parent extends React.Component {
update = () => {
this.forceUpdate();
};
render() {
return (
<div>
<Child key="1" visible={false} />
<Child key="0" visible={true} onMount={this.update} />
<Child key="2" visible={false} />
</div>
);
}
}
expect(function() {
ReactTestUtils.renderIntoDocument(<Parent />);
}).not.toThrow();
});
it('preserves the dom node during updates', () => {
class Empty extends React.Component {
render() {
return null;
}
}
var container = document.createElement('div');
ReactDOM.render(<Empty />, container);
var noscript1 = container.firstChild;
if (ReactDOMFeatureFlags.useFiber) {
expect(noscript1).toBe(null);
} else {
expect(noscript1.nodeName).toBe('#comment');
}
// This update shouldn't create a DOM node
ReactDOM.render(<Empty />, container);
var noscript2 = container.firstChild;
if (ReactDOMFeatureFlags.useFiber) {
expect(noscript1).toBe(null);
} else {
expect(noscript2.nodeName).toBe('#comment');
}
expect(noscript1).toBe(noscript2);
});
});
| flipactual/react | src/renderers/__tests__/ReactEmptyComponent-test.js | JavaScript | bsd-3-clause | 8,879 |
/* axios v0.19.0-beta.1 | (c) 2018 by Matt Zabriskie */
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["axios"] = factory();
else
root["axios"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(1);
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(2);
var bind = __webpack_require__(3);
var Axios = __webpack_require__(5);
var mergeConfig = __webpack_require__(22);
var defaults = __webpack_require__(11);
/**
* Create an instance of Axios
*
* @param {Object} defaultConfig The default config for the instance
* @return {Axios} A new instance of Axios
*/
function createInstance(defaultConfig) {
var context = new Axios(defaultConfig);
var instance = bind(Axios.prototype.request, context);
// Copy axios.prototype to instance
utils.extend(instance, Axios.prototype, context);
// Copy context to instance
utils.extend(instance, context);
return instance;
}
// Create the default instance to be exported
var axios = createInstance(defaults);
// Expose Axios class to allow class inheritance
axios.Axios = Axios;
// Factory for creating new instances
axios.create = function create(instanceConfig) {
return createInstance(mergeConfig(axios.defaults, instanceConfig));
};
// Expose Cancel & CancelToken
axios.Cancel = __webpack_require__(23);
axios.CancelToken = __webpack_require__(24);
axios.isCancel = __webpack_require__(10);
// Expose all/spread
axios.all = function all(promises) {
return Promise.all(promises);
};
axios.spread = __webpack_require__(25);
module.exports = axios;
// Allow use of default import syntax in TypeScript
module.exports.default = axios;
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var bind = __webpack_require__(3);
var isBuffer = __webpack_require__(4);
/*global toString:true*/
// utils is a library of generic helper functions non-specific to axios
var toString = Object.prototype.toString;
/**
* Determine if a value is an Array
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an Array, otherwise false
*/
function isArray(val) {
return toString.call(val) === '[object Array]';
}
/**
* Determine if a value is an ArrayBuffer
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an ArrayBuffer, otherwise false
*/
function isArrayBuffer(val) {
return toString.call(val) === '[object ArrayBuffer]';
}
/**
* Determine if a value is a FormData
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an FormData, otherwise false
*/
function isFormData(val) {
return (typeof FormData !== 'undefined') && (val instanceof FormData);
}
/**
* Determine if a value is a view on an ArrayBuffer
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
*/
function isArrayBufferView(val) {
var result;
if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
result = ArrayBuffer.isView(val);
} else {
result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer);
}
return result;
}
/**
* Determine if a value is a String
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a String, otherwise false
*/
function isString(val) {
return typeof val === 'string';
}
/**
* Determine if a value is a Number
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Number, otherwise false
*/
function isNumber(val) {
return typeof val === 'number';
}
/**
* Determine if a value is undefined
*
* @param {Object} val The value to test
* @returns {boolean} True if the value is undefined, otherwise false
*/
function isUndefined(val) {
return typeof val === 'undefined';
}
/**
* Determine if a value is an Object
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an Object, otherwise false
*/
function isObject(val) {
return val !== null && typeof val === 'object';
}
/**
* Determine if a value is a Date
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Date, otherwise false
*/
function isDate(val) {
return toString.call(val) === '[object Date]';
}
/**
* Determine if a value is a File
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a File, otherwise false
*/
function isFile(val) {
return toString.call(val) === '[object File]';
}
/**
* Determine if a value is a Blob
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Blob, otherwise false
*/
function isBlob(val) {
return toString.call(val) === '[object Blob]';
}
/**
* Determine if a value is a Function
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Function, otherwise false
*/
function isFunction(val) {
return toString.call(val) === '[object Function]';
}
/**
* Determine if a value is a Stream
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Stream, otherwise false
*/
function isStream(val) {
return isObject(val) && isFunction(val.pipe);
}
/**
* Determine if a value is a URLSearchParams object
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a URLSearchParams object, otherwise false
*/
function isURLSearchParams(val) {
return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams;
}
/**
* Trim excess whitespace off the beginning and end of a string
*
* @param {String} str The String to trim
* @returns {String} The String freed of excess whitespace
*/
function trim(str) {
return str.replace(/^\s*/, '').replace(/\s*$/, '');
}
/**
* Determine if we're running in a standard browser environment
*
* This allows axios to run in a web worker, and react-native.
* Both environments support XMLHttpRequest, but not fully standard globals.
*
* web workers:
* typeof window -> undefined
* typeof document -> undefined
*
* react-native:
* navigator.product -> 'ReactNative'
* nativescript
* navigator.product -> 'NativeScript' or 'NS'
*/
function isStandardBrowserEnv() {
if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||
navigator.product === 'NativeScript' ||
navigator.product === 'NS')) {
return false;
}
return (
typeof window !== 'undefined' &&
typeof document !== 'undefined'
);
}
/**
* Iterate over an Array or an Object invoking a function for each item.
*
* If `obj` is an Array callback will be called passing
* the value, index, and complete array for each item.
*
* If 'obj' is an Object callback will be called passing
* the value, key, and complete object for each property.
*
* @param {Object|Array} obj The object to iterate
* @param {Function} fn The callback to invoke for each item
*/
function forEach(obj, fn) {
// Don't bother if no value provided
if (obj === null || typeof obj === 'undefined') {
return;
}
// Force an array if not already something iterable
if (typeof obj !== 'object') {
/*eslint no-param-reassign:0*/
obj = [obj];
}
if (isArray(obj)) {
// Iterate over array values
for (var i = 0, l = obj.length; i < l; i++) {
fn.call(null, obj[i], i, obj);
}
} else {
// Iterate over object keys
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
fn.call(null, obj[key], key, obj);
}
}
}
}
/**
* Accepts varargs expecting each argument to be an object, then
* immutably merges the properties of each object and returns result.
*
* When multiple objects contain the same key the later object in
* the arguments list will take precedence.
*
* Example:
*
* ```js
* var result = merge({foo: 123}, {foo: 456});
* console.log(result.foo); // outputs 456
* ```
*
* @param {Object} obj1 Object to merge
* @returns {Object} Result of all merge properties
*/
function merge(/* obj1, obj2, obj3, ... */) {
var result = {};
function assignValue(val, key) {
if (typeof result[key] === 'object' && typeof val === 'object') {
result[key] = merge(result[key], val);
} else {
result[key] = val;
}
}
for (var i = 0, l = arguments.length; i < l; i++) {
forEach(arguments[i], assignValue);
}
return result;
}
/**
* Function equal to merge with the difference being that no reference
* to original objects is kept.
*
* @see merge
* @param {Object} obj1 Object to merge
* @returns {Object} Result of all merge properties
*/
function deepMerge(/* obj1, obj2, obj3, ... */) {
var result = {};
function assignValue(val, key) {
if (typeof result[key] === 'object' && typeof val === 'object') {
result[key] = deepMerge(result[key], val);
} else if (typeof val === 'object') {
result[key] = deepMerge({}, val);
} else {
result[key] = val;
}
}
for (var i = 0, l = arguments.length; i < l; i++) {
forEach(arguments[i], assignValue);
}
return result;
}
/**
* Extends object a by mutably adding to it the properties of object b.
*
* @param {Object} a The object to be extended
* @param {Object} b The object to copy properties from
* @param {Object} thisArg The object to bind function to
* @return {Object} The resulting value of object a
*/
function extend(a, b, thisArg) {
forEach(b, function assignValue(val, key) {
if (thisArg && typeof val === 'function') {
a[key] = bind(val, thisArg);
} else {
a[key] = val;
}
});
return a;
}
module.exports = {
isArray: isArray,
isArrayBuffer: isArrayBuffer,
isBuffer: isBuffer,
isFormData: isFormData,
isArrayBufferView: isArrayBufferView,
isString: isString,
isNumber: isNumber,
isObject: isObject,
isUndefined: isUndefined,
isDate: isDate,
isFile: isFile,
isBlob: isBlob,
isFunction: isFunction,
isStream: isStream,
isURLSearchParams: isURLSearchParams,
isStandardBrowserEnv: isStandardBrowserEnv,
forEach: forEach,
merge: merge,
deepMerge: deepMerge,
extend: extend,
trim: trim
};
/***/ }),
/* 3 */
/***/ (function(module, exports) {
'use strict';
module.exports = function bind(fn, thisArg) {
return function wrap() {
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
return fn.apply(thisArg, args);
};
};
/***/ }),
/* 4 */
/***/ (function(module, exports) {
/*!
* Determine if an object is a Buffer
*
* @author Feross Aboukhadijeh <https://feross.org>
* @license MIT
*/
module.exports = function isBuffer (obj) {
return obj != null && obj.constructor != null &&
typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
}
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(2);
var buildURL = __webpack_require__(6);
var InterceptorManager = __webpack_require__(7);
var dispatchRequest = __webpack_require__(8);
var mergeConfig = __webpack_require__(22);
/**
* Create a new instance of Axios
*
* @param {Object} instanceConfig The default config for the instance
*/
function Axios(instanceConfig) {
this.defaults = instanceConfig;
this.interceptors = {
request: new InterceptorManager(),
response: new InterceptorManager()
};
}
/**
* Dispatch a request
*
* @param {Object} config The config specific for this request (merged with this.defaults)
*/
Axios.prototype.request = function request(config) {
/*eslint no-param-reassign:0*/
// Allow for axios('example/url'[, config]) a la fetch API
if (typeof config === 'string') {
config = arguments[1] || {};
config.url = arguments[0];
} else {
config = config || {};
}
config = mergeConfig(this.defaults, config);
config.method = config.method ? config.method.toLowerCase() : 'get';
// Hook up interceptors middleware
var chain = [dispatchRequest, undefined];
var promise = Promise.resolve(config);
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
chain.unshift(interceptor.fulfilled, interceptor.rejected);
});
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
chain.push(interceptor.fulfilled, interceptor.rejected);
});
while (chain.length) {
promise = promise.then(chain.shift(), chain.shift());
}
return promise;
};
Axios.prototype.getUri = function getUri(config) {
config = mergeConfig(this.defaults, config);
return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, '');
};
// Provide aliases for supported request methods
utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
/*eslint func-names:0*/
Axios.prototype[method] = function(url, config) {
return this.request(utils.merge(config || {}, {
method: method,
url: url
}));
};
});
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
/*eslint func-names:0*/
Axios.prototype[method] = function(url, data, config) {
return this.request(utils.merge(config || {}, {
method: method,
url: url,
data: data
}));
};
});
module.exports = Axios;
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(2);
function encode(val) {
return encodeURIComponent(val).
replace(/%40/gi, '@').
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace(/%20/g, '+').
replace(/%5B/gi, '[').
replace(/%5D/gi, ']');
}
/**
* Build a URL by appending params to the end
*
* @param {string} url The base of the url (e.g., http://www.google.com)
* @param {object} [params] The params to be appended
* @returns {string} The formatted url
*/
module.exports = function buildURL(url, params, paramsSerializer) {
/*eslint no-param-reassign:0*/
if (!params) {
return url;
}
var serializedParams;
if (paramsSerializer) {
serializedParams = paramsSerializer(params);
} else if (utils.isURLSearchParams(params)) {
serializedParams = params.toString();
} else {
var parts = [];
utils.forEach(params, function serialize(val, key) {
if (val === null || typeof val === 'undefined') {
return;
}
if (utils.isArray(val)) {
key = key + '[]';
} else {
val = [val];
}
utils.forEach(val, function parseValue(v) {
if (utils.isDate(v)) {
v = v.toISOString();
} else if (utils.isObject(v)) {
v = JSON.stringify(v);
}
parts.push(encode(key) + '=' + encode(v));
});
});
serializedParams = parts.join('&');
}
if (serializedParams) {
url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
}
return url;
};
/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(2);
function InterceptorManager() {
this.handlers = [];
}
/**
* Add a new interceptor to the stack
*
* @param {Function} fulfilled The function to handle `then` for a `Promise`
* @param {Function} rejected The function to handle `reject` for a `Promise`
*
* @return {Number} An ID used to remove interceptor later
*/
InterceptorManager.prototype.use = function use(fulfilled, rejected) {
this.handlers.push({
fulfilled: fulfilled,
rejected: rejected
});
return this.handlers.length - 1;
};
/**
* Remove an interceptor from the stack
*
* @param {Number} id The ID that was returned by `use`
*/
InterceptorManager.prototype.eject = function eject(id) {
if (this.handlers[id]) {
this.handlers[id] = null;
}
};
/**
* Iterate over all the registered interceptors
*
* This method is particularly useful for skipping over any
* interceptors that may have become `null` calling `eject`.
*
* @param {Function} fn The function to call for each interceptor
*/
InterceptorManager.prototype.forEach = function forEach(fn) {
utils.forEach(this.handlers, function forEachHandler(h) {
if (h !== null) {
fn(h);
}
});
};
module.exports = InterceptorManager;
/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(2);
var transformData = __webpack_require__(9);
var isCancel = __webpack_require__(10);
var defaults = __webpack_require__(11);
var isAbsoluteURL = __webpack_require__(20);
var combineURLs = __webpack_require__(21);
/**
* Throws a `Cancel` if cancellation has been requested.
*/
function throwIfCancellationRequested(config) {
if (config.cancelToken) {
config.cancelToken.throwIfRequested();
}
}
/**
* Dispatch a request to the server using the configured adapter.
*
* @param {object} config The config that is to be used for the request
* @returns {Promise} The Promise to be fulfilled
*/
module.exports = function dispatchRequest(config) {
throwIfCancellationRequested(config);
// Support baseURL config
if (config.baseURL && !isAbsoluteURL(config.url)) {
config.url = combineURLs(config.baseURL, config.url);
}
// Ensure headers exist
config.headers = config.headers || {};
// Transform request data
config.data = transformData(
config.data,
config.headers,
config.transformRequest
);
// Flatten headers
config.headers = utils.merge(
config.headers.common || {},
config.headers[config.method] || {},
config.headers || {}
);
utils.forEach(
['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
function cleanHeaderConfig(method) {
delete config.headers[method];
}
);
var adapter = config.adapter || defaults.adapter;
return adapter(config).then(function onAdapterResolution(response) {
throwIfCancellationRequested(config);
// Transform response data
response.data = transformData(
response.data,
response.headers,
config.transformResponse
);
return response;
}, function onAdapterRejection(reason) {
if (!isCancel(reason)) {
throwIfCancellationRequested(config);
// Transform response data
if (reason && reason.response) {
reason.response.data = transformData(
reason.response.data,
reason.response.headers,
config.transformResponse
);
}
}
return Promise.reject(reason);
});
};
/***/ }),
/* 9 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(2);
/**
* Transform the data for a request or a response
*
* @param {Object|String} data The data to be transformed
* @param {Array} headers The headers for the request or response
* @param {Array|Function} fns A single function or Array of functions
* @returns {*} The resulting transformed data
*/
module.exports = function transformData(data, headers, fns) {
/*eslint no-param-reassign:0*/
utils.forEach(fns, function transform(fn) {
data = fn(data, headers);
});
return data;
};
/***/ }),
/* 10 */
/***/ (function(module, exports) {
'use strict';
module.exports = function isCancel(value) {
return !!(value && value.__CANCEL__);
};
/***/ }),
/* 11 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(2);
var normalizeHeaderName = __webpack_require__(12);
var DEFAULT_CONTENT_TYPE = {
'Content-Type': 'application/x-www-form-urlencoded'
};
function setContentTypeIfUnset(headers, value) {
if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
headers['Content-Type'] = value;
}
}
function getDefaultAdapter() {
var adapter;
// Only Node.JS has a process variable that is of [[Class]] process
if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
// For node use HTTP adapter
adapter = __webpack_require__(13);
} else if (typeof XMLHttpRequest !== 'undefined') {
// For browsers use XHR adapter
adapter = __webpack_require__(13);
}
return adapter;
}
var defaults = {
adapter: getDefaultAdapter(),
transformRequest: [function transformRequest(data, headers) {
normalizeHeaderName(headers, 'Accept');
normalizeHeaderName(headers, 'Content-Type');
if (utils.isFormData(data) ||
utils.isArrayBuffer(data) ||
utils.isBuffer(data) ||
utils.isStream(data) ||
utils.isFile(data) ||
utils.isBlob(data)
) {
return data;
}
if (utils.isArrayBufferView(data)) {
return data.buffer;
}
if (utils.isURLSearchParams(data)) {
setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
return data.toString();
}
if (utils.isObject(data)) {
setContentTypeIfUnset(headers, 'application/json;charset=utf-8');
return JSON.stringify(data);
}
return data;
}],
transformResponse: [function transformResponse(data) {
/*eslint no-param-reassign:0*/
if (typeof data === 'string') {
try {
data = JSON.parse(data);
} catch (e) { /* Ignore */ }
}
return data;
}],
/**
* A timeout in milliseconds to abort a request. If set to 0 (default) a
* timeout is not created.
*/
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
validateStatus: function validateStatus(status) {
return status >= 200 && status < 300;
}
};
defaults.headers = {
common: {
'Accept': 'application/json, text/plain, */*'
}
};
utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {
defaults.headers[method] = {};
});
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
});
module.exports = defaults;
/***/ }),
/* 12 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(2);
module.exports = function normalizeHeaderName(headers, normalizedName) {
utils.forEach(headers, function processHeader(value, name) {
if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
headers[normalizedName] = value;
delete headers[name];
}
});
};
/***/ }),
/* 13 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(2);
var settle = __webpack_require__(14);
var buildURL = __webpack_require__(6);
var parseHeaders = __webpack_require__(17);
var isURLSameOrigin = __webpack_require__(18);
var createError = __webpack_require__(15);
module.exports = function xhrAdapter(config) {
return new Promise(function dispatchXhrRequest(resolve, reject) {
var requestData = config.data;
var requestHeaders = config.headers;
if (utils.isFormData(requestData)) {
delete requestHeaders['Content-Type']; // Let the browser set it
}
var request = new XMLHttpRequest();
// HTTP basic authentication
if (config.auth) {
var username = config.auth.username || '';
var password = config.auth.password || '';
requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
}
request.open(config.method.toUpperCase(), buildURL(config.url, config.params, config.paramsSerializer), true);
// Set the request timeout in MS
request.timeout = config.timeout;
// Listen for ready state
request.onreadystatechange = function handleLoad() {
if (!request || request.readyState !== 4) {
return;
}
// The request errored out and we didn't get a response, this will be
// handled by onerror instead
// With one exception: request that using file: protocol, most browsers
// will return status as 0 even though it's a successful request
if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
return;
}
// Prepare the response
var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response;
var response = {
data: responseData,
status: request.status,
statusText: request.statusText,
headers: responseHeaders,
config: config,
request: request
};
settle(resolve, reject, response);
// Clean up request
request = null;
};
// Handle browser request cancellation (as opposed to a manual cancellation)
request.onabort = function handleAbort() {
if (!request) {
return;
}
reject(createError('Request aborted', config, 'ECONNABORTED', request));
// Clean up request
request = null;
};
// Handle low level network errors
request.onerror = function handleError() {
// Real errors are hidden from us by the browser
// onerror should only fire if it's a network error
reject(createError('Network Error', config, null, request));
// Clean up request
request = null;
};
// Handle timeout
request.ontimeout = function handleTimeout() {
reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED',
request));
// Clean up request
request = null;
};
// Add xsrf header
// This is only done if running in a standard browser environment.
// Specifically not if we're in a web worker, or react-native.
if (utils.isStandardBrowserEnv()) {
var cookies = __webpack_require__(19);
// Add xsrf header
var xsrfValue = (config.withCredentials || isURLSameOrigin(config.url)) && config.xsrfCookieName ?
cookies.read(config.xsrfCookieName) :
undefined;
if (xsrfValue) {
requestHeaders[config.xsrfHeaderName] = xsrfValue;
}
}
// Add headers to the request
if ('setRequestHeader' in request) {
utils.forEach(requestHeaders, function setRequestHeader(val, key) {
if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
// Remove Content-Type if data is undefined
delete requestHeaders[key];
} else {
// Otherwise add header to the request
request.setRequestHeader(key, val);
}
});
}
// Add withCredentials to request if needed
if (config.withCredentials) {
request.withCredentials = true;
}
// Add responseType to request if needed
if (config.responseType) {
try {
request.responseType = config.responseType;
} catch (e) {
// Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2.
// But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function.
if (config.responseType !== 'json') {
throw e;
}
}
}
// Handle progress if needed
if (typeof config.onDownloadProgress === 'function') {
request.addEventListener('progress', config.onDownloadProgress);
}
// Not all browsers support upload events
if (typeof config.onUploadProgress === 'function' && request.upload) {
request.upload.addEventListener('progress', config.onUploadProgress);
}
if (config.cancelToken) {
// Handle cancellation
config.cancelToken.promise.then(function onCanceled(cancel) {
if (!request) {
return;
}
request.abort();
reject(cancel);
// Clean up request
request = null;
});
}
if (requestData === undefined) {
requestData = null;
}
// Send the request
request.send(requestData);
});
};
/***/ }),
/* 14 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var createError = __webpack_require__(15);
/**
* Resolve or reject a Promise based on response status.
*
* @param {Function} resolve A function that resolves the promise.
* @param {Function} reject A function that rejects the promise.
* @param {object} response The response.
*/
module.exports = function settle(resolve, reject, response) {
var validateStatus = response.config.validateStatus;
if (!validateStatus || validateStatus(response.status)) {
resolve(response);
} else {
reject(createError(
'Request failed with status code ' + response.status,
response.config,
null,
response.request,
response
));
}
};
/***/ }),
/* 15 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var enhanceError = __webpack_require__(16);
/**
* Create an Error with the specified message, config, error code, request and response.
*
* @param {string} message The error message.
* @param {Object} config The config.
* @param {string} [code] The error code (for example, 'ECONNABORTED').
* @param {Object} [request] The request.
* @param {Object} [response] The response.
* @returns {Error} The created error.
*/
module.exports = function createError(message, config, code, request, response) {
var error = new Error(message);
return enhanceError(error, config, code, request, response);
};
/***/ }),
/* 16 */
/***/ (function(module, exports) {
'use strict';
/**
* Update an Error with the specified config, error code, and response.
*
* @param {Error} error The error to update.
* @param {Object} config The config.
* @param {string} [code] The error code (for example, 'ECONNABORTED').
* @param {Object} [request] The request.
* @param {Object} [response] The response.
* @returns {Error} The error.
*/
module.exports = function enhanceError(error, config, code, request, response) {
error.config = config;
if (code) {
error.code = code;
}
error.request = request;
error.response = response;
error.toJSON = function() {
return {
// Standard
message: this.message,
name: this.name,
// Microsoft
description: this.description,
number: this.number,
// Mozilla
fileName: this.fileName,
lineNumber: this.lineNumber,
columnNumber: this.columnNumber,
stack: this.stack,
// Axios
config: this.config,
code: this.code
};
};
return error;
};
/***/ }),
/* 17 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(2);
// Headers whose duplicates are ignored by node
// c.f. https://nodejs.org/api/http.html#http_message_headers
var ignoreDuplicateOf = [
'age', 'authorization', 'content-length', 'content-type', 'etag',
'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
'last-modified', 'location', 'max-forwards', 'proxy-authorization',
'referer', 'retry-after', 'user-agent'
];
/**
* Parse headers into an object
*
* ```
* Date: Wed, 27 Aug 2014 08:58:49 GMT
* Content-Type: application/json
* Connection: keep-alive
* Transfer-Encoding: chunked
* ```
*
* @param {String} headers Headers needing to be parsed
* @returns {Object} Headers parsed into an object
*/
module.exports = function parseHeaders(headers) {
var parsed = {};
var key;
var val;
var i;
if (!headers) { return parsed; }
utils.forEach(headers.split('\n'), function parser(line) {
i = line.indexOf(':');
key = utils.trim(line.substr(0, i)).toLowerCase();
val = utils.trim(line.substr(i + 1));
if (key) {
if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {
return;
}
if (key === 'set-cookie') {
parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);
} else {
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
}
}
});
return parsed;
};
/***/ }),
/* 18 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(2);
module.exports = (
utils.isStandardBrowserEnv() ?
// Standard browser envs have full support of the APIs needed to test
// whether the request URL is of the same origin as current location.
(function standardBrowserEnv() {
var msie = /(msie|trident)/i.test(navigator.userAgent);
var urlParsingNode = document.createElement('a');
var originURL;
/**
* Parse a URL to discover it's components
*
* @param {String} url The URL to be parsed
* @returns {Object}
*/
function resolveURL(url) {
var href = url;
if (msie) {
// IE needs attribute set twice to normalize properties
urlParsingNode.setAttribute('href', href);
href = urlParsingNode.href;
}
urlParsingNode.setAttribute('href', href);
// urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
return {
href: urlParsingNode.href,
protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
host: urlParsingNode.host,
search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
hostname: urlParsingNode.hostname,
port: urlParsingNode.port,
pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
urlParsingNode.pathname :
'/' + urlParsingNode.pathname
};
}
originURL = resolveURL(window.location.href);
/**
* Determine if a URL shares the same origin as the current location
*
* @param {String} requestURL The URL to test
* @returns {boolean} True if URL shares the same origin, otherwise false
*/
return function isURLSameOrigin(requestURL) {
var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
return (parsed.protocol === originURL.protocol &&
parsed.host === originURL.host);
};
})() :
// Non standard browser envs (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return function isURLSameOrigin() {
return true;
};
})()
);
/***/ }),
/* 19 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(2);
module.exports = (
utils.isStandardBrowserEnv() ?
// Standard browser envs support document.cookie
(function standardBrowserEnv() {
return {
write: function write(name, value, expires, path, domain, secure) {
var cookie = [];
cookie.push(name + '=' + encodeURIComponent(value));
if (utils.isNumber(expires)) {
cookie.push('expires=' + new Date(expires).toGMTString());
}
if (utils.isString(path)) {
cookie.push('path=' + path);
}
if (utils.isString(domain)) {
cookie.push('domain=' + domain);
}
if (secure === true) {
cookie.push('secure');
}
document.cookie = cookie.join('; ');
},
read: function read(name) {
var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
return (match ? decodeURIComponent(match[3]) : null);
},
remove: function remove(name) {
this.write(name, '', Date.now() - 86400000);
}
};
})() :
// Non standard browser env (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return {
write: function write() {},
read: function read() { return null; },
remove: function remove() {}
};
})()
);
/***/ }),
/* 20 */
/***/ (function(module, exports) {
'use strict';
/**
* Determines whether the specified URL is absolute
*
* @param {string} url The URL to test
* @returns {boolean} True if the specified URL is absolute, otherwise false
*/
module.exports = function isAbsoluteURL(url) {
// A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
// RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
// by any combination of letters, digits, plus, period, or hyphen.
return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
};
/***/ }),
/* 21 */
/***/ (function(module, exports) {
'use strict';
/**
* Creates a new URL by combining the specified URLs
*
* @param {string} baseURL The base URL
* @param {string} relativeURL The relative URL
* @returns {string} The combined URL
*/
module.exports = function combineURLs(baseURL, relativeURL) {
return relativeURL
? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
: baseURL;
};
/***/ }),
/* 22 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(2);
/**
* Config-specific merge-function which creates a new config-object
* by merging two configuration objects together.
*
* @param {Object} config1
* @param {Object} config2
* @returns {Object} New object resulting from merging config2 to config1
*/
module.exports = function mergeConfig(config1, config2) {
// eslint-disable-next-line no-param-reassign
config2 = config2 || {};
var config = {};
utils.forEach(['url', 'method', 'params', 'data'], function valueFromConfig2(prop) {
if (typeof config2[prop] !== 'undefined') {
config[prop] = config2[prop];
}
});
utils.forEach(['headers', 'auth', 'proxy'], function mergeDeepProperties(prop) {
if (utils.isObject(config2[prop])) {
config[prop] = utils.deepMerge(config1[prop], config2[prop]);
} else if (typeof config2[prop] !== 'undefined') {
config[prop] = config2[prop];
} else if (utils.isObject(config1[prop])) {
config[prop] = utils.deepMerge(config1[prop]);
} else if (typeof config1[prop] !== 'undefined') {
config[prop] = config1[prop];
}
});
utils.forEach([
'baseURL', 'transformRequest', 'transformResponse', 'paramsSerializer',
'timeout', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName',
'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', 'maxContentLength',
'validateStatus', 'maxRedirects', 'httpAgent', 'httpsAgent', 'cancelToken',
'socketPath'
], function defaultToConfig2(prop) {
if (typeof config2[prop] !== 'undefined') {
config[prop] = config2[prop];
} else if (typeof config1[prop] !== 'undefined') {
config[prop] = config1[prop];
}
});
return config;
};
/***/ }),
/* 23 */
/***/ (function(module, exports) {
'use strict';
/**
* A `Cancel` is an object that is thrown when an operation is canceled.
*
* @class
* @param {string=} message The message.
*/
function Cancel(message) {
this.message = message;
}
Cancel.prototype.toString = function toString() {
return 'Cancel' + (this.message ? ': ' + this.message : '');
};
Cancel.prototype.__CANCEL__ = true;
module.exports = Cancel;
/***/ }),
/* 24 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var Cancel = __webpack_require__(23);
/**
* A `CancelToken` is an object that can be used to request cancellation of an operation.
*
* @class
* @param {Function} executor The executor function.
*/
function CancelToken(executor) {
if (typeof executor !== 'function') {
throw new TypeError('executor must be a function.');
}
var resolvePromise;
this.promise = new Promise(function promiseExecutor(resolve) {
resolvePromise = resolve;
});
var token = this;
executor(function cancel(message) {
if (token.reason) {
// Cancellation has already been requested
return;
}
token.reason = new Cancel(message);
resolvePromise(token.reason);
});
}
/**
* Throws a `Cancel` if cancellation has been requested.
*/
CancelToken.prototype.throwIfRequested = function throwIfRequested() {
if (this.reason) {
throw this.reason;
}
};
/**
* Returns an object that contains a new `CancelToken` and a function that, when called,
* cancels the `CancelToken`.
*/
CancelToken.source = function source() {
var cancel;
var token = new CancelToken(function executor(c) {
cancel = c;
});
return {
token: token,
cancel: cancel
};
};
module.exports = CancelToken;
/***/ }),
/* 25 */
/***/ (function(module, exports) {
'use strict';
/**
* Syntactic sugar for invoking a function and expanding an array for arguments.
*
* Common use case would be to use `Function.prototype.apply`.
*
* ```js
* function f(x, y, z) {}
* var args = [1, 2, 3];
* f.apply(null, args);
* ```
*
* With `spread` this example can be re-written.
*
* ```js
* spread(function(x, y, z) {})([1, 2, 3]);
* ```
*
* @param {Function} callback
* @returns {Function}
*/
module.exports = function spread(callback) {
return function wrap(arr) {
return callback.apply(null, arr);
};
};
/***/ })
/******/ ])
});
;
//# sourceMappingURL=axios.map | jonobr1/cdnjs | ajax/libs/axios/0.19.0-beta.1/axios.js | JavaScript | mit | 44,448 |