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 |
|---|---|---|---|---|---|
/**
* Copyright (C) 2014 TopCoder Inc., All Rights Reserved.
* @version 1.1
* @author Sky_, TCSASSEMBLER
* changes in 1.1:
* 1. change handleError. Return sql error with unique constrains as Bad Request.
* 2. close db when request ends.
* 3. don't create transactions for GET requests
*/
"use strict";
var _ = require('underscore');
var async = require('async');
var winston = require('winston');
var BadRequestError = require("../errors/BadRequestError");
var IllegalArgumentError = require("../errors/IllegalArgumentError");
var NotFoundError = require("../errors/NotFoundError");
var initDb = require("../db");
/**
* Api codes
*/
var apiCodes = {
OK: { name: 'OK', value: 200, description: 'Success' },
notModified: { name: 'Not Modified', value: 304, description: 'There was no new data to return.' },
badRequest: { name: 'Bad Request', value: 400, description: 'The request was invalid. An accompanying message will explain why.' },
unauthorized: { name: 'Unauthorized', value: 401, description: 'Authentication credentials were missing or incorrect.' },
forbidden: { name: 'Forbidden', value: 403, description: 'The request is understood, but it has been refused or access is not allowed.' },
notFound: { name: 'Not Found', value: 404, description: 'The URI requested is invalid or the requested resource does not exist.' },
serverError: { name: 'Internal Server Error', value: 500, description: 'Something is broken. Please contact support.' }
};
/**
* Handle error and return as JSON to the response.
* @param {Error} error the error to handle
* @param {Object} res the express response object
*/
function handleError(error, res) {
var errdetail, baseError = apiCodes.serverError;
if (error.isValidationError ||
error instanceof IllegalArgumentError ||
error instanceof BadRequestError) {
baseError = apiCodes.badRequest;
} else if (error instanceof NotFoundError) {
baseError = apiCodes.notFound;
} else if (error.code === 'ER_DUP_ENTRY') {
baseError = apiCodes.badRequest;
if (error.message.indexOf("UC_c_sort") !== -1) {
error.message += ". Pair of the columns 'sort' and 'tab' must be unique.";
}
}
errdetail = _.clone(baseError);
errdetail.details = error.message;
res.statusCode = baseError.value;
res.json(errdetail);
}
/**
* This function create a delegate for the express action.
* Input and output logging is performed.
* Errors are handled also and proper http status code is set.
* Wrapped method must always call the callback function, first param is error, second param is object to return.
* @param {String} signature the signature of the method caller
* @param {Function} fn the express method to call. It must have signature (req, res, callback) or (req, callback). Res
* parameter is optional, because he is usually not used.
* @param {Boolean} customHandled true if the express action is handling the response.
* This is useful for downloading files. Wrapper will render only the error response.
* @returns {Function} the wrapped function
*/
function wrapExpress(signature, fn, customHandled) {
if (!_.isString(signature)) {
throw new Error("signature should be a string");
}
if (!_.isFunction(fn)) {
throw new Error("fn should be a function");
}
return function (req, res, next) {
var paramsToLog, db, transaction, apiResult, canRollback = false, useGlobalDB = req.method === 'GET';
paramsToLog = {
body: req.body,
params: req.params,
query : req.query,
url: req.url
};
winston.info("ENTER %s %j", signature, paramsToLog, {});
var disposeDB = function () {
if (useGlobalDB) {
return;
}
//close db connection
//we need this timeout because there is a bug for parallel requests
setTimeout(function () {
db.driver.close();
}, 1000);
};
async.waterfall([
function (cb) {
if (useGlobalDB) {
db = global.db;
cb();
} else {
async.waterfall([
function (cb) {
initDb(cb, false);
}, function (result, cb) {
db = result;
db.transaction(cb);
}, function (t, cb) {
transaction = t;
canRollback = true;
cb();
}
], cb);
}
}, function (cb) {
if (fn.length === 3) {
fn(req, db, cb);
} else {
fn(req, res, db, cb);
}
}, function (result, cb) {
apiResult = result;
if (useGlobalDB) {
cb();
} else {
transaction.commit(cb);
}
}, function (cb) {
if (process.env.NO_LOG_RESPONSE) {
paramsToLog.response = "<disabled>";
} else {
paramsToLog.response = apiResult;
}
winston.info("EXIT %s %j", signature, paramsToLog, {});
if (!customHandled) {
res.json(apiResult);
}
disposeDB();
}
], function (error) {
if (canRollback && transaction) {
transaction.rollback(function () {
});
}
disposeDB();
winston.error("EXIT %s %j\n", signature, paramsToLog, error.stack);
handleError(error, res);
});
};
}
module.exports = {
wrapExpress: wrapExpress,
apiCodes: apiCodes,
handleError: handleError
}; | elkhawajah/NTL-Solution-Mechanism-Guide | helpers/logging.js | JavaScript | apache-2.0 | 6,051 |
'use strict';
var mongoose = require('mongoose');
var mongoose_uuid = require('mongoose-uuid');
var mongoose_relationship = require('mongoose-relationship');
function tierModel () {
var tierSchema = mongoose.Schema({
environment: { type: String, ref: 'Environment', childPath: 'tiers', index: true },
platform: { type: String, ref: 'Platform', childPath: 'tiers', index: true },
machines: [{ type: String, ref: 'Machine' }],
cfpersonas: { type: String, ref: 'CfPersonas', index: true },
name: { type: String },
system_name: { type: String },
user_script: { type: String },
base_image: { type: String },
base_package: { type: String },
home_network: { type: String },
networks: [{ type: String }]
}, { _id: false, versionKey: false });
tierSchema.plugin(mongoose_uuid.plugin, 'Tier');
tierSchema.plugin(mongoose_relationship, {
relationshipPathName: [ 'environment', 'platform' ]
});
tierSchema.pre('save', function (next) {
var tier = this;
if (tier.system_name && tier.system_name.length > 0) {
next();
return;
}
tier.system_name = tier.name.toLowerCase().replace(/\s+/g, '_');
next();
});
return mongoose.model('Tier', tierSchema);
}
module.exports = new tierModel();
| converged/imperator | models/tier.js | JavaScript | apache-2.0 | 1,276 |
// Copyright 2012, 2013 Patrick Wang <kk1fff@patrickz.net>
//
// 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.
var EventEmitter = require('events').EventEmitter,
fs = require('fs'),
_ = require('underscore'),
fsQueue = require('./fs-sync.js'),
config = require('./config.js').getConfig(),
cachedTemplate = {},
cachedPageParts = {},
pagePartWaitingQueue = {};
var STATE_ERROR = 0;
var STATE_AVAILABLE = 1;
var STATE_GETTING_TEMPLATE_RAW_FILE = 2;
var STATE_PREPROC_TEMPLATE = 3;
var STATE_BUILDING_PAGE = 4;
var RESULT_OK = 0;
var RESULT_ERROR = 1;
var RESULT_PROCESS_PAGE = 2;
var RESULT_GOT_CACHED_TEMPLATE = 3;
function getPageProperties() {
return {
site: {
title: config.siteTitle,
css: [ config.httpPrefix + "/css/main.css" ],
js: [ config.httpPrefix + "/js/album.js" ],
googleanalystics: config.googleanalystics,
main: config.httpPrefix + "/",
disqus: config.disqus,
facebookapp: config.facebookapp
}
};
}
// Load template part from file.
function getPagePart(name, loadedList) {
var cached = cachedPageParts[name];
if (cached) return cached;
try {
cached = fs.readFileSync(config.pagePartDir + "/" + name, 'utf8');
// Process inclusion in this page part.
cached = formatPagePart(cached, loadedList);
cachedPageParts[name] = cached;
} catch (err) {
console.log("unable to load: " + name);
return "";
}
return cached;
}
function formatPagePart(pagePartText, loadedList) {
var replaced;
loadedList = loadedList || [];
do {
// Reset replaced. If the replacer is called, it will be set true,
// and we will have the next round.
replaced = false;
pagePartText = pagePartText.replace(/<%![\w\. _-]+%>/, function(str) {
var matching = str.match(/<%!([\w\. _-]+)%>/),
pagePartName = matching[1].trim(),
pagePart;
replaced = true; // Tell outer that we should check again.
if (loadedList.indexOf(pagePartName) >= 0) {
// Loop
console.warn("Inclusion loop: " + pagePartName);
return "";
}
loadedList.push(pagePartName);
pagePart = getPagePart(pagePartName, loadedList);
loadedList.pop();
return pagePart;
});
} while(replaced);
return pagePartText;
}
function PageGenerator(templateName, data) {
this.templateName = templateName;
this.pageData = _.extend(data, getPageProperties());
this.state = STATE_AVAILABLE;
}
PageGenerator.prototype = {
generatePage: function() {
this.emitter = new EventEmitter();
this.onOperationDone(RESULT_PROCESS_PAGE);
return this.emitter;
},
_buildPage: function _buildPage() {
var template = _.template(this.preprocessedTemplate);
delete this.preprocessedTemplate;
try {
this.resultPage = template(this.pageData);
this.onOperationDone(RESULT_OK);
} catch (e) {
throw e;
console.error("Error when building template: " + this.templateName + ", " + e);
this.onOperationDone(RESULT_ERROR, e);
}
},
_preprocessTemplate: function _preprocessTemplate() {
this.preprocessedTemplate = formatPagePart(this.rawTemplate),
delete this.rawTemplate;
this.onOperationDone(RESULT_OK);
},
_getTemplateRawFile: function _getTemplateRawFile() {
var cached = cachedTemplate[this.templateName];
if (cached) {
this.preprocessedTemplate = cached;
this.onOperationDone(RESULT_GOT_CACHED_TEMPLATE);
} else {
try {
this.rawTemplate =
fs.readFileSync(config.templateDir + "/" + this.templateName, 'utf8');
} catch (err) {
this.onOperationDone(RESULT_ERROR, err);
return;
}
this.onOperationDone(RESULT_OK);
};
},
onOperationDone: function(result, err) {
switch(this.state) {
case STATE_AVAILABLE:
if (result == RESULT_PROCESS_PAGE) {
this.state = STATE_GETTING_TEMPLATE_RAW_FILE;
setTimeout(this._getTemplateRawFile.bind(this), 0);
}
break;
case STATE_GETTING_TEMPLATE_RAW_FILE:
if (result == RESULT_OK) {
this.state = STATE_PREPROC_TEMPLATE;
setTimeout(this._preprocessTemplate.bind(this), 0);
} else if (result == RESULT_GOT_CACHED_TEMPLATE) {
// We can skip preprocessing.
this.state = STATE_BUILDING_PAGE;
setTimeout(this._buildPage.bind(this), 0);
} else {
this.handleError(err);
}
break;
case STATE_PREPROC_TEMPLATE:
if (result == RESULT_OK) {
this.state = STATE_BUILDING_PAGE;
setTimeout(this._buildPage.bind(this), 0);
} else {
this.handleError(err);
}
break;
case STATE_BUILDING_PAGE:
if (result == RESULT_OK) {
this.state = STATE_AVAILABLE;
this.handleSuccess();
} else {
this.handleError(err);
}
break;
}
},
handleSuccess: function handleSuccess() {
this.emitter.emit('ok', this.resultPage);
},
handleError: function handleError(err) {
this.emitter.emit('error', err);
}
};
exports.generatePage = function generatePage(templateName, data) {
var pageGenerator = new PageGenerator(templateName, data);
return pageGenerator.generatePage();
};
exports.generatePageAndStoreTo = function generatePageAndStoreTo(templateName,
targetFile,
data) {
var emitter = new EventEmitter(),
generatingPage = this.generatePage(templateName, data);
generatingPage.on('ok', function(page) {
if (config.debug) console.log('Page is generated: ' + page);
fsQueue.writeFile(targetFile, page, 'utf8', function(err) {
if (err) {
emitter.emit('error', err);
} else {
emitter.emit('ok');
}
});
});
generatingPage.on('error', function(err) {
emitter.emit('error', err);
});
return emitter;
};
| kk1fff/album-generator | template-interface.js | JavaScript | apache-2.0 | 6,516 |
var gId = '#dataGrid';
var lastIndex;
$(document).ready(function(){
//列表
$(gId).datagrid({
url:getUrlOpt(),
idField:'id',
fitColumns:true,
frozenColumns:[[
{field:'ck',checkbox:true}
]],
columns:[
getTableHeadOpt(),
getColumnsOpt(),
getTotal()
],
rownumbers:true,
pagination:false,
loadMsg:'数据装载中......',
onClickRow:function(rowIndex){
if (lastIndex != rowIndex){
$(gId).datagrid('endEdit', lastIndex);
$(gId).datagrid('beginEdit', rowIndex);
}
lastIndex = rowIndex;
}
});
});
//计算总计
function getTotal()
{
var opt=[
{field:'totalSalesmoney',title:'出货金额总计',hidden:true,align:'left',formatter:totalFormat},
{field:'totalCostmoney',title:'成本金额总计',hidden:true,align:'left'},
{field:'totalOrderNum',title:'出货数量总计',hidden:true,align:'left'}
];
return opt;
}
//格式化总计
function totalFormat(value,rowData,rowIndex){
var totalSalesmoney = rowData.totalSalesmoney;
var totalCostmoney=rowData.totalCostmoney;
var totalOrderNum=rowData.totalOrderNum;
$("#num").html(totalOrderNum);
$("#sale").html(totalSalesmoney);
$("#cost").html(totalCostmoney);
return totalSalesmoney;
}
//获取表头参数
function getTableHeadOpt(){
var opt = [];
opt.push({title:'销售汇总报表',colspan:11});
return opt;
}
//获取列头参数
function getColumnsOpt(){
var opt = [
{field:'goodCode',title:'资料编号',width:15,align:'left'},
{field:'goodTypeName',title:'资料类别',width:10,align:'left'},
{field:'goodName',title:'资料名',width:30,align:'left'},
{field:'unit',title:'单位',width:10,align:'left'},
{field:'purchasePrice',title:'进货价',width:15,align:'left'},
{field:'goodPrice',title:'销售单价',width:15,align:'left'},
{field:'taxRate',title:'资料税率',width:15,align:'left'},
{field:'orderNumber',title:'销售数量',width:20,align:'left'},
{field:'taxDueSum',title:'销售税金',width:15,align:'left',formatter:taxDueSumFormat},
{field:'salesmoney',title:'不含税销售金额',width:20,align:'left'},
{field:'costmoney',title:'成本金额',width:20,align:'left'}
];
return opt;
}
//Json加载数据路径
function getUrlOpt(){
var url = ctx+'/Salesummary_json!listJson.do?1=1';
return url;
}
//搜索框检查用户是否按下‘回车键’,按下则调用搜索方法
function checkKey(){
if(event.keyCode=='13'){
searchData();
}
}
//格式化销售税金显示方式
function taxDueSumFormat(value,rowData,rowIndex){
var taxDueSum = rowData.taxDueSum;
if(taxDueSum){
taxDueSum = taxDueSum.toFixed(2);
}
return taxDueSum;
}
//搜索功能
function searchData(){
var goodTypeName = $('#goodTypeName').val();
var goodName = $('#goodName').val();
var begin = $('#begin').val();
var end = $('#end').val();
var brandName=$('#brandName').val();
var positionName=$('#warehousePositionName').val();
realoadGrid(goodTypeName,goodName,begin,end,brandName,positionName);
}
function cancelSearch(){
$('#goodTypeName').val('');
$('#goodName').val('');
$('#begin').val('');
$('#end').val('');
$('#brandName').val('');
$('#warehouseName').val('');
$('#warehousePositionName').val('');
searchData();
}
//确定搜索时重新加载datagrid
function realoadGrid(goodTypeName,goodName,begin,end,brandName,positionName){
var queryParams = $(gId).datagrid('options').queryParams;
queryParams={"saleWare.goodTypeName":goodTypeName,"saleWare.goodName":goodName,"saleWare.begin":begin,"saleWare.end":end,"saleWare.brandName":brandName,"saleWare.warehousePositionName":positionName};
$(gId).datagrid('options').queryParams = queryParams;
$(gId).datagrid('reload');
}
//仓库
function selectWarehouse(){
var warehouse = common.getWarehouse();
if(warehouse){
$('#warehouseId').val(warehouse.id);
$('#warehouseName').val(warehouse.name);
}
}
//选择仓库
function selectWarehousePosition(){
var warehouseName=$('#warehouseName').val();
if(warehouseName==null||warehouseName=='')
{
alert('请选择仓库');
}
else
{
WarehousePosition();
}
}
//仓位
function WarehousePosition(){
var warehousePosition = common.getWarehousePosition();
if(warehousePosition){
$('#warehousePositionName').val(warehousePosition.name);
}
}
//选择资料品牌
function selectBrand(obj){
var obj = $(obj);
var dataArr = window.showModalDialog(ctx+"/goodBrand!list.do?todo=show", '',"status:no;left:yes;scroll:yes;resizable:no;help:no;dialogWidth:800px;dialogHeight:600px");
if(dataArr!=null){
$(obj).val(dataArr.brandName);
$("#brandId").val(dataArr.brandId);
$(obj).focus();
}
}
//选择资料类别弹出窗
function selectType(obj){
var obj = $(obj);
var dataArr = window.showModalDialog(ctx+"/goodType!list.do?todo=show", '',"status:no;left:yes;scroll:yes;resizable:no;help:no;dialogWidth:800px;dialogHeight:600px");
if(dataArr!=null){
$(obj).val(dataArr.typeName);
$(obj).focus();
}
}
//重新加载
function reloadDataGrid(){
$(gId).datagrid('reload');
}
| shenzeyu/recommend | src/main/webapp/scripts/formcenter/orderform/salesummary/list_salesummary.js | JavaScript | apache-2.0 | 5,021 |
module.exports = require('./lib/SimpleNodeDb');
| darrylwest/simple-node-db | index.js | JavaScript | apache-2.0 | 49 |
/*!
* ${copyright}
*/
// Provides control sap.m.ColumnListItem.
sap.ui.define([
"sap/ui/core/Element",
"sap/ui/core/library",
"./library",
"./ListItemBase",
"./ColumnListItemRenderer",
"sap/ui/thirdparty/jquery",
// jQuery custom selectors ":sapFocusable", ":sapTabbable"
"sap/ui/dom/jquery/Selectors"
],
function(Element, coreLibrary, library, ListItemBase, ColumnListItemRenderer, jQuery) {
"use strict";
// shortcut for sap.m.ListType
var ListItemType = library.ListType;
// shortcut for sap.ui.core.VerticalAlign
var VerticalAlign = coreLibrary.VerticalAlign;
/**
* Constructor for a new ColumnListItem.
*
* @param {string} [sId] Id for the new control, generated automatically if no id is given
* @param {object} [mSettings] Initial settings for the new control
*
* @class
* <code>sap.m.ColumnListItem</code> can be used with the <code>cells</code> aggregation to create rows for the <code>sap.m.Table</code> control.
* The <code>columns</code> aggregation of the <code>sap.m.Table</code> should match with the cells aggregation.
*
* <b>Note:</b> This control should only be used within the <code>sap.m.Table</code> control.
* The inherited <code>counter</code> property of <code>sap.m.ListItemBase</code> is not supported.
*
* @extends sap.m.ListItemBase
*
* @author SAP SE
* @version ${version}
*
* @constructor
* @public
* @since 1.12
* @alias sap.m.ColumnListItem
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var ColumnListItem = ListItemBase.extend("sap.m.ColumnListItem", /** @lends sap.m.ColumnListItem.prototype */ { metadata : {
library : "sap.m",
properties : {
/**
* Sets the vertical alignment of all the cells within the table row (including selection and navigation).
* <b>Note:</b> <code>vAlign</code> property of <code>sap.m.Column</code> overrides the property for cell vertical alignment if both are set.
* @since 1.20
*/
vAlign : {type : "sap.ui.core.VerticalAlign", group : "Appearance", defaultValue : VerticalAlign.Inherit}
},
defaultAggregation : "cells",
aggregations : {
/**
* Every <code>control</code> inside the <code>cells</code> aggregation defines one cell of the row.
* <b>Note:</b> The order of the <code>cells</code> aggregation must match the order of the <code>columns</code> aggregation of <code>sap.m.Table</code>.
*/
cells : {type : "sap.ui.core.Control", multiple : true, singularName : "cell", bindable : "bindable"}
}
}});
/**
* TablePopin element that handles own events.
*/
var TablePopin = Element.extend("sap.m.TablePopin", {
ontap: function(oEvent) {
// prevent the tap event if selection is done within the popin control and mark the event
if (oEvent.isMarked() || ListItemBase.detectTextSelection(this.getDomRef())) {
return oEvent.stopImmediatePropagation(true);
}
// focus to the main row if there is nothing to focus in the popin
if (oEvent.srcControl === this || !jQuery(oEvent.target).is(":sapFocusable")) {
this.getParent().focus();
}
},
_onMouseEnter: function() {
var $this = jQuery(this),
$parent = $this.prev();
if (!$parent.length || !$parent.hasClass("sapMLIBHoverable") || $parent.hasClass("sapMPopinHovered")) {
return;
}
$parent.addClass("sapMPopinHovered");
},
_onMouseLeave: function() {
var $this = jQuery(this),
$parent = $this.prev();
if (!$parent.length || !$parent.hasClass("sapMLIBHoverable") || !$parent.hasClass("sapMPopinHovered")) {
return;
}
$parent.removeClass("sapMPopinHovered");
}
});
// defines tag name
ColumnListItem.prototype.TagName = "tr";
// enable the ACC announcement for "not selected"
ColumnListItem.prototype._bAnnounceNotSelected = true;
ColumnListItem.prototype.init = function() {
ListItemBase.prototype.init.call(this);
this._bNeedsTypeColumn = false;
this._aClonedHeaders = [];
};
ColumnListItem.prototype.onAfterRendering = function() {
ListItemBase.prototype.onAfterRendering.call(this);
this._checkTypeColumn();
var oPopin = this.hasPopin();
if (oPopin) {
this.$Popin().on("mouseenter", oPopin._onMouseEnter).on("mouseleave", oPopin._onMouseLeave);
}
};
ColumnListItem.prototype.exit = function() {
ListItemBase.prototype.exit.call(this);
this._checkTypeColumn(false);
this._destroyClonedHeaders();
if (this._oPopin) {
this._oPopin.destroy(true);
this._oPopin = null;
}
};
// remove pop-in from DOM when setVisible false is called
ColumnListItem.prototype.setVisible = function(bVisible) {
ListItemBase.prototype.setVisible.call(this, bVisible);
if (!bVisible && this.hasPopin()) {
this.removePopin();
}
return this;
};
// returns responsible table control for the item
ColumnListItem.prototype.getTable = function() {
var oParent = this.getParent();
if (oParent && oParent.isA("sap.m.Table")) {
return oParent;
}
};
/**
* Returns the pop-in element.
*
* @protected
* @since 1.30.9
*/
ColumnListItem.prototype.getPopin = function() {
if (!this._oPopin) {
this._oPopin = new TablePopin({
id: this.getId() + "-sub"
}).addDelegate({
// handle the events of pop-in
ontouchstart: this.ontouchstart,
ontouchmove: this.ontouchmove,
ontap: this.ontap,
ontouchend: this.ontouchend,
ontouchcancel: this.ontouchcancel,
onsaptabnext: this.onsaptabnext,
onsaptabprevious: this.onsaptabprevious,
onsapup: this.onsapup,
onsapdown: this.onsapdown,
oncontextmenu: this.oncontextmenu
}, this).setParent(this, null, true);
}
return this._oPopin;
};
/**
* Returns pop-in DOMRef as a jQuery Object
*
* @protected
* @since 1.26
*/
ColumnListItem.prototype.$Popin = function() {
return this.$("sub");
};
/**
* Determines whether control has pop-in or not.
* @protected
*/
ColumnListItem.prototype.hasPopin = function() {
return this._oPopin;
};
/**
* Pemove pop-in from DOM
* @protected
*/
ColumnListItem.prototype.removePopin = function() {
this._oPopin && this.$Popin().remove();
};
/**
* Returns the tabbable DOM elements as a jQuery collection
* When popin is available this separated dom should also be included
*
* @returns {jQuery} jQuery object
* @protected
* @since 1.26
*/
ColumnListItem.prototype.getTabbables = function() {
return this.$().add(this.$Popin()).find(":sapTabbable");
};
ColumnListItem.prototype.getAccessibilityType = function(oBundle) {
return oBundle.getText("ACC_CTR_TYPE_ROW");
};
ColumnListItem.prototype.getContentAnnouncement = function(oBundle) {
var oTable = this.getTable();
if (!oTable) {
return;
}
var aOutput = [],
aCells = this.getCells(),
aColumns = oTable.getColumns(true);
aColumns.sort(function(oCol1, oCol2) {
var iCol1Index = oCol1.getIndex(), iCol2Index = oCol2.getIndex(), iIndexDiff = iCol1Index - iCol2Index;
if (iIndexDiff == 0) { return 0; }
if (iCol1Index < 0) { return 1; }
if (iCol2Index < 0) { return -1; }
return iIndexDiff;
}).forEach(function(oColumn) {
var oCell = aCells[oColumn.getInitialOrder()];
if (!oCell || !oColumn.getVisible() || (oColumn.isHidden() && !oColumn.isPopin())) {
return;
}
var oHeader = oColumn.getHeader();
if (oHeader && oHeader.getVisible()) {
aOutput.push(ListItemBase.getAccessibilityText(oHeader) + " " + ListItemBase.getAccessibilityText(oCell, true));
} else {
aOutput.push(ListItemBase.getAccessibilityText(oCell, true));
}
});
return aOutput.join(" . ").trim();
};
// update the aria-selected for the cells
ColumnListItem.prototype.updateSelectedDOM = function(bSelected, $This) {
ListItemBase.prototype.updateSelectedDOM.apply(this, arguments);
// update popin as well
if (this.hasPopin()) {
this.$Popin().attr("aria-selected", bSelected);
}
};
ColumnListItem.prototype.onfocusin = function(oEvent) {
if (oEvent.isMarked()) {
return;
}
if (oEvent.srcControl === this) {
this.$().children(".sapMListTblCellDup").find(":sapTabbable").attr("tabindex", -1);
}
ListItemBase.prototype.onfocusin.apply(this, arguments);
};
// informs the table when item's type column requirement is changed
ColumnListItem.prototype._checkTypeColumn = function(bNeedsTypeColumn) {
if (bNeedsTypeColumn == undefined) {
bNeedsTypeColumn = this._needsTypeColumn();
}
if (this._bNeedsTypeColumn != bNeedsTypeColumn) {
this._bNeedsTypeColumn = bNeedsTypeColumn;
this.informList("TypeColumnChange", bNeedsTypeColumn);
}
};
// determines whether type column for this item is necessary or not
ColumnListItem.prototype._needsTypeColumn = function() {
var sType = this.getType();
return this.getVisible() && (
sType == ListItemType.Detail ||
sType == ListItemType.Navigation ||
sType == ListItemType.DetailAndActive
);
};
// Adds cloned header to the local collection
ColumnListItem.prototype._addClonedHeader = function(oHeader) {
return this._aClonedHeaders.push(oHeader);
};
// Destroys cloned headers that are generated for popin
ColumnListItem.prototype._destroyClonedHeaders = function() {
if (this._aClonedHeaders.length) {
this._aClonedHeaders.forEach(function(oClone) {
oClone.destroy("KeepDom");
});
this._aClonedHeaders = [];
}
};
// active feedback for pop-in
ColumnListItem.prototype._activeHandlingInheritor = function() {
this._toggleActiveClass(true);
};
// inactive feedback for pop-in
ColumnListItem.prototype._inactiveHandlingInheritor = function() {
this._toggleActiveClass(false);
};
// toggles the active class of the pop-in.
ColumnListItem.prototype._toggleActiveClass = function(bSwitch) {
if (this.hasPopin()) {
this.$Popin().toggleClass("sapMLIBActive", bSwitch);
}
};
return ColumnListItem;
}); | SAP/openui5 | src/sap.m/src/sap/m/ColumnListItem.js | JavaScript | apache-2.0 | 9,887 |
//// [tests/cases/compiler/importHelpersWithLocalCollisions.ts] ////
//// [a.ts]
declare var dec: any, __decorate: any;
@dec export class A {
}
const o = { a: 1 };
const y = { ...o };
//// [tslib.d.ts]
export declare function __extends(d: Function, b: Function): void;
export declare function __decorate(decorators: Function[], target: any, key?: string | symbol, desc?: any): any;
export declare function __param(paramIndex: number, decorator: Function): Function;
export declare function __metadata(metadataKey: any, metadataValue: any): Function;
export declare function __awaiter(thisArg: any, _arguments: any, P: Function, generator: Function): any;
//// [a.js]
define(["require", "exports", "tslib"], function (require, exports, tslib_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.A = void 0;
let A = class A {
};
A = (0, tslib_1.__decorate)([
dec
], A);
exports.A = A;
const o = { a: 1 };
const y = Object.assign({}, o);
});
| kpreisser/TypeScript | tests/baselines/reference/importHelpersWithLocalCollisions(module=amd).js | JavaScript | apache-2.0 | 1,051 |
new require('styles/dark')
module.exports = class extends require('base/app'){
prototype(){
this.tools = {
Rect:require('shaders/quad'),
Code: require('views/code').extend({
w:'100#',
h:'100%'
})
}
}
constructor(){
super()
//this.code = new this.Code(this, {text:require('/examples/tiny.js').__module__.source})
let code =
'var x=(1,2,)\n'
this.code = new this.Code(this, {text:code})
//this.code = new this.Code(this, {text:module.source})
//this.code = new this.Code(this, {text:'if(x){\n\t1+2\nif(t){\n}\n}'})
}
onDraw(){
/*this.drawRect({
w:100,
h:100,
color:'red'
})*/
this.code.draw(this)
}
}
| makepad/makepad.github.io | platform/tests/codetest.js | JavaScript | apache-2.0 | 664 |
/* global document */
import test from 'ava'
import { $ } from '../lib/traversal.js'
import { addClass, removeClass, css, chain } from '../lib/manipulation.js'
test.beforeEach(() => { document.body.innerHTML = '' })
/**
* addClass
*/
test('addClass', t => {
t.is(typeof addClass, 'function')
})
test('addClass adds a class to the list of an elements classes', t => {
document.body.innerHTML = `
<div id="element"></div>
`
const element = $('#element')
addClass(element, 'some-class')
t.is(element.className, 'some-class')
})
test('addClass adds a class to a given list of an elements classes', t => {
document.body.innerHTML = `
<div id="element" class="fubar"></div>
`
const element = $('#element')
addClass(element, 'some-class')
addClass(element, 'fubar')
t.is(element.className, 'fubar some-class')
})
/**
* removeClass
*/
test('removeClass', t => {
t.is(typeof removeClass, 'function')
})
test('removeClass removes a given class from the list of an elements classes', t => {
document.body.innerHTML = `
<div id="element" class="some-other fubar second"></div>
`
const element = $('#element')
removeClass(element, 'fubar')
t.is(element.className, 'some-other second')
removeClass(element, 'second')
removeClass(element, 'some-class')
t.is(element.className, 'some-other')
})
/**
* css
*/
test('css function is specified', t => {
t.is(typeof css, 'function')
})
test('css retrieves property values, if no value is set', t => {
document.body.innerHTML = `
<div id="element" style="display:inline"></div>
`
const element = $('#element')
t.is(css(element, 'display'), 'inline')
})
test('css resets property values, if empty string is given', t => {
document.body.innerHTML = `
<div id="element" style="display:inline"></div>
`
const element = $('#element')
css(element, 'display', '')
t.is(css(element, 'display'), 'block')
})
test('css sets property values, if an actual value is given', t => {
document.body.innerHTML = `
<div id="element" style="height:50px">Some Content</div>
`
const element = $('#element')
css(element, 'border', '1px solid red')
t.is(css(element, 'border'), '1px solid red')
css(element, 'height', 0)
t.is(css(element, 'height'), '0px')
})
/**
* chain
*/
test('chain function is specified', t => {
t.is(typeof chain, 'function')
})
test('chain returns an object, containing a set of curried functions for the given element', t => {
document.body.innerHTML = `
<div id="element" class="initial"></div>
`
const element = $('#element')
chain(element)
.addClass('changed')
.removeClass('initial')
t.is(element.className, 'changed')
})
| mechanoid/cathedral | test/manipulation-test.js | JavaScript | apache-2.0 | 2,723 |
var util = require('../../../utils/util.js');
var check = require('../../../utils/check.js');
var api = require('../../../config/api.js');
var app = getApp();
Page({
data: {
array: ['请选择反馈类型', '商品相关', '功能异常', '优化建议', '其他'],
index: 0,
content: '',
contentLength: 0,
mobile: '',
hasPicture: false,
picUrls: [],
files: []
},
chooseImage: function(e) {
if (this.data.files.length >= 5) {
util.showErrorToast('只能上传五张图片')
return false;
}
var that = this;
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success: function(res) {
that.setData({
files: that.data.files.concat(res.tempFilePaths)
});
that.upload(res);
}
})
},
upload: function(res) {
var that = this;
const uploadTask = wx.uploadFile({
url: api.StorageUpload,
filePath: res.tempFilePaths[0],
name: 'file',
success: function(res) {
var _res = JSON.parse(res.data);
if (_res.errno === 0) {
var url = _res.data.url
that.data.picUrls.push(url)
that.setData({
hasPicture: true,
picUrls: that.data.picUrls
})
}
},
fail: function(e) {
wx.showModal({
title: '错误',
content: '上传失败',
showCancel: false
})
},
})
uploadTask.onProgressUpdate((res) => {
console.log('上传进度', res.progress)
console.log('已经上传的数据长度', res.totalBytesSent)
console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
})
},
previewImage: function(e) {
wx.previewImage({
current: e.currentTarget.id, // 当前显示图片的http链接
urls: this.data.files // 需要预览的图片http链接列表
})
},
bindPickerChange: function(e) {
this.setData({
index: e.detail.value
});
},
mobileInput: function(e) {
this.setData({
mobile: e.detail.value
});
},
contentInput: function(e) {
this.setData({
contentLength: e.detail.cursor,
content: e.detail.value,
});
},
clearMobile: function(e) {
this.setData({
mobile: ''
});
},
submitFeedback: function(e) {
if (!app.globalData.hasLogin) {
wx.navigateTo({
url: "/pages/auth/login/login"
});
}
let that = this;
if (that.data.index == 0) {
util.showErrorToast('请选择反馈类型');
return false;
}
if (that.data.content == '') {
util.showErrorToast('请输入反馈内容');
return false;
}
if (that.data.mobile == '') {
util.showErrorToast('请输入手机号码');
return false;
}
if (!check.isValidPhone(this.data.mobile)) {
this.setData({
mobile: ''
});
util.showErrorToast('请输入手机号码');
return false;
}
wx.showLoading({
title: '提交中...',
mask: true,
success: function() {
}
});
util.request(api.FeedbackAdd, {
mobile: that.data.mobile,
feedType: that.data.array[that.data.index],
content: that.data.content,
hasPicture: that.data.hasPicture,
picUrls: that.data.picUrls
}, 'POST').then(function(res) {
wx.hideLoading();
if (res.errno === 0) {
wx.showToast({
title: '感谢您的反馈!',
icon: 'success',
duration: 2000,
complete: function() {
that.setData({
index: 0,
content: '',
contentLength: 0,
mobile: '',
hasPicture: false,
picUrls: [],
files: []
});
}
});
} else {
util.showErrorToast(res.errmsg);
}
});
},
onLoad: function(options) {
},
onReady: function() {
},
onShow: function() {
},
onHide: function() {
// 页面隐藏
},
onUnload: function() {
// 页面关闭
}
}) | leiphp/100txy | pages/ucenter/feedback/feedback.js | JavaScript | apache-2.0 | 4,159 |
define(
"dojo/cldr/nls/en-ie/gregorian", //begin v1.x content
{
"dateFormatItem-Md": "d/M",
"dateFormatItem-yMEd": "EEE, d/M/yyyy",
"timeFormat-full": "HH:mm:ss zzzz",
"timeFormat-medium": "HH:mm:ss",
"dateFormatItem-yyyyMMMM": "MMMM y",
"dateFormatItem-MEd": "E, d/M",
"dateFormat-medium": "d MMM y",
"dateFormatItem-MMdd": "dd/MM",
"dateFormatItem-yyyyMM": "MM/yyyy",
"dateFormat-full": "EEEE d MMMM y",
"timeFormat-long": "HH:mm:ss z",
"dayPeriods-format-wide-am": "a.m.",
"timeFormat-short": "HH:mm",
"dateFormat-short": "dd/MM/yyyy",
"dateFormatItem-MMMMd": "d MMMM",
"dayPeriods-format-wide-pm": "p.m.",
"dateFormat-long": "d MMMM y"
}
//end v1.x content
); | WASdev/skunkworks.libertycar | LibertyCar/WebContent/remote/dojo-release-1.7.4/dojo/cldr/nls/en-ie/gregorian.js | JavaScript | apache-2.0 | 680 |
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development Company, L.P.
import path from 'path';
import fecha from 'fecha';
import lunr from 'lunr';
import GithubPostDAO from '../persistance/GithubPostDAO';
import PostDAO from '../persistance/PostDAO';
export function loadPosts () {
return new PostDAO().getAll();
}
export function getPostById (id) {
return new PostDAO().getById(id);
}
export function postsMonthMap (posts) {
return posts.reduce((postMap, post) => {
let monthLabel = fecha.format(
new Date(post.createdAt), 'MMMM, YYYY'
);
if (postMap.hasOwnProperty(monthLabel)) {
postMap[monthLabel].push(post);
} else {
postMap[monthLabel] = [post];
}
return postMap;
}, {});
}
export function filterPostsMapByMonth (postsByMonth, year, month) {
let monthLabel = fecha.format(
new Date(year, month - 1), 'MMMM, YYYY'
);
let archive = {};
if (monthLabel in postsByMonth) {
archive[monthLabel] = postsByMonth[monthLabel];
}
return archive;
}
export function buildSearchIndex (posts) {
const index = lunr(function () {
this.field('title', {boost: 10});
this.field('author', {boost: 2});
this.field('content', {boost: 5});
this.field('tags');
this.ref('id');
});
posts.forEach((post) => index.add(post));
return index;
}
export function addPost (content, metadata, images) {
const titleId = metadata.title
.replace(/ /g, '-').replace(/[^a-zA-Z0-9\-]/g, '').toLowerCase();
const today = new Date();
const idDateFormat = fecha.format(today, 'YYYY/MM/DD');
const folderDateFormat = fecha.format(today, 'YYYY-MM-DD');
metadata.id = `${idDateFormat}/${titleId}`;
metadata.createdAt = today;
const postFolderName = `${folderDateFormat}__${titleId}`;
if (process.env.BLOG_PERSISTANCE === 'github') {
return new GithubPostDAO(postFolderName, content, metadata, images).add();
} else {
return new PostDAO(postFolderName, content, metadata, images).add(
path.resolve(path.join(__dirname, '../../'))
);
}
}
export function editPost (content, metadata, images) {
const titleId = metadata.title
.replace(/ /g, '-').replace(/[^a-zA-Z0-9\-]/g, '').toLowerCase();
const folderDateFormat = fecha.format(
new Date(metadata.createdAt), 'YYYY-MM-DD'
);
const postFolderName = `${folderDateFormat}__${titleId}`;
if (process.env.BLOG_PERSISTANCE === 'github') {
return new GithubPostDAO(postFolderName, content, metadata, images).edit();
} else {
return new PostDAO(postFolderName, content, metadata, images).edit(
path.resolve(path.join(__dirname, '../../'))
);
}
}
function getPostFolderName (id) {
const idGroup = id.split('/');
const postTitle = idGroup[idGroup.length - 1];
idGroup.pop();
const postDate = idGroup.join('-');
return `${postDate}__${postTitle}`;
}
export function deletePost (id) {
const postFolderName = getPostFolderName(id);
if (process.env.BLOG_PERSISTANCE === 'github') {
return new GithubPostDAO(postFolderName).delete();
} else {
return new PostDAO(postFolderName).delete(
path.resolve(path.join(__dirname, '../../'))
);
}
}
export function getAllPosts () {
return new GithubPostDAO().getAll();
}
export function cancelChange (post) {
const titleId = post.title
.replace(/ /g, '-').replace(/[^a-zA-Z0-9\-]/g, '').toLowerCase();
const folderDateFormat = fecha.format(
new Date(post.createdAt), 'YYYY-MM-DD'
);
const postFolderName = `${folderDateFormat}__${titleId}`;
return new GithubPostDAO(postFolderName).cancelChange(post.action);
}
export function getPendingPost (id) {
const postFolderName = getPostFolderName(id);
return new GithubPostDAO(postFolderName).getPending();
}
export function getImageAsBase64 (imagePath) {
const postPath = imagePath.split('server/posts/')[1];
const postFolderGroup = postPath.split('/images/');
const postFolderName = postFolderGroup[0];
const imageName = decodeURI(postFolderGroup[1]);
return new GithubPostDAO(postFolderName).getImageAsBase64(imageName);
}
| grommet/grommet-blog | server/utils/post.js | JavaScript | apache-2.0 | 4,081 |
"use strict";
var net = require('net');
var events = require('events');
var util = require('util');
var async = require('async');
var tls = require('tls');
var Encoder = require('./encoder.js');
var writers = require('./writers');
var requests = require('./requests');
var streams = require('./streams');
var utils = require('./utils');
var types = require('./types');
var errors = require('./errors');
var StreamIdStack = require('./stream-id-stack');
/** @const */
var idleQuery = 'SELECT key from system.local';
/** @const */
var maxProtocolVersion = 4;
/**
* Represents a connection to a Cassandra node
* @param {String} endPoint An string containing ip address and port of the host
* @param {Number} protocolVersion
* @param {ClientOptions} options
* @constructor
*/
function Connection(endPoint, protocolVersion, options) {
events.EventEmitter.call(this);
this.setMaxListeners(0);
if (!endPoint || endPoint.indexOf(':') <= 0) {
throw new Error('EndPoint must contain the ip address and port separated by : symbol');
}
this.endPoint = endPoint;
var hostAndPort = endPoint.split(':');
this.address = hostAndPort[0];
this.port = hostAndPort[1];
Object.defineProperty(this, "options", { value: options, enumerable: false, writable: false});
if (protocolVersion === null) {
//Set initial protocol version
protocolVersion = maxProtocolVersion;
if (options.protocolOptions.maxVersion > 0 && options.protocolOptions.maxVersion < maxProtocolVersion) {
//limit the protocol version
protocolVersion = options.protocolOptions.maxVersion;
}
//Allow to check version using this connection instance
this.checkingVersion = true;
}
this.protocolVersion = protocolVersion;
this.streamHandlers = {};
this.pendingWrites = [];
this.preparing = {};
/**
* The timeout state for the idle request (heartbeat)
*/
this.idleTimeout = null;
this.timedOutHandlers = 0;
this.streamIds = new StreamIdStack(this.protocolVersion);
this.encoder = new Encoder(protocolVersion, options);
}
util.inherits(Connection, events.EventEmitter);
Connection.prototype.log = utils.log;
/**
* Binds the necessary event listeners for the socket
*/
Connection.prototype.bindSocketListeners = function() {
//Remove listeners that were used for connecting
this.netClient.removeAllListeners('connect');
this.netClient.removeAllListeners('timeout');
var self = this;
this.netClient.on('close', function() {
self.log('info', 'Connection to ' + self.address + ':' + self.port + ' closed');
self.connected = false;
self.connecting = false;
self.clearAndInvokePending();
});
var protocol = new streams.Protocol({objectMode: true}, this.protocolVersion);
this.parser = new streams.Parser({objectMode: true}, this.encoder);
var resultEmitter = new streams.ResultEmitter({objectMode: true});
resultEmitter.on('result', this.handleResult.bind(this));
resultEmitter.on('row', this.handleRow.bind(this));
resultEmitter.on('frameEnded', this.freeStreamId.bind(this));
resultEmitter.on('nodeEvent', this.handleNodeEvent.bind(this));
this.netClient
.pipe(protocol)
.pipe(this.parser)
.pipe(resultEmitter);
this.writeQueue = new writers.WriteQueue(this.netClient, this.encoder, this.options);
};
/**
* Connects a socket and sends the startup protocol messages.
*/
Connection.prototype.open = function (callback) {
var self = this;
this.log('info', 'Connecting to ' + this.address + ':' + this.port);
this.connecting = true;
if (!this.options.sslOptions) {
this.netClient = new net.Socket();
this.netClient.connect(this.port, this.address, function connectCallback() {
self.log('verbose', 'Socket connected to ' + self.address + ':' + self.port);
self.bindSocketListeners();
self.startup(callback);
});
}
else {
//use TLS
var sslOptions = utils.extend({rejectUnauthorized: false}, this.options.sslOptions);
this.netClient = tls.connect(this.port, this.address, sslOptions, function tlsConnectCallback() {
self.log('verbose', 'Secure socket connected to ' + self.address + ':' + self.port);
self.bindSocketListeners();
self.startup(callback);
});
}
this.netClient.once('error', function (err) {
self.errorConnecting(err, false, callback);
});
this.netClient.once('timeout', function connectTimedOut() {
var err = new types.DriverError('Connection timeout');
self.errorConnecting(err, true, callback);
});
this.netClient.setTimeout(this.options.socketOptions.connectTimeout);
// Improve failure detection with TCP keep-alives
if (this.options.socketOptions.keepAlive) {
this.netClient.setKeepAlive(true, this.options.socketOptions.keepAliveDelay);
}
this.netClient.setNoDelay(!!this.options.socketOptions.tcpNoDelay);
};
/**
* Determines the protocol version to use and sends the STARTUP request
* @param {Function} callback
*/
Connection.prototype.startup = function (callback) {
if (this.checkingVersion) {
this.log('info', 'Trying to use protocol version ' + this.protocolVersion);
}
var self = this;
this.sendStream(new requests.StartupRequest(), null, function (err, response) {
if (err && self.checkingVersion && self.protocolVersion > 1) {
var invalidProtocol = (err instanceof errors.ResponseError &&
err.code === types.responseErrorCodes.protocolError &&
err.message.indexOf('Invalid or unsupported protocol version') >= 0);
if (!invalidProtocol && self.protocolVersion > 3) {
//For some versions of Cassandra, the error is wrapped into a server error
//See CASSANDRA-9451
invalidProtocol = (err instanceof errors.ResponseError &&
err.code === types.responseErrorCodes.serverError &&
err.message.indexOf('ProtocolException: Invalid or unsupported protocol version') > 0);
}
if (invalidProtocol) {
self.log('info', 'Protocol v' + self.protocolVersion + ' not supported, using v' + (self.protocolVersion-1));
self.decreaseVersion();
//The host closed the connection, close the socket
setImmediate(function () {
self.close(function () {
//Retry
self.open(callback);
});
});
return;
}
}
if (response && response.mustAuthenticate) {
return self.authenticate(null, null, startupCallback);
}
startupCallback(err);
});
function startupCallback(err) {
if (err) {
return self.errorConnecting(err, true, callback);
}
//The socket is connected and the connection is authenticated
return self.connectionReady(callback);
}
};
Connection.prototype.errorConnecting = function (err, destroy, callback) {
this.connecting = false;
this.log('warning', 'There was an error when trying to connect to the host ' + this.address, err);
if (destroy) {
//there is a TCP connection that should be killed.
this.netClient.destroy();
}
callback(err);
};
/**
* Sets the connection to ready/connected status
*/
Connection.prototype.connectionReady = function (callback) {
this.emit('connected');
this.connected = true;
this.connecting = false;
// Remove existing error handlers as the connection is now ready.
this.netClient.removeAllListeners('error');
this.netClient.on('error', this.handleSocketError.bind(this));
callback();
};
Connection.prototype.decreaseVersion = function () {
this.protocolVersion--;
this.encoder.setProtocolVersion(this.protocolVersion);
this.streamIds.setVersion(this.protocolVersion);
};
/**
* Handle socket errors, if the socket is not readable invoke all pending callbacks
*/
Connection.prototype.handleSocketError = function (err) {
this.clearAndInvokePending(err);
};
/**
* Cleans all internal state and invokes all pending callbacks of sent streams
*/
Connection.prototype.clearAndInvokePending = function (innerError) {
if (this.idleTimeout) {
//Remove the idle request
clearTimeout(this.idleTimeout);
this.idleTimeout = null;
}
this.streamIds.clear();
var err = new types.DriverError('Socket was closed');
err.isServerUnhealthy = true;
if (innerError) {
err.innerError = innerError;
}
//copy all handlers
var handlers = utils.objectValues(this.streamHandlers);
//remove it from the map
this.streamHandlers = {};
if (handlers.length > 0) {
this.log('info', 'Invoking ' + handlers.length + ' pending callbacks');
}
var self = this;
//invoke all handlers
async.each(handlers, function (item, next) {
self.invokeCallback(item, err);
next();
});
var pendingWritesCopy = this.pendingWrites;
this.pendingWrites = [];
async.each(pendingWritesCopy, function (item, next) {
if (!item.callback) return;
item.callback(err);
next();
});
};
/**
* Handles authentication requests and responses.
* @param {Authenticator} authenticator
* @param {Buffer} token
* @param {Function} callback
*/
Connection.prototype.authenticate = function(authenticator, token, callback) {
var self = this;
if (authenticator === null) {
//initial token
if (!this.options.authProvider) {
return callback(new errors.AuthenticationError('Authentication provider not set'));
}
authenticator = this.options.authProvider.newAuthenticator();
authenticator.initialResponse(function (err, t) {
//let's start again with the correct args
if (err) return callback(err);
self.authenticate(authenticator, t, callback);
});
return;
}
var request = new requests.AuthResponseRequest(token);
if (this.protocolVersion === 1) {
//No Sasl support, use CREDENTIALS
//noinspection JSUnresolvedVariable
if (!authenticator.username) {
return callback(new errors.AuthenticationError('Only plain text authenticator providers allowed under protocol v1'));
}
//noinspection JSUnresolvedVariable
request = new requests.CredentialsRequest(authenticator.username, authenticator.password);
}
this.sendStream(request, null, function (err, result) {
if (err) {
if (err instanceof errors.ResponseError && err.code === types.responseErrorCodes.badCredentials) {
var authError = new errors.AuthenticationError(err.message);
authError.additionalInfo = err;
err = authError;
}
return callback(err);
}
if (result.ready) {
authenticator.onAuthenticationSuccess();
return callback();
}
if (result.authChallenge) {
authenticator.evaluateChallenge(result.token, function (err, t) {
if (err) {
return callback(err);
}
//here we go again
self.authenticate(authenticator, t, callback);
});
}
callback(new errors.DriverInternalError('Unexpected response from Cassandra: ' + util.inspect(result)))
});
};
/**
* Executes a 'USE ' query, if keyspace is provided and it is different from the current keyspace
* @param {?String} keyspace
* @param {Function} callback
*/
Connection.prototype.changeKeyspace = function (keyspace, callback) {
if (!keyspace || this.keyspace === keyspace) {
return callback();
}
if (this.toBeKeyspace === keyspace) {
return this.once('keyspaceChanged', callback);
}
this.toBeKeyspace = keyspace;
var query = util.format('USE "%s"', keyspace);
var self = this;
this.sendStream(
new requests.QueryRequest(query, null, null),
null,
function (err) {
if (!err) {
self.keyspace = keyspace;
}
callback(err);
self.emit('keyspaceChanged', err, keyspace);
});
};
/**
* Prepares a query on a given connection. If its already being prepared, it queues the callback.
* @param {String} query
* @param {function} callback
*/
Connection.prototype.prepareOnce = function (query, callback) {
var name = ( this.keyspace || '' ) + query;
var info = this.preparing[name];
if (this.preparing[name]) {
//Its being already prepared
return info.once('prepared', callback);
}
info = new events.EventEmitter();
info.setMaxListeners(0);
info.once('prepared', callback);
this.preparing[name] = info;
var self = this;
this.sendStream(new requests.PrepareRequest(query), null, function (err, response) {
info.emit('prepared', err, response);
delete self.preparing[name];
});
};
/**
* Uses the frame writer to write into the wire
* @param request
* @param options
* @param {function} callback Function to be called once the response has been received
*/
Connection.prototype.sendStream = function (request, options, callback) {
var self = this;
var streamId = this.getStreamId();
if (streamId === null) {
self.log('info',
'Enqueuing ' +
this.pendingWrites.length +
', if this message is recurrent consider configuring more connections per host or lowering the pressure');
return this.pendingWrites.push({request: request, options: options, callback: callback});
}
if (!callback) {
callback = function noop () {};
}
this.log('verbose', 'Sending stream #' + streamId);
request.streamId = streamId;
request.version = this.protocolVersion;
this.writeQueue.push(request, this.getWriteCallback(request, options, callback));
};
Connection.prototype.getWriteCallback = function (request, options, callback) {
var self = this;
return (function writeCallback (err) {
if (err) {
if (!(err instanceof TypeError)) {
//TypeError is raised when there is a serialization issue
//If it is not a serialization issue is a socket issue
err.isServerUnhealthy = true;
}
return callback(err);
}
self.log('verbose', 'Sent stream #' + request.streamId + ' to ' + self.endPoint);
//the request was successfully written, use a timer to set the readTimeout
var timeout;
if (self.options.socketOptions.readTimeout > 0) {
timeout = setTimeout(function () {
self.onTimeout(request.streamId);
}, self.options.socketOptions.readTimeout);
}
if (request instanceof requests.ExecuteRequest || request instanceof requests.QueryRequest) {
if (options && options.byRow) {
self.parser.setOptions(request.streamId, { byRow: true });
}
}
if (self.options.pooling.heartBeatInterval) {
if (self.idleTimeout) {
//remove the previous timeout for the idle request
clearTimeout(self.idleTimeout);
}
self.idleTimeout = setTimeout(function () {
self.idleTimeoutHandler();
}, self.options.pooling.heartBeatInterval);
}
self.streamHandlers[request.streamId] = {
callback: callback,
options: options,
timeout: timeout
};
});
};
/**
* Function that gets executed once the idle timeout has passed to issue a request to keep the connection alive
*/
Connection.prototype.idleTimeoutHandler = function () {
var self = this;
if (this.sendingIdleQuery) {
//don't issue another
//schedule for next time
this.idleTimeout = setTimeout(function () {
self.idleTimeoutHandler();
}, this.options.pooling.heartBeatInterval);
return;
}
this.log('verbose', 'Connection idling, issuing a Request to prevent idle disconnects');
this.sendingIdleQuery = true;
this.sendStream(new requests.QueryRequest(idleQuery), utils.emptyObject, function (err) {
self.sendingIdleQuery = false;
if (!err) {
//The sending succeeded
//There is a valid response but we don't care about the response
return;
}
self.log('warning', 'Received heartbeat request error', err);
self.emit('idleRequestError', err);
});
};
/**
* Returns an available streamId or null if there isn't any available
* @returns {Number}
*/
Connection.prototype.getStreamId = function() {
return this.streamIds.pop();
};
Connection.prototype.freeStreamId = function(header) {
var streamId = header.streamId;
if (streamId < 0) {
return;
}
delete this.streamHandlers[streamId];
this.streamIds.push(streamId);
this.writeNext();
this.log('verbose', 'Done receiving frame #' + streamId);
};
Connection.prototype.writeNext = function () {
var self = this;
setImmediate(function writeNextPending() {
var pending = self.pendingWrites.shift();
if (!pending) {
return;
}
self.sendStream(pending.request, pending.options, pending.callback);
});
};
/**
* Returns the number of requests waiting for response
* @returns {Number}
*/
Connection.prototype.getInFlight = function () {
return this.streamIds.inUse;
};
/**
* Handles a result and error response
*/
Connection.prototype.handleResult = function (header, err, result) {
var streamId = header.streamId;
if(streamId < 0) {
return this.log('verbose', 'event received', header);
}
var handler = this.streamHandlers[streamId];
if (!handler) {
return this.log('error', 'The server replied with a wrong streamId #' + streamId);
}
this.log('verbose', 'Received frame #' + streamId + ' from ' + this.endPoint);
this.invokeCallback(handler, err, result);
};
Connection.prototype.handleNodeEvent = function (header, event) {
switch (event.eventType) {
case types.protocolEvents.schemaChange:
this.emit('nodeSchemaChange', event);
break;
case types.protocolEvents.topologyChange:
this.emit('nodeTopologyChange', event);
break;
case types.protocolEvents.statusChange:
this.emit('nodeStatusChange', event);
break;
}
};
/**
* Handles a row response
*/
Connection.prototype.handleRow = function (header, row, meta, rowLength, flags) {
var streamId = header.streamId;
if(streamId < 0) {
return this.log('verbose', 'Event received', header);
}
var handler = this.streamHandlers[streamId];
if (!handler) {
return this.log('error', 'The server replied with a wrong streamId #' + streamId);
}
this.log('verbose', 'Received streaming frame #' + streamId);
if (handler.timeout) {
//It started receiving, clear the read timeout
clearTimeout(handler.timeout);
handler.timeout = null;
}
handler.rowIndex = handler.rowIndex || 0;
var rowCallback = handler.options && handler.options.rowCallback;
if (rowCallback) {
rowCallback(handler.rowIndex++, row, rowLength);
}
if (handler.rowIndex === rowLength) {
this.invokeCallback(handler, null, { rowLength: rowLength, meta: meta, flags: flags });
}
};
/**
* Invokes the handler callback and clears the callback and timers
* @param {{callback, timeout}} handler
* @param {Error} err
* @param [response]
*/
Connection.prototype.invokeCallback = function (handler, err, response) {
var callback = handler.callback;
//Prevent chained invocations
handler.callback = null;
if (handler.timeout) {
clearTimeout(handler.timeout);
handler.timeout = null;
}
if (callback) {
callback(err, response);
}
};
/**
* Executed on request timeout, it callbacks with OperationTimedOutError and clears the closures
*/
Connection.prototype.onTimeout = function (streamId) {
var handler = this.streamHandlers[streamId];
if (!handler || !handler.callback) {
//it's being cleared, don't mind
return;
}
this.timedOutHandlers++;
var originalCallback = handler.callback;
var self = this;
//clear callback closures
handler.callback = function () {
//if replies, remove from timedOutQueries
self.timedOutHandlers--;
};
if (handler.options && handler.options.rowCallback) {
handler.options.rowCallback = function noop() {};
}
var message = util.format('The host %s did not reply before timeout %d ms', this.endPoint, this.options.socketOptions.readTimeout);
originalCallback(new errors.OperationTimedOutError(message));
};
/**
* @param {Function} [callback]
*/
Connection.prototype.close = function (callback) {
this.log('verbose', 'disconnecting');
this.clearAndInvokePending();
if(!callback) {
callback = function () {};
}
if (!this.netClient) {
callback();
return;
}
if (!this.connected) {
this.netClient.destroy();
setImmediate(callback);
return;
}
var self = this;
this.netClient.once('close', function (hadError) {
if (hadError) {
self.log('info', 'The socket closed with a transmission error');
}
setImmediate(callback);
});
this.netClient.end();
this.streamHandlers = {};
};
module.exports = Connection;
| lucasrpb/com-github-lucasrpb-drivers-cassandra | node_modules/cassandra-driver/lib/connection.js | JavaScript | apache-2.0 | 20,399 |
/*
* Copyright (C) 2010 Chandra Sekar S
*
* 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.
*/
var url = require('url'),
fs = require('fs'),
util = require('util'),
mime = require('./mime'),
uuid = require('./uuid'),
session = require('./session'),
ghp = require('./ghp'),
i18n = require('./i18n'),
base64 = require('./base64'),
Cookie = require('./cookie').api.Cookie;
var viewsDir = '.',
defaultViewExtn = 'html',
staticsDir = '.',
defaultEncoding = 'utf8',
defaultCharset = 'UTF-8',
flashEnabled = true,
layout = undefined,
logErrors = true,
errorHandler = undefined;
exports.configure = function(config) {
if(config.viewsDir)
viewsDir = config.viewsDir;
if(config.defaultViewExtn)
defaultViewExtn = config.defaultViewExtn;
if(config.staticsDir)
staticsDir = config.staticsDir;
if(config.defaultCharset)
defaultCharset = config.defaultCharset;
if(config.defaultEncoding)
defaultEncoding = config.defaultEncoding;
if(config.layout)
layout = config.layout;
if(config.logErrors !== undefined)
logErrors = config.logErrors;
if(config.errorHandler)
errorHandler = config.errorHandler;
if(config.flashEnabled !== undefined)
flashEnabled = config.flashEnabled;
};
// Class: RequestContext
function RequestContext(request, response, secure) {
this.request = request;
this.response = response;
this.secure = secure;
this.model = {};
this.status = 200;
this.extn = this._getExtn();
this.encoding = defaultEncoding;
this.headers = {
'content-type': mime.mimes[this.extn]
? mime.mimes[this.extn]
: 'application/octet-stream',
'date': new Date().toUTCString(),
'x-powered-by': 'Grasshopper'
};
var cookieLine = request.headers['cookie'];
this.requestCookies = {};
if(cookieLine) {
var cookies = cookieLine.split(';');
for(var i = 0; i < cookies.length; i++) {
var cookieParts = cookies[i].trim().split('=');
if(cookieParts[0] == 'GHSESSION') {
this.sessionId = decodeURIComponent(cookieParts[1]);
} else {
this.requestCookies[cookieParts[0]]
= decodeURIComponent(cookieParts[1]);
}
}
}
i18n.init(this);
this.charset = defaultCharset;
}
RequestContext.prototype.challengeAuth = function(type, options) {
var challengeHeader = type + ' ';
Object.keys(options).forEach(function(key) {
challengeHeader += key + '="' + options[key] + '",';
});
challengeHeader = challengeHeader.substring(0, challengeHeader.length - 1);
this.headers['www-authenticate'] = challengeHeader;
this.renderError(401);
};
RequestContext.prototype.getAuth = function() {
var authHeader = this.request.headers['authorization'];
if(authHeader && authHeader.substring(0, 6) == "Basic ") {
var credentials = base64.decode(authHeader.substring(6), this.encoding);
var userPass = credentials.split(":", 2);
return {
username: userPass[0],
password: userPass[1]
};
} else if(authHeader && authHeader.substring(0, 7) == "Digest ") {
var credentials = authHeader.substring(7);
var auth = {};
credentials.split(',').forEach(function(part) {
var subParts = part.trim().split('=');
var value = subParts[1];
if(value.charAt(0) == '"'
&& value.charAt(0) == value.charAt(value.length - 1)) {
value = value.substring(1, value.length - 1);
}
auth[subParts[0]] = value;
});
return auth;
}
};
RequestContext.prototype.addCookie = function(cookie) {
if(this.secure) cookie.secure = true;
var cookieLine = cookie.name + '=' + encodeURIComponent(cookie.value);
cookieLine += cookie.path ? '; path=' + cookie.path : '';
cookieLine += cookie.expires ? '; expires=' + cookie.expires : '';
cookieLine += cookie.domain ? '; domain=' + cookie.domain : '';
cookieLine += cookie.secure ? '; secure' : '';
cookieLine += cookie.httpOnly ? '; HttpOnly' : '';
if(this.headers['set-cookie']) {
this.headers['set-cookie'] += '\r\nset-cookie: ' + cookieLine;
} else {
this.headers['set-cookie'] = cookieLine;
}
};
RequestContext.prototype.render = function(view, useLayout, cb) {
if(typeof useLayout == 'function') {
cb = useLayout;
useLayout = undefined;
}
if(view === undefined) {
this.response.writeHead(this.status, this.headers);
this.response.end();
cb && cb();
} else if(typeof view == 'function') {
this.response.writeHead(this.status, this.headers);
if(this.request.method != 'HEAD') {
view();
cb && cb();
}
} else {
this.model['flash'] = this.flash;
if(useLayout === undefined) {
useLayout = true;
}
var viewFile = viewsDir + '/' + view + '.' + this.extn;
if(useLayout && (layout || typeof useLayout == 'string')) {
useLayout = (typeof useLayout == 'string') ? useLayout : layout;
this.model.view = view;
viewFile = useLayout + '.' + this.extn;
}
try {
this._writeHead();
ghp.fill(viewFile, this.response, this.model, this.encoding, viewsDir, this.extn, this.locale);
cb && cb();
} catch(e) {
this._handleError(e);
cb && cb();
}
}
};
RequestContext.prototype.renderText = function(text) {
this._writeHead();
if(this.request.method != 'HEAD') {
this.response.write(text, this.encoding);
}
this.response.end();
};
RequestContext.prototype.renderError = function(status, error, cb) {
this.status = status;
if(error === undefined) {
error = {};
}
if(typeof error == 'function') {
cb = error;
error = {};
}
var viewFile = viewsDir + '/' + this.status + '.' + this.extn;
var self = this;
fs.stat(viewFile, function(err, stats) {
if(!err && stats.isFile()) {
try {
self._writeHead();
ghp.fill(viewFile, self.response, {error: error},
self.encoding, viewsDir, self.extn, this.locale);
cb && cb();
} catch(e) {
self._handleError(e);
cb && cb();
}
} else {
self._writeHead();
self.response.end();
cb && cb();
}
});
};
RequestContext.prototype.redirect = function(location, cb) {
var self = this;
function proceed() {
self.headers['location'] = location;
self.renderError(302, {location: location}, cb);
}
if(flashEnabled && this.flash && Object.keys(this.flash).length > 0) {
this.setSessionValue('flash', this.flash, function(err) {
proceed();
});
} else {
proceed();
}
};
RequestContext.prototype.disableCache = function() {
this.headers['expires'] = 'Thu, 11 Mar 2010 12:48:43 GMT';
this.headers['cache-control'] = 'no-store, no-cache, must-revalidate';
this.headers['pragma'] = 'no-cache';
};
RequestContext.prototype.sendFile = function(file, fileName, cb) {
if(typeof fileName == 'function') {
cb = fileName;
fileName = undefined;
}
var self = this;
fs.stat(file, function(err, stats) {
if(err) {
self._handleError(err);
cb && cb();
} else {
if(!fileName) {
fileName = file.substring(file.lastIndexOf('/') + 1);
}
var extn = fileName.substring(fileName.lastIndexOf('.') + 1);
self.headers['content-type'] = mime.mimes[extn]
? mime.mimes[extn]
: 'application/octet-stream';
self.headers['content-disposition'] = 'attachment; filename="' + fileName + '"';
sendStatic(file, stats, self, cb);
}
});
};
RequestContext.prototype.setSessionValue = function(key, value, callback) {
var self = this;
var store = session.getSessionStore();
var setter = function (err) {
if(err) {
callback(err);
} else {
store.setValue(self.sessionId, key, value, callback);
}
};
store.hasSession(this.sessionId, function(err, has) {
if(err) {
callback(err);
} else {
if(!has) {
self._beginSession(setter);
} else {
setter();
}
}
});
};
RequestContext.prototype.unsetSessionValue = function(key, callback) {
var store = session.getSessionStore();
var self = this;
store.hasSession(this.sessionId, function(err, has) {
if(err) {
callback(err);
} else {
if(has) {
store.unsetValue(self.sessionId, key, callback);
} else {
callback();
}
}
});
};
RequestContext.prototype.getSessionValue = function(key, callback) {
var self = this;
var store = session.getSessionStore();
store.hasSession(this.sessionId, function(err, has) {
if(!err && has) {
store.getValue(self.sessionId, key, callback);
} else {
callback(err);
}
});
};
RequestContext.prototype.endSession = function(callback) {
var self = this;
var store = session.getSessionStore();
store.hasSession(this.sessionId, function(err, has) {
if(!err && has) {
store.endSession(self.sessionId, callback);
} else {
callback(err)
}
});
};
RequestContext.prototype._getExtn = function() {
var extn = defaultViewExtn;
var path = url.parse(this.request.url).pathname;
if(path.match(/\.[^\/]+$/)) {
extn = path.substring(path.lastIndexOf('.') + 1);
this.requestExtn = extn;
}
return extn;
};
RequestContext.prototype._writeHead = function() {
if(this.charset) {
this.headers['content-type'] += '; charset=' + this.charset
}
this.response.writeHead(this.status, this.headers);
};
RequestContext.prototype._renderStatic = function() {
if(this.request.method != 'GET' && this.request.method != 'HEAD') {
this.extn = defaultViewExtn;
this.headers['content-type'] = mime.mimes[defaultViewExtn];
this.renderError(404);
return;
}
if(this.request.url.indexOf('/../') >= 0) {
this.extn = defaultViewExtn;
this.headers['content-type'] = mime.mimes[defaultViewExtn];
this.renderError(403);
return;
}
var staticFile = staticsDir + decodeURIComponent(url.parse(this.request.url).pathname);
var self = this;
fs.stat(staticFile, function(err, stats) {
if(err || !stats.isFile()) {
if((err && err.code == 'ENOENT') || !stats.isFile()) {
self.extn = defaultViewExtn;
self.headers['content-type'] = mime.mimes[defaultViewExtn];
self.renderError(404);
} else {
self._handleError(err);
}
} else {
sendStatic(staticFile, stats, self);
}
});
};
RequestContext.prototype._handleError = function(err) {
var self = this;
if(errorHandler == undefined) {
defaultHandler();
} else {
errorHandler.call(this, err, defaultHandler);
}
function defaultHandler() {
if(logErrors && err) {
util.debug(err.stack);
}
self.renderError(500, err);
}
};
RequestContext.prototype._beginSession = function(callback) {
var sessionId = new Buffer(uuid.api.generateUUID()).toString('base64');
var self = this;
session.getSessionStore().beginSession(sessionId, function(err) {
if(!err) {
self.sessionId = sessionId;
self.addCookie(new Cookie('GHSESSION', sessionId));
}
callback(err);
});
};
RequestContext.prototype._rotateFlash = function(cb) {
var self = this;
this.flash = {};
if(flashEnabled) {
this.getSessionValue('flash', function(err, flash) {
if(flash) {
self.flash = flash;
self.unsetSessionValue('flash', function() {
cb();
});
} else {
cb();
}
});
} else {
cb();
}
};
exports.RequestContext = RequestContext;
function sendStatic(staticFile, stats, ctx, cb) {
function sendBytes() {
if(satisfiesConditions(stats, ctx)) {
ctx.headers['last-modified'] = stats.mtime.toUTCString();
ctx.headers['etag'] = stats.mtime.getTime();
var range;
if(ctx.request.headers['range'] && (range = parseRange(ctx, stats))) {;
ctx.status = 206;
ctx.headers['content-length'] = range[1] - range[0] + 1;
ctx.headers['content-range'] = 'bytes ' + range[0] + '-' + range[1] + '/' + stats.size;
var stream = fs.createReadStream(staticFile, {start: range[0], end: range[1]});
} else {
ctx.headers['content-length'] = stats.size;
var stream = fs.createReadStream(staticFile);
}
ctx.response.writeHead(ctx.status, ctx.headers);
if(ctx.request.method == 'GET') {
stream.pipe(ctx.response);
cb && stream.on('end', cb);
} else {
ctx.response.end();
cb && cb();
}
}
}
var acceptHeader = ctx.request.headers['accept-encoding'];
if(acceptHeader && acceptHeader.indexOf('gzip') >= 0) {
fs.stat(staticFile + '.gz', function(err, gzipStats) {
if(!err) {
ctx.headers['content-encoding'] = 'gzip';
staticFile = staticFile + '.gz';
stats = gzipStats;
sendBytes();
} else {
sendBytes();
}
});
} else {
sendBytes();
}
}
function parseRange(ctx, stats) {
var range = ctx.request.headers['range'],
ifRange = ctx.request.headers['if-range'],
fileSize = stats.size,
ranges = range.substring(6).split(',');
if(ifRange) {
if(ifRange.match(/^\d{3}/) && ifRange != stats.mtime.getTime()) {
return;
} else if(!ifRange.match(/^\d{3}/) && ifRange != stats.mtime.toUTCString()) {
return;
}
}
if(range.length > 5 && ranges.length == 1) {
var range = ranges[0].split('-');
if(range[1].length == 0) {
range[1] = fileSize;
}
range[0] = Number(range[0]), range[1] = Number(range[1]);
if(range[1] > range[0]) {
range[0] = Math.max(range[0], 0);
range[1] = Math.min(range[1], fileSize - 1);
return range;
}
}
}
function satisfiesConditions(stats, ctx) {
var mtime = stats.mtime,
modifiedSince = new Date(ctx.request.headers['if-modified-since']),
noneMatch = Number(ctx.request.headers['if-none-match']);
if(modifiedSince && modifiedSince >= mtime) {
var status = 304;
} else if(noneMatch && noneMatch == mtime.getTime()) {
var status = 304;
}
if(status) {
ctx.extn = defaultViewExtn;
ctx.headers['content-type'] = mime.mimes[defaultViewExtn];
delete ctx.headers['last-modified'];
delete ctx.headers['content-disposition'];
ctx.response.writeHead(status, ctx.headers);
ctx.response.end();
return false;
} else {
return true;
}
}
| tuxychandru/grasshopper | grasshopper/lib/context.js | JavaScript | apache-2.0 | 16,361 |
/* Copyright 2014 Open Ag Data Alliance
*
* 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.
*/
'use strict';
var debug = require('debug-logger')('oada-error');
var codes = {
OK: 200,
CREATED: 201,
NO_CONTENT: 204,
PARTIAL_CONTENT: 206,
MOVED_PERMANENTLY: 301,
NOT_MODIFIED: 304,
TEMPORARY_REDIRECT: 307,
BAD_REQUEST: 400,
UNAUTHORIZED: 401,
FORBIDDEN: 403,
NOT_FOUND: 404,
NOT_ACCEPTABLE: 406,
CONFLICT: 409,
LENGTH_REQUIRED: 411,
PRECONDITION_FAILED: 412,
UNSUPPORTED_MEDIA_TYPE: 415,
REQUESTED_RANGE_NOT_SATISFIABLE: 416,
TOO_MANY_REQUESTS: 429,
INTERNAL_ERROR: 500,
};
module.exports.codes = codes;
var names = {
200: 'OK',
201: 'Created',
204: 'No Content',
206: 'Partial Content',
301: 'Moved Permanently',
304: 'Not Modified',
307: 'Temporary Redirect',
400: 'Bad Request',
401: 'Unauthorized',
403: 'Forbidden',
404: 'Not Found',
406: 'Not Acceptable',
409: 'Conflict',
411: 'Length Required',
412: 'Precondition Failed',
415: 'Unsupported Media Type',
416: 'Requested Range Not Satisfiable',
429: 'Too Many Requests',
500: 'Internal Error',
};
function OADAError(message, code, userMessage, href, detail) {
var error = Error.apply(null, arguments);
// Copy Error's properties
var self = this;
Object.getOwnPropertyNames(error).forEach(function(propertyName) {
Object.defineProperty(self, propertyName,
Object.getOwnPropertyDescriptor(error, propertyName));
});
// Convert named code to numeric code
if (isNaN(parseFloat(code))) {
this.code = codes[code];
} else {
this.code = code;
}
// Make sure code is OADA compliant
if (!names[code]) {
this.code = codes['INTERNAL_ERROR'];
}
this.status = names[this.code];
Object.defineProperty(this, 'message', {
configurable: true,
enumerable: false,
value: this.message || message || '',
writable: true
});
Object.defineProperty(this, 'type', {
configurable: true,
enumerable: false,
value: 'OADAError',
writable: true
});
this.title = this.message;
this.href = href || 'https://github.com/OADA/oada-docs';
if (detail) {
this.detail = detail;
}
this.userMessage = userMessage ||
'Unexpected error. Please try again or contact support.';
}
OADAError.prototype = Object.create(Error.prototype);
OADAError.prototype.name = 'OADAError';
OADAError.codes = codes;
module.exports.OADAError = OADAError;
function middleware(cb) {
return function(err, req, res, next) {
debug.trace('**** OADAError: ',err);
if (err.name === 'Error') {
debug.error(err);
// Don't expose interal error to client
err = new OADAError('Unexpected Error', codes.INTERNAL_ERROR);
}
if (err.type !== 'OADAError') {
return next(err);
}
if (typeof cb === 'function') {
cb(err);
}
debug.error('OADAError: ' + err);
res.status(err.code).json(err);
};
}
module.exports.middleware = middleware;
| OADA/oada-error-js | error.js | JavaScript | apache-2.0 | 3,734 |
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/app';
ReactDOM.render(<App />, document.getElementById('main'));
| jiaola/marc-editor | src/js/main.js | JavaScript | apache-2.0 | 158 |
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('@angular/core');
var helper_service_1 = require('../../services/helper/helper.service');
var transaction_service_1 = require('../../services/transaction/transaction.service');
var router_deprecated_1 = require('@angular/router-deprecated');
var GetEntity_service_1 = require('../../services/GetEntity/GetEntity.service');
var transactionline_component_1 = require('../transactionline/transactionline.component');
var main_1 = require('ag-grid-ng2/main');
var TransactionComponent = (function () {
function TransactionComponent(transactionService, router) {
var _this = this;
this.transactionService = transactionService;
this.router = router;
this.getTransactionSuccess = true;
this.ok = new core_1.EventEmitter();
this.transaction = {
comment: '',
debtorID: -1,
entityID: -1,
transactionID: -1,
transactionLineArray: [],
bankAccountID: -1,
chequeNumber: -1,
sTransactionDate: '',
transactionType: 0
};
this.transactionVisible = false;
this.calculateTransactionTotal = function () {
var i;
var total = 0;
for (i = 0; i < _this.transaction.transactionLineArray.length; i = i + 1) {
if (_this.transaction.transactionLineArray[i].debit) {
total += _this.transaction.transactionLineArray[i].amount;
}
else {
total -= _this.transaction.transactionLineArray[i].amount;
}
}
_this.transactionTotal = helper_service_1.HelperService.formatMoney(total);
};
this.newTransaction = function (ledgerAccounts, transactionType, bankAccounts) {
_this.selectedTransactionLineIndex = -1;
var newTransactionThis = _this;
if (helper_service_1.HelperService.tokenIsValid()) {
_this.ledgerAccounts = ledgerAccounts;
_this.bankAccounts = bankAccounts;
switch (transactionType) {
case 0:
_this.titleTransaction = 'Add Cheque';
_this.bankAccountDisabled = false;
break;
case 1:
_this.titleTransaction = 'Add Deposit';
_this.bankAccountDisabled = false;
break;
case 4:
_this.titleTransaction = 'Add General Journal';
_this.bankAccountDisabled = true;
break;
}
var EntityId = GetEntity_service_1.GetEntityService.getInstance().getEntityId();
if (EntityId === -1) {
_this.router.navigate(['Entities']);
}
else {
_this.transaction = {
comment: '',
debtorID: -1,
entityID: EntityId,
transactionID: -1,
transactionLineArray: [],
bankAccountID: -1,
chequeNumber: -1,
sTransactionDate: helper_service_1.HelperService.formatDateForJSon(new Date()),
transactionType: transactionType
};
_this.gridOptions.api.setRowData(_this.transaction.transactionLineArray);
_this.selectedTransactionLineIndex = -1;
}
_this.editTransaction = false;
_this.getTransactionSuccess = true;
_this.calculateTransactionTotal();
_this.transactionVisible = true;
}
else {
_this.router.navigate(['Login']);
}
};
this.getTransaction = function (transactionID, ledgerAccounts, bankAccounts, copyTransaction) {
var getTransactionThis = _this;
getTransactionThis.editTransaction = !copyTransaction;
if (helper_service_1.HelperService.tokenIsValid()) {
_this.ledgerAccounts = ledgerAccounts;
_this.bankAccounts = bankAccounts;
var EntityId = GetEntity_service_1.GetEntityService.getInstance().getEntityId();
_this.transactionService.getTransaction(transactionID, EntityId).subscribe(onGetTransaction, logTransactionError);
}
else {
_this.router.navigate(['Login']);
}
function onGetTransaction(transaction) {
getTransactionThis.transaction = transaction;
getTransactionThis.gridOptions.api.setRowData(transaction.transactionLineArray);
getTransactionThis.gridOptions.api.sizeColumnsToFit();
this.selectedTransactionLineIndex = -1;
getTransactionThis.getTransactionSuccess = true;
getTransactionThis.calculateTransactionTotal();
getTransactionThis.transactionVisible = true;
var verb;
if (copyTransaction) {
verb = 'Copy ';
}
else {
verb = 'Edit ';
}
switch (transaction.transactionType) {
case 0:
getTransactionThis.titleTransaction = verb + 'Cheque';
getTransactionThis.bankAccountDisabled = false;
break;
case 1:
getTransactionThis.titleTransaction = verb + ' Deposit';
getTransactionThis.bankAccountDisabled = false;
break;
case 4:
getTransactionThis.titleTransaction = verb + ' General Journal';
getTransactionThis.bankAccountDisabled = true;
break;
case 5:
getTransactionThis.titleTransaction = verb + ' Invoice';
getTransactionThis.bankAccountDisabled = true;
break;
case 6:
getTransactionThis.titleTransaction = verb + ' Pay Invoice';
getTransactionThis.bankAccountDisabled = true;
break;
}
}
function logTransactionError() {
console.log('getTransaction Error');
getTransactionThis.getTransactionSuccess = false;
}
};
this.cancelTransaction = function () {
_this.transactionVisible = false;
};
this.okClicked = function () {
var okClickedThis = _this;
if (_this.editTransaction) {
if (helper_service_1.HelperService.tokenIsValid()) {
_this.transactionService.updateTransaction(_this.transaction).subscribe(updateTransactionSuccess, logError, complete);
_this.transactionVisible = false;
}
else {
_this.router.navigate(['Login']);
}
}
else {
if (helper_service_1.HelperService.tokenIsValid()) {
_this.transactionService.saveNewTransaction(_this.transaction).subscribe(updateTransactionSuccess, logError, complete);
}
else {
_this.router.navigate(['Login']);
}
}
function logError(obj) {
console.log(obj);
console.log(JSON.stringify(obj));
}
function complete() {
console.log('transaction complete');
}
function updateTransactionSuccess(response) {
console.log('updateTransactionSuccess');
okClickedThis.transactionVisible = false;
okClickedThis.ok.emit('');
}
};
this.selectedTransactionLineIndex = -1;
this.deleteTransactionLine = function () {
if (_this.selectedTransactionLineIndex === -1) {
alert('Please choose a line to delete');
}
else {
_this.transaction.transactionLineArray.splice(_this.selectedTransactionLineIndex, 1);
_this.gridOptions.api.setRowData(_this.transaction.transactionLineArray);
_this.selectedTransactionLineIndex = -1;
}
};
this.saveTransactionLine = function (savededTransactionLine) {
if (_this.bEditTransactionLine) {
_this.transaction.transactionLineArray[_this.selectedTransactionLineIndex] = savededTransactionLine;
}
else {
_this.transaction.transactionLineArray.push(savededTransactionLine);
}
;
_this.gridOptions.api.setRowData(_this.transaction.transactionLineArray);
_this.selectedTransactionLineIndex = -1;
_this.calculateTransactionTotal();
};
this.newTransactionLine = function () {
_this.bEditTransactionLine = false;
_this.transactionLineComponent.newTransactionLine(_this.ledgerAccounts, _this.transaction.transactionType);
};
this.columnDefs = [
{ headerName: 'Ledger Account', field: 'ledgerAccountName' },
{ headerName: 'Amount', field: 'amount', cellClass: 'rightJustify', cellRenderer: function (params) { return helper_service_1.HelperService.formatMoney(Number(params.value)); } },
{ headerName: 'Debit', field: 'debit' },
{ headerName: 'Comment', field: 'comment' }
];
this.onRowClicked = function (params) {
_this.selectedTransactionLineIndex = params.node.id;
};
this.onRowDoubleClicked = function (params) {
var selectedTransactionLine = params.data;
_this.bEditTransactionLine = true;
_this.transactionLineComponent.displayTransactionline(selectedTransactionLine, _this.ledgerAccounts, _this.transaction.transactionType);
};
this.gridOptions = helper_service_1.HelperService.getGridOptions(this.columnDefs, this.onRowClicked, this.onRowDoubleClicked);
console.log('constructor transactionComponent');
}
TransactionComponent.prototype.ngOnInit = function () {
if (helper_service_1.HelperService.tokenIsValid() === false) {
this.router.navigate(['Login']);
}
};
__decorate([
core_1.Output(),
__metadata('design:type', core_1.EventEmitter)
], TransactionComponent.prototype, "ok", void 0);
__decorate([
core_1.ViewChild(transactionline_component_1.TransactionLineComponent),
__metadata('design:type', transactionline_component_1.TransactionLineComponent)
], TransactionComponent.prototype, "transactionLineComponent", void 0);
TransactionComponent = __decorate([
core_1.Component({
selector: 'transactionModal',
templateUrl: 'src/app/components/transaction/transaction.component.html',
styles: ['.modalSolsofVisible {display: block;}'],
providers: [transaction_service_1.TransactionService],
directives: [main_1.AgGridNg2, transactionline_component_1.TransactionLineComponent]
}),
__metadata('design:paramtypes', [transaction_service_1.TransactionService, router_deprecated_1.Router])
], TransactionComponent);
return TransactionComponent;
}());
exports.TransactionComponent = TransactionComponent;
//# sourceMappingURL=Transaction.component.js.map | helix46/solsof-ng2 | app/components/transaction/transaction.component.js | JavaScript | apache-2.0 | 12,623 |
ConstructIndex(); //non ui
for(let B of Bakteriler) {
AddBacteriaToDisplay(B);//sadece isimler ve aileler //only ui with variables
BakteriRouterSearch(B); //non ui +
}
ConstructBottomPanel(); //only ui with variables
IndexFamilies(); //non ui
PremakeLeftPanel(); //only ui
if(HaveNotification) {
document.querySelector("#notificationCircle").style.display = "block";
}
FilterRuleQueExec(); //sayi vs icin //non ui
//asd
//SozlukBuilderStart();
| occ55/Mikrobiyoloji | init.js | JavaScript | apache-2.0 | 472 |
'use strict';
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
debug: true,
context: path.join(__dirname, '/client'),
entry: {
app: './index.js',
},
output: {
path: path.join(__dirname, 'public'),
hash: true,
filename: '[name]-[hash].js',
sourceMapFilename: '[file].map',
},
devtool: '#source-map',
module: {
loaders: [
{
test: /\.css$/i,
loader: 'style!css!autoprefixer',
},
{
test: /\.js(x)?$/i,
exclude: /node_modules/,
loader: 'babel',
},
{
test: /\.(png|jpg|jpeg|gif)$/i,
loader: 'file?name=[path][name]-[sha512:hash:hex:7].[ext]',
},
],
},
resolve: {
extensions: ['', '.js', '.jsx'],
},
plugins: [
new HtmlWebpackPlugin({
title: 'Mochi',
favicon: './assets/favicon.ico',
chunks: ['app'],
inject: false,
template: './index-template.html',
}),
new CleanWebpackPlugin(['public'], {
root: __dirname,
verbose: true,
}),
],
};
| seanjh/mochi | webpack.config.js | JavaScript | apache-2.0 | 1,155 |
/**
* Copyright 2016 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.
*/
import {Services} from '../../../src/services';
import {SignatureVerifier, VerificationStatus} from './signature-verifier';
import {
is3pThrottled,
getAmpAdRenderOutsideViewport,
incrementLoadingAds,
} from '../../amp-ad/0.1/concurrent-load';
import {createElementWithAttributes} from '../../../src/dom';
import {cancellation, isCancellation} from '../../../src/error';
import {
installFriendlyIframeEmbed,
setFriendlyIframeEmbedVisible,
} from '../../../src/friendly-iframe-embed';
import {isLayoutSizeDefined, Layout} from '../../../src/layout';
import {isAdPositionAllowed} from '../../../src/ad-helper';
import {dev, user, duplicateErrorIfNecessary} from '../../../src/log';
import {dict} from '../../../src/utils/object';
import {getMode} from '../../../src/mode';
import {isArray, isObject, isEnumValue} from '../../../src/types';
import {utf8Decode} from '../../../src/utils/bytes';
import {getBinaryType, isExperimentOn} from '../../../src/experiments';
import {setStyle} from '../../../src/style';
import {
assertHttpsUrl,
isSecureUrl,
tryDecodeUriComponent,
} from '../../../src/url';
import {parseJson} from '../../../src/json';
import {handleClick} from '../../../ads/alp/handler';
import {
getDefaultBootstrapBaseUrl,
generateSentinel,
} from '../../../src/3p-frame';
import {
installUrlReplacementsForEmbed,
} from '../../../src/service/url-replacements-impl';
import {A4AVariableSource} from './a4a-variable-source';
// TODO(tdrl): Temporary. Remove when we migrate to using amp-analytics.
import {getTimingDataAsync} from '../../../src/service/variable-source';
import {getContextMetadata} from '../../../src/iframe-attributes';
import {getBinaryTypeNumericalCode} from '../../../ads/google/a4a/utils';
import {signingServerURLs} from '../../../ads/_a4a-config';
import {triggerAnalyticsEvent} from '../../../src/analytics';
import {insertAnalyticsElement} from '../../../src/extension-analytics';
/** @type {Array<string>} */
const METADATA_STRINGS = [
'<script amp-ad-metadata type=application/json>',
'<script type="application/json" amp-ad-metadata>',
'<script type=application/json amp-ad-metadata>'];
// TODO(tdrl): Temporary, while we're verifying whether SafeFrame is an
// acceptable solution to the 'Safari on iOS doesn't fetch iframe src from
// cache' issue. See https://github.com/ampproject/amphtml/issues/5614
/** @type {string} */
export const DEFAULT_SAFEFRAME_VERSION = '1-0-14';
/** @const {string} */
export const CREATIVE_SIZE_HEADER = 'X-CreativeSize';
/** @type {string} @visibleForTesting */
export const RENDERING_TYPE_HEADER = 'X-AmpAdRender';
/** @type {string} @visibleForTesting */
export const SAFEFRAME_VERSION_HEADER = 'X-AmpSafeFrameVersion';
/** @type {string} @visibleForTesting */
export const EXPERIMENT_FEATURE_HEADER_NAME = 'amp-ff-exps';
/** @type {string} */
const TAG = 'amp-a4a';
/** @type {string} */
const NO_CONTENT_RESPONSE = 'NO-CONTENT-RESPONSE';
/** @enum {string} */
export const XORIGIN_MODE = {
CLIENT_CACHE: 'client_cache',
SAFEFRAME: 'safeframe',
NAMEFRAME: 'nameframe',
};
/** @type {!Object} @private */
const SHARED_IFRAME_PROPERTIES = dict({
'frameborder': '0',
'allowfullscreen': '',
'allowtransparency': '',
'scrolling': 'no',
'marginwidth': '0',
'marginheight': '0',
});
/** @typedef {{width: number, height: number}} */
export let SizeInfoDef;
/** @typedef {{
minifiedCreative: string,
customElementExtensions: !Array<string>,
customStylesheets: !Array<{href: string}>,
images: (Array<string>|undefined),
}} */
let CreativeMetaDataDef;
/** @private */
export const LIFECYCLE_STAGES = {
// Note: Use strings as values here, rather than numbers, so that "0" does
// not test as `false` later.
adSlotCleared: '-1',
urlBuilt: '1',
adRequestStart: '2',
adRequestEnd: '3',
adResponseValidateStart: '5',
renderFriendlyStart: '6', // TODO(dvoytenko): this signal and similar are actually "embed-create", not "render-start".
renderCrossDomainStart: '7',
renderFriendlyEnd: '8',
renderCrossDomainEnd: '9',
preAdThrottle: '10',
renderSafeFrameStart: '11',
throttled3p: '12',
adResponseValidateEnd: '13',
xDomIframeLoaded: '14',
friendlyIframeLoaded: '15',
adSlotCollapsed: '16',
adSlotUnhidden: '17',
layoutAdPromiseDelay: '18',
signatureVerifySuccess: '19',
networkError: '20',
friendlyIframeIniLoad: '21',
visHalf: '22',
visHalfIniLoad: '23',
firstVisible: '24',
visLoadAndOneSec: '25',
iniLoad: '26',
resumeCallback: '27',
visIniLoad: '29',
upgradeDelay: '30',
// TODO(warrengm): This should replace xDomIframeLoaded once delayed fetch
// is fully deprecated. A new lifecycle stage, crossDomainIframeLoaded, was
// introduced since xDomIframeLoaded is handled in AmpAdXOriginIframeHandler
// outside A4A.
crossDomainIframeLoaded: '31',
};
/**
* Name of A4A lifecycle triggers.
* @enum {string}
*/
export const AnalyticsTrigger = {
AD_REQUEST_START: 'ad-request-start',
AD_RESPONSE_END: 'ad-response-end',
AD_RENDER_START: 'ad-render-start',
AD_RENDER_END: 'ad-render-end',
AD_IFRAME_LOADED: 'ad-iframe-loaded',
};
/**
* Maps the names of lifecycle events to analytics triggers.
* @const {!Object<string, !AnalyticsTrigger>}
*/
const LIFECYCLE_STAGE_TO_ANALYTICS_TRIGGER = {
'adRequestStart': AnalyticsTrigger.AD_REQUEST_START,
'adRequestEnd': AnalyticsTrigger.AD_RESPONSE_END,
'renderFriendlyStart': AnalyticsTrigger.AD_RENDER_START,
'renderCrossDomainStart': AnalyticsTrigger.AD_RENDER_START,
'renderSafeFrameStart': AnalyticsTrigger.AD_RENDER_START,
'renderFriendlyEnd': AnalyticsTrigger.AD_RENDER_END,
'renderCrossDomainEnd': AnalyticsTrigger.AD_RENDER_END,
'friendlyIframeIniLoad': AnalyticsTrigger.AD_IFRAME_LOADED,
'crossDomainIframeLoaded': AnalyticsTrigger.AD_IFRAME_LOADED,
};
/**
* Utility function that ensures any error thrown is handled by optional
* onError handler (if none provided or handler throws, error is swallowed and
* undefined is returned).
* @param {!Function} fn to protect
* @param {T=} inThis An optional object to use as the 'this' object
* when calling the function. If not provided, undefined is bound as this
* when calling function.
* @param {function(this:T, !Error, ...*):?=} onError function given error
* and arguments provided to function call.
* @return {!Function} protected function
* @template T
* @visibleForTesting
*/
export function protectFunctionWrapper(
fn, inThis = undefined, onError = undefined) {
return (...fnArgs) => {
try {
return fn.apply(inThis, fnArgs);
} catch (err) {
if (onError) {
try {
// Ideally we could use [err, ...var_args] but linter disallows
// spread so instead using unshift :(
fnArgs.unshift(err);
return onError.apply(inThis, fnArgs);
} catch (captureErr) {
// swallow error if error handler throws.
}
}
// In the event of no optional on error function or its execution throws,
// return undefined.
return undefined;
}
};
};
export class AmpA4A extends AMP.BaseElement {
// TODO: Add more error handling throughout code.
// TODO: Handle creatives that do not fill.
/**
* @param {!Element} element
*/
constructor(element) {
super(element);
dev().assert(AMP.AmpAdUIHandler);
dev().assert(AMP.AmpAdXOriginIframeHandler);
/** @private {?Promise<undefined>} */
this.keysetPromise_ = null;
/** @private {?Promise<?CreativeMetaDataDef>} */
this.adPromise_ = null;
/**
* @private {number} unique ID of the currently executing promise to allow
* for cancellation.
*/
this.promiseId_ = 0;
/** @private {?string} */
this.adUrl_ = null;
/** @private {?../../../src/friendly-iframe-embed.FriendlyIframeEmbed} */
this.friendlyIframeEmbed_ = null;
/** {?AMP.AmpAdUIHandler} */
this.uiHandler = null;
/** @private {?AMP.AmpAdXOriginIframeHandler} */
this.xOriginIframeHandler_ = null;
/** @private {boolean} whether creative has been verified as AMP */
this.isVerifiedAmpCreative_ = false;
/** @private {?ArrayBuffer} */
this.creativeBody_ = null;
/**
* Initialize this with the slot width/height attributes, and override
* later with what the network implementation returns via extractSize.
* Note: Either value may be 'auto' (i.e., non-numeric).
*
* @private {?({width, height}|../../../src/layout-rect.LayoutRectDef)}
*/
this.creativeSize_ = null;
/** @private {?../../../src/layout-rect.LayoutRectDef} */
this.originalSlotSize_ = null;
/**
* Note(keithwrightbos) - ensure the default here is null so that ios
* uses safeframe when response header is not specified.
* @private {?XORIGIN_MODE}
*/
this.experimentalNonAmpCreativeRenderMethod_ =
this.getNonAmpCreativeRenderingMethod();
/**
* Gets a notion of current time, in ms. The value is not necessarily
* absolute, so should be used only for computing deltas. When available,
* the performance system will be used; otherwise Date.now() will be
* returned.
*
* @const {function():number}
*/
this.getNow_ = (this.win.performance && this.win.performance.now) ?
this.win.performance.now.bind(this.win.performance) : Date.now;
/**
* Protected version of emitLifecycleEvent that ensures error does not
* cause promise chain to reject.
* @private {function(string, !Object=)}
*/
this.protectedEmitLifecycleEvent_ = protectFunctionWrapper(
this.emitLifecycleEvent, this,
(err, varArgs) => {
dev().error(TAG, this.element.getAttribute('type'),
'Error on emitLifecycleEvent', err, varArgs) ;
});
/** @const {string} */
this.sentinel = generateSentinel(window);
/**
* Used to indicate whether this slot should be collapsed or not. Marked
* true if the ad response has status 204, is null, or has a null
* arrayBuffer.
* @private {boolean}
*/
this.isCollapsed_ = false;
/**
* Frame in which the creative renders (friendly if validated AMP, xdomain
* otherwise).
* {?HTMLIframeElement}
*/
this.iframe = null;
/**
* TODO(keithwrightbos) - remove once resume behavior is verified.
* {boolean} whether most recent ad request was generated as part
* of resume callback.
*/
this.fromResumeCallback = false;
/** @protected {string} */
this.safeframeVersion = DEFAULT_SAFEFRAME_VERSION;
/**
* @protected {boolean} Indicates whether the ad is currently in the
* process of being refreshed.
*/
this.isRefreshing = false;
/** @protected {boolean} */
this.isRelayoutNeededFlag = false;
/**
* Used as a signal in some of the CSI pings.
* @private @const {string}
*/
this.releaseType_ = getBinaryTypeNumericalCode(getBinaryType(this.win)) ||
'-1';
/**
* Mapping of feature name to value extracted from ad response header
* amp-ff-exps with comma separated pairs of '=' separated key/value.
* @type {!Object<string,string>}
*/
this.postAdResponseExperimentFeatures = {};
/**
* The configuration for amp-analytics. If null, no amp-analytics element
* will be inserted and no analytics events will be fired.
* This will be initialized inside of buildCallback.
* @private {?JsonObject}
*/
this.a4aAnalyticsConfig_ = null;
/**
* The amp-analytics element that for this impl's analytics config. It will
* be null before buildCallback() executes or if the impl does not provide
* an analytice config.
* @private {?Element}
*/
this.a4aAnalyticsElement_ = null;
}
/** @override */
getPriority() {
// Priority used for scheduling preload and layout callback. Because
// AMP creatives will be injected as part of the promise chain created
// within onLayoutMeasure, this is only relevant to non-AMP creatives
// therefore we want this to match the 3p priority.
const isPWA = !this.element.getAmpDoc().isSingleDoc();
// give the ad higher priority if it is inside a PWA
return isPWA ? 1 : 2;
}
/** @override */
isLayoutSupported(layout) {
return isLayoutSizeDefined(layout);
}
/** @override */
isRelayoutNeeded() {
return this.isRelayoutNeededFlag;
}
/**
* @return {!Promise<boolean>} promise blocked on ad promise whose result is
* whether creative returned is validated as AMP.
*/
isVerifiedAmpCreativePromise() {
return this.adPromise_.then(() => this.isVerifiedAmpCreative_);
}
/** @override */
buildCallback() {
this.creativeSize_ = {
width: this.element.getAttribute('width'),
height: this.element.getAttribute('height'),
};
const upgradeDelayMs = Math.round(this.getResource().getUpgradeDelayMs());
dev().info(TAG,
`upgradeDelay ${this.element.getAttribute('type')}: ${upgradeDelayMs}`);
this.handleLifecycleStage_('upgradeDelay', {
'forced_delta': upgradeDelayMs,
});
this.uiHandler = new AMP.AmpAdUIHandler(this);
const verifier = signatureVerifierFor(this.win);
this.keysetPromise_ =
Services.viewerForDoc(this.getAmpDoc()).whenFirstVisible().then(() => {
this.getSigningServiceNames().forEach(signingServiceName => {
verifier.loadKeyset(signingServiceName);
});
});
this.a4aAnalyticsConfig_ = this.getA4aAnalyticsConfig();
if (this.a4aAnalyticsConfig_) {
// TODO(warrengm): Consider having page-level singletons for networks that
// use the same config for all ads.
this.a4aAnalyticsElement_ = insertAnalyticsElement(
this.element, this.a4aAnalyticsConfig_, true /* loadAnalytics */);
}
}
/** @override */
renderOutsideViewport() {
// Ensure non-verified AMP creatives are throttled.
if (!this.isVerifiedAmpCreative_ && is3pThrottled(this.win)) {
this.handleLifecycleStage_('throttled3p');
return false;
}
// Otherwise the ad is good to go.
const elementCheck = getAmpAdRenderOutsideViewport(this.element);
return elementCheck !== null ?
elementCheck : super.renderOutsideViewport();
}
/**
* To be overridden by network specific implementation indicating if element
* (and environment generally) are valid for sending XHR queries.
* @return {boolean} whether element is valid and ad request should be
* sent. If false, no ad request is sent and slot will be collapsed if
* possible.
*/
isValidElement() {
return true;
}
/**
* @return {boolean} whether ad request should be delayed until
* renderOutsideViewport is met.
*/
delayAdRequestEnabled() {
return false;
}
/**
* Returns preconnect urls for A4A. Ad network should overwrite in their
* Fast Fetch implementation and return an array of urls for the runtime to
* preconnect to.
* @return {!Array<string>}
*/
getPreconnectUrls() {
return [];
}
/**
* Returns prefetch urls for A4A. Ad network should overwrite in their
* Fast Fetch implementation and return an array of urls for the runtime to
* prefetch.
* @return {!Array<string>}
*/
getPrefetchUrls() {
return [];
}
/**
* Returns true if this element was loaded from an amp-ad element. For use by
* network-specific implementations that don't want to allow themselves to be
* embedded directly into a page.
* @return {boolean}
*/
isAmpAdElement() {
return this.element.tagName == 'AMP-AD' ||
this.element.tagName == 'AMP-EMBED';
}
/**
* Prefetches and preconnects URLs related to the ad using adPreconnect
* registration which assumes ad request domain used for 3p is applicable.
* @param {boolean=} unusedOnLayout
* @override
*/
preconnectCallback(unusedOnLayout) {
this.preconnect.preload(this.getSafeframePath_());
this.preconnect.preload(getDefaultBootstrapBaseUrl(this.win, 'nameframe'));
const preconnect = this.getPreconnectUrls();
// NOTE(keithwrightbos): using onLayout to indicate if preconnect should be
// given preferential treatment. Currently this would be false when
// relevant (i.e. want to preconnect on or before onLayoutMeasure) which
// causes preconnect to delay for 1 sec (see custom-element#preconnect)
// therefore hard coding to true.
// NOTE(keithwrightbos): Does not take isValidElement into account so could
// preconnect unnecessarily, however it is assumed that isValidElement
// matches amp-ad loader predicate such that A4A impl does not load.
if (preconnect) {
preconnect.forEach(p => {
this.preconnect.url(p, true);
});
}
}
/** @override */
resumeCallback() {
// FIE that was not destroyed on unlayoutCallback does not require a new
// ad request.
if (this.friendlyIframeEmbed_) {
return;
}
this.handleLifecycleStage_('resumeCallback');
this.fromResumeCallback = true;
// If layout of page has not changed, onLayoutMeasure will not be called
// so do so explicitly.
const resource = this.getResource();
if (resource.hasBeenMeasured() && !resource.isMeasureRequested()) {
this.onLayoutMeasure();
}
}
/**
* @return {!../../../src/service/resource.Resource}
* @visibileForTesting
*/
getResource() {
return this.element.getResources().getResourceForElement(this.element);
}
/**
* @return {boolean} whether adPromise was initialized (indicator of
* element validity).
* @protected
*/
hasAdPromise() {
return !!this.adPromise_;
}
/**
* @return {boolean} whether environment/element should initialize ad request
* promise chain.
* @private
*/
shouldInitializePromiseChain_() {
const slotRect = this.getIntersectionElementLayoutBox();
if (this.getLayout() != Layout.FLUID &&
(slotRect.height == 0 || slotRect.width == 0)) {
dev().fine(
TAG, 'onLayoutMeasure canceled due height/width 0', this.element);
return false;
}
if (!isAdPositionAllowed(this.element, this.win)) {
user().warn(TAG, `<${this.element.tagName}> is not allowed to be ` +
`placed in elements with position:fixed: ${this.element}`);
return false;
}
// OnLayoutMeasure can be called when page is in prerender so delay until
// visible. Assume that it is ok to call isValidElement as it should
// only being looking at window, immutable properties (i.e. location) and
// its element ancestry.
if (!this.isValidElement()) {
// TODO(kjwright): collapse?
user().warn(TAG, this.element.getAttribute('type'),
'Amp ad element ignored as invalid', this.element);
return false;
}
return true;
}
/** @override */
onLayoutMeasure() {
this.initiateAdRequest();
}
/**
* This is the entry point into the ad promise chain.
*
* Calling this function will initiate the following sequence of events: ad
* url construction, ad request issuance, creative verification, and metadata
* parsing.
*
* @protected
*/
initiateAdRequest() {
if (this.xOriginIframeHandler_) {
this.xOriginIframeHandler_.onLayoutMeasure();
}
if (this.adPromise_ || !this.shouldInitializePromiseChain_()) {
return;
}
// If in localDev `type=fake` Ad specifies `force3p`, it will be forced
// to go via 3p.
if (getMode().localDev &&
this.element.getAttribute('type') == 'fake' &&
this.element.getAttribute('force3p') == 'true') {
this.adUrl_ = this.getAdUrl();
this.adPromise_ = Promise.resolve();
return;
}
// Increment unique promise ID so that if its value changes within the
// promise chain due to cancel from unlayout, the promise will be rejected.
++this.promiseId_;
// Shorthand for: reject promise if current promise chain is out of date.
const checkStillCurrent = this.verifyStillCurrent();
// Return value from this chain: True iff rendering was "successful"
// (i.e., shouldn't try to render later via iframe); false iff should
// try to render later in iframe.
// Cases to handle in this chain:
// - Everything ok => Render; return true
// - Empty network response returned => Don't render; return true
// - Can't parse creative out of response => Don't render; return false
// - Can parse, but creative is empty => Don't render; return true
// - Validation fails => return false
// - Rendering fails => return false
// - Chain cancelled => don't return; drop error
// - Uncaught error otherwise => don't return; percolate error up
this.adPromise_ = Services.viewerForDoc(this.getAmpDoc()).whenFirstVisible()
.then(() => {
checkStillCurrent();
// See if experiment that delays request until slot is within
// renderOutsideViewport. Within render outside viewport will not
// resolve if already within viewport thus the check for already
// meeting the definition as opposed to waiting on the promise.
if (this.delayAdRequestEnabled() &&
!this.getResource().renderOutsideViewport()) {
return this.getResource().whenWithinRenderOutsideViewport();
}
})
// This block returns the ad URL, if one is available.
/** @return {!Promise<?string>} */
.then(() => {
checkStillCurrent();
return /** @type {!Promise<?string>} */(
this.getAdUrl(this.tryExecuteRealTimeConfig_()));
})
// This block returns the (possibly empty) response to the XHR request.
/** @return {!Promise<?Response>} */
.then(adUrl => {
checkStillCurrent();
this.adUrl_ = adUrl;
this.handleLifecycleStage_('urlBuilt');
return adUrl && this.sendXhrRequest(adUrl);
})
// The following block returns either the response (as a {bytes, headers}
// object), or null if no response is available / response is empty.
/** @return {?Promise<?{bytes: !ArrayBuffer, headers: !Headers}>} */
.then(fetchResponse => {
checkStillCurrent();
this.handleLifecycleStage_('adRequestEnd');
// If the response is null, we want to return null so that
// unlayoutCallback will attempt to render via x-domain iframe,
// assuming ad url or creative exist.
if (!fetchResponse) {
return null;
}
if (fetchResponse.headers && fetchResponse.headers.has(
EXPERIMENT_FEATURE_HEADER_NAME)) {
this.populatePostAdResponseExperimentFeatures_(
fetchResponse.headers.get(EXPERIMENT_FEATURE_HEADER_NAME));
}
if (getMode().localDev && this.win.location &&
this.win.location.search) {
// Allow for setting experiment features via query param which
// will potentially override values returned in response.
const match = /(?:\?|&)a4a_feat_exp=([^&]+)/.exec(
this.win.location.search);
if (match && match[1]) {
dev().info(TAG, `Using debug exp features: ${match[1]}`);
this.populatePostAdResponseExperimentFeatures_(
tryDecodeUriComponent(match[1]));
}
}
// If the response has response code 204, or arrayBuffer is null,
// collapse it.
if (!fetchResponse.arrayBuffer || fetchResponse.status == 204) {
this.forceCollapse();
return Promise.reject(NO_CONTENT_RESPONSE);
}
// TODO(tdrl): Temporary, while we're verifying whether SafeFrame is
// an acceptable solution to the 'Safari on iOS doesn't fetch
// iframe src from cache' issue. See
// https://github.com/ampproject/amphtml/issues/5614
const method = this.getNonAmpCreativeRenderingMethod(
fetchResponse.headers.get(RENDERING_TYPE_HEADER));
this.experimentalNonAmpCreativeRenderMethod_ = method;
const safeframeVersionHeader =
fetchResponse.headers.get(SAFEFRAME_VERSION_HEADER);
if (/^[0-9-]+$/.test(safeframeVersionHeader) &&
safeframeVersionHeader != DEFAULT_SAFEFRAME_VERSION) {
this.safeframeVersion = safeframeVersionHeader;
this.preconnect.preload(this.getSafeframePath_());
}
// Note: Resolving a .then inside a .then because we need to capture
// two fields of fetchResponse, one of which is, itself, a promise,
// and one of which isn't. If we just return
// fetchResponse.arrayBuffer(), the next step in the chain will
// resolve it to a concrete value, but we'll lose track of
// fetchResponse.headers.
return fetchResponse.arrayBuffer().then(bytes => {
if (bytes.byteLength == 0) {
// The server returned no content. Instead of displaying a blank
// rectangle, we collapse the slot instead.
this.forceCollapse();
return Promise.reject(NO_CONTENT_RESPONSE);
}
return {
bytes,
headers: fetchResponse.headers,
};
});
})
// This block returns the ad creative if it exists and validates as AMP;
// null otherwise.
/** @return {!Promise<?ArrayBuffer>} */
.then(responseParts => {
checkStillCurrent();
// Keep a handle to the creative body so that we can render into
// SafeFrame or NameFrame later, if necessary. TODO(tdrl): Temporary,
// while we
// assess whether this is the right solution to the Safari+iOS iframe
// src cache issue. If we decide to keep a SafeFrame-like solution,
// we should restructure the promise chain to pass this info along
// more cleanly, without use of an object variable outside the chain.
if (!responseParts) {
return Promise.resolve();
}
const {bytes, headers} = responseParts;
const size = this.extractSize(responseParts.headers);
this.creativeSize_ = size || this.creativeSize_;
if (this.experimentalNonAmpCreativeRenderMethod_ !=
XORIGIN_MODE.CLIENT_CACHE &&
bytes) {
this.creativeBody_ = bytes;
}
this.handleLifecycleStage_('adResponseValidateStart');
return this.keysetPromise_
.then(() => signatureVerifierFor(this.win)
.verify(bytes, headers, (eventName, extraVariables) => {
this.handleLifecycleStage_(
eventName, extraVariables);
}))
.then(status => {
if (getMode().localDev &&
this.element.getAttribute('type') == 'fake') {
// do not verify signature for fake type ad
status = VerificationStatus.OK;
}
this.handleLifecycleStage_('adResponseValidateEnd', {
'signatureValidationResult': status,
'releaseType': this.releaseType_,
});
switch (status) {
case VerificationStatus.OK:
return bytes;
case VerificationStatus.UNVERIFIED:
return null;
case VerificationStatus.CRYPTO_UNAVAILABLE:
return this.shouldPreferentialRenderWithoutCrypto() ?
bytes : null;
// TODO(@taymonbeal, #9274): differentiate between these
case VerificationStatus.ERROR_KEY_NOT_FOUND:
case VerificationStatus.ERROR_SIGNATURE_MISMATCH:
user().error(
TAG, this.element.getAttribute('type'),
'Signature verification failed');
return null;
}
});
})
.then(creative => {
checkStillCurrent();
// Need to know if creative was verified as part of render outside
// viewport but cannot wait on promise. Sadly, need a state a
// variable.
this.isVerifiedAmpCreative_ = !!creative;
return creative && utf8Decode(creative);
})
// This block returns CreativeMetaDataDef iff the creative was verified
// as AMP and could be properly parsed for friendly iframe render.
/** @return {?CreativeMetaDataDef} */
.then(creativeDecoded => {
checkStillCurrent();
// Note: It's critical that #getAmpAdMetadata_ be called
// on precisely the same creative that was validated
// via #validateAdResponse_. See GitHub issue
// https://github.com/ampproject/amphtml/issues/4187
let creativeMetaDataDef;
if (!creativeDecoded ||
!(creativeMetaDataDef = this.getAmpAdMetadata_(creativeDecoded))) {
return null;
}
// Update priority.
this.updatePriority(0);
// Load any extensions; do not wait on their promises as this
// is just to prefetch.
const extensions = Services.extensionsFor(this.win);
creativeMetaDataDef.customElementExtensions.forEach(
extensionId => extensions.preloadExtension(extensionId));
// Preload any fonts.
(creativeMetaDataDef.customStylesheets || []).forEach(font =>
this.preconnect.preload(font.href));
// Preload any AMP images.
(creativeMetaDataDef.images || []).forEach(image =>
isSecureUrl(image) && this.preconnect.preload(image));
return creativeMetaDataDef;
})
.catch(error => {
if (error == NO_CONTENT_RESPONSE) {
return {
minifiedCreative: '',
customElementExtensions: [],
customStylesheets: [],
};
}
// If error in chain occurs, report it and return null so that
// layoutCallback can render via cross domain iframe assuming ad
// url or creative exist.
this.promiseErrorHandler_(error);
return null;
});
}
/**
* Populates object mapping of feature to value used for post ad response
* behavior experimentation. Assumes comma separated, = delimited key/value
* pairs. If key appears more than once, last value wins.
* @param {string} input
* @private
*/
populatePostAdResponseExperimentFeatures_(input) {
input.split(',').forEach(line => {
if (!line) {
return;
}
const parts = line.split('=');
if (parts.length != 2 || !parts[0]) {
dev().warn(TAG, `invalid experiment feature ${line}`);
return;
}
this.postAdResponseExperimentFeatures[parts[0]] = parts[1];
});
}
/**
* Refreshes ad slot by fetching a new creative and rendering it. This leaves
* the current creative displayed until the next one is ready.
*
* @param {function()} refreshEndCallback When called, this function will
* restart the refresh cycle.
* @return {Promise} A promise that resolves when all asynchronous portions of
* the refresh function complete. This is particularly handy for testing.
*/
refresh(refreshEndCallback) {
dev().assert(!this.isRefreshing);
this.isRefreshing = true;
this.tearDownSlot();
this.initiateAdRequest();
dev().assert(this.adPromise_);
const promiseId = this.promiseId_;
return this.adPromise_.then(() => {
if (!this.isRefreshing || promiseId != this.promiseId_) {
// If this refresh cycle was canceled, such as in a no-content
// response case, keep showing the old creative.
refreshEndCallback();
return;
}
return this.mutateElement(() => {
this.togglePlaceholder(true);
// This delay provides a 1 second buffer where the ad loader is
// displayed in between the creatives.
return Services.timerFor(this.win).promise(1000).then(() => {
this.isRelayoutNeededFlag = true;
this.getResource().layoutCanceled();
Services.resourcesForDoc(this.getAmpDoc())
./*OK*/requireLayout(this.element);
});
});
});
}
/**
* Handles uncaught errors within promise flow.
* @param {*} error
* @param {boolean=} opt_ignoreStack
* @private
*/
promiseErrorHandler_(error, opt_ignoreStack) {
if (isCancellation(error)) {
// Rethrow if cancellation.
throw error;
}
if (error && error.message) {
error = duplicateErrorIfNecessary(/** @type {!Error} */(error));
} else {
error = new Error('unknown error ' + error);
}
if (opt_ignoreStack) {
error.ignoreStack = opt_ignoreStack;
}
// Add `type` to the message. Ensure to preserve the original stack.
const type = this.element.getAttribute('type') || 'notype';
if (error.message.indexOf(`${TAG}: ${type}:`) != 0) {
error.message = `${TAG}: ${type}: ${error.message}`;
}
// Additional arguments.
assignAdUrlToError(/** @type {!Error} */(error), this.adUrl_);
if (getMode().development || getMode().localDev || getMode().log) {
user().error(TAG, error);
} else {
user().warn(TAG, error);
// Report with 1% sampling as an expected dev error.
if (Math.random() < 0.01) {
dev().expectedError(TAG, error);
}
}
}
/** @override */
layoutCallback() {
if (this.isRefreshing) {
this.destroyFrame(true);
}
return this.attemptToRenderCreative();
}
/**
* Attemps to render the returned creative following the resolution of the
* adPromise.
*
* @return {!Promise<boolean>|!Promise<undefined>} A promise that resolves
* when the rendering attempt has finished.
* @protected
*/
attemptToRenderCreative() {
// Promise may be null if element was determined to be invalid for A4A.
if (!this.adPromise_) {
if (this.shouldInitializePromiseChain_()) {
dev().error(TAG, 'Null promise in layoutCallback');
}
return Promise.resolve();
}
// There's no real throttling with A4A, but this is the signal that is
// most comparable with the layout callback for 3p ads.
this.handleLifecycleStage_('preAdThrottle');
const layoutCallbackStart = this.getNow_();
const checkStillCurrent = this.verifyStillCurrent();
// Promise chain will have determined if creative is valid AMP.
return this.adPromise_.then(creativeMetaData => {
checkStillCurrent();
const delta = this.getNow_() - layoutCallbackStart;
this.handleLifecycleStage_('layoutAdPromiseDelay', {
layoutAdPromiseDelay: Math.round(delta),
isAmpCreative: !!creativeMetaData,
});
if (this.isCollapsed_) {
return Promise.resolve();
}
// If this.iframe already exists, and we're not currently in the middle
// of refreshing, bail out here. This should only happen in
// testing context, not in production.
if (this.iframe && !this.isRefreshing) {
this.handleLifecycleStage_('iframeAlreadyExists');
return Promise.resolve();
}
if (!creativeMetaData) {
// Non-AMP creative case, will verify ad url existence.
return this.renderNonAmpCreative_();
}
// Must be an AMP creative.
return this.renderAmpCreative_(creativeMetaData)
.catch(err => {
checkStillCurrent();
// Failed to render via AMP creative path so fallback to non-AMP
// rendering within cross domain iframe.
user().error(TAG, this.element.getAttribute('type'),
'Error injecting creative in friendly frame', err);
this.promiseErrorHandler_(err);
return this.renderNonAmpCreative_();
});
}).catch(error => {
this.promiseErrorHandler_(error);
throw cancellation();
});
}
/** @override **/
attemptChangeSize(newHeight, newWidth) {
// Store original size of slot in order to allow re-expansion on
// unlayoutCallback so that it is reverted to original size in case
// of resumeCallback.
this.originalSlotSize_ = this.originalSlotSize_ || this.getLayoutBox();
return super.attemptChangeSize(newHeight, newWidth).catch(() => {});
}
/** @override */
unlayoutCallback() {
this.tearDownSlot();
return true;
}
/**
* Attempts to tear down and set all state variables to initial conditions.
* @protected
*/
tearDownSlot() {
// Increment promiseId to cause any pending promise to cancel.
this.promiseId_++;
this.handleLifecycleStage_('adSlotCleared');
this.uiHandler.applyUnlayoutUI();
if (this.originalSlotSize_) {
super.attemptChangeSize(
this.originalSlotSize_.height, this.originalSlotSize_.width)
.then(() => {
this.originalSlotSize_ = null;
})
.catch(err => {
// TODO(keithwrightbos): if we are unable to revert size, on next
// trigger of promise chain the ad request may fail due to invalid
// slot size. Determine how to handle this case.
dev().warn(TAG, 'unable to revert to original size', err);
});
}
this.isCollapsed_ = false;
// Remove rendering frame, if it exists.
this.destroyFrame();
this.adPromise_ = null;
this.adUrl_ = null;
this.creativeBody_ = null;
this.isVerifiedAmpCreative_ = false;
this.fromResumeCallback = false;
this.experimentalNonAmpCreativeRenderMethod_ =
this.getNonAmpCreativeRenderingMethod();
this.postAdResponseExperimentFeatures = {};
}
/**
* Attempts to remove the current frame and free any associated resources.
* This function will no-op if this ad slot is currently in the process of
* being refreshed.
*
* @param {boolean=} force Forces the removal of the frame, even if
* this.isRefreshing is true.
* @protected
*/
destroyFrame(force = false) {
if (!force && this.isRefreshing) {
return;
}
if (this.iframe && this.iframe.parentElement) {
this.iframe.parentElement.removeChild(this.iframe);
this.iframe = null;
}
if (this.xOriginIframeHandler_) {
this.xOriginIframeHandler_.freeXOriginIframe();
this.xOriginIframeHandler_ = null;
}
// Allow embed to release its resources.
if (this.friendlyIframeEmbed_) {
this.friendlyIframeEmbed_.destroy();
this.friendlyIframeEmbed_ = null;
}
}
/** @override */
viewportCallback(inViewport) {
if (this.friendlyIframeEmbed_) {
setFriendlyIframeEmbedVisible(this.friendlyIframeEmbed_, inViewport);
}
if (this.xOriginIframeHandler_) {
this.xOriginIframeHandler_.viewportCallback(inViewport);
}
}
/** @override */
createPlaceholderCallback() {
return this.uiHandler.createPlaceholder();
}
/**
* Gets the Ad URL to send an XHR Request to. To be implemented
* by network.
* @param {Promise<!Array<rtcResponseDef>>=} opt_rtcResponsesPromise
* @return {!Promise<string>|string}
*/
getAdUrl(opt_rtcResponsesPromise) {
throw new Error('getAdUrl not implemented!');
}
/**
* Resets ad url state to null, used to prevent frame get fallback if error
* is thrown after url construction but prior to layoutCallback.
*/
resetAdUrl() {
this.adUrl_ = null;
}
/**
* @return {!function()} function that when called will verify if current
* ad retrieval is current (meaning unlayoutCallback was not executed).
* If not, will throw cancellation exception;
* @throws {Error}
*/
verifyStillCurrent() {
const promiseId = this.promiseId_;
return () => {
if (promiseId != this.promiseId_) {
throw cancellation();
}
};
}
/**
* Determine the desired size of the creative based on the HTTP response
* headers. Must be less than or equal to the original size of the ad slot
* along each dimension. May be overridden by network.
*
* @param {!../../../src/service/xhr-impl.FetchResponseHeaders} responseHeaders
* @return {?SizeInfoDef}
*/
extractSize(responseHeaders) {
const headerValue = responseHeaders.get(CREATIVE_SIZE_HEADER);
if (!headerValue) {
return null;
}
const match = /^([0-9]+)x([0-9]+)$/.exec(headerValue);
if (!match) {
// TODO(@taymonbeal, #9274): replace this with real error reporting
user().error(TAG, `Invalid size header: ${headerValue}`);
return null;
}
return /** @type {?SizeInfoDef} */ (
{width: Number(match[1]), height: Number(match[2])});
}
/**
* Forces the UI Handler to collapse this slot.
* @visibleForTesting
*/
forceCollapse() {
if (this.isRefreshing) {
// If, for whatever reason, the new creative would collapse this slot,
// stick with the old creative until the next refresh cycle.
this.isRefreshing = false;
return;
}
dev().assert(this.uiHandler);
// Store original size to allow for reverting on unlayoutCallback so that
// subsequent pageview allows for ad request.
this.originalSlotSize_ = this.originalSlotSize_ || this.getLayoutBox();
this.uiHandler.applyNoContentUI();
this.isCollapsed_ = true;
}
/**
* Callback executed when creative has successfully rendered within the
* publisher page but prior to load (or ini-load for friendly frame AMP
* creative render). To be overridden by network implementations as needed.
*
* @param {?CreativeMetaDataDef} creativeMetaData metadata if AMP creative,
* null otherwise.
*/
onCreativeRender(creativeMetaData) {
const lifecycleStage =
creativeMetaData ? 'renderFriendlyEnd' : 'renderCrossDomainEnd';
this.handleLifecycleStage_(lifecycleStage);
}
/**
* @param {!Element} iframe that was just created. To be overridden for
* testing.
* @visibleForTesting
*/
onCrossDomainIframeCreated(iframe) {
dev().info(TAG, this.element.getAttribute('type'),
`onCrossDomainIframeCreated ${iframe}`);
}
/**
* Send ad request, extract the creative and signature from the response.
* @param {string} adUrl Request URL to send XHR to.
* @return {!Promise<?../../../src/service/xhr-impl.FetchResponse>}
* @protected
*/
sendXhrRequest(adUrl) {
this.handleLifecycleStage_('adRequestStart');
const xhrInit = {
mode: 'cors',
method: 'GET',
credentials: 'include',
};
return Services.xhrFor(this.win)
.fetch(adUrl, xhrInit)
.catch(error => {
// If an error occurs, let the ad be rendered via iframe after delay.
// TODO(taymonbeal): Figure out a more sophisticated test for deciding
// whether to retry with an iframe after an ad request failure or just
// give up and render the fallback content (or collapse the ad slot).
this.handleLifecycleStage_('networkError');
const networkFailureHandlerResult =
this.onNetworkFailure(error, this.adUrl_);
dev().assert(!!networkFailureHandlerResult);
if (networkFailureHandlerResult.frameGetDisabled) {
// Reset adUrl to null which will cause layoutCallback to not
// fetch via frame GET.
dev().info(
TAG, 'frame get disabled as part of network failure handler');
this.resetAdUrl();
} else {
this.adUrl_ = networkFailureHandlerResult.adUrl || this.adUrl_;
}
return null;
});
}
/**
* Called on network failure sending XHR CORS ad request allowing for
* modification of ad url and prevent frame GET request on layoutCallback.
* By default, GET frame request will be executed with same ad URL as used
* for XHR CORS request.
* @param {*} unusedError from network failure
* @param {string} unusedAdUrl used for network request
* @return {!{adUrl: (string|undefined), frameGetDisabled: (boolean|undefined)}}
*/
onNetworkFailure(unusedError, unusedAdUrl) {
return {};
}
/**
* To be overridden by network specific implementation indicating which
* signing service(s) is to be used.
* @return {!Array<string>} A list of signing services.
*/
getSigningServiceNames() {
return getMode().localDev ? ['google', 'google-dev'] : ['google'];
}
/**
* Render non-AMP creative within cross domain iframe.
* @return {Promise<boolean>} Whether the creative was successfully rendered.
* @private
*/
renderNonAmpCreative_() {
if (this.element.getAttribute('disable3pfallback') == 'true') {
user().warn(TAG, this.element.getAttribute('type'),
'fallback to 3p disabled');
return Promise.resolve(false);
}
this.promiseErrorHandler_(
new Error('fallback to 3p'),
/* ignoreStack */ true);
// Haven't rendered yet, so try rendering via one of our
// cross-domain iframe solutions.
const method = this.experimentalNonAmpCreativeRenderMethod_;
let renderPromise = Promise.resolve(false);
if ((method == XORIGIN_MODE.SAFEFRAME ||
method == XORIGIN_MODE.NAMEFRAME) &&
this.creativeBody_) {
renderPromise = this.renderViaNameAttrOfXOriginIframe_(
this.creativeBody_);
this.creativeBody_ = null; // Free resources.
} else if (this.adUrl_) {
assertHttpsUrl(this.adUrl_, this.element);
renderPromise = this.renderViaCachedContentIframe_(this.adUrl_);
} else {
// Ad URL may not exist if buildAdUrl throws error or returns empty.
// If error occurred, it would have already been reported but let's
// report to user in case of empty.
user().warn(TAG, this.element.getAttribute('type'),
'No creative or URL available -- A4A can\'t render any ad');
}
incrementLoadingAds(this.win, renderPromise);
return renderPromise.then(
result => {
this.handleLifecycleStage_('crossDomainIframeLoaded');
// Pass on the result to the next value in the promise change.
return result;
});
}
/**
* Render a validated AMP creative directly in the parent page.
* @param {!CreativeMetaDataDef} creativeMetaData Metadata required to render
* AMP creative.
* @return {!Promise} Whether the creative was successfully rendered.
* @private
*/
renderAmpCreative_(creativeMetaData) {
dev().assert(creativeMetaData.minifiedCreative,
'missing minified creative');
dev().assert(!!this.element.ownerDocument, 'missing owner document?!');
this.handleLifecycleStage_('renderFriendlyStart');
// Create and setup friendly iframe.
this.iframe = /** @type {!HTMLIFrameElement} */(
createElementWithAttributes(
/** @type {!Document} */(this.element.ownerDocument), 'iframe',
dict({
// NOTE: It is possible for either width or height to be 'auto',
// a non-numeric value.
'height': this.creativeSize_.height,
'width': this.creativeSize_.width,
'frameborder': '0',
'allowfullscreen': '',
'allowtransparency': '',
'scrolling': 'no',
})));
this.applyFillContent(this.iframe);
const fontsArray = [];
if (creativeMetaData.customStylesheets) {
creativeMetaData.customStylesheets.forEach(s => {
const href = s['href'];
if (href) {
fontsArray.push(href);
}
});
}
const checkStillCurrent = this.verifyStillCurrent();
return installFriendlyIframeEmbed(
this.iframe, this.element, {
host: this.element,
url: this.adUrl_,
html: creativeMetaData.minifiedCreative,
extensionIds: creativeMetaData.customElementExtensions || [],
fonts: fontsArray,
}, embedWin => {
installUrlReplacementsForEmbed(this.getAmpDoc(), embedWin,
new A4AVariableSource(this.getAmpDoc(), embedWin));
}).then(friendlyIframeEmbed => {
checkStillCurrent();
this.friendlyIframeEmbed_ = friendlyIframeEmbed;
setFriendlyIframeEmbedVisible(
friendlyIframeEmbed, this.isInViewport());
// Ensure visibility hidden has been removed (set by boilerplate).
const frameDoc = friendlyIframeEmbed.iframe.contentDocument ||
friendlyIframeEmbed.win.document;
setStyle(frameDoc.body, 'visibility', 'visible');
// Bubble phase click handlers on the ad.
this.registerAlpHandler_(friendlyIframeEmbed.win);
// Capture timing info for friendly iframe load completion.
getTimingDataAsync(
friendlyIframeEmbed.win,
'navigationStart', 'loadEventEnd').then(delta => {
checkStillCurrent();
this.handleLifecycleStage_('friendlyIframeLoaded', {
'navStartToLoadEndDelta.AD_SLOT_ID': Math.round(delta),
});
}).catch(err => {
dev().error(TAG, this.element.getAttribute('type'),
'getTimingDataAsync for renderFriendlyEnd failed: ', err);
});
protectFunctionWrapper(this.onCreativeRender, this, err => {
dev().error(TAG, this.element.getAttribute('type'),
'Error executing onCreativeRender', err);
})(creativeMetaData);
// It's enough to wait for "ini-load" signal because in a FIE case
// we know that the embed no longer consumes significant resources
// after the initial load.
return friendlyIframeEmbed.whenIniLoaded();
}).then(() => {
checkStillCurrent();
// Capture ini-load ping.
this.handleLifecycleStage_('friendlyIframeIniLoad');
});
}
/**
* Shared functionality for cross-domain iframe-based rendering methods.
* @param {!JsonObject<string, string>} attributes The attributes of the iframe.
* @return {!Promise} awaiting load event for ad frame
* @private
*/
iframeRenderHelper_(attributes) {
const mergedAttributes = Object.assign(attributes, dict({
'height': this.creativeSize_.height,
'width': this.creativeSize_.width,
}));
if (this.sentinel) {
mergedAttributes['data-amp-3p-sentinel'] = this.sentinel;
}
this.iframe = createElementWithAttributes(
/** @type {!Document} */ (this.element.ownerDocument),
'iframe', /** @type {!JsonObject} */ (
Object.assign(mergedAttributes, SHARED_IFRAME_PROPERTIES)));
// TODO(keithwrightbos): noContentCallback?
this.xOriginIframeHandler_ = new AMP.AmpAdXOriginIframeHandler(this);
// Iframe is appended to element as part of xorigin frame handler init.
// Executive onCreativeRender after init to ensure it can get reference
// to frame but prior to load to allow for earlier access.
const frameLoadPromise =
this.xOriginIframeHandler_.init(this.iframe, /* opt_isA4A */ true);
protectFunctionWrapper(this.onCreativeRender, this, err => {
dev().error(TAG, this.element.getAttribute('type'),
'Error executing onCreativeRender', err);
})(null);
return frameLoadPromise;
}
/**
* Creates iframe whose src matches that of the ad URL. The response should
* have been cached causing the browser to render without callout. However,
* it is possible for cache miss to occur which can be detected server-side
* by missing ORIGIN header.
*
* Note: As of 2016-10-18, the fill-from-cache assumption appears to fail on
* Safari-on-iOS, which issues a fresh network request, even though the
* content is already in cache.
*
* @param {string} adUrl Ad request URL, as sent to #sendXhrRequest (i.e.,
* before any modifications that XHR module does to it.)
* @return {!Promise} awaiting ad completed insertion.
* @private
*/
renderViaCachedContentIframe_(adUrl) {
this.handleLifecycleStage_('renderCrossDomainStart', {
'isAmpCreative': this.isVerifiedAmpCreative_,
'releaseType': this.releaseType_,
});
return this.iframeRenderHelper_(dict({
'src': Services.xhrFor(this.win).getCorsUrl(this.win, adUrl),
'name': JSON.stringify(
getContextMetadata(this.win, this.element, this.sentinel)),
}));
}
/**
* Render the creative via some "cross domain iframe that accepts the creative
* in the name attribute". This could be SafeFrame or the AMP-native
* NameFrame.
*
* @param {!ArrayBuffer} creativeBody
* @return {!Promise} awaiting load event for ad frame
* @private
*/
renderViaNameAttrOfXOriginIframe_(creativeBody) {
/** @type {string} */
const method = this.experimentalNonAmpCreativeRenderMethod_;
dev().assert(method == XORIGIN_MODE.SAFEFRAME ||
method == XORIGIN_MODE.NAMEFRAME,
'Unrecognized A4A cross-domain rendering mode: %s', method);
this.handleLifecycleStage_('renderSafeFrameStart', {
'isAmpCreative': this.isVerifiedAmpCreative_,
'releaseType': this.releaseType_,
});
const checkStillCurrent = this.verifyStillCurrent();
return utf8Decode(creativeBody).then(creative => {
checkStillCurrent();
let srcPath;
let name = '';
switch (method) {
case XORIGIN_MODE.SAFEFRAME:
srcPath = this.getSafeframePath_() + '?n=0';
break;
case XORIGIN_MODE.NAMEFRAME:
srcPath = getDefaultBootstrapBaseUrl(this.win, 'nameframe');
// Name will be set for real below in nameframe case.
break;
default:
// Shouldn't be able to get here, but... Because of the assert, above,
// we can only get here in non-dev mode, so give user feedback.
user().error('A4A', 'A4A received unrecognized cross-domain name'
+ ' attribute iframe rendering mode request: %s. Unable to'
+ ' render a creative for'
+ ' slot %s.', method, this.element.getAttribute('id'));
return Promise.reject('Unrecognized rendering mode request');
}
// TODO(bradfrizzell): change name of function and var
let contextMetadata = getContextMetadata(
this.win, this.element, this.sentinel,
this.getAdditionalContextMetadata());
// TODO(bradfrizzell) Clean up name assigning.
if (method == XORIGIN_MODE.NAMEFRAME) {
contextMetadata['creative'] = creative;
name = JSON.stringify(contextMetadata);
} else if (method == XORIGIN_MODE.SAFEFRAME) {
contextMetadata = JSON.stringify(contextMetadata);
name = `${this.safeframeVersion};${creative.length};${creative}` +
`${contextMetadata}`;
}
return this.iframeRenderHelper_(dict({'src': srcPath, 'name': name}));
});
}
/**
*
* Throws {@code SyntaxError} if the metadata block delimiters are missing
* or corrupted or if the metadata content doesn't parse as JSON.
* @param {string} creative from which CSS is extracted
* @return {?CreativeMetaDataDef} Object result of parsing JSON data blob inside
* the metadata markers on the ad text, or null if no metadata markers are
* found.
* @private
* TODO(keithwrightbos@): report error cases
*/
getAmpAdMetadata_(creative) {
let metadataStart = -1;
let metadataString;
for (let i = 0; i < METADATA_STRINGS.length; i++) {
metadataString = METADATA_STRINGS[i];
metadataStart = creative.lastIndexOf(metadataString);
if (metadataStart >= 0) {
break;
}
}
if (metadataStart < 0) {
// Couldn't find a metadata blob.
dev().warn(TAG, this.element.getAttribute('type'),
'Could not locate start index for amp meta data in: %s', creative);
return null;
}
const metadataEnd = creative.lastIndexOf('</script>');
if (metadataEnd < 0) {
// Couldn't find a metadata blob.
dev().warn(TAG, this.element.getAttribute('type'),
'Could not locate closing script tag for amp meta data in: %s',
creative);
return null;
}
try {
const metaDataObj = parseJson(
creative.slice(metadataStart + metadataString.length, metadataEnd));
const ampRuntimeUtf16CharOffsets =
metaDataObj['ampRuntimeUtf16CharOffsets'];
if (!isArray(ampRuntimeUtf16CharOffsets) ||
ampRuntimeUtf16CharOffsets.length != 2 ||
typeof ampRuntimeUtf16CharOffsets[0] !== 'number' ||
typeof ampRuntimeUtf16CharOffsets[1] !== 'number') {
throw new Error('Invalid runtime offsets');
}
const metaData = {};
if (metaDataObj['customElementExtensions']) {
metaData.customElementExtensions =
metaDataObj['customElementExtensions'];
if (!isArray(metaData.customElementExtensions)) {
throw new Error(
'Invalid extensions', metaData.customElementExtensions);
}
} else {
metaData.customElementExtensions = [];
}
if (metaDataObj['customStylesheets']) {
// Expect array of objects with at least one key being 'href' whose
// value is URL.
metaData.customStylesheets = metaDataObj['customStylesheets'];
const errorMsg = 'Invalid custom stylesheets';
if (!isArray(metaData.customStylesheets)) {
throw new Error(errorMsg);
}
metaData.customStylesheets.forEach(stylesheet => {
if (!isObject(stylesheet) || !stylesheet['href'] ||
typeof stylesheet['href'] !== 'string' ||
!isSecureUrl(stylesheet['href'])) {
throw new Error(errorMsg);
}
});
}
if (isArray(metaDataObj['images'])) {
// Load maximum of 5 images.
metaData.images = metaDataObj['images'].splice(0, 5);
}
// TODO(keithwrightbos): OK to assume ampRuntimeUtf16CharOffsets is before
// metadata as its in the head?
metaData.minifiedCreative =
creative.slice(0, ampRuntimeUtf16CharOffsets[0]) +
creative.slice(ampRuntimeUtf16CharOffsets[1], metadataStart) +
creative.slice(metadataEnd + '</script>'.length);
return metaData;
} catch (err) {
dev().warn(
TAG, this.element.getAttribute('type'), 'Invalid amp metadata: %s',
creative.slice(metadataStart + metadataString.length, metadataEnd));
return null;
}
}
/**
* Registers a click handler for "A2A" (AMP-to-AMP navigation where the AMP
* viewer navigates to an AMP destination on our behalf.
* @param {!Window} iframeWin
*/
registerAlpHandler_(iframeWin) {
if (!isExperimentOn(this.win, 'alp-for-a4a')) {
return;
}
iframeWin.document.documentElement.addEventListener('click', event => {
handleClick(event, url => {
Services.viewerForDoc(this.getAmpDoc()).navigateTo(url, 'a4a');
});
});
}
/**
* @return {string} full url to safeframe implementation.
* @private
*/
getSafeframePath_() {
return 'https://tpc.googlesyndication.com/safeframe/' +
`${this.safeframeVersion}/html/container.html`;
}
/**
* Receive collapse notifications and record lifecycle events for them.
*
* @param unusedElement {!AmpElement}
* @override
*/
collapsedCallback(unusedElement) {
this.handleLifecycleStage_('adSlotCollapsed');
}
/**
* Handles a lifecycle event by triggering the corresponding analytics event
* (if such an event exists) and by forwarding the event to the impl-specific
* handler in #emitLifecycleEvent.
* @param {string} eventName
* @param {!Object<string, string>=} opt_vars
* @private
*/
handleLifecycleStage_(eventName, opt_vars) {
this.maybeTriggerAnalyticsEvent_(eventName);
this.protectedEmitLifecycleEvent_(eventName, opt_vars);
}
/**
* Checks if the given lifecycle event has a corresponding amp-analytics event
* and fires the analytics trigger if so.
* @param {string} lifecycleStage
* @private
*/
maybeTriggerAnalyticsEvent_(lifecycleStage) {
if (!this.a4aAnalyticsConfig_) {
// No config exists that will listen to this event.
return;
}
const analyticsEvent =
LIFECYCLE_STAGE_TO_ANALYTICS_TRIGGER[lifecycleStage];
if (!analyticsEvent) {
// No analytics event is defined for this lifecycle stage.
return;
}
const analyticsVars = Object.assign(
{'time': Math.round(this.getNow_())},
this.getA4aAnalyticsVars(analyticsEvent));
triggerAnalyticsEvent(this.element, analyticsEvent, analyticsVars);
}
/**
* Returns variables to be included on an analytics event. This can be
* overridden by specific network implementations.
* Note that this function is called for each time an analytics event is
* fired.
* @param {string} unusedAnalyticsEvent The name of the analytics event.
* @return {!Object<string, string>}
*/
getA4aAnalyticsVars(unusedAnalyticsEvent) { return {}; }
/**
* Returns network-specific config for amp-analytics. It should overridden
* with network-specific configurations.
* This function may return null. If so, no amp-analytics element will be
* added to this A4A element and no A4A triggers will be fired.
* @return {?JsonObject}
*/
getA4aAnalyticsConfig() { return null; }
/**
* To be overriden by network specific implementation.
* This function will be called for each lifecycle event as specified in the
* LIFECYCLE_STAGES enum declaration. It may additionally pass extra
* variables of the form { name: val }. It is up to the subclass what to
* do with those variables.
*
* @param {string} unusedEventName
* @param {!Object<string, string|number>=} opt_extraVariables
*/
emitLifecycleEvent(unusedEventName, opt_extraVariables) {}
/**
* Attempts to execute Real Time Config, if the ad network has enabled it.
* If it is not supported by the network, but the publisher has included
* the rtc-config attribute on the amp-ad element, warn.
* @return {Promise<!Array<!rtcResponseDef>>|undefined}
*/
tryExecuteRealTimeConfig_() {
if (!!AMP.maybeExecuteRealTimeConfig) {
try {
return AMP.maybeExecuteRealTimeConfig(
this, this.getCustomRealTimeConfigMacros_());
} catch (err) {
user().error(TAG, 'Could not perform Real Time Config.', err);
}
} else if (this.element.getAttribute('rtc-config')) {
user().error(TAG, 'RTC not supported for ad network ' +
`${this.element.getAttribute('type')}`);
}
}
/**
* To be overriden by network impl. Should return a mapping of macro keys
* to values for substitution in publisher-specified URLs for RTC.
* @return {?Object<string,
* !../../../src/service/variable-source.SyncResolverDef>}
*/
getCustomRealTimeConfigMacros_() {
return null;
}
/**
* Whether preferential render should still be utilized if web crypto is unavailable,
* and crypto signature header is present.
* @return {!boolean}
*/
shouldPreferentialRenderWithoutCrypto() {
return false;
}
/**
* @param {string=} headerValue Method as given in header.
*/
getNonAmpCreativeRenderingMethod(headerValue) {
if (headerValue) {
if (!isEnumValue(XORIGIN_MODE, headerValue)) {
dev().error(
'AMP-A4A', `cross-origin render mode header ${headerValue}`);
} else {
return headerValue;
}
}
return Services.platformFor(this.win).isIos() ?
XORIGIN_MODE.SAFEFRAME : null;
}
/**
* Returns base object that will be written to cross-domain iframe name
* attribute.
* @return {!JsonObject}
*/
getAdditionalContextMetadata() {
return /** @type {!JsonObject} */ ({});
}
}
/**
* Attachs query string portion of ad url to error.
* @param {!Error} error
* @param {string} adUrl
*/
export function assignAdUrlToError(error, adUrl) {
if (!adUrl || (error.args && error.args['au'])) {
return;
}
const adQueryIdx = adUrl.indexOf('?');
if (adQueryIdx == -1) {
return;
}
(error.args || (error.args = {}))['au'] =
adUrl.substring(adQueryIdx + 1, adQueryIdx + 251);
};
/**
* Returns the signature verifier for the given window. Lazily creates it if it
* doesn't already exist.
*
* This ensures that only one signature verifier exists per window, which allows
* multiple Fast Fetch ad slots on a page (even ones from different ad networks)
* to share the same cached public keys.
*
* @param {!Window} win
* @return {!SignatureVerifier}
* @visibleForTesting
*/
export function signatureVerifierFor(win) {
const propertyName = 'AMP_FAST_FETCH_SIGNATURE_VERIFIER_';
return win[propertyName] ||
(win[propertyName] = new SignatureVerifier(win, signingServerURLs));
}
| shawnbuso/amphtml | extensions/amp-a4a/0.1/amp-a4a.js | JavaScript | apache-2.0 | 66,004 |
var jms_response_time20150206184935 = [ [ 'Time', 'Minimum', 'Maximum', 'Average', 'Result' ] ];
var offset = (new Date()).getTimezoneOffset() * 60 * 1000;
jms_response_time20150206184935.push([new Date(1492 + offset), 0.750176, 219.364885, 2.448107105121296, 1.027068]);
jms_response_time20150206184935.push([new Date(2786 + offset), 0.438558, 219.364885, 1.9759946787709501, 0.505838]);
jms_response_time20150206184935.push([new Date(3948 + offset), 0.369667, 219.364885, 1.5749583012224948, 0.437801]);
jms_response_time20150206184935.push([new Date(5133 + offset), 0.343574, 219.364885, 1.358425526858214, 0.601402]);
jms_response_time20150206184935.push([new Date(6347 + offset), 0.321262, 219.364885, 1.2026826015744572, 0.478834]);
jms_response_time20150206184935.push([new Date(7514 + offset), 0.27409, 219.364885, 1.1441235868926132, 3.774246]);
jms_response_time20150206184935.push([new Date(8769 + offset), 0.27409, 250.010894, 1.0966112883968626, 0.588543]);
jms_response_time20150206184935.push([new Date(9931 + offset), 0.27409, 250.010894, 1.0256921648729103, 0.720565]);
jms_response_time20150206184935.push([new Date(11204 + offset), 0.237231, 250.010894, 0.9799816589750968, 0.485768]);
jms_response_time20150206184935.push([new Date(12364 + offset), 0.218521, 250.010894, 0.9341491530401789, 0.553603]);
jms_response_time20150206184935.push([new Date(13520 + offset), 0.218521, 250.010894, 0.8982657269383338, 0.506586]);
jms_response_time20150206184935.push([new Date(14683 + offset), 0.203888, 250.010894, 0.8700018399999992, 0.493659]);
jms_response_time20150206184935.push([new Date(15923 + offset), 0.203888, 250.010894, 0.8512799292940898, 0.498056]);
jms_response_time20150206184935.push([new Date(17081 + offset), 0.203888, 250.010894, 0.8325209182031849, 0.485108]);
jms_response_time20150206184935.push([new Date(18240 + offset), 0.203888, 250.010894, 0.816254706391315, 0.575176]);
jms_response_time20150206184935.push([new Date(19420 + offset), 0.203888, 250.010894, 0.80339655259794, 0.488276]);
jms_response_time20150206184935.push([new Date(20574 + offset), 0.203888, 250.010894, 0.7916666080058815, 0.504035]);
jms_response_time20150206184935.push([new Date(21810 + offset), 0.189216, 250.010894, 0.784493082020966, 0.486507]);
jms_response_time20150206184935.push([new Date(22967 + offset), 0.189216, 250.010894, 0.7761483557049298, 0.462888]);
jms_response_time20150206184935.push([new Date(24144 + offset), 0.189216, 250.010894, 0.7747507542890008, 0.341878]);
jms_response_time20150206184935.push([new Date(25399 + offset), 0.189216, 250.010894, 0.7725164870033949, 0.506459]);
jms_response_time20150206184935.push([new Date(26565 + offset), 0.189216, 250.010894, 0.7672224161621006, 0.459863]);
jms_response_time20150206184935.push([new Date(27761 + offset), 0.189216, 250.010894, 0.7661195449870648, 0.49815]);
jms_response_time20150206184935.push([new Date(28943 + offset), 0.189216, 250.010894, 0.7665174637753767, 0.489894]);
jms_response_time20150206184935.push([new Date(30167 + offset), 0.189216, 250.010894, 0.7660981759222094, 0.484415]);
jms_response_time20150206184935.push([new Date(31370 + offset), 0.189216, 250.010894, 0.766670992266577, 0.497162]);
jms_response_time20150206184935.push([new Date(32615 + offset), 0.189216, 250.010894, 0.7634648584947313, 0.744061]);
jms_response_time20150206184935.push([new Date(33772 + offset), 0.189216, 250.010894, 0.7590470750223911, 0.439498]);
jms_response_time20150206184935.push([new Date(34933 + offset), 0.189216, 250.010894, 0.7559685439101769, 0.4962]);
jms_response_time20150206184935.push([new Date(36091 + offset), 0.189216, 250.010894, 0.7520591038470702, 0.513778]);
jms_response_time20150206184935.push([new Date(37282 + offset), 0.189216, 250.010894, 0.7546103643202191, 0.408191]);
jms_response_time20150206184935.push([new Date(38548 + offset), 0.189216, 250.010894, 0.7562324605560334, 0.518596]);
jms_response_time20150206184935.push([new Date(39709 + offset), 0.175408, 250.010894, 0.753075874025585, 0.473243]);
jms_response_time20150206184935.push([new Date(40894 + offset), 0.175408, 250.010894, 0.752864785615276, 0.501709]);
jms_response_time20150206184935.push([new Date(42145 + offset), 0.175408, 250.010894, 0.7537658741118819, 0.465026]);
jms_response_time20150206184935.push([new Date(43345 + offset), 0.175408, 250.010894, 0.7541004857542849, 0.503345]);
jms_response_time20150206184935.push([new Date(44610 + offset), 0.175408, 262.749316, 0.7548742487575334, 0.410616]);
jms_response_time20150206184935.push([new Date(45834 + offset), 0.175408, 262.749316, 0.7552230784715458, 0.490482]);
jms_response_time20150206184935.push([new Date(47034 + offset), 0.175408, 262.749316, 0.7542004346216289, 0.470975]);
jms_response_time20150206184935.push([new Date(48192 + offset), 0.175408, 262.749316, 0.7517899959603138, 0.539201]);
jms_response_time20150206184935.push([new Date(49354 + offset), 0.175408, 262.749316, 0.7497943008212496, 0.504436]);
jms_response_time20150206184935.push([new Date(50516 + offset), 0.175408, 262.749316, 0.7483551853831832, 0.441358]);
jms_response_time20150206184935.push([new Date(51680 + offset), 0.175408, 262.749316, 0.7456058163538412, 0.496532]);
jms_response_time20150206184935.push([new Date(52914 + offset), 0.175408, 262.749316, 0.7463719544686249, 0.469323]);
jms_response_time20150206184935.push([new Date(54132 + offset), 0.175408, 262.749316, 0.7475962478446678, 0.432327]);
jms_response_time20150206184935.push([new Date(55438 + offset), 0.175408, 262.749316, 0.7505461345803822, 0.486975]);
jms_response_time20150206184935.push([new Date(56595 + offset), 0.175408, 262.749316, 0.7498747336001591, 0.246381]);
jms_response_time20150206184935.push([new Date(57807 + offset), 0.175408, 262.749316, 0.7500151013527144, 0.804133]);
jms_response_time20150206184935.push([new Date(59066 + offset), 0.175408, 262.749316, 0.7513911141048005, 0.504061]);
jms_response_time20150206184935.push([new Date(60000 + offset), 0.175408, 262.749316, 0.752526793330891, 0.484277]);
| PerfCake/Demos | DevConf2015/sample-results/jms-threads-gc/data/jms_response_time20150206184935.js | JavaScript | apache-2.0 | 6,033 |
/*
* jQuery - New Wave Javascript
*
* Copyright (c) 2006 John Resig (jquery.com)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* $Date: 2006-10-27 23:14:48 -0400 (Fri, 27 Oct 2006) $
* $Rev: 509 $
*/
// Global undefined variable
window.undefined = window.undefined;
function jQuery(a,c) {
// Shortcut for document ready (because $(document).each() is silly)
if ( a && a.constructor == Function && jQuery.fn.ready )
return jQuery(document).ready(a);
// Make sure that a selection was provided
a = a || jQuery.context || document;
// Watch for when a jQuery object is passed as the selector
if ( a.jquery )
return $( jQuery.merge( a, [] ) );
// Watch for when a jQuery object is passed at the context
if ( c && c.jquery )
return $( c ).find(a);
// If the context is global, return a new object
if ( window == this )
return new jQuery(a,c);
// Handle HTML strings
var m = /^[^<]*(<.+>)[^>]*$/.exec(a);
if ( m ) a = jQuery.clean( [ m[1] ] );
// Watch for when an array is passed in
this.get( a.constructor == Array || a.length && !a.nodeType && a[0] != undefined && a[0].nodeType ?
// Assume that it is an array of DOM Elements
jQuery.merge( a, [] ) :
// Find the matching elements and save them for later
jQuery.find( a, c ) );
// See if an extra function was provided
var fn = arguments[ arguments.length - 1 ];
// If so, execute it in context
if ( fn && fn.constructor == Function )
this.each(fn);
}
// Map over the $ in case of overwrite
if ( $ )
jQuery._$ = $;
// Map the jQuery namespace to the '$' one
var $ = jQuery;
jQuery.fn = jQuery.prototype = {
jquery: "$Rev: 509 $",
size: function() {
return this.length;
},
get: function( num ) {
// Watch for when an array (of elements) is passed in
if ( num && num.constructor == Array ) {
// Use a tricky hack to make the jQuery object
// look and feel like an array
this.length = 0;
[].push.apply( this, num );
return this;
} else
return num == undefined ?
// Return a 'clean' array
jQuery.map( this, function(a){ return a } ) :
// Return just the object
this[num];
},
each: function( fn, args ) {
return jQuery.each( this, fn, args );
},
index: function( obj ) {
var pos = -1;
this.each(function(i){
if ( this == obj ) pos = i;
});
return pos;
},
attr: function( key, value, type ) {
// Check to see if we're setting style values
return key.constructor != String || value != undefined ?
this.each(function(){
// See if we're setting a hash of styles
if ( value == undefined )
// Set all the styles
for ( var prop in key )
jQuery.attr(
type ? this.style : this,
prop, key[prop]
);
// See if we're setting a single key/value style
else
jQuery.attr(
type ? this.style : this,
key, value
);
}) :
// Look for the case where we're accessing a style value
jQuery[ type || "attr" ]( this[0], key );
},
css: function( key, value ) {
return this.attr( key, value, "curCSS" );
},
text: function(e) {
e = e || this;
var t = "";
for ( var j = 0; j < e.length; j++ ) {
var r = e[j].childNodes;
for ( var i = 0; i < r.length; i++ )
t += r[i].nodeType != 1 ?
r[i].nodeValue : jQuery.fn.text([ r[i] ]);
}
return t;
},
wrap: function() {
// The elements to wrap the target around
var a = jQuery.clean(arguments);
// Wrap each of the matched elements individually
return this.each(function(){
// Clone the structure that we're using to wrap
var b = a[0].cloneNode(true);
// Insert it before the element to be wrapped
this.parentNode.insertBefore( b, this );
// Find he deepest point in the wrap structure
while ( b.firstChild )
b = b.firstChild;
// Move the matched element to within the wrap structure
b.appendChild( this );
});
},
append: function() {
return this.domManip(arguments, true, 1, function(a){
this.appendChild( a );
});
},
prepend: function() {
return this.domManip(arguments, true, -1, function(a){
this.insertBefore( a, this.firstChild );
});
},
before: function() {
return this.domManip(arguments, false, 1, function(a){
this.parentNode.insertBefore( a, this );
});
},
after: function() {
return this.domManip(arguments, false, -1, function(a){
this.parentNode.insertBefore( a, this.nextSibling );
});
},
end: function() {
return this.get( this.stack.pop() );
},
find: function(t) {
return this.pushStack( jQuery.map( this, function(a){
return jQuery.find(t,a);
}), arguments );
},
clone: function(deep) {
return this.pushStack( jQuery.map( this, function(a){
return a.cloneNode( deep != undefined ? deep : true );
}), arguments );
},
filter: function(t) {
return this.pushStack(
t.constructor == Array &&
jQuery.map(this,function(a){
for ( var i = 0; i < t.length; i++ )
if ( jQuery.filter(t[i],[a]).r.length )
return a;
}) ||
t.constructor == Boolean &&
( t ? this.get() : [] ) ||
t.constructor == Function &&
jQuery.grep( this, t ) ||
jQuery.filter(t,this).r, arguments );
},
not: function(t) {
return this.pushStack( t.constructor == String ?
jQuery.filter(t,this,false).r :
jQuery.grep(this,function(a){ return a != t; }), arguments );
},
add: function(t) {
return this.pushStack( jQuery.merge( this, t.constructor == String ?
jQuery.find(t) : t.constructor == Array ? t : [t] ), arguments );
},
is: function(expr) {
return expr ? jQuery.filter(expr,this).r.length > 0 : this.length > 0;
},
domManip: function(args, table, dir, fn){
var clone = this.size() > 1;
var a = jQuery.clean(args);
return this.each(function(){
var obj = this;
if ( table && this.nodeName == "TABLE" && a[0].nodeName != "THEAD" ) {
var tbody = this.getElementsByTagName("tbody");
if ( !tbody.length ) {
obj = document.createElement("tbody");
this.appendChild( obj );
} else
obj = tbody[0];
}
for ( var i = ( dir < 0 ? a.length - 1 : 0 );
i != ( dir < 0 ? dir : a.length ); i += dir ) {
fn.apply( obj, [ clone ? a[i].cloneNode(true) : a[i] ] );
}
});
},
pushStack: function(a,args) {
var fn = args && args[args.length-1];
if ( !fn || fn.constructor != Function ) {
if ( !this.stack ) this.stack = [];
this.stack.push( this.get() );
this.get( a );
} else {
var old = this.get();
this.get( a );
if ( fn.constructor == Function )
return this.each( fn );
this.get( old );
}
return this;
}
};
jQuery.extend = jQuery.fn.extend = function(obj,prop) {
if ( !prop ) { prop = obj; obj = this; }
for ( var i in prop ) obj[i] = prop[i];
return obj;
};
jQuery.extend({
init: function(){
jQuery.initDone = true;
jQuery.each( jQuery.macros.axis, function(i,n){
jQuery.fn[ i ] = function(a) {
var ret = jQuery.map(this,n);
if ( a && a.constructor == String )
ret = jQuery.filter(a,ret).r;
return this.pushStack( ret, arguments );
};
});
jQuery.each( jQuery.macros.to, function(i,n){
jQuery.fn[ i ] = function(){
var a = arguments;
return this.each(function(){
for ( var j = 0; j < a.length; j++ )
$(a[j])[n]( this );
});
};
});
jQuery.each( jQuery.macros.each, function(i,n){
jQuery.fn[ i ] = function() {
return this.each( n, arguments );
};
});
jQuery.each( jQuery.macros.filter, function(i,n){
jQuery.fn[ n ] = function(num,fn) {
return this.filter( ":" + n + "(" + num + ")", fn );
};
});
jQuery.each( jQuery.macros.attr, function(i,n){
n = n || i;
jQuery.fn[ i ] = function(h) {
return h == undefined ?
this.length ? this[0][n] : null :
this.attr( n, h );
};
});
jQuery.each( jQuery.macros.css, function(i,n){
jQuery.fn[ n ] = function(h) {
return h == undefined ?
( this.length ? jQuery.css( this[0], n ) : null ) :
this.css( n, h );
};
});
},
each: function( obj, fn, args ) {
if ( obj.length == undefined )
for ( var i in obj )
fn.apply( obj[i], args || [i, obj[i]] );
else
for ( var i = 0; i < obj.length; i++ )
fn.apply( obj[i], args || [i, obj[i]] );
return obj;
},
className: {
add: function(o,c){
if (jQuery.className.has(o,c)) return;
o.className += ( o.className ? " " : "" ) + c;
},
remove: function(o,c){
o.className = !c ? "" :
o.className.replace(
new RegExp("(^|\\s*\\b[^-])"+c+"($|\\b(?=[^-]))", "g"), "");
},
has: function(e,a) {
if ( e.className != undefined )
e = e.className;
return new RegExp("(^|\\s)" + a + "(\\s|$)").test(e);
}
},
swap: function(e,o,f) {
for ( var i in o ) {
e.style["old"+i] = e.style[i];
e.style[i] = o[i];
}
f.apply( e, [] );
for ( var i in o )
e.style[i] = e.style["old"+i];
},
css: function(e,p) {
if ( p == "height" || p == "width" ) {
var old = {}, oHeight, oWidth, d = ["Top","Bottom","Right","Left"];
for ( var i in d ) {
old["padding" + d[i]] = 0;
old["border" + d[i] + "Width"] = 0;
}
jQuery.swap( e, old, function() {
if (jQuery.css(e,"display") != "none") {
oHeight = e.offsetHeight;
oWidth = e.offsetWidth;
} else {
e = $(e.cloneNode(true)).css({
visibility: "hidden", position: "absolute", display: "block"
}).prependTo("body")[0];
oHeight = e.clientHeight;
oWidth = e.clientWidth;
e.parentNode.removeChild(e);
}
});
return p == "height" ? oHeight : oWidth;
} else if ( p == "opacity" && jQuery.browser.msie )
return parseFloat( jQuery.curCSS(e,"filter").replace(/[^0-9.]/,"") ) || 1;
return jQuery.curCSS( e, p );
},
curCSS: function(elem, prop, force) {
var ret;
if (!force && elem.style[prop]) {
ret = elem.style[prop];
} else if (elem.currentStyle) {
var newProp = prop.replace(/\-(\w)/g,function(m,c){return c.toUpperCase()});
ret = elem.currentStyle[prop] || elem.currentStyle[newProp];
} else if (document.defaultView && document.defaultView.getComputedStyle) {
prop = prop.replace(/([A-Z])/g,"-$1").toLowerCase();
var cur = document.defaultView.getComputedStyle(elem, null);
if ( cur )
ret = cur.getPropertyValue(prop);
else if ( prop == 'display' )
ret = 'none';
else
jQuery.swap(elem, { display: 'block' }, function() {
ret = document.defaultView.getComputedStyle(this,null).getPropertyValue(prop);
});
}
return ret;
},
clean: function(a) {
var r = [];
for ( var i = 0; i < a.length; i++ ) {
if ( a[i].constructor == String ) {
var table = "";
if ( !a[i].indexOf("<thead") || !a[i].indexOf("<tbody") ) {
table = "thead";
a[i] = "<table>" + a[i] + "</table>";
} else if ( !a[i].indexOf("<tr") ) {
table = "tr";
a[i] = "<table>" + a[i] + "</table>";
} else if ( !a[i].indexOf("<td") || !a[i].indexOf("<th") ) {
table = "td";
a[i] = "<table><tbody><tr>" + a[i] + "</tr></tbody></table>";
}
var div = document.createElement("div");
div.innerHTML = a[i];
if ( table ) {
div = div.firstChild;
if ( table != "thead" ) div = div.firstChild;
if ( table == "td" ) div = div.firstChild;
}
for ( var j = 0; j < div.childNodes.length; j++ )
r.push( div.childNodes[j] );
} else if ( a[i].jquery || a[i].length && !a[i].nodeType )
for ( var k = 0; k < a[i].length; k++ )
r.push( a[i][k] );
else if ( a[i] !== null )
r.push( a[i].nodeType ? a[i] : document.createTextNode(a[i].toString()) );
}
return r;
},
expr: {
"": "m[2]== '*'||a.nodeName.toUpperCase()==m[2].toUpperCase()",
"#": "a.getAttribute('id')&&a.getAttribute('id')==m[2]",
":": {
// Position Checks
lt: "i<m[3]-0",
gt: "i>m[3]-0",
nth: "m[3]-0==i",
eq: "m[3]-0==i",
first: "i==0",
last: "i==r.length-1",
even: "i%2==0",
odd: "i%2",
// Child Checks
"first-child": "jQuery.sibling(a,0).cur",
"last-child": "jQuery.sibling(a,0).last",
"only-child": "jQuery.sibling(a).length==1",
// Parent Checks
parent: "a.childNodes.length",
empty: "!a.childNodes.length",
// Text Check
contains: "(a.innerText||a.innerHTML).indexOf(m[3])>=0",
// Visibility
visible: "a.type!='hidden'&&jQuery.css(a,'display')!='none'&&jQuery.css(a,'visibility')!='hidden'",
hidden: "a.type=='hidden'||jQuery.css(a,'display')=='none'||jQuery.css(a,'visibility')=='hidden'",
// Form elements
enabled: "!a.disabled",
disabled: "a.disabled",
checked: "a.checked",
selected: "a.selected"
},
".": "jQuery.className.has(a,m[2])",
"@": {
"=": "z==m[4]",
"!=": "z!=m[4]",
"^=": "!z.indexOf(m[4])",
"$=": "z.substr(z.length - m[4].length,m[4].length)==m[4]",
"*=": "z.indexOf(m[4])>=0",
"": "z"
},
"[": "jQuery.find(m[2],a).length"
},
token: [
"\\.\\.|/\\.\\.", "a.parentNode",
">|/", "jQuery.sibling(a.firstChild)",
"\\+", "jQuery.sibling(a).next",
"~", function(a){
var r = [];
var s = jQuery.sibling(a);
if ( s.n > 0 )
for ( var i = s.n; i < s.length; i++ )
r.push( s[i] );
return r;
}
],
find: function( t, context ) {
// Make sure that the context is a DOM Element
if ( context && context.nodeType == undefined )
context = null;
// Set the correct context (if none is provided)
context = context || jQuery.context || document;
if ( t.constructor != String ) return [t];
if ( !t.indexOf("//") ) {
context = context.documentElement;
t = t.substr(2,t.length);
} else if ( !t.indexOf("/") ) {
context = context.documentElement;
t = t.substr(1,t.length);
// FIX Assume the root element is right :(
if ( t.indexOf("/") >= 1 )
t = t.substr(t.indexOf("/"),t.length);
}
var ret = [context];
var done = [];
var last = null;
while ( t.length > 0 && last != t ) {
var r = [];
last = t;
t = jQuery.trim(t).replace( /^\/\//i, "" );
var foundToken = false;
for ( var i = 0; i < jQuery.token.length; i += 2 ) {
var re = new RegExp("^(" + jQuery.token[i] + ")");
var m = re.exec(t);
if ( m ) {
r = ret = jQuery.map( ret, jQuery.token[i+1] );
t = jQuery.trim( t.replace( re, "" ) );
foundToken = true;
}
}
if ( !foundToken ) {
if ( !t.indexOf(",") || !t.indexOf("|") ) {
if ( ret[0] == context ) ret.shift();
done = jQuery.merge( done, ret );
r = ret = [context];
t = " " + t.substr(1,t.length);
} else {
var re2 = /^([#.]?)([a-z0-9\\*_-]*)/i;
var m = re2.exec(t);
if ( m[1] == "#" ) {
// Ummm, should make this work in all XML docs
var oid = document.getElementById(m[2]);
r = ret = oid ? [oid] : [];
t = t.replace( re2, "" );
} else {
if ( !m[2] || m[1] == "." ) m[2] = "*";
for ( var i = 0; i < ret.length; i++ )
r = jQuery.merge( r,
m[2] == "*" ?
jQuery.getAll(ret[i]) :
ret[i].getElementsByTagName(m[2])
);
}
}
}
if ( t ) {
var val = jQuery.filter(t,r);
ret = r = val.r;
t = jQuery.trim(val.t);
}
}
if ( ret && ret[0] == context ) ret.shift();
done = jQuery.merge( done, ret );
return done;
},
getAll: function(o,r) {
r = r || [];
var s = o.childNodes;
for ( var i = 0; i < s.length; i++ )
if ( s[i].nodeType == 1 ) {
r.push( s[i] );
jQuery.getAll( s[i], r );
}
return r;
},
attr: function(elem, name, value){
var fix = {
"for": "htmlFor",
"class": "className",
"float": "cssFloat",
innerHTML: "innerHTML",
className: "className"
};
if ( fix[name] ) {
if ( value != undefined ) elem[fix[name]] = value;
return elem[fix[name]];
} else if ( elem.getAttribute ) {
if ( value != undefined ) elem.setAttribute( name, value );
return elem.getAttribute( name, 2 );
} else {
name = name.replace(/-([a-z])/ig,function(z,b){return b.toUpperCase();});
if ( value != undefined ) elem[name] = value;
return elem[name];
}
},
// The regular expressions that power the parsing engine
parse: [
// Match: [@value='test'], [@foo]
[ "\\[ *(@)S *([!*$^=]*) *Q\\]", 1 ],
// Match: [div], [div p]
[ "(\\[)Q\\]", 0 ],
// Match: :contains('foo')
[ "(:)S\\(Q\\)", 0 ],
// Match: :even, :last-chlid
[ "([:.#]*)S", 0 ]
],
filter: function(t,r,not) {
// Figure out if we're doing regular, or inverse, filtering
var g = not !== false ? jQuery.grep :
function(a,f) {return jQuery.grep(a,f,true);};
while ( t && /^[a-z[({<*:.#]/i.test(t) ) {
var p = jQuery.parse;
for ( var i = 0; i < p.length; i++ ) {
var re = new RegExp( "^" + p[i][0]
// Look for a string-like sequence
.replace( 'S', "([a-z*_-][a-z0-9_-]*)" )
// Look for something (optionally) enclosed with quotes
.replace( 'Q', " *'?\"?([^'\"]*?)'?\"? *" ), "i" );
var m = re.exec( t );
if ( m ) {
// Re-organize the match
if ( p[i][1] )
m = ["", m[1], m[3], m[2], m[4]];
// Remove what we just matched
t = t.replace( re, "" );
break;
}
}
// :not() is a special case that can be optomized by
// keeping it out of the expression list
if ( m[1] == ":" && m[2] == "not" )
r = jQuery.filter(m[3],r,false).r;
// Otherwise, find the expression to execute
else {
var f = jQuery.expr[m[1]];
if ( f.constructor != String )
f = jQuery.expr[m[1]][m[2]];
// Build a custom macro to enclose it
eval("f = function(a,i){" +
( m[1] == "@" ? "z=jQuery.attr(a,m[3]);" : "" ) +
"return " + f + "}");
// Execute it against the current filter
r = g( r, f );
}
}
// Return an array of filtered elements (r)
// and the modified expression string (t)
return { r: r, t: t };
},
trim: function(t){
return t.replace(/^\s+|\s+$/g, "");
},
parents: function( elem ){
var matched = [];
var cur = elem.parentNode;
while ( cur && cur != document ) {
matched.push( cur );
cur = cur.parentNode;
}
return matched;
},
sibling: function(elem, pos, not) {
var elems = [];
var siblings = elem.parentNode.childNodes;
for ( var i = 0; i < siblings.length; i++ ) {
if ( not === true && siblings[i] == elem ) continue;
if ( siblings[i].nodeType == 1 )
elems.push( siblings[i] );
if ( siblings[i] == elem )
elems.n = elems.length - 1;
}
return jQuery.extend( elems, {
last: elems.n == elems.length - 1,
cur: pos == "even" && elems.n % 2 == 0 || pos == "odd" && elems.n % 2 || elems[pos] == elem,
prev: elems[elems.n - 1],
next: elems[elems.n + 1]
});
},
merge: function(first, second) {
var result = [];
// Move b over to the new array (this helps to avoid
// StaticNodeList instances)
for ( var k = 0; k < first.length; k++ )
result[k] = first[k];
// Now check for duplicates between a and b and only
// add the unique items
for ( var i = 0; i < second.length; i++ ) {
var noCollision = true;
// The collision-checking process
for ( var j = 0; j < first.length; j++ )
if ( second[i] == first[j] )
noCollision = false;
// If the item is unique, add it
if ( noCollision )
result.push( second[i] );
}
return result;
},
grep: function(elems, fn, inv) {
// If a string is passed in for the function, make a function
// for it (a handy shortcut)
if ( fn.constructor == String )
fn = new Function("a","i","return " + fn);
var result = [];
// Go through the array, only saving the items
// that pass the validator function
for ( var i = 0; i < elems.length; i++ )
if ( !inv && fn(elems[i],i) || inv && !fn(elems[i],i) )
result.push( elems[i] );
return result;
},
map: function(elems, fn) {
// If a string is passed in for the function, make a function
// for it (a handy shortcut)
if ( fn.constructor == String )
fn = new Function("a","return " + fn);
var result = [];
// Go through the array, translating each of the items to their
// new value (or values).
for ( var i = 0; i < elems.length; i++ ) {
var val = fn(elems[i],i);
if ( val !== null && val != undefined ) {
if ( val.constructor != Array ) val = [val];
result = jQuery.merge( result, val );
}
}
return result;
},
/*
* A number of helper functions used for managing events.
* Many of the ideas behind this code orignated from Dean Edwards' addEvent library.
*/
event: {
// Bind an event to an element
// Original by Dean Edwards
add: function(element, type, handler) {
// For whatever reason, IE has trouble passing the window object
// around, causing it to be cloned in the process
if ( jQuery.browser.msie && element.setInterval != undefined )
element = window;
// Make sure that the function being executed has a unique ID
if ( !handler.guid )
handler.guid = this.guid++;
// Init the element's event structure
if (!element.events)
element.events = {};
// Get the current list of functions bound to this event
var handlers = element.events[type];
// If it hasn't been initialized yet
if (!handlers) {
// Init the event handler queue
handlers = element.events[type] = {};
// Remember an existing handler, if it's already there
if (element["on" + type])
handlers[0] = element["on" + type];
}
// Add the function to the element's handler list
handlers[handler.guid] = handler;
// And bind the global event handler to the element
element["on" + type] = this.handle;
// Remember the function in a global list (for triggering)
if (!this.global[type])
this.global[type] = [];
this.global[type].push( element );
},
guid: 1,
global: {},
// Detach an event or set of events from an element
remove: function(element, type, handler) {
if (element.events)
if (type && element.events[type])
if ( handler )
delete element.events[type][handler.guid];
else
for ( var i in element.events[type] )
delete element.events[type][i];
else
for ( var j in element.events )
this.remove( element, j );
},
trigger: function(type,data,element) {
// Touch up the incoming data
data = data || [];
// Handle a global trigger
if ( !element ) {
var g = this.global[type];
if ( g )
for ( var i = 0; i < g.length; i++ )
this.trigger( type, data, g[i] );
// Handle triggering a single element
} else if ( element["on" + type] ) {
// Pass along a fake event
data.unshift( this.fix({ type: type, target: element }) );
// Trigger the event
element["on" + type].apply( element, data );
}
},
handle: function(event) {
if ( typeof jQuery == "undefined" ) return;
event = event || jQuery.event.fix( window.event );
// If no correct event was found, fail
if ( !event ) return;
var returnValue = true;
var c = this.events[event.type];
for ( var j in c ) {
if ( c[j].apply( this, [event] ) === false ) {
event.preventDefault();
event.stopPropagation();
returnValue = false;
}
}
return returnValue;
},
fix: function(event) {
if ( event ) {
event.preventDefault = function() {
this.returnValue = false;
};
event.stopPropagation = function() {
this.cancelBubble = true;
};
}
return event;
}
}
});
new function() {
var b = navigator.userAgent.toLowerCase();
// Figure out what browser is being used
jQuery.browser = {
safari: /webkit/.test(b),
opera: /opera/.test(b),
msie: /msie/.test(b) && !/opera/.test(b),
mozilla: /mozilla/.test(b) && !/compatible/.test(b)
};
// Check to see if the W3C box model is being used
jQuery.boxModel = !jQuery.browser.msie || document.compatMode == "CSS1Compat";
};
jQuery.macros = {
to: {
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after"
},
css: "width,height,top,left,position,float,overflow,color,background".split(","),
filter: [ "eq", "lt", "gt", "contains" ],
attr: {
val: "value",
html: "innerHTML",
id: null,
title: null,
name: null,
href: null,
src: null,
rel: null
},
axis: {
parent: "a.parentNode",
ancestors: jQuery.parents,
parents: jQuery.parents,
next: "jQuery.sibling(a).next",
prev: "jQuery.sibling(a).prev",
siblings: jQuery.sibling,
children: "a.childNodes"
},
each: {
removeAttr: function( key ) {
this.removeAttribute( key );
},
show: function(){
this.style.display = this.oldblock ? this.oldblock : "";
if ( jQuery.css(this,"display") == "none" )
this.style.display = "block";
},
hide: function(){
this.oldblock = this.oldblock || jQuery.css(this,"display");
if ( this.oldblock == "none" )
this.oldblock = "block";
this.style.display = "none";
},
toggle: function(){
$(this)[ $(this).is(":hidden") ? "show" : "hide" ].apply( $(this), arguments );
},
addClass: function(c){
jQuery.className.add(this,c);
},
removeClass: function(c){
jQuery.className.remove(this,c);
},
toggleClass: function( c ){
jQuery.className[ jQuery.className.has(this,c) ? "remove" : "add" ](this,c);
},
remove: function(a){
if ( !a || jQuery.filter( [this], a ).r )
this.parentNode.removeChild( this );
},
empty: function(){
while ( this.firstChild )
this.removeChild( this.firstChild );
},
bind: function( type, fn ) {
if ( fn.constructor == String )
fn = new Function("e", ( !fn.indexOf(".") ? "$(this)" : "return " ) + fn);
jQuery.event.add( this, type, fn );
},
unbind: function( type, fn ) {
jQuery.event.remove( this, type, fn );
},
trigger: function( type, data ) {
jQuery.event.trigger( type, data, this );
}
}
};
jQuery.init();jQuery.fn.extend({
// We're overriding the old toggle function, so
// remember it for later
_toggle: jQuery.fn.toggle,
toggle: function(a,b) {
// If two functions are passed in, we're
// toggling on a click
return a && b && a.constructor == Function && b.constructor == Function ? this.click(function(e){
// Figure out which function to execute
this.last = this.last == a ? b : a;
// Make sure that clicks stop
e.preventDefault();
// and execute the function
return this.last.apply( this, [e] ) || false;
}) :
// Otherwise, execute the old toggle function
this._toggle.apply( this, arguments );
},
hover: function(f,g) {
// A private function for haandling mouse 'hovering'
function handleHover(e) {
// Check if mouse(over|out) are still within the same parent element
var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
// Traverse up the tree
while ( p && p != this ) p = p.parentNode;
// If we actually just moused on to a sub-element, ignore it
if ( p == this ) return false;
// Execute the right function
return (e.type == "mouseover" ? f : g).apply(this, [e]);
}
// Bind the function to the two event listeners
return this.mouseover(handleHover).mouseout(handleHover);
},
ready: function(f) {
// If the DOM is already ready
if ( jQuery.isReady )
// Execute the function immediately
f.apply( document );
// Otherwise, remember the function for later
else {
// Add the function to the wait list
jQuery.readyList.push( f );
}
return this;
}
});
jQuery.extend({
/*
* All the code that makes DOM Ready work nicely.
*/
isReady: false,
readyList: [],
// Handle when the DOM is ready
ready: function() {
// Make sure that the DOM is not already loaded
if ( !jQuery.isReady ) {
// Remember that the DOM is ready
jQuery.isReady = true;
// If there are functions bound, to execute
if ( jQuery.readyList ) {
// Execute all of them
for ( var i = 0; i < jQuery.readyList.length; i++ )
jQuery.readyList[i].apply( document );
// Reset the list of functions
jQuery.readyList = null;
}
}
}
});
new function(){
var e = ("blur,focus,load,resize,scroll,unload,click,dblclick," +
"mousedown,mouseup,mousemove,mouseover,mouseout,change,reset,select," +
"submit,keydown,keypress,keyup,error").split(",");
// Go through all the event names, but make sure that
// it is enclosed properly
for ( var i = 0; i < e.length; i++ ) new function(){
var o = e[i];
// Handle event binding
jQuery.fn[o] = function(f){
return f ? this.bind(o, f) : this.trigger(o);
};
// Handle event unbinding
jQuery.fn["un"+o] = function(f){ return this.unbind(o, f); };
// Finally, handle events that only fire once
jQuery.fn["one"+o] = function(f){
// Attach the event listener
return this.each(function(){
var count = 0;
// Add the event
jQuery.event.add( this, o, function(e){
// If this function has already been executed, stop
if ( count++ ) return;
// And execute the bound function
return f.apply(this, [e]);
});
});
};
};
// If Mozilla is used
if ( jQuery.browser.mozilla || jQuery.browser.opera ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", jQuery.ready, false );
// If IE is used, use the excellent hack by Matthias Miller
// http://www.outofhanwell.com/blog/index.php?title=the_window_onload_problem_revisited
} else if ( jQuery.browser.msie ) {
// Only works if you document.write() it
document.write("<scr" + "ipt id=__ie_init defer=true " +
"src=//:><\/script>");
// Use the defer script hack
var script = document.getElementById("__ie_init");
script.onreadystatechange = function() {
if ( this.readyState == "complete" )
jQuery.ready();
};
// Clear from memory
script = null;
// If Safari is used
} else if ( jQuery.browser.safari ) {
// Continually check to see if the document.readyState is valid
jQuery.safariTimer = setInterval(function(){
// loaded and complete are both valid states
if ( document.readyState == "loaded" ||
document.readyState == "complete" ) {
// If either one are found, remove the timer
clearInterval( jQuery.safariTimer );
jQuery.safariTimer = null;
// and execute any waiting functions
jQuery.ready();
}
}, 10);
}
// A fallback to window.onload, that will always work
jQuery.event.add( window, "load", jQuery.ready );
};
jQuery.fn.extend({
// overwrite the old show method
_show: jQuery.fn.show,
show: function(speed,callback){
return speed ? this.animate({
height: "show", width: "show", opacity: "show"
}, speed, callback) : this._show();
},
// Overwrite the old hide method
_hide: jQuery.fn.hide,
hide: function(speed,callback){
return speed ? this.animate({
height: "hide", width: "hide", opacity: "hide"
}, speed, callback) : this._hide();
},
slideDown: function(speed,callback){
return this.animate({height: "show"}, speed, callback);
},
slideUp: function(speed,callback){
return this.animate({height: "hide"}, speed, callback);
},
slideToggle: function(speed,callback){
return this.each(function(){
var state = $(this).is(":hidden") ? "show" : "hide";
$(this).animate({height: state}, speed, callback);
});
},
fadeIn: function(speed,callback){
return this.animate({opacity: "show"}, speed, callback);
},
fadeOut: function(speed,callback){
return this.animate({opacity: "hide"}, speed, callback);
},
fadeTo: function(speed,to,callback){
return this.animate({opacity: to}, speed, callback);
},
animate: function(prop,speed,callback) {
return this.queue(function(){
this.curAnim = prop;
for ( var p in prop ) {
var e = new jQuery.fx( this, jQuery.speed(speed,callback), p );
if ( prop[p].constructor == Number )
e.custom( e.cur(), prop[p] );
else
e[ prop[p] ]( prop );
}
});
},
queue: function(type,fn){
if ( !fn ) {
fn = type;
type = "fx";
}
return this.each(function(){
if ( !this.queue )
this.queue = {};
if ( !this.queue[type] )
this.queue[type] = [];
this.queue[type].push( fn );
if ( this.queue[type].length == 1 )
fn.apply(this);
});
}
});
jQuery.extend({
setAuto: function(e,p) {
if ( e.notAuto ) return;
if ( p == "height" && e.scrollHeight != parseInt(jQuery.curCSS(e,p)) ) return;
if ( p == "width" && e.scrollWidth != parseInt(jQuery.curCSS(e,p)) ) return;
// Remember the original height
var a = e.style[p];
// Figure out the size of the height right now
var o = jQuery.curCSS(e,p,1);
if ( p == "height" && e.scrollHeight != o ||
p == "width" && e.scrollWidth != o ) return;
// Set the height to auto
e.style[p] = e.currentStyle ? "" : "auto";
// See what the size of "auto" is
var n = jQuery.curCSS(e,p,1);
// Revert back to the original size
if ( o != n && n != "auto" ) {
e.style[p] = a;
e.notAuto = true;
}
},
speed: function(s,o) {
o = o || {};
if ( o.constructor == Function )
o = { complete: o };
var ss = { slow: 600, fast: 200 };
o.duration = (s && s.constructor == Number ? s : ss[s]) || 400;
// Queueing
o.oldComplete = o.complete;
o.complete = function(){
jQuery.dequeue(this, "fx");
if ( o.oldComplete && o.oldComplete.constructor == Function )
o.oldComplete.apply( this );
};
return o;
},
queue: {},
dequeue: function(elem,type){
type = type || "fx";
if ( elem.queue && elem.queue[type] ) {
// Remove self
elem.queue[type].shift();
// Get next function
var f = elem.queue[type][0];
if ( f ) f.apply( elem );
}
},
/*
* I originally wrote fx() as a clone of moo.fx and in the process
* of making it small in size the code became illegible to sane
* people. You've been warned.
*/
fx: function( elem, options, prop ){
var z = this;
// The users options
z.o = {
duration: options.duration || 400,
complete: options.complete,
step: options.step
};
// The element
z.el = elem;
// The styles
var y = z.el.style;
// Simple function for setting a style value
z.a = function(){
if ( options.step )
options.step.apply( elem, [ z.now ] );
if ( prop == "opacity" ) {
if (z.now == 1) z.now = 0.9999;
if (window.ActiveXObject)
y.filter = "alpha(opacity=" + z.now*100 + ")";
else
y.opacity = z.now;
// My hate for IE will never die
} else if ( parseInt(z.now) )
y[prop] = parseInt(z.now) + "px";
y.display = "block";
};
// Figure out the maximum number to run to
z.max = function(){
return parseFloat( jQuery.css(z.el,prop) );
};
// Get the current size
z.cur = function(){
var r = parseFloat( jQuery.curCSS(z.el, prop) );
return r && r > -10000 ? r : z.max();
};
// Start an animation from one number to another
z.custom = function(from,to){
z.startTime = (new Date()).getTime();
z.now = from;
z.a();
z.timer = setInterval(function(){
z.step(from, to);
}, 13);
};
// Simple 'show' function
z.show = function( p ){
if ( !z.el.orig ) z.el.orig = {};
// Remember where we started, so that we can go back to it later
z.el.orig[prop] = this.cur();
z.custom( 0, z.el.orig[prop] );
// Stupid IE, look what you made me do
if ( prop != "opacity" )
y[prop] = "1px";
};
// Simple 'hide' function
z.hide = function(){
if ( !z.el.orig ) z.el.orig = {};
// Remember where we started, so that we can go back to it later
z.el.orig[prop] = this.cur();
z.o.hide = true;
// Begin the animation
z.custom(z.el.orig[prop], 0);
};
// IE has trouble with opacity if it does not have layout
if ( jQuery.browser.msie && !z.el.currentStyle.hasLayout )
y.zoom = "1";
// Remember the overflow of the element
if ( !z.el.oldOverlay )
z.el.oldOverflow = jQuery.css( z.el, "overflow" );
// Make sure that nothing sneaks out
y.overflow = "hidden";
// Each step of an animation
z.step = function(firstNum, lastNum){
var t = (new Date()).getTime();
if (t > z.o.duration + z.startTime) {
// Stop the timer
clearInterval(z.timer);
z.timer = null;
z.now = lastNum;
z.a();
z.el.curAnim[ prop ] = true;
var done = true;
for ( var i in z.el.curAnim )
if ( z.el.curAnim[i] !== true )
done = false;
if ( done ) {
// Reset the overflow
y.overflow = z.el.oldOverflow;
// Hide the element if the "hide" operation was done
if ( z.o.hide )
y.display = 'none';
// Reset the property, if the item has been hidden
if ( z.o.hide ) {
for ( var p in z.el.curAnim ) {
y[ p ] = z.el.orig[p] + ( p == "opacity" ? "" : "px" );
// set its height and/or width to auto
if ( p == 'height' || p == 'width' )
jQuery.setAuto( z.el, p );
}
}
}
// If a callback was provided, execute it
if( done && z.o.complete && z.o.complete.constructor == Function )
// Execute the complete function
z.o.complete.apply( z.el );
} else {
// Figure out where in the animation we are and set the number
var p = (t - this.startTime) / z.o.duration;
z.now = ((-Math.cos(p*Math.PI)/2) + 0.5) * (lastNum-firstNum) + firstNum;
// Perform the next step of the animation
z.a();
}
};
}
});
// AJAX Plugin
// Docs Here:
// http://jquery.com/docs/ajax/
jQuery.fn.loadIfModified = function( url, params, callback ) {
this.load( url, params, callback, 1 );
};
jQuery.fn.load = function( url, params, callback, ifModified ) {
if ( url.constructor == Function )
return this.bind("load", url);
callback = callback || function(){};
// Default to a GET request
var type = "GET";
// If the second parameter was provided
if ( params ) {
// If it's a function
if ( params.constructor == Function ) {
// We assume that it's the callback
callback = params;
params = null;
// Otherwise, build a param string
} else {
params = jQuery.param( params );
type = "POST";
}
}
var self = this;
// Request the remote document
jQuery.ajax( type, url, params,function(res, status){
if ( status == "success" || !ifModified && status == "notmodified" ) {
// Inject the HTML into all the matched elements
self.html(res.responseText).each( callback, [res.responseText, status] );
// Execute all the scripts inside of the newly-injected HTML
$("script", self).each(function(){
if ( this.src )
$.getScript( this.src );
else
eval.call( window, this.text || this.textContent || this.innerHTML || "" );
});
} else
callback.apply( self, [res.responseText, status] );
}, ifModified);
return this;
};
// If IE is used, create a wrapper for the XMLHttpRequest object
if ( jQuery.browser.msie )
XMLHttpRequest = function(){
return new ActiveXObject(
navigator.userAgent.indexOf("MSIE 5") >= 0 ?
"Microsoft.XMLHTTP" : "Msxml2.XMLHTTP"
);
};
// Attach a bunch of functions for handling common AJAX events
new function(){
var e = "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess".split(',');
for ( var i = 0; i < e.length; i++ ) new function(){
var o = e[i];
jQuery.fn[o] = function(f){
return this.bind(o, f);
};
};
};
jQuery.extend({
get: function( url, data, callback, type, ifModified ) {
if ( data.constructor == Function ) {
type = callback;
callback = data;
data = null;
}
if ( data ) url += "?" + jQuery.param(data);
// Build and start the HTTP Request
jQuery.ajax( "GET", url, null, function(r, status) {
if ( callback ) callback( jQuery.httpData(r,type), status );
}, ifModified);
},
getIfModified: function( url, data, callback, type ) {
jQuery.get(url, data, callback, type, 1);
},
getScript: function( url, data, callback ) {
jQuery.get(url, data, callback, "script");
},
post: function( url, data, callback, type ) {
// Build and start the HTTP Request
jQuery.ajax( "POST", url, jQuery.param(data), function(r, status) {
if ( callback ) callback( jQuery.httpData(r,type), status );
});
},
// timeout (ms)
timeout: 0,
ajaxTimeout: function(timeout) {
jQuery.timeout = timeout;
},
// Last-Modified header cache for next request
lastModified: {},
ajax: function( type, url, data, ret, ifModified ) {
// If only a single argument was passed in,
// assume that it is a object of key/value pairs
if ( !url ) {
ret = type.complete;
var success = type.success;
var error = type.error;
data = type.data;
url = type.url;
type = type.type;
}
// Watch for a new set of requests
if ( ! jQuery.active++ )
jQuery.event.trigger( "ajaxStart" );
var requestDone = false;
// Create the request object
var xml = new XMLHttpRequest();
// Open the socket
xml.open(type || "GET", url, true);
// Set the correct header, if data is being sent
if ( data )
xml.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// Set the If-Modified-Since header, if ifModified mode.
if ( ifModified )
xml.setRequestHeader("If-Modified-Since",
jQuery.lastModified[url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
// Set header so calling script knows that it's an XMLHttpRequest
xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");
// Make sure the browser sends the right content length
if ( xml.overrideMimeType )
xml.setRequestHeader("Connection", "close");
// Wait for a response to come back
var onreadystatechange = function(istimeout){
// The transfer is complete and the data is available, or the request timed out
if ( xml && (xml.readyState == 4 || istimeout == "timeout") ) {
requestDone = true;
var status = jQuery.httpSuccess( xml ) && istimeout != "timeout" ?
ifModified && jQuery.httpNotModified( xml, url ) ? "notmodified" : "success" : "error";
// Make sure that the request was successful or notmodified
if ( status != "error" ) {
// Cache Last-Modified header, if ifModified mode.
var modRes = xml.getResponseHeader("Last-Modified");
if ( ifModified && modRes ) jQuery.lastModified[url] = modRes;
// If a local callback was specified, fire it
if ( success ) success( xml, status );
// Fire the global callback
jQuery.event.trigger( "ajaxSuccess" );
// Otherwise, the request was not successful
} else {
// If a local callback was specified, fire it
if ( error ) error( xml, status );
// Fire the global callback
jQuery.event.trigger( "ajaxError" );
}
// The request was completed
jQuery.event.trigger( "ajaxComplete" );
// Handle the global AJAX counter
if ( ! --jQuery.active )
jQuery.event.trigger( "ajaxStop" );
// Process result
if ( ret ) ret(xml, status);
// Stop memory leaks
xml.onreadystatechange = function(){};
xml = null;
}
};
xml.onreadystatechange = onreadystatechange;
// Timeout checker
if(jQuery.timeout > 0)
setTimeout(function(){
// Check to see if the request is still happening
if (xml) {
// Cancel the request
xml.abort();
if ( !requestDone ) onreadystatechange( "timeout" );
// Clear from memory
xml = null;
}
}, jQuery.timeout);
// Send the data
xml.send(data);
},
// Counter for holding the number of active queries
active: 0,
// Determines if an XMLHttpRequest was successful or not
httpSuccess: function(r) {
try {
return !r.status && location.protocol == "file:" ||
( r.status >= 200 && r.status < 300 ) || r.status == 304 ||
jQuery.browser.safari && r.status == undefined;
} catch(e){}
return false;
},
// Determines if an XMLHttpRequest returns NotModified
httpNotModified: function(xml, url) {
try {
var xmlRes = xml.getResponseHeader("Last-Modified");
// Firefox always returns 200. check Last-Modified date
return xml.status == 304 || xmlRes == jQuery.lastModified[url] ||
jQuery.browser.safari && xml.status == undefined;
} catch(e){}
return false;
},
// Get the data out of an XMLHttpRequest.
// Return parsed XML if content-type header is "xml" and type is "xml" or omitted,
// otherwise return plain text.
httpData: function(r,type) {
var ct = r.getResponseHeader("content-type");
var data = !type && ct && ct.indexOf("xml") >= 0;
data = type == "xml" || data ? r.responseXML : r.responseText;
// If the type is "script", eval it
if ( type == "script" ) eval.call( window, data );
return data;
},
// Serialize an array of form elements or a set of
// key/values into a query string
param: function(a) {
var s = [];
// If an array was passed in, assume that it is an array
// of form elements
if ( a.constructor == Array ) {
// Serialize the form elements
for ( var i = 0; i < a.length; i++ )
s.push( a[i].name + "=" + encodeURIComponent( a[i].value ) );
// Otherwise, assume that it's an object of key/value pairs
} else {
// Serialize the key/values
for ( var j in a )
s.push( j + "=" + encodeURIComponent( a[j] ) );
}
// Return the resulting serialization
return s.join("&");
}
}); | keil/TbDA | test/jquery1/jquery.js | JavaScript | apache-2.0 | 47,181 |
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// MODULES //
var tape = require( 'tape' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var isPositiveZero = require( '@stdlib/math/base/assert/is-positive-zero' );
var PINF = require( '@stdlib/constants/float64/pinf' );
var NINF = require( '@stdlib/constants/float64/ninf' );
var Float64Array = require( '@stdlib/array/float64' );
var minmaxabs = require( './../lib' );
// TESTS //
tape( 'main export is a function', function test( t ) {
t.ok( true, __filename );
t.strictEqual( typeof minmaxabs, 'function', 'main export is a function' );
t.end();
});
tape( 'the function returns `NaN` for both the minimum and maximum absolute value if provided a `NaN`', function test( t ) {
var v;
v = minmaxabs( NaN, 3.14 );
t.strictEqual( isnan( v[ 0 ] ), true, 'returns NaN' );
t.strictEqual( isnan( v[ 1 ] ), true, 'returns NaN' );
v = minmaxabs( 3.14, NaN );
t.strictEqual( isnan( v[ 0 ] ), true, 'returns NaN' );
t.strictEqual( isnan( v[ 1 ] ), true, 'returns NaN' );
v = minmaxabs( NaN, NaN );
t.strictEqual( isnan( v[ 0 ] ), true, 'returns NaN' );
t.strictEqual( isnan( v[ 1 ] ), true, 'returns NaN' );
v = minmaxabs( NaN );
t.strictEqual( isnan( v[ 0 ] ), true, 'returns NaN' );
t.strictEqual( isnan( v[ 1 ] ), true, 'returns NaN' );
v = minmaxabs( 3.14, 4.2, NaN );
t.strictEqual( isnan( v[ 0 ] ), true, 'returns NaN' );
t.strictEqual( isnan( v[ 1 ] ), true, 'returns NaN' );
v = minmaxabs( NaN, 4.2, NaN );
t.strictEqual( isnan( v[ 0 ] ), true, 'returns NaN' );
t.strictEqual( isnan( v[ 1 ] ), true, 'returns NaN' );
v = minmaxabs( NaN, NaN, NaN );
t.strictEqual( isnan( v[ 0 ] ), true, 'returns NaN' );
t.strictEqual( isnan( v[ 1 ] ), true, 'returns NaN' );
t.end();
});
tape( 'the function returns `Infinity` as the maximum value if provided `-Infinity`', function test( t ) {
var v;
v = minmaxabs( NINF, 3.14 );
t.strictEqual( v[ 0 ], 3.14, 'returns expected value' );
t.strictEqual( v[ 1 ], PINF, 'returns expected value' );
v = minmaxabs( 3.14, NINF );
t.strictEqual( v[ 0 ], 3.14, 'returns expected value' );
t.strictEqual( v[ 1 ], PINF, 'returns expected value' );
v = minmaxabs( NINF );
t.strictEqual( v[ 0 ], PINF, 'returns expected value' );
t.strictEqual( v[ 1 ], PINF, 'returns expected value' );
v = minmaxabs( 3.14, 4.2, NINF );
t.strictEqual( v[ 0 ], 3.14, 'returns exected value' );
t.strictEqual( v[ 1 ], PINF, 'returns expected value' );
t.end();
});
tape( 'the function returns `+Infinity` as the maximum value if provided `+Infinity`', function test( t ) {
var v;
v = minmaxabs( PINF, 3.14 );
t.strictEqual( v[ 0 ], 3.14, 'returns expected value' );
t.strictEqual( v[ 1 ], PINF, 'returns expected value' );
v = minmaxabs( 3.14, PINF );
t.strictEqual( v[ 0 ], 3.14, 'returns expected value' );
t.strictEqual( v[ 1 ], PINF, 'returns expected value' );
v = minmaxabs( PINF );
t.strictEqual( v[ 0 ], PINF, 'returns expected value' );
t.strictEqual( v[ 1 ], PINF, 'returns +infinity' );
v = minmaxabs( 3.14, 4.2, PINF );
t.strictEqual( v[ 0 ], 3.14, 'returns expected value' );
t.strictEqual( v[ 1 ], PINF, 'returns expected value' );
t.end();
});
tape( 'the function returns correctly signed zeros', function test( t ) {
var v;
v = minmaxabs( +0.0, -0.0 );
t.strictEqual( isPositiveZero( v[ 0 ] ), true, 'returns +0' );
t.strictEqual( isPositiveZero( v[ 1 ] ), true, 'returns +0' );
v = minmaxabs( -0.0, +0.0 );
t.strictEqual( isPositiveZero( v[ 0 ] ), true, 'returns +0' );
t.strictEqual( isPositiveZero( v[ 1 ] ), true, 'returns +0' );
v = minmaxabs( -0.0, -0.0 );
t.strictEqual( isPositiveZero( v[ 0 ] ), true, 'returns +0' );
t.strictEqual( isPositiveZero( v[ 1 ] ), true, 'returns +0' );
v = minmaxabs( +0.0, +0.0 );
t.strictEqual( isPositiveZero( v[ 0 ] ), true, 'returns +0' );
t.strictEqual( isPositiveZero( v[ 1 ] ), true, 'returns +0' );
v = minmaxabs( -0.0 );
t.strictEqual( isPositiveZero( v[ 0 ] ), true, 'returns +0' );
t.strictEqual( isPositiveZero( v[ 1 ] ), true, 'returns +0' );
v = minmaxabs( +0.0 );
t.strictEqual( isPositiveZero( v[ 0 ] ), true, 'returns +0' );
t.strictEqual( isPositiveZero( v[ 1 ] ), true, 'returns +0' );
v = minmaxabs( +0.0, -0.0, +0.0 );
t.strictEqual( isPositiveZero( v[ 0 ] ), true, 'returns +0' );
t.strictEqual( isPositiveZero( v[ 1 ] ), true, 'returns +0' );
t.end();
});
tape( 'the function returns the minimum and maximum absolute values', function test( t ) {
var v;
v = minmaxabs( 4.2, 3.14 );
t.strictEqual( v[ 0 ], 3.14, 'returns min value' );
t.strictEqual( v[ 1 ], 4.2, 'returns max value' );
v = minmaxabs( -4.2, 3.14 );
t.strictEqual( v[ 0 ], 3.14, 'returns min value' );
t.strictEqual( v[ 1 ], 4.2, 'returns max value' );
v = minmaxabs( 3.14 );
t.strictEqual( v[ 0 ], 3.14, 'returns min value' );
t.strictEqual( v[ 1 ], 3.14, 'returns max value' );
v = minmaxabs( PINF );
t.strictEqual( v[ 0 ], PINF, 'returns min value' );
t.strictEqual( v[ 1 ], PINF, 'returns max value' );
v = minmaxabs( 4.2, 3.14, -1.0 );
t.strictEqual( v[ 0 ], 1.0, 'returns min value' );
t.strictEqual( v[ 1 ], 4.2, 'returns max value' );
v = minmaxabs( 4.2, 3.14, -1.0, -6.14 );
t.strictEqual( v[ 0 ], 1.0, 'returns min value' );
t.strictEqual( v[ 1 ], 6.14, 'returns max value' );
t.end();
});
tape( 'the function supports providing an output object (array)', function test( t ) {
var out;
var v;
out = [ 0.0, 0.0 ];
v = minmaxabs( out, 4.2, 3.14 );
t.strictEqual( v, out, 'returns output array' );
t.strictEqual( v[ 0 ], 3.14, 'returns min value' );
t.strictEqual( v[ 1 ], 4.2, 'returns max value' );
out = [ 0.0, 0.0 ];
v = minmaxabs( out, -4.2, -3.14 );
t.strictEqual( v, out, 'returns output array' );
t.strictEqual( v[ 0 ], 3.14, 'returns min value' );
t.strictEqual( v[ 1 ], 4.2, 'returns max value' );
out = [ 0.0, 0.0 ];
v = minmaxabs( out, 3.14 );
t.strictEqual( v, out, 'returns output array' );
t.strictEqual( v[ 0 ], 3.14, 'returns min value' );
t.strictEqual( v[ 1 ], 3.14, 'returns max value' );
out = [ 0.0, 0.0 ];
v = minmaxabs( out, PINF );
t.strictEqual( v, out, 'returns output array' );
t.strictEqual( v[ 0 ], PINF, 'returns min value' );
t.strictEqual( v[ 1 ], PINF, 'returns max value' );
out = [ 0.0, 0.0 ];
v = minmaxabs( out, 4.2, 3.14, -1.0 );
t.strictEqual( v, out, 'returns output array' );
t.strictEqual( v[ 0 ], 1.0, 'returns min value' );
t.strictEqual( v[ 1 ], 4.2, 'returns max value' );
out = [ 0.0, 0.0 ];
v = minmaxabs( out, 4.2, 3.14, -1.0, -6.14 );
t.strictEqual( v, out, 'returns output array' );
t.strictEqual( v[ 0 ], 1.0, 'returns min value' );
t.strictEqual( v[ 1 ], 6.14, 'returns max value' );
t.end();
});
tape( 'the function supports providing an output object (typed array)', function test( t ) {
var out;
var v;
out = new Float64Array( 2 );
v = minmaxabs( out, 4.2, 3.14 );
t.strictEqual( v, out, 'returns output array' );
t.strictEqual( v[ 0 ], 3.14, 'returns min value' );
t.strictEqual( v[ 1 ], 4.2, 'returns max value' );
out = new Float64Array( 2 );
v = minmaxabs( out, -4.2, 3.14 );
t.strictEqual( v, out, 'returns output array' );
t.strictEqual( v[ 0 ], 3.14, 'returns min value' );
t.strictEqual( v[ 1 ], 4.2, 'returns max value' );
out = new Float64Array( 2 );
v = minmaxabs( out, 3.14 );
t.strictEqual( v, out, 'returns output array' );
t.strictEqual( v[ 0 ], 3.14, 'returns min value' );
t.strictEqual( v[ 1 ], 3.14, 'returns max value' );
out = new Float64Array( 2 );
v = minmaxabs( out, PINF );
t.strictEqual( v, out, 'returns output array' );
t.strictEqual( v[ 0 ], PINF, 'returns min value' );
t.strictEqual( v[ 1 ], PINF, 'returns max value' );
out = new Float64Array( 2 );
v = minmaxabs( out, 4.2, 3.14, -1.0 );
t.strictEqual( v, out, 'returns output array' );
t.strictEqual( v[ 0 ], 1.0, 'returns min value' );
t.strictEqual( v[ 1 ], 4.2, 'returns max value' );
out = new Float64Array( 2 );
v = minmaxabs( out, 4.2, 3.14, -1.0, -6.14 );
t.strictEqual( v, out, 'returns output array' );
t.strictEqual( v[ 0 ], 1.0, 'returns min value' );
t.strictEqual( v[ 1 ], 6.14, 'returns max value' );
t.end();
});
| stdlib-js/stdlib | lib/node_modules/@stdlib/math/base/special/minmaxabs/test/test.js | JavaScript | apache-2.0 | 8,786 |
/*global QUnit*/
sap.ui.define([
"sap/ui/test/opaQunit",
"./pages/Home",
"./pages/Overview"
], function (opaTest) {
"use strict";
QUnit.module("Home");
opaTest("Should see the homepage displayed", function (Given, When, Then) {
// Arrangements
Given.iStartMyApp({
hash: ""
});
// Assertions
Then.onTheHomePage.iShouldSeeSomeFontTiles();
});
opaTest("Should navigate to SAP icon TNT", function (Given, When, Then) {
// Actions
When.onTheHomePage.iClickOnTheTNTTitleLink();
// Assertions
Then.onTheOverviewPage.iShouldSeeTheTNTFontPage();
});
opaTest("Should be on the Home page when back button is pressed", function (Given, When, Then) {
//Actions
When.onTheOverviewPage.iPressTheNavigationBackButton();
// Assertions
Then.onTheHomePage.iShouldSeeSomeFontTiles();
// Cleanup
Then.iTeardownMyApp();
});
});
| SAP/openui5 | src/sap.m/test/sap/m/demokit/iconExplorer/webapp/test/integration/HomeJourney.js | JavaScript | apache-2.0 | 859 |
define(['backbone', 'collections/players', 'views/player'], function(Backbone, PlayersCollection, PlayerView) {
return Backbone.View.extend({
tagName: 'table',
className: 'table table-striped',
template: _.template($('#players-view').html()),
initialize: function() {
this.collection = new PlayersCollection();
this.listenTo(this.collection, 'reset', this.render);
this.collection.fetch({reset: true});
},
render: function () {
this.$el.html(this.template());
this.$tbody = this.$el.find('tbody');
this.$tbody.empty();
this.collection.each(this.renderOne, this);
return this;
},
renderOne: function (player) {
var view = new PlayerView({model: player});
this.$tbody.append(view.render().el);
}
});
});
| blstream/ut-arena | ut-arena-www/App/scripts/views/players.js | JavaScript | apache-2.0 | 794 |
/*
* Copyright 2015 Concept
*
* 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.
*/
/**
* SEO configuration for EvaluationCriteria route
*/
Meteor.startup(function() {
SeoCollection.update({
route_name: 'EvaluationCriteria'
},
{
$set: {
route_name: 'EvaluationCriteria',
title: 'Evalueringskriterier',
meta: {
'description': 'Etterevaluering av en rekke statlige prosjekter gjort av Concept-programmet. På oppdrag fra Finansdepartementet'
},
og: {
'title': 'Evalueringskriterier',
'image': '/images/logo.jpg'
}
}
},
{
upsert: true
});
});
| bompi88/concept | server/seo/evaluation_criteria.js | JavaScript | apache-2.0 | 1,133 |
/**
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const ISO6391 = require('iso-639-1');
module.exports = eleventy => {
// Transforms given date string into local date string
// Requires full-icu and NODE_ICU_DATA=node_modules/full-icu to function
eleventy.addFilter('date', (date, locale = 'en-US', format = {}) => new Date(date).toLocaleDateString(locale, format));
// Transforms given URL into a URL for the given locale
eleventy.addFilter('localeURL', (url, locale) => {
const changed = url.split('/');
if (changed[changed.length - 1] === '') {
changed.splice(-1, 1);
}
changed.splice(1, 1, locale);
return changed.join('/');
});
// Returns the native name for the language code
eleventy.addFilter('langName', code => ISO6391.getNativeName(code));
};
| chromeos/static-site-scaffold-modules | modules/static-site-scaffold/lib/11ty/l10n.js | JavaScript | apache-2.0 | 1,344 |
/* eslint prefer-arrow-callback: 0, func-names: 0, 'react/jsx-filename-extension': [1, { "extensions": [".js", ".jsx"] }] */
import React from 'react';
import assert from 'assert';
import { shallow } from 'enzyme';
import sinon from 'sinon';
import DisplayNameSlugEditor from '../partials/display-name-slug-editor';
import CollectionSettings from './settings';
import Thumbnail from '../components/thumbnail';
const collectionWithDefaultSubject = {
id: '1',
default_subject_src: 'subject.png',
display_name: 'A collection',
private: false,
slug: 'username/a-collection'
};
const collectionWithoutDefaultSubject = {
id: '1',
display_name: 'A collection',
private: false,
slug: 'username/a-collection'
};
describe('<CollectionSettings />', function () {
let wrapper;
let confirmationSpy;
let deleteButton;
let handleDescriptionInputChangeStub;
before(function () {
confirmationSpy = sinon.spy(CollectionSettings.prototype, 'confirmDelete');
handleDescriptionInputChangeStub = sinon.stub(CollectionSettings.prototype, 'handleDescriptionInputChange');
wrapper = shallow(<CollectionSettings
canCollaborate={true}
collection={collectionWithoutDefaultSubject}
/>,
{ context: { router: {}}}
);
deleteButton = wrapper.find('button.error');
});
it('should render without crashing', function () {
assert.equal(wrapper, wrapper);
});
it('should render a <DisplayNameSlugEditor /> component', function () {
assert.equal(wrapper.find(DisplayNameSlugEditor).length, 1);
});
it('should render the correct default checked attribute for visibility', function () {
const privateChecked = wrapper.find('input[type="radio"]').first().props().defaultChecked;
const publicChecked = wrapper.find('input[type="radio"]').last().props().defaultChecked;
assert.equal(privateChecked, collectionWithoutDefaultSubject.private);
assert.notEqual(publicChecked, collectionWithoutDefaultSubject.private);
});
it('should render the thumbnail correctly depending on presence of default_subject_src', function () {
const thumbnailFirstInstance = wrapper.find(Thumbnail);
assert.equal(thumbnailFirstInstance.length, 0);
wrapper.setProps({ collection: collectionWithDefaultSubject });
const thumbnailSecondInstance = wrapper.find(Thumbnail);
assert.equal(thumbnailSecondInstance.length, 1);
});
it('should call this.handleDescriptionInputChange() when a user changes description text', function () {
wrapper.find('textarea').simulate('change');
sinon.assert.calledOnce(handleDescriptionInputChangeStub);
});
it('should render permission messaging if there is no user', function () {
wrapper.setProps({ canCollaborate: false, user: null });
const permissionMessage = wrapper.contains(<p>Not allowed to edit this collection</p>);
assert(permissionMessage, true);
});
it('should call this.confirmDelete() when the delete button is clicked', function () {
deleteButton.simulate('click');
sinon.assert.calledOnce(confirmationSpy);
});
});
| jelliotartz/Panoptes-Front-End | app/collections/settings.spec.js | JavaScript | apache-2.0 | 3,078 |
var path = require('path');
var fs = require('fs')
var http = require('http')
var url = require('url')
var mime = require('./mime').types
var config = require("./config");
var zlib = require("zlib")
var utils = require("./utils")
var port = 8089;
var server = http.createServer(function(request, response){
var pathname = url.parse(request.url).pathname;
var realpath = path.join("assets", path.normalize(pathname.replace(/\.\./g, "")))
var ext = path.extname(realpath)
ext = ext ? ext.slice(1):"unknown"
var contentType = mime[ext] || "text/plain"
fs.exists(realpath, function(exists) {
if (!exists) {
response.writeHead(404, {
'Content-Type': 'text/plain'
})
response.write("This request URL " + pathname + "was not found on this server");
response.end();
} else {
response.setHeader("Content-Type",contentType);
var stats = fs.statSync(realpath);
if (request.headers["range"]) {
var range = utils.parseRange(request.headers["range"], stats.size);
if (range) {
response.setHeader("Content-Range", "bytes " + range.start + "-" + range.end + "/" + stats.size);
response.setHeader("Content-Length", (range.end - range.start + 1));
var stream = fs.createReadStream(realpath, {
"start": range.start,
"end": range.end
});
response.writeHead('206', "Partial Content");
stream.pipe(response);
} else {
response.removeHeader("Content-Length");
response.writeHead(416, "Request Range Not Satisfiable");
response.end();
}
} else {
var stream = fs.createReadStream(realpath);
response.writeHead('200', "Partial Content");
stream.pipe(response);
}
}
})
})
server.listen(port)
| huang303513/Debug-Instruments | 视频断点播放/app.js | JavaScript | apache-2.0 | 2,168 |
/**
* Copyright 2014 Daniel Furtlehner
*
* 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.
*/
describe('Conditionalgroup Provider', function() {
var crossfilterUtils,
groupData = {
type: 'conditional',
parameters: {
init: {
a: 0,
b: 0,
c: 0,
d: 0
},
conditions: {
isA: 'v.type === "A"',
isB: 'v.type === "B"',
isC: 'v.type === "C"'
},
handlers: {
add: {
isA: {
'p.a': 'p.a + v.val'
},
isB: {
'p.b': 'p.b + v.val'
},
isC: {
'p.c': 'p.c + v.val',
'p.d': 'p.d + 1'
}
},
remove: {
isA: {
'p.a': 'p.a - v.val'
},
isB: {
'p.b': 'p.b - v.val'
},
isC: {
'p.c': 'p.c - v.val',
'p.d': 'p.d - 1'
}
}
}
}
};
var preGroupData = {
type: 'conditional',
parameters: {
conditions: {
aCheck: 'v.type === "C"'
},
handlers: {
add: {
pre: {
'p.c': 'p.c * v.val'
},
aCheck: {
'p.c': 'p.c + v.val'
}
},
remove: {
pre: {
'p.c': 'p.c - v.val'
},
aCheck: {
'p.c': 'p.c / v.val'
}
}
}
}
};
var postGroupData = {
type: 'conditional',
parameters: {
conditions: {
aCheck: 'v.type === "C"'
},
handlers: {
add: {
aCheck: {
'p.c': 'p.c + v.val'
},
post: {
'p.c': 'p.c * v.val'
}
},
remove: {
aCheck: {
'p.c': 'p.c / v.val'
},
post: {
'p.c': 'p.c - v.val'
}
}
}
}
};
beforeEach(function() {
module('ngDashboard');
inject(function(_crossfilterUtils_) {
crossfilterUtils = _crossfilterUtils_;
});
});
it('Init function defined', function() {
var groupFunctions = crossfilterUtils.groupFunctions(groupData);
expect(groupFunctions.init).toBeDefined();
});
it('Add function defined', function() {
var groupFunctions = crossfilterUtils.groupFunctions(groupData);
expect(groupFunctions.add).toBeDefined();
});
it('Remove function defined', function() {
var groupFunctions = crossfilterUtils.groupFunctions(groupData);
expect(groupFunctions.remove).toBeDefined();
});
it('Init should return object', function() {
var groupFunctions = crossfilterUtils.groupFunctions(groupData);
expect(groupFunctions.init()).toEqual({
a: 0,
b: 0,
c: 0,
d: 0
});
});
it('Add a should increment a', function() {
var groupFunctions = crossfilterUtils.groupFunctions(groupData);
var p = {
a: 1,
b: 10,
c: 5,
d: 0
};
var v = {
val: 10,
type: 'A'
};
expect(groupFunctions.add(p, v)).toEqual({
a: 11,
b: 10,
c: 5,
d: 0
});
});
it('Add b should increment b', function() {
var groupFunctions = crossfilterUtils.groupFunctions(groupData);
var p = {
a: 1,
b: 10,
c: 5,
d: 0
};
var v = {
val: 5,
type: 'B'
};
expect(groupFunctions.add(p, v)).toEqual({
a: 1,
b: 15,
c: 5,
d: 0
});
});
it('Add c should increment c and d', function() {
var groupFunctions = crossfilterUtils.groupFunctions(groupData);
var p = {
a: 1,
b: 10,
c: 5,
d: 0
};
var v = {
val: 1,
type: 'C'
};
expect(groupFunctions.add(p, v)).toEqual({
a: 1,
b: 10,
c: 6,
d: 1
});
});
it('Remove a should decrement a', function() {
var groupFunctions = crossfilterUtils.groupFunctions(groupData);
var p = {
a: 5,
b: 10,
c: 5,
d: 0
};
var v = {
val: 3,
type: 'A'
};
expect(groupFunctions.remove(p, v)).toEqual({
a: 2,
b: 10,
c: 5,
d: 0
});
});
it('Remove b should decrement b', function() {
var groupFunctions = crossfilterUtils.groupFunctions(groupData);
var p = {
a: 1,
b: 10,
c: 5,
d: 0
};
var v = {
val: 5,
type: 'B'
};
expect(groupFunctions.remove(p, v)).toEqual({
a: 1,
b: 5,
c: 5,
d: 0
});
});
it('Remove c should decrement c and d', function() {
var groupFunctions = crossfilterUtils.groupFunctions(groupData);
var p = {
a: 1,
b: 10,
c: 5,
d: 5
};
var v = {
val: 1,
type: 'C'
};
expect(groupFunctions.remove(p, v)).toEqual({
a: 1,
b: 10,
c: 4,
d: 4
});
});
it('Pre handlers should be called before others when adding', function() {
var groupFunctions = crossfilterUtils.groupFunctions(preGroupData);
var p = {
a: 1,
b: 10,
c: 6,
d: 5
};
var v = {
val: 2,
type: 'C'
};
expect(groupFunctions.add(p, v)).toEqual({
a: 1,
b: 10,
c: 14,
d: 5
});
});
it('Pre handlers should be called before others when removing', function() {
var groupFunctions = crossfilterUtils.groupFunctions(preGroupData);
var p = {
a: 1,
b: 10,
c: 14,
d: 5
};
var v = {
val: 2,
type: 'C'
};
expect(groupFunctions.remove(p, v)).toEqual({
a: 1,
b: 10,
c: 6,
d: 5
});
});
it('post handlers should be called after others when adding', function() {
var groupFunctions = crossfilterUtils.groupFunctions(postGroupData);
var p = {
a: 1,
b: 10,
c: 5,
d: 5
};
var v = {
val: 3,
type: 'C'
};
expect(groupFunctions.add(p, v)).toEqual({
a: 1,
b: 10,
c: 24,
d: 5
});
});
it('post handlers should be called after others when removing', function() {
var groupFunctions = crossfilterUtils.groupFunctions(postGroupData);
var p = {
a: 1,
b: 10,
c: 24,
d: 5
};
var v = {
val: 3,
type: 'C'
};
expect(groupFunctions.remove(p, v)).toEqual({
a: 1,
b: 10,
c: 5,
d: 5
});
});
}); | furti/ng-dashboard | specs/conditionalGroupProvider.spec.js | JavaScript | apache-2.0 | 8,929 |
import React, {
Component
} from 'react';
class ProjectItem extends Component {
render() {
return ( <
li className = "Project" >
<
strong > {
this.props.project.title
} < /strong> - {this.props.project.category} < /
li >
);
}
}
export default ProjectItem;
| morselapp/shop_directory | src/Components/ProjectItem.js | JavaScript | apache-2.0 | 311 |
/**
* Copyright 2014 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.
*/
/* jshint maxlen: false */
'use strict';
var apirequest = require('../../lib/apirequest');
var createAPIRequest = apirequest.createAPIRequest;
/**
* Cloud Storage API
*
* @classdesc Lets you store and retrieve potentially-large, immutable data objects.
* @namespace storage
* @version v1
* @variation v1
* @this Storage
* @param {object=} options Options for Storage
*/
function Storage(options) {
var self = this;
this._options = options || {};
this.bucketAccessControls = {
/**
* storage.bucketAccessControls.delete
*
* @desc Permanently deletes the ACL entry for the specified entity on the specified bucket.
*
* @alias storage.bucketAccessControls.delete
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
delete: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/' + params.bucket + '/acl/' + params.entity,
method: 'DELETE'
},
params: params,
requiredParams: ['bucket', 'entity'],
pathParams: ['bucket', 'entity'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.bucketAccessControls.get
*
* @desc Returns the ACL entry for the specified entity on the specified bucket.
*
* @alias storage.bucketAccessControls.get
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
get: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/' + params.bucket + '/acl/' + params.entity,
method: 'GET'
},
params: params,
requiredParams: ['bucket', 'entity'],
pathParams: ['bucket', 'entity'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.bucketAccessControls.insert
*
* @desc Creates a new ACL entry on the specified bucket.
*
* @alias storage.bucketAccessControls.insert
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
insert: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/' + params.bucket + '/acl',
method: 'POST'
},
params: params,
requiredParams: ['bucket'],
pathParams: ['bucket'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.bucketAccessControls.list
*
* @desc Retrieves ACL entries on the specified bucket.
*
* @alias storage.bucketAccessControls.list
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
list: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/' + params.bucket + '/acl',
method: 'GET'
},
params: params,
requiredParams: ['bucket'],
pathParams: ['bucket'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.bucketAccessControls.patch
*
* @desc Updates an ACL entry on the specified bucket. This method supports patch semantics.
*
* @alias storage.bucketAccessControls.patch
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
patch: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/' + params.bucket + '/acl/' + params.entity,
method: 'PATCH'
},
params: params,
requiredParams: ['bucket', 'entity'],
pathParams: ['bucket', 'entity'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.bucketAccessControls.update
*
* @desc Updates an ACL entry on the specified bucket.
*
* @alias storage.bucketAccessControls.update
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
update: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/' + params.bucket + '/acl/' + params.entity,
method: 'PUT'
},
params: params,
requiredParams: ['bucket', 'entity'],
pathParams: ['bucket', 'entity'],
context: self
};
return createAPIRequest(parameters, callback);
}
};
this.buckets = {
/**
* storage.buckets.delete
*
* @desc Permanently deletes an empty bucket.
*
* @alias storage.buckets.delete
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {string=} params.ifMetagenerationMatch - If set, only deletes the bucket if its metageneration matches this value.
* @param {string=} params.ifMetagenerationNotMatch - If set, only deletes the bucket if its metageneration does not match this value.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
delete: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/' + params.bucket,
method: 'DELETE'
},
params: params,
requiredParams: ['bucket'],
pathParams: ['bucket'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.buckets.get
*
* @desc Returns metadata for the specified bucket.
*
* @alias storage.buckets.get
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {string=} params.ifMetagenerationMatch - Makes the return of the bucket metadata conditional on whether the bucket's current metageneration matches the given value.
* @param {string=} params.ifMetagenerationNotMatch - Makes the return of the bucket metadata conditional on whether the bucket's current metageneration does not match the given value.
* @param {string=} params.projection - Set of properties to return. Defaults to noAcl.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
get: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/' + params.bucket,
method: 'GET'
},
params: params,
requiredParams: ['bucket'],
pathParams: ['bucket'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.buckets.insert
*
* @desc Creates a new bucket.
*
* @alias storage.buckets.insert
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string=} params.predefinedAcl - Apply a predefined set of access controls to this bucket.
* @param {string} params.project - A valid API project identifier.
* @param {string=} params.projection - Set of properties to return. Defaults to noAcl, unless the bucket resource specifies acl or defaultObjectAcl properties, when it defaults to full.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
insert: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b',
method: 'POST'
},
params: params,
requiredParams: ['project'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.buckets.list
*
* @desc Retrieves a list of buckets for a given project.
*
* @alias storage.buckets.list
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {integer=} params.maxResults - Maximum number of buckets to return.
* @param {string=} params.pageToken - A previously-returned page token representing part of the larger set of results to view.
* @param {string} params.project - A valid API project identifier.
* @param {string=} params.projection - Set of properties to return. Defaults to noAcl.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
list: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b',
method: 'GET'
},
params: params,
requiredParams: ['project'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.buckets.patch
*
* @desc Updates a bucket. This method supports patch semantics.
*
* @alias storage.buckets.patch
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {string=} params.ifMetagenerationMatch - Makes the return of the bucket metadata conditional on whether the bucket's current metageneration matches the given value.
* @param {string=} params.ifMetagenerationNotMatch - Makes the return of the bucket metadata conditional on whether the bucket's current metageneration does not match the given value.
* @param {string=} params.predefinedAcl - Apply a predefined set of access controls to this bucket.
* @param {string=} params.projection - Set of properties to return. Defaults to full.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
patch: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/' + params.bucket,
method: 'PATCH'
},
params: params,
requiredParams: ['bucket'],
pathParams: ['bucket'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.buckets.update
*
* @desc Updates a bucket.
*
* @alias storage.buckets.update
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {string=} params.ifMetagenerationMatch - Makes the return of the bucket metadata conditional on whether the bucket's current metageneration matches the given value.
* @param {string=} params.ifMetagenerationNotMatch - Makes the return of the bucket metadata conditional on whether the bucket's current metageneration does not match the given value.
* @param {string=} params.predefinedAcl - Apply a predefined set of access controls to this bucket.
* @param {string=} params.projection - Set of properties to return. Defaults to full.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
update: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/' + params.bucket,
method: 'PUT'
},
params: params,
requiredParams: ['bucket'],
pathParams: ['bucket'],
context: self
};
return createAPIRequest(parameters, callback);
}
};
this.channels = {
/**
* storage.channels.stop
*
* @desc Stop watching resources through this channel
*
* @alias storage.channels.stop
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
stop: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/channels/stop',
method: 'POST'
},
params: params,
context: self
};
return createAPIRequest(parameters, callback);
}
};
this.defaultObjectAccessControls = {
/**
* storage.defaultObjectAccessControls.delete
*
* @desc Permanently deletes the default object ACL entry for the specified entity on the specified bucket.
*
* @alias storage.defaultObjectAccessControls.delete
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
delete: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/' + params.bucket + '/defaultObjectAcl/' + params.entity,
method: 'DELETE'
},
params: params,
requiredParams: ['bucket', 'entity'],
pathParams: ['bucket', 'entity'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.defaultObjectAccessControls.get
*
* @desc Returns the default object ACL entry for the specified entity on the specified bucket.
*
* @alias storage.defaultObjectAccessControls.get
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
get: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/' + params.bucket + '/defaultObjectAcl/' + params.entity,
method: 'GET'
},
params: params,
requiredParams: ['bucket', 'entity'],
pathParams: ['bucket', 'entity'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.defaultObjectAccessControls.insert
*
* @desc Creates a new default object ACL entry on the specified bucket.
*
* @alias storage.defaultObjectAccessControls.insert
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
insert: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/' + params.bucket + '/defaultObjectAcl',
method: 'POST'
},
params: params,
requiredParams: ['bucket'],
pathParams: ['bucket'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.defaultObjectAccessControls.list
*
* @desc Retrieves default object ACL entries on the specified bucket.
*
* @alias storage.defaultObjectAccessControls.list
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {string=} params.ifMetagenerationMatch - If present, only return default ACL listing if the bucket's current metageneration matches this value.
* @param {string=} params.ifMetagenerationNotMatch - If present, only return default ACL listing if the bucket's current metageneration does not match the given value.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
list: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/' + params.bucket + '/defaultObjectAcl',
method: 'GET'
},
params: params,
requiredParams: ['bucket'],
pathParams: ['bucket'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.defaultObjectAccessControls.patch
*
* @desc Updates a default object ACL entry on the specified bucket. This method supports patch semantics.
*
* @alias storage.defaultObjectAccessControls.patch
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
patch: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/' + params.bucket + '/defaultObjectAcl/' + params.entity,
method: 'PATCH'
},
params: params,
requiredParams: ['bucket', 'entity'],
pathParams: ['bucket', 'entity'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.defaultObjectAccessControls.update
*
* @desc Updates a default object ACL entry on the specified bucket.
*
* @alias storage.defaultObjectAccessControls.update
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
update: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/' + params.bucket + '/defaultObjectAcl/' + params.entity,
method: 'PUT'
},
params: params,
requiredParams: ['bucket', 'entity'],
pathParams: ['bucket', 'entity'],
context: self
};
return createAPIRequest(parameters, callback);
}
};
this.objectAccessControls = {
/**
* storage.objectAccessControls.delete
*
* @desc Permanently deletes the ACL entry for the specified entity on the specified object.
*
* @alias storage.objectAccessControls.delete
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
* @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default).
* @param {string} params.object - Name of the object.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
delete: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/' + params.bucket + '/o/' + params.object + '/acl/' + params.entity,
method: 'DELETE'
},
params: params,
requiredParams: ['bucket', 'object', 'entity'],
pathParams: ['bucket', 'entity', 'object'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.objectAccessControls.get
*
* @desc Returns the ACL entry for the specified entity on the specified object.
*
* @alias storage.objectAccessControls.get
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
* @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default).
* @param {string} params.object - Name of the object.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
get: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/' + params.bucket + '/o/' + params.object + '/acl/' + params.entity,
method: 'GET'
},
params: params,
requiredParams: ['bucket', 'object', 'entity'],
pathParams: ['bucket', 'entity', 'object'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.objectAccessControls.insert
*
* @desc Creates a new ACL entry on the specified object.
*
* @alias storage.objectAccessControls.insert
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default).
* @param {string} params.object - Name of the object.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
insert: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/' + params.bucket + '/o/' + params.object + '/acl',
method: 'POST'
},
params: params,
requiredParams: ['bucket', 'object'],
pathParams: ['bucket', 'object'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.objectAccessControls.list
*
* @desc Retrieves ACL entries on the specified object.
*
* @alias storage.objectAccessControls.list
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default).
* @param {string} params.object - Name of the object.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
list: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/' + params.bucket + '/o/' + params.object + '/acl',
method: 'GET'
},
params: params,
requiredParams: ['bucket', 'object'],
pathParams: ['bucket', 'object'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.objectAccessControls.patch
*
* @desc Updates an ACL entry on the specified object. This method supports patch semantics.
*
* @alias storage.objectAccessControls.patch
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
* @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default).
* @param {string} params.object - Name of the object.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
patch: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/' + params.bucket + '/o/' + params.object + '/acl/' + params.entity,
method: 'PATCH'
},
params: params,
requiredParams: ['bucket', 'object', 'entity'],
pathParams: ['bucket', 'entity', 'object'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.objectAccessControls.update
*
* @desc Updates an ACL entry on the specified object.
*
* @alias storage.objectAccessControls.update
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of a bucket.
* @param {string} params.entity - The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers.
* @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default).
* @param {string} params.object - Name of the object.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
update: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/' + params.bucket + '/o/' + params.object + '/acl/' + params.entity,
method: 'PUT'
},
params: params,
requiredParams: ['bucket', 'object', 'entity'],
pathParams: ['bucket', 'entity', 'object'],
context: self
};
return createAPIRequest(parameters, callback);
}
};
this.objects = {
/**
* storage.objects.compose
*
* @desc Concatenates a list of existing objects into a new object in the same bucket.
*
* @alias storage.objects.compose
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.destinationBucket - Name of the bucket in which to store the new object.
* @param {string} params.destinationObject - Name of the new object.
* @param {string=} params.destinationPredefinedAcl - Apply a predefined set of access controls to the destination object.
* @param {string=} params.ifGenerationMatch - Makes the operation conditional on whether the object's current generation matches the given value.
* @param {string=} params.ifMetagenerationMatch - Makes the operation conditional on whether the object's current metageneration matches the given value.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
compose: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/' + params.destinationBucket + '/o/' + params.destinationObject + '/compose',
method: 'POST'
},
params: params,
requiredParams: ['destinationBucket', 'destinationObject'],
pathParams: ['destinationBucket', 'destinationObject'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.objects.copy
*
* @desc Copies an object to a specified location. Optionally overrides metadata.
*
* @alias storage.objects.copy
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.destinationBucket - Name of the bucket in which to store the new object. Overrides the provided object metadata's bucket value, if any.
* @param {string} params.destinationObject - Name of the new object. Required when the object metadata is not otherwise provided. Overrides the object metadata's name value, if any.
* @param {string=} params.destinationPredefinedAcl - Apply a predefined set of access controls to the destination object.
* @param {string=} params.ifGenerationMatch - Makes the operation conditional on whether the destination object's current generation matches the given value.
* @param {string=} params.ifGenerationNotMatch - Makes the operation conditional on whether the destination object's current generation does not match the given value.
* @param {string=} params.ifMetagenerationMatch - Makes the operation conditional on whether the destination object's current metageneration matches the given value.
* @param {string=} params.ifMetagenerationNotMatch - Makes the operation conditional on whether the destination object's current metageneration does not match the given value.
* @param {string=} params.ifSourceGenerationMatch - Makes the operation conditional on whether the source object's generation matches the given value.
* @param {string=} params.ifSourceGenerationNotMatch - Makes the operation conditional on whether the source object's generation does not match the given value.
* @param {string=} params.ifSourceMetagenerationMatch - Makes the operation conditional on whether the source object's current metageneration matches the given value.
* @param {string=} params.ifSourceMetagenerationNotMatch - Makes the operation conditional on whether the source object's current metageneration does not match the given value.
* @param {string=} params.projection - Set of properties to return. Defaults to noAcl, unless the object resource specifies the acl property, when it defaults to full.
* @param {string} params.sourceBucket - Name of the bucket in which to find the source object.
* @param {string=} params.sourceGeneration - If present, selects a specific revision of the source object (as opposed to the latest version, the default).
* @param {string} params.sourceObject - Name of the source object.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
copy: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/' + params.sourceBucket + '/o/' + params.sourceObject + '/copyTo/b/' + params.destinationBucket + '/o/' + params.destinationObject,
method: 'POST'
},
params: params,
requiredParams: ['sourceBucket', 'sourceObject', 'destinationBucket', 'destinationObject'],
pathParams: ['destinationBucket', 'destinationObject', 'sourceBucket', 'sourceObject'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.objects.delete
*
* @desc Deletes an object and its metadata. Deletions are permanent if versioning is not enabled for the bucket, or if the generation parameter is used.
*
* @alias storage.objects.delete
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of the bucket in which the object resides.
* @param {string=} params.generation - If present, permanently deletes a specific revision of this object (as opposed to the latest version, the default).
* @param {string=} params.ifGenerationMatch - Makes the operation conditional on whether the object's current generation matches the given value.
* @param {string=} params.ifGenerationNotMatch - Makes the operation conditional on whether the object's current generation does not match the given value.
* @param {string=} params.ifMetagenerationMatch - Makes the operation conditional on whether the object's current metageneration matches the given value.
* @param {string=} params.ifMetagenerationNotMatch - Makes the operation conditional on whether the object's current metageneration does not match the given value.
* @param {string} params.object - Name of the object.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
delete: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/' + params.bucket + '/o/' + params.object,
method: 'DELETE'
},
params: params,
requiredParams: ['bucket', 'object'],
pathParams: ['bucket', 'object'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.objects.get
*
* @desc Retrieves objects or their metadata.
*
* @alias storage.objects.get
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of the bucket in which the object resides.
* @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default).
* @param {string=} params.ifGenerationMatch - Makes the operation conditional on whether the object's generation matches the given value.
* @param {string=} params.ifGenerationNotMatch - Makes the operation conditional on whether the object's generation does not match the given value.
* @param {string=} params.ifMetagenerationMatch - Makes the operation conditional on whether the object's current metageneration matches the given value.
* @param {string=} params.ifMetagenerationNotMatch - Makes the operation conditional on whether the object's current metageneration does not match the given value.
* @param {string} params.object - Name of the object.
* @param {string=} params.projection - Set of properties to return. Defaults to noAcl.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
get: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/' + params.bucket + '/o/' + params.object,
method: 'GET'
},
params: params,
requiredParams: ['bucket', 'object'],
pathParams: ['bucket', 'object'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.objects.insert
*
* @desc Stores a new object and metadata.
*
* @alias storage.objects.insert
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of the bucket in which to store the new object. Overrides the provided object metadata's bucket value, if any.
* @param {string=} params.contentEncoding - If set, sets the contentEncoding property of the final object to this value. Setting this parameter is equivalent to setting the contentEncoding metadata property. This can be useful when uploading an object with uploadType=media to indicate the encoding of the content being uploaded.
* @param {string=} params.ifGenerationMatch - Makes the operation conditional on whether the object's current generation matches the given value.
* @param {string=} params.ifGenerationNotMatch - Makes the operation conditional on whether the object's current generation does not match the given value.
* @param {string=} params.ifMetagenerationMatch - Makes the operation conditional on whether the object's current metageneration matches the given value.
* @param {string=} params.ifMetagenerationNotMatch - Makes the operation conditional on whether the object's current metageneration does not match the given value.
* @param {string=} params.name - Name of the object. Required when the object metadata is not otherwise provided. Overrides the object metadata's name value, if any.
* @param {string=} params.predefinedAcl - Apply a predefined set of access controls to this object.
* @param {string=} params.projection - Set of properties to return. Defaults to noAcl, unless the object resource specifies the acl property, when it defaults to full.
* @param {object} params.resource - Media resource metadata
* @param {object} params.media - Media object
* @param {string} params.media.mimeType - Media mime-type
* @param {string|object} params.media.body - Media body contents
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
insert: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/' + params.bucket + '/o',
method: 'POST'
},
params: params,
mediaUrl: 'https://www.googleapis.com/upload/storage/v1/b/' + params.bucket + '/o',
requiredParams: ['bucket'],
pathParams: ['bucket'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.objects.list
*
* @desc Retrieves a list of objects matching the criteria.
*
* @alias storage.objects.list
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of the bucket in which to look for objects.
* @param {string=} params.delimiter - Returns results in a directory-like mode. items will contain only objects whose names, aside from the prefix, do not contain delimiter. Objects whose names, aside from the prefix, contain delimiter will have their name, truncated after the delimiter, returned in prefixes. Duplicate prefixes are omitted.
* @param {integer=} params.maxResults - Maximum number of items plus prefixes to return. As duplicate prefixes are omitted, fewer total results may be returned than requested.
* @param {string=} params.pageToken - A previously-returned page token representing part of the larger set of results to view.
* @param {string=} params.prefix - Filter results to objects whose names begin with this prefix.
* @param {string=} params.projection - Set of properties to return. Defaults to noAcl.
* @param {boolean=} params.versions - If true, lists all versions of a file as distinct results.
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
list: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/' + params.bucket + '/o',
method: 'GET'
},
params: params,
requiredParams: ['bucket'],
pathParams: ['bucket'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.objects.patch
*
* @desc Updates an object's metadata. This method supports patch semantics.
*
* @alias storage.objects.patch
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of the bucket in which the object resides.
* @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default).
* @param {string=} params.ifGenerationMatch - Makes the operation conditional on whether the object's current generation matches the given value.
* @param {string=} params.ifGenerationNotMatch - Makes the operation conditional on whether the object's current generation does not match the given value.
* @param {string=} params.ifMetagenerationMatch - Makes the operation conditional on whether the object's current metageneration matches the given value.
* @param {string=} params.ifMetagenerationNotMatch - Makes the operation conditional on whether the object's current metageneration does not match the given value.
* @param {string} params.object - Name of the object.
* @param {string=} params.predefinedAcl - Apply a predefined set of access controls to this object.
* @param {string=} params.projection - Set of properties to return. Defaults to full.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
patch: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/' + params.bucket + '/o/' + params.object,
method: 'PATCH'
},
params: params,
requiredParams: ['bucket', 'object'],
pathParams: ['bucket', 'object'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.objects.update
*
* @desc Updates an object's metadata.
*
* @alias storage.objects.update
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of the bucket in which the object resides.
* @param {string=} params.generation - If present, selects a specific revision of this object (as opposed to the latest version, the default).
* @param {string=} params.ifGenerationMatch - Makes the operation conditional on whether the object's current generation matches the given value.
* @param {string=} params.ifGenerationNotMatch - Makes the operation conditional on whether the object's current generation does not match the given value.
* @param {string=} params.ifMetagenerationMatch - Makes the operation conditional on whether the object's current metageneration matches the given value.
* @param {string=} params.ifMetagenerationNotMatch - Makes the operation conditional on whether the object's current metageneration does not match the given value.
* @param {string} params.object - Name of the object.
* @param {string=} params.predefinedAcl - Apply a predefined set of access controls to this object.
* @param {string=} params.projection - Set of properties to return. Defaults to full.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
update: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/' + params.bucket + '/o/' + params.object,
method: 'PUT'
},
params: params,
requiredParams: ['bucket', 'object'],
pathParams: ['bucket', 'object'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* storage.objects.watchAll
*
* @desc Watch for changes on all objects in a bucket.
*
* @alias storage.objects.watchAll
* @memberOf! storage(v1)
*
* @param {object} params - Parameters for request
* @param {string} params.bucket - Name of the bucket in which to look for objects.
* @param {string=} params.delimiter - Returns results in a directory-like mode. items will contain only objects whose names, aside from the prefix, do not contain delimiter. Objects whose names, aside from the prefix, contain delimiter will have their name, truncated after the delimiter, returned in prefixes. Duplicate prefixes are omitted.
* @param {integer=} params.maxResults - Maximum number of items plus prefixes to return. As duplicate prefixes are omitted, fewer total results may be returned than requested.
* @param {string=} params.pageToken - A previously-returned page token representing part of the larger set of results to view.
* @param {string=} params.prefix - Filter results to objects whose names begin with this prefix.
* @param {string=} params.projection - Set of properties to return. Defaults to noAcl.
* @param {boolean=} params.versions - If true, lists all versions of a file as distinct results.
* @param {object} params.resource - Request body data
* @param {callback} callback - The callback that handles the response.
* @return {object} Request object
*/
watchAll: function(params, callback) {
var parameters = {
options: {
url: 'https://www.googleapis.com/storage/v1/b/' + params.bucket + '/o/watch',
method: 'POST'
},
params: params,
requiredParams: ['bucket'],
pathParams: ['bucket'],
context: self
};
return createAPIRequest(parameters, callback);
}
};
}
/**
* Exports Storage object
* @type Storage
*/
module.exports = Storage; | naskogithub/google-api-nodejs-client | apis/storage/v1.js | JavaScript | apache-2.0 | 49,086 |
/* Copyright (C) 2012-2014 NS Solutions Corporation. Licensed under the Apache License, Version 2.0. hifive version 1.1.14 gitCommitId a4c4bbab5019987c08ee2ba99ec4612a7054b8b3 (util,controller,modelWithBinding,view,ui,api.geo,api.sqldb,api.storage) */
(function(a){function d(a,d,k){var x=null,C=ib[a],O=tb[a];O&&(x=O(a,C,d,k));!x&&C&&(x=e.u.str.format.apply(null,[C].concat(d)));x&&(x+="(code="+a+")");d=x?Error(x):Error("FwError: code = "+a);a&&(d.code=a);k&&(d.detail=k);throw d;}function ca(a,d,k){var x=null,C=ib[a];C&&(d=[C].concat(d),x=e.u.str.format.apply(null,d));return{code:a,message:x,detail:k}}function R(a){return null==a?a:M(a)?a:[a]}function Z(a){var d=document.createElement("span");d.innerHTML='<a href="'+a+'" />';return d.firstChild.href}
function y(a){return"string"===typeof a}function Da(a){return a.isRejected?a.isRejected():"rejected"===a.state()}function Ea(a){return a.isResolved?a.isResolved():"resolved"===a.state()}function la(a){return!y(a)?!1:!!a.match(/^[A-Za-z_\$][\w|\$]*$/)}function va(d){if("regexp"===a.type(d))return d;var e="",e=-1!==d.indexOf("*")?a.map(d.split("*"),function(a){return a.replace(/\W/g,"\\$&")}).join(".*"):d;return RegExp("^"+e+"$")}function wa(a,d,e){a&&(a._h5UnwrappedCall?a._h5UnwrappedCall(d,e):a[d](e))}
function aa(d,e,k,x){return d[a.hasOwnProperty("curCSS")?"pipe":"then"](e,k,x)}function jb(a){return a&&a.document&&a.document.nodeType===Ja&&V(a.document)===a}function T(a){return typeof a.nodeType===ja?jb(a)?a.document:null:a.nodeType===Ja?a:a.ownerDocument}function V(a){return window.document===a?window:a.defaultView||a.parentWindow}function Ka(a,d,k,x){function C(){!q&&++j===p&&d&&d()}function O(){q=!0;k?k.apply(this,arguments):x&&e.settings.commonFailHandler&&e.settings.commonFailHandler.call(this,
arguments)}var D=a?a.length:0,I=e.async.isPromise;if(1===D){D=a[0];if(I(D)){D.done(d);k?D.fail(k):x&&e.settings.commonFailHandler&&D.fail(e.settings.commonFailHandler);return}D=0}if(0===D)d();else{for(var H=[],u=0,o=a.length;u<o;u++)D=a[u],I(D)&&H.push(D);var p=H.length;if(0===p)d&&d();else for(var j=0,q=!1,u=0;u<p;u++)H[u].done(C).fail(O)}}var kb=void 0;if(window.h5){if(window.h5.env&&"1.1.14"===window.h5.env.version)return;kb=window.h5}var e={};window.h5=e;e.coexist=function(){window.h5=kb;return e};
e.env={version:"1.1.14"};var ib={},tb={},lb=12029,ja="undefined",ba=1,Ja=9,M=Array.isArray||function(){var a=Object.prototype.toString;return function(d){return"[object Array]"===a.call(d)}}(),Q=function(){if("function"===typeof RegExp()){var a=Object.prototype.toString;return function(d){return"[object Function]"===a.call(d)}}return function(a){return"function"===typeof a}}(),mb={controllerInternal:null},nb;(function(){function m(a){switch(a){case "string":return"s";case "number":return"n";case "boolean":return"b";
case "String":return"S";case "Number":return"N";case "Boolean":return"B";case "infinity":return"i";case "-infinity":return"I";case "nan":return"x";case "date":return"d";case "regexp":return"r";case "array":return"a";case "object":return"o";case "null":return"l";case H:return"u";case "undefElem":return"_";case "objElem":return"@"}}function G(a,b){if(y(a)){var c=a;b&&(c=c.replace(/\\n/g,"\n").replace(/\\r/g,"\r"));return c=c.replace(/\\/g,"\\\\").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\b]/g,
"\\b").replace(/\f/g,"\\f").replace(/\t/g,"\\t")}return a instanceof String?new String(G(a.toString())):a}function k(a,b){return"1"===b?a:y(a)?a.replace(/\\\\/g,"\\-").replace(/\\b/g,"").replace(/\\f/g,"").replace(/\\n/g,"\n").replace(/\\r/g,"\r").replace(/\\t/g,"\t").replace(/\\-/g,"\\"):a instanceof String?new String(k(a.toString())):a}function x(a,b,c){var d=e.async.deferred();e.ajax({url:a,async:b,cache:c,dataType:"script",converters:{"text script":function(a){return a}}}).done(function(){var a=
I(arguments);a.push(this.url);d.notifyWith(d,a);d.resolveWith(d,a)}).fail(function(){d.rejectWith(d,I(arguments))});return d.promise()}function C(a){y(a)||d(u,"h5.u.obj.ns()");for(var a=a.split("."),b=a.length,c=0;c<b;c++)la(a[c])||d(u,"h5.u.obj.ns()");for(var g=window,c=0;c<b;c++){var F=a[c];typeof g[F]===H&&(g[F]={});g=g[F]}return g}function O(a,b){var c=C(a),g;for(g in b)b.hasOwnProperty(g)&&(void 0!==c[g]&&d(o,[a,g]),c[g]=b[g])}function D(b){return!b||!b.jquery?!1:b.jquery===a().jquery}function I(a){return Array.prototype.slice.call(a)}
var H="undefined",u=11E3,o=11001,p=11004,j=11005,q=11006,A={},c={"&":"&",'"':""","<":"<",">":">","'":"'"},b=void 0!==document.createElement("script").onload,f=-1===/\r\n/.toString().indexOf("\r\n");O("h5.u",{loadScript:function(c,f){var o=e.async.deferred,g=R(c);(!g||0===g.length)&&d(11007);for(var F=0,S=g.length;F<S;F++)c=g[F],(!y(c)||!a.trim(c))&&d(11007);null!=f&&!a.isPlainObject(f)&&d(11008,"h5.u.loadScript()");var r=f&&!1===f.async?!1:!0,t=!!(f&&!0===f.force),F=!!(f&&!0===
f.parallel),j=!!(f&&!0===f.atomic),m=!t,q=r?o():null,k=r?function(a){q.reject(ca(11010,[a]))}:null,S=r?function(){var a=o();setTimeout(function(){a.resolve([])},0);return a.promise()}:null,D=F?[]:null,C=[],p={};if(r){if(!j&&b){var u=a("head"),H=function(a){var b=o(),c=document.createElement("script");c.onload=function(){c.onload=null;A[a]=a;b.resolve()};c.onerror=function(){c.onerror=null;b.reject(a)};c.type="text/javascript";c.src=m?a:a+(-1<a.indexOf("?")?"&_":"?_")+ +new Date;u[0].appendChild(c);
return b.promise()};if(F)D.push(S()),a.each(g,function(){var a=Z(this);if(!t&&a in A)return!0;D.push(H(a))}),Ka(D,function(){q.resolve()},k);else{var G=aa(o().resolve(),S);a.each(g,function(){var a=Z(this);G=aa(G,function(){if(t||!(a in A))return H(a)},k)});aa(G,function(){q.resolve()},k)}}else if(F){var n=[];D.push(S());n.push(null);a.each(g,function(){var a=Z(this);if(!t&&(a in A||a in p))return!0;D.push(x(a,r,m));j?p[a]=a:n.push(null)});F=g=null;j?(g=function(){a.each(I(arguments),function(b,c){a.globalEval(c[0])});
a.extend(A,p);q.resolve()},F=a.noop):(g=function(){q.resolve()},F=function(){for(var b=I(arguments),c=0;c<n.length;c++)if(b[c]){var d=b[c][3];n[c]!==d&&(a.globalEval(b[c][0]),n.splice(c,1,d))}});e.async.when(D).done(g).fail(k).progress(F)}else G=aa(o().resolve(),S),a.each(g,function(){var b=Z(this);G=aa(G,function(){var c=o();!t&&(b in A||b in p)?c.resolve():x(b,r,m).done(function(d){j?(C.push(d),p[b]=b):(a.globalEval(d),A[b]=b);c.resolve()}).fail(function(){c.reject(this.url)});return c.promise()},
k)}),aa(G,function(){j&&(a.each(C,function(b,c){a.globalEval(c)}),a.extend(A,p));q.resolve()},k);return q.promise()}a.each(g,function(){var b=Z(this);if(!t&&(b in A||b in p))return!0;x(b,r,m).done(function(c){j?(C.push(c),p[b]=b):(a.globalEval(c),A[b]=b)}).fail(function(){d(11010,[b])})});j&&(a.each(C,function(b,c){a.globalEval(c)}),a.extend(A,p))},createInterceptor:function(a,b){return function(c){var d={},F=a?a.call(this,c,d):c.proceed();c.result=F;if(!b)return F;if(F&&Q(F.promise)&&!D(F)){var f=
this;wa(F,"always",function(){b.call(f,c,d)});return F}b.call(this,c,d);return F}}});O("h5.u.str",{startsWith:function(a,b){return 0===a.lastIndexOf(b,0)},endsWith:function(a,b){var c=a.length-b.length;return 0<=c&&a.lastIndexOf(b)===c},format:function(a,b){if(null==a)return"";var c=arguments;return a.replace(/\{(\d+)\}/g,function(a,b){var d=c[parseInt(b,10)+1];return typeof d===H?H:d})},escapeHtml:function(b){return"string"!==a.type(b)?b:b.replace(/[&"'<>]/g,function(a){return c[a]})}});O("h5.u.obj",
{expose:O,ns:C,serialize:function(b){function c(a){for(var b=0,d=F.length;b<d;b++)if(a===F[b])return!0;return!1}function o(a){for(var b=0,c=F.length;b<c;b++)a===F[b]&&F.splice(b,1)}function g(b){var r=b,t=a.type(b);"object"===typeof b&&(b instanceof String?t="String":b instanceof Number?t="Number":b instanceof Boolean&&(t="Boolean"));switch(t){case "String":case "string":r=m(t)+G(r);break;case "Boolean":r=r.valueOf();case "boolean":r=m(t)+(r?1:0);break;case "Number":r=r.valueOf();if(a.isNaN&&a.isNaN(b)||
a.isNumeric&&!a.isNumeric(b))r=Infinity===b.valueOf()?m("infinity"):-Infinity===b.valueOf()?m("-infinity"):m("nan");r=m(t)+r;break;case "number":r=a.isNaN&&a.isNaN(b)||a.isNumeric&&!a.isNumeric(b)?Infinity===b?m("infinity"):-Infinity===b?m("-infinity"):m("nan"):m(t)+r;break;case "regexp":r=m(t)+G(r.toString(),f);break;case "date":r=m(t)+ +r;break;case "array":c(b)&&d(ERR_CODE_REFERENCE_CYCLE);F.push(b);for(var l=[],r=m(t)+"[",t=0,e=b.length;t<e;t++){l[t.toString()]=!0;var x;x=b.hasOwnProperty(t)?
"function"===a.type(b[t])?m(H):g(b[t]).replace(/\\/g,"\\\\").replace(/"/g,'\\"'):m("undefElem");r+='"'+x+'"';t!==b.length-1&&(r+=",")}var t="",q;for(q in b)l[q]||"function"!==a.type(b[q])&&(t+='"'+G(q)+'":"'+g(b[q]).replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'",');t&&(r+=(b.length?",":"")+'"'+m("objElem")+"{"+t.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),r=r.replace(/,$/,""),r+='}"');r+="]";o(b);break;case "object":c(b)&&d(j);F.push(b);r=m(t)+"{";for(q in b)b.hasOwnProperty(q)&&"function"!==a.type(b[q])&&
(r+='"'+q+'":"'+g(b[q]).replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'",');r=r.replace(/,$/,"");r+="}";o(b);break;case "null":case H:r=m(t)}return r}Q(b)&&d(11002);var F=[];return"2|"+g(b)},deserialize:function(b){function c(b){function o(a){switch(a){case "s":return"string";case "n":return"number";case "b":return"boolean";case "S":return"String";case "N":return"Number";case "B":return"Boolean";case "i":return"infinity";case "I":return"-infinity";case "x":return"nan";case "d":return"date";case "r":return"regexp";
case "a":return"array";case "o":return"object";case "l":return"null";case "u":return H;case "_":return"undefElem";case "@":return"objElem"}}b.match(/^(.)(.*)/);b=RegExp.$1;g=RegExp.$2?RegExp.$2:"";if(void 0!==b&&""!==b)switch(o(b)){case "String":g=new String(k(g,f));break;case "string":break;case "Boolean":"0"===g||"1"===g?g=new Boolean("1"===g):d(q);break;case "boolean":"0"===g||"1"===g?g="1"===g:d(q);break;case "nan":""!==g&&d(q);g=NaN;break;case "infinity":""!==g&&d(q);g=Infinity;break;case "-infinity":""!==
g&&d(q);g=-Infinity;break;case "Number":"infinity"===o(g)?g=new Number(Infinity):"-infinity"===o(g)?g=new Number(-Infinity):"nan"===o(g)?g=new Number(NaN):(g=new Number(g),isNaN(g.valueOf())&&d(q));break;case "number":g=(new Number(g)).valueOf();isNaN(g)&&d(q);break;case "array":var r;try{r=a.parseJSON(g)}catch(j){d(q)}M(r)||d(q);for(var l=0;l<r.length;l++)switch(o(r[l].substring(0,1))){case "undefElem":delete r[l];break;case "objElem":for(var e=c(m("object")+r[l].substring(1)),b=[],l=0,x=r.length-
1;l<x;l++)b[l]=r[l];r=b;for(var A in e)r[A]=e[A];break;default:r[l]=c(r[l])}g=r;break;case "object":try{r=a.parseJSON(g)}catch(D){d(q)}a.isPlainObject(r)||d(q);for(A in r)r[A]=c(r[A]);g=r;break;case "date":g=new Date(parseInt(g,10));break;case "regexp":try{l=g.match(/^\/(.*)\/(.*)$/),e=k(l[1],f),g=RegExp(e,l[2])}catch(C){d(q)}break;case "null":""!==g&&d(q);g=null;break;case H:""!==g&&d(q);g=void 0;break;default:d(p)}return k(g,f)}y(b)||d(11009);b.match(/^(.)\|(.*)/);var f=RegExp.$1;"1"!==f&&"2"!==
f&&d(11003,[f,"2"]);var g=RegExp.$2;return c(g)},isJQueryObject:D,argsToArray:I,getByPath:function(a,b){y(a)||d(u,"h5.u.obj.getByPath()");var c=a.split("."),f=0;if("window"===c[0]&&(!b||b===window))f=1;for(var F=b||window,o=c.length;f<o&&!(F=F[c[f]],null==F);f++);return F}})})();(function(){function m(a,d){a.target||(a.target=d);a.timeStamp||(a.timeStamp=(new Date).getTime());if(!a.isDefaultPrevented){var e=!1;a.isDefaultPrevented=function(){return e};a.preventDefault=function(){e=true}}if(!a.isImmediatePropagationStopped){var m=
!1;a.isImmediatePropagationStopped=function(){return m};a.stopImmediatePropagation=function(){m=true}}}function G(a){var d={},m;for(m in a){var k=a[m];if(a.hasOwnProperty(m)&&(Q(k)||null===k||"string"===typeof k||"number"===typeof k||"boolean"===typeof k))d[m]=k}this._mix=function(a){for(var e in d)a[e]=d[e]};this._hasInterface=function(a){for(var m in d)if(!e.u.str.startsWith(m,"_")&&typeof a[m]===ja)return!1;return!0}}function k(a){return new G(a)}a.extend(G.prototype,{mix:function(a){return this._mix(a)},
hasInterface:function(a){return this._hasInterface(a)}});e.u.obj.expose("h5.mixin",{createMixin:k,eventDispatcher:k({hasEventListener:function(a,d){if(!this._eventListeners)return!1;var e=this._eventListeners[a];if(!e||!this._eventListeners.hasOwnProperty(a))return!1;for(var m=0,k=e.length;m<k;m++)if(e[m]===d)return!0;return!1},addEventListener:function(a,e){(2>arguments.length||!y(a))&&d(16E3);null==e||this.hasEventListener(a,e)||(this._eventListeners||(this._eventListeners={}),this._eventListeners.hasOwnProperty(a)||
(this._eventListeners[a]=[]),this._eventListeners[a].push(e))},removeEventListener:function(a,d){if(this.hasEventListener(a,d))for(var e=this._eventListeners[a],m=0,k=e.length;m<k;m++)if(e[m]===d){e.splice(m,1);break}},dispatchEvent:function(a){if(this._eventListeners){var d=this._eventListeners[a.type];if(d){d=d.slice(0);m(a,this);for(var e=0,k=d.length;e<k&&!a.isImmediatePropagationStopped();e++)Q(d[e])?d[e].call(a.target,a):d[e].handleEvent&&d[e].handleEvent(a);return a.isDefaultPrevented()}}}})})})();
(function(){var m,G,k,x,C,O,D;function I(a){return a.match(/^error$/i)?m:a.match(/^warn$/i)?G:a.match(/^info$/i)?k:a.match(/^debug$/i)?x:a.match(/^trace$/i)?C:a.match(/^all$/i)?O:a.match(/^none$/i)?D:null}function H(a,b){var c={},d=a.slice(0,b),f=Math.min(J,b),e=d.slice(0,f).join(" <- ");d.length>f&&(e+=" ...");c.preview=e;c.all=d.join("\n");return c}function u(a){var b="";a.name?b=a.name:(/^\s*function\s*([\w\-\$]+)?\s*\(/i.test(a.toString()),b=RegExp.$1);return b}function o(b){for(var b=e.u.obj.argsToArray(b),
c=[],d=0,f=b.length;d<f;d++)c.push(a.type(b[d]));return c.join(", ")}function p(){}function j(c){(!y(c)||0===a.trim(c).length)&&d(b);this.category=a.trim(c)}var q=10002,A=10003,c=10004,b=10005,f=10007,l=10008,N=10010,J=3;m=50;G=40;k=30;x=20;C=10;O=0;D=-1;var g=null;p.prototype={init:function(){},log:function(a){window.console&&(y(a.args[0])?this._logMsg(a):this._logObj(a))},_logMsg:function(a){var b=a.args,c=null,c=1===b.length?b[0]:e.u.str.format.apply(e.u.str,b),b=this._getLogPrefix(a)+c;a.logger.enableStackTrace&&
(b+=" ["+a.stackTrace.preview+"]");a.logger.enableStackTrace&&console.groupCollapsed?console.groupCollapsed(b):this._consoleOut(a.level,b);a.logger.enableStackTrace&&this._consoleOut(a.level,a.stackTrace.all);a.logger.enableStackTrace&&console.groupEnd&&console.groupEnd()},_consoleOut:function(a,b){var c=!1;a==m&&console.error?(console.error(b),c=!0):a==G&&console.warn?(console.warn(b),c=!0):a==k&&console.info?(console.info(b),c=!0):a==x&&console.debug&&(console.debug(b),c=!0);!c&&console.log&&console.log(b)},
_getLogPrefix:function(a){return"["+a.levelString+"]"+a.date.getHours()+":"+a.date.getMinutes()+":"+a.date.getSeconds()+","+a.date.getMilliseconds()+": "},_logObj:function(a){var b=a.args,c=this._getLogPrefix(a);b.unshift(c);a.level==m&&console.error?this._output(console.error,b):a.level==G&&console.warn?this._output(console.warn,b):a.level==k&&console.info?this._output(console.info,b):a.level==x&&console.debug?this._output(console.debug,b):this._output(console.log,b)},_output:function(a,b){try{if(a.apply){a.apply(console,
b);return}}catch(c){}a(b)}};j.prototype={enableStackTrace:!1,maxStackSize:10,error:function(a){this._log(m,arguments,this.error)},warn:function(a){this._log(G,arguments,this.warn)},info:function(a){this._log(k,arguments,this.info)},debug:function(a){this._log(x,arguments,this.debug)},trace:function(a){this._log(C,arguments,this.trace)},_traceFunctionName:function(b){var c=Error(),d=c.stack||c.stacktrace,c=[];if(d)var c=d.replace(/\r\n/,"\n").replace(/at\b|@|Error\b|\t|\[arguments not available\]/ig,
"").replace(/(http|https|file):.+[0-9]/g,"").replace(/ +/g," ").split("\n"),f=null,c=a.map(c,function(b){return f=0===b.length?null:""===a.trim(b)?"{anonymous}":a.trim(b)}).slice(3);else for(var d=0,e=this.maxStackSize;d<e;d++){var g=u(b),l=o(b.arguments),j;try{j=b.caller}catch(m){c.push("{unable to trace}");break}if(!g)if(j){c.push("{anonymous}("+l+")");break}else c.push("{root}("+l+")");c.push("{"+g+"}("+l+")");b=j}return H(c,this.maxStackSize)},_log:function(a,b,c){var b={level:a,args:e.u.obj.argsToArray(b),
stackTrace:this.enableStackTrace?this._traceFunctionName(c):""},d=g.out,f=g.defaultOut,c=null;if(d)for(var d=R(d),o=0,l=d.length;o<l;o++){var j=d[o];if(j.compiledCategory.test(this.category)){c=j;break}}c||(c=f);o=c.compiledLevel;c=c.compiledTargets;if(!(a<o||0>o))if(b.logger=this,b.date=new Date,b.levelString=this._levelToString(a),c&&0!==c.length){o=0;for(l=c.length;o<l;o++)c[o].log(b)}},_levelToString:function(a){if(a===m)return"ERROR";if(a===G)return"WARN";if(a===k)return"INFO";if(a===x)return"DEBUG";
if(a===C)return"TRACE"}};e.u.obj.expose("h5.log",{createLogger:function(a){return new j(a)},configure:function(){function b(e,g,m){var k=null==m;if(!k){var t=g.category;(!y(t)||0===a.trim(t).length)&&d(N);t=a.trim(t);-1!==a.inArray(t,j)&&d(q,g.category);g.compiledCategory=va(t);j.push(t)}t=null==g.level?I(k?o.level:m.level):y(g.level)?I(a.trim(g.level)):g.level;"number"!==typeof t&&d(A,g.level);g.compiledLevel=t;var t=[],n=g.targets;if(!k||null!=n){var L=[];null==n||M(n)||y(n)&&a.trim(n).length||
d(l);for(var n=R(n),E=0,w=n.length;E<w;E++){null==n[E]||y(n[E])&&a.trim(n[E]).length||d(l);var v=n[E];if(v){-1!==a.inArray(v,L)&&d(f,v);var p=e[v];p||d(c,v);L.push(v);t.push(p.compiledTarget)}}if(!k&&(e=m.targets,null!=e)){e=R(e);E=0;for(w=e.length;E<w;E++)v=e[E],-1===a.inArray(v,L)&&(t.push(m.compiledTargets[E]),L.push(v))}}g.compiledTargets=t}var o={level:"NONE",targets:null},j=[],m=a.extend(!0,{},e.settings.log?e.settings.log:{defaultOut:o}),k=m.target;k||(k={},m.target=k);(function(b){a.isPlainObject(b)||
d(10009);for(var c in b){var f=b[c];a.type(f.type)!=="object"&&f.type!=="console"&&d(1E4);var o=null,o=f.type==="console"?new p:a.extend(true,{},f.type);o.init&&o.init(f);f.compiledTarget=o}b.console={type:"console",compiledTarget:new p}})(k);var u=m.defaultOut;u||(u=o,m.defaultOut=u);b(k,u);var J=m.out;if(J)for(var J=R(J),x=0,G=J.length;x<G;x++)b(k,J[x],u);g=m}})})();(function(){function d(m){e.settings.aspects=a.map(R(m),function(a){a.target&&(a.compiledTarget=va(a.target));a.pointCut&&(a.compiledPointCut=
va(a.pointCut));return a})}e.u.obj.ns("h5.settings");e.settings={commonFailHandler:null,aspects:null,log:null,listenerElementType:1,dynamicLoading:{retryCount:3,retryInterval:500},ajax:{retryCount:0,retryInterval:500,retryFilter:function(a){a=a.status;if("POST"===this.type||!(0===a||a===lb))return!1}},trackstartTouchAction:"none"};var G=e.u.createInterceptor(function(a,d){this.log.info("{0}.{1}が開始されました。",this.__name,a.funcName);this.log.info(a.args);d.start=new Date;return a.proceed()},function(a,
d){var e=(new Date).getTime()-d.start.getTime();this.log.info("{0}.{1}が終了しました。 Time={2}ms",this.__name,a.funcName,e)});e.u.obj.expose("h5.core.interceptor",{lapInterceptor:G,logInterceptor:G,errorInterceptor:function(a){var d=null;try{d=a.proceed()}catch(m){e.settings.commonFailHandler&&Q(e.settings.commonFailHandler)&&e.settings.commonFailHandler.call(null,m)}return d}});a(document).trigger("h5preinit");e.settings.aspects&&d(e.settings.aspects);e.log.configure()})();(function(){e.u.obj.expose("h5.env",
{ua:function(d){function e(a,b){var c=F(a,"[^;)]*",b).split(" ");return 1===c.length?"":c[c.length-1]}function k(a,b){var c=F(a,"[^;) ]*",b).split("/");return 1===c.length?"":c[c.length-1]}function x(a,b){var c=F(a,"[^;) ]*",b).split(":");return 1===c.length?"":c[c.length-1]}var C=!!d.match(/iPhone/i),y=!!d.match(/iPad/i),D=C||y,I=!!d.match(/android/i),H=!!d.match(/Windows Phone/i),u=!!d.match(/MSIE/)||!!d.match(/Trident/),o=!!d.match(/Firefox/i),p=!!d.match(/Chrome/i)||!!d.match(/CrMo/)||!!d.match(/CriOS/),
j=!I&&!!d.match(/Safari/i)&&!p,q=!!d.match(/Webkit/i),A=!!d.match(/Opera/i),c=I&&!!d.match(/Safari/i)&&!p,b=!(!C&&!H&&!(c&&d.match(/Mobile/)&&!d.match(/SC-01C/)||I&&p&&d.match(/Mobile/)||d.match(/Fennec/i)||d.match(/Opera Mobi/i))),f=!(!y&&!(c&&!d.match(/Mobile/)||I&&p&&!d.match(/Mobile/)||d.match(/SC-01C/)||d.match(/Fennec/i)||d.match(/Opera Tablet/i))),l=!b&&!f,N=null,J=null,g=function(b,c){return a.trim(d.substring(d.indexOf(b)+b.length,d.indexOf(c))).split("_")},F=function(b,c,f){return a.trim(d.match(!1===
f?RegExp(b+c):RegExp(b+c,"i")))};if(C)J=g("iPhone OS","like"),N=parseInt(J[0]),J=J.join(".");else if(y)J=g("CPU OS","like"),N=parseInt(J[0]),J=J.join(".");else if(!I||!o)I?(J=e("Android"),N=parseInt(J.split(".")[0])):H&&((J=e("Windows Phone OS"))||(J=e("Windows Phone")),N=parseInt(J.split(".")[0]));u&&A&&(u=!1);var S=g=null;if(D||I&&c)g=N,S=J;else{var r=null;u?r=e("MSIE",!1)||x("rv"):p?(r=k("Chrome",!1))||(r=k("CrMo",!1)):j?r=k("Version"):o?r=k("Firefox"):A&&((r=k("Version"))||(r=k("Opera")),r||(r=
e("Opera")));r&&(g=parseInt(r.split(".")[0]),S=r)}return{osVersion:N,osVersionFull:J,browserVersion:g,browserVersionFull:S,isiPhone:C,isiPad:y,isiOS:D,isAndroid:I,isWindowsPhone:H,isIE:u,isFirefox:o,isChrome:p,isSafari:j,isOpera:A,isAndroidDefaultBrowser:c,isSmartPhone:b,isTablet:f,isDesktop:l,isWebkit:q}}(navigator.userAgent)})})();(function(){function m(a){function d(){e=!0;q=this;m=D(arguments);if(Da(a)||Ea(a))return a;var b=D(arguments);if(0<c.length)for(var f=0,l=c.length;f<l;f++){var k=b;k!==
arguments&&(k=R(k));Q(c[f])&&c[f].apply(this,k)}return a}var e=!1,q=null,m=null,c=[];a.progress=function(){for(var b=D(arguments),d=0,l=b.length;d<l;d++){var k=b[d];if(M(k))a.progress.apply(this,k);else if(Q(k))if(e){var p=m;p!==m&&(p=R(p));k.apply(q,p)}else c.push(k)}return this};a.notify=d;a.notifyWith=function(a,c){return!c?d.apply(a):d.apply(a,c)}}function G(a){if(!a)return!1;for(var a=R(a),d=0,e=a.length;d<e;d++)if(Q(a[d]))return!0;return!1}function k(d,p){function j(a){p?p[a]&&(d[a]=p[a]):(f[a]=
d[a],d[a]=function(){return function(){if(!c){var b=D(arguments);if("then"===a||"pipe"===a)b=b[1];G(b)&&(c=!0)}return d._h5UnwrappedCall.call(this,a,D(arguments))}}(a),l[a]=d[a])}function q(a){return function(){var f=e.settings.commonFailHandler;!c&&f&&!b&&(d.fail.call(this,f),b=!0);return a.apply(this,arguments)}}if(d._h5UnwrappedCall)return d;var A=!!d.progress;!A&&!u(d)?m(d):p&&(d.progress=p.progress);var c=!1,b=!1,f={},l={};d._h5UnwrappedCall=p?p._h5UnwrappedCall:function(b,c){c=R(c);a.extend(d,
f);var e=d[b].apply(this,c);a.extend(d,l);return e};for(var N=0,J=x.length;N<J;N++){var g=x[N];d[g]&&j(g)}d.pipe&&!p&&(d.pipe=function(){for(var a=e.async.deferred(),b=D(arguments),c=0,d=C.length;c<d;c++){var f=this;(function(b,c,d){function e(){if(g){var c=b.apply(this,arguments);if(c&&Q(c.promise)){k(c);c.done(a.resolve);c._h5UnwrappedCall("fail",a.reject);Q(c.progress)&&c.progress(a.notify)}else a[d+"With"](this,[c])}else a[d+"With"](this,arguments)}var g=Q(b);if(!g&&c==="fail")f._h5UnwrappedCall(c,
e);else f[c](e)})(b[c],C[c],y[c])}return a.promise()},l.pipe=d.pipe);if(d.then&&!p){var F=d.then;d.then=I?d.pipe:function(){var a=arguments,b=F.apply(this,a);!A&&G(a[2])&&d.progress.call(d,a[2]);return b};l.then=d.then}d.reject&&(d.reject=p&&p.reject?p.reject:q(d.reject));d.rejectWith&&(d.rejectWith=p&&p.rejectWith?p.rejectWith:q(d.rejectWith));if(d.promise)if(p&&p.promise)d.promise=p.promise;else{var H=d.promise;d.promise=function(){return k(H.apply(this,arguments),d)}}return d}var x=["fail","always",
"pipe","then"],C=["done","fail","progress"],y=["resolve","reject","notify"],D=e.u.obj.argsToArray,I=function(){var d=a.Deferred();return d!==d.then()}(),H=function(){var d=a.Deferred();return k(d)},u=function(a){return!!a&&a.done&&a.fail&&!a.resolve&&!a.reject};e.u.obj.expose("h5.async",{deferred:H,when:function(){var d=D(arguments);1===d.length&&M(d[0])&&(d=d[0]);var m=d.length,j=e.async.deferred(),q=j.promise(),k=a.when.apply(a,d).done(function(){j.resolveWith(this&&this.promise&&this.promise()===
k?j:this,D(arguments))}).fail(function(){j.rejectWith(this,D(arguments))});if(k.progress)k.progress(function(){j.notifyWith(this===k?q:this,D(arguments))});else{for(var c=[],b=0;b<m;b++)c[b]=void 0;for(var f=function(a){return function(b){c[a]=1<arguments.length?D(arguments):b;j.notifyWith(q,c)}},b=0;b<m;b++){var l=d[b];l&&Q(l.promise)&&l.progress&&(1<m?l.progress(f(b)):l.progress(function(){j.notifyWith(q,D(arguments))}))}}return q},isPromise:u,loop:function(e,m,j){M(e)||d(5E3);var k=H(),A="number"===
a.type(j)?j:20,c=0,b=e.length,f,l=null,N=function(){if(c===b)k.resolve(e);else{var a=m.call(e,c,e[c],l);c++;u(a)?a.done(function(){f()}).fail(function(){k.reject(e)}):f()}},J=function(){setTimeout(function(){var a=c-1;0<c&&k.notify({data:e,index:a,value:e[a]});N()},0)},g=!1;f=function(){g||(0===c%A?J():N())};var F=!1,l={resume:function(){!F&&g&&(g=!1,f())},pause:function(){g=!0},stop:function(){F=!0;k.resolve(e)}};J();return k.promise()}})})();(function(){function d(a,e){for(var k=0,m=C.length;k<
m;k++){var o=C[k];a[o]&&(e[O[o]](a[o]),a[o]=void 0)}}function G(d,e,k){for(var m in e)if(e.hasOwnProperty(m)&&(k||!Q(e[m]))&&-1===a.inArray(m,x))d[m]=e[m]}function k(a,d){G(this,a,!0);d.promise(this);var e=this.always;this.always=function(){e.apply(this,arguments);return this}}var x=["error","success","complete"],C=["error","success","complete"],O={success:"done",error:"fail",complete:"always"};e.u.obj.expose("h5",{ajax:function(){function x(a,d,e){G(p,e);o.resolveWith(this,arguments)}function C(d,
e,k){if(0===H.retryCount||!1===H.retryFilter.apply(this,arguments))G(p,d),o.rejectWith(this,arguments);else if(H.retryCount--,this.async){var c=this;setTimeout(function(){a.ajax(c).done(x).fail(C)},H.retryInterval)}else a.ajax(this).done(x).fail(C)}var H={},u=arguments;y(u[0])?(a.extend(H,u[1]),H.url=u[0]):a.extend(H,u[0]);var H=a.extend({},e.settings.ajax,H),o=e.async.deferred();d(H,o);var u=a.ajax(H),p=new k(u,o);u.done(x).fail(C);return p}})})();(function(){function m(a,b,c,h,i){for(var e in c)e in
vb&&d(wa,[i,e],{controllerDefObj:c})}function G(b,c){function h(i,e){-1!==a.inArray(i,e)&&d(Fa,[c],{controllerDefObj:b});u(i,function(a){h(a,e.concat([i]))},!0)}h(b,[])}function k(b){function c(h,i){-1!==a.inArray(h,i)&&d(ka,[b.__name],{logicDefObj:b});o(h,function(a){c(a,i.concat(h))})}c(b,[])}function x(b,c,h){null==b&&d(Ua,[h],{controllerDefObj:c});!y(b)&&"object"!==typeof b&&d(B,[h],{controllerDefObj:c});b=a(b);0===b.length&&d(Va,[h],{controllerDefObj:c});1<b.length&&d(qa,[h],{controllerDefObj:c});
b[0].nodeType!==Ja&&b[0].nodeType!==ba&&d(ha,[h],{controllerDefObj:c})}function C(a,b,c,h,d){this.controller=a;this.event=b;this.evArg=c;this.selector=h;this.selectorType=d}function O(a){return v(this)||!this.__controllerContext.executeListeners?void 0:a.proceed()}function D(a,b,c){var h;h=a.__name;var d=[],i=e.settings.aspects;if(i&&0!==i.length)for(var i=R(i),f=i.length-1;-1<f;f--){var n=i[f];if(!n.target||n.compiledTarget.test(h)){var B=n.interceptors;if(!n.pointCut||n.compiledPointCut.test(b))if(M(B))for(n=
B.length-1;-1<n;n--)d=d.concat(B[n]);else d.push(B)}}h=d;c&&h.push(O);return I(a[b],b,h)}function I(a,b,c){for(var h=function(a,b,c){return function(){var za=this;return c.call(za,{target:za,func:a,funcName:b,args:arguments,proceed:function(){return a.apply(za,this.args)}})}},d=0,i=c.length;d<i;d++)a=h(a,b,c[d]);return a}function H(a,b,c){if(c&&a===la)return c.rootElement;for(var h=["window","document","navigator"],d=0,i=h.length;d<i;d++){var f=h[d];if(a===f||pb(a,f+"."))return e.u.obj.getByPath(a,
V(b))}return c&&pb(a,"this.")?e.u.obj.getByPath(a.slice(5),c):a}function u(a,b,c){var h=c?da.get(a.__name):a.__controllerContext&&a.__controllerContext.cache;if(h)for(var c=0,d=h.childControllerProperties.length;c<d;c++){var i=h.childControllerProperties[c];if(!1===b(a[i],a,i))return!1}else for(i in a){var h=a,d=i,e=c,f=h[d];if(La(d,aa)&&"rootController"!==d&&"parentController"!==d&&f&&(e||f.__controllerContext&&!f.__controllerContext.isRoot&&(!f.parentController||f.parentController===h))&&!1===b(a[i],
a,i))return!1}}function o(a,b){var c=da.get(a.__name);if(c)for(var h=0,d=c.logicProperties.length;h<d;h++){var i=c.logicProperties[h];if(!1===b(a[i],a,i))return!1}else for(i in a)if(a.hasOwnProperty(i)&&La(i,Z)&&!1===b(a[i],a,i))return!1}function p(a,b,c,h){function d(a,c,h){if(!1===p(a,b,c,h))return!1}return!1===b.call(this,a,c,h)?!1:u(a,d)}function j(a,b,c,h){if(!1===u(a,function(a,c,h){if(!1===j(a,b,c,h))return!1})||!1===b.call(this,a,c,h))return!1}function q(a,b){var c=[];u(a,function(a){(a=a[b])&&
c.push(a)});return c}function A(b,c,h){function d(b){var c=b.handler,h=b.controller;b.originalHandler=c;b.handler=function(){var d=!b.isNativeBind&&1===e.settings.listenerElementType?a(this):this;c.call(h,ea(b,arguments),d)}}var i=c.selector,f=c.eventName;switch(f){case "mousewheel":h=t(b,i,f,h);break;case Ma:case qb:case Wa:h=xa(b,i,f,h);break;default:h=r(b,i,f,h)}M(h)||(h=[h]);i=0;for(f=h.length;i<f;i++){var n=h[i];d(n);n.isBindRequested=c.isBindRequested;n.isGlobal=c.isGlobal;n.bindTarget=c.bindTarget;
n.controller=b}return h}function c(b,c){var h=b.controller,d=h.rootElement,i=b.selector,f=b.eventName,n=b.handler,B=b.isBindRequested,z=b.isGlobal;b.bindTarget?(b.evSelectorType=ra.SELECTOR_TYPE_OBJECT,Na(b)):z?(h=H(i,c,h),B||!y(h)?(b.evSelectorType=ra.SELECTOR_TYPE_OBJECT,b.bindTarget=y(h)?a(h):h,Na(b)):(b.evSelectorType=ra.SELECTOR_TYPE_GLOBAL,a(c).delegate(h,f,n)),b.evSelector=h):(b.evSelectorType=ra.SELECTOR_TYPE_LOCAL,b.evSelector=i,B?(b.bindTarget=a(i,d),Na(b)):a(d).delegate(i,f,n));b.isBindCanceled||
(b.controller.__controllerContext.boundHandlers.push(b),wb&&f===Ma&&null!=e.settings.trackstartTouchAction&&(z?a(b.evSelector,c):a(b.evSelector,d)).each(function(){this.style[db]=e.settings.trackstartTouchAction}))}function b(b,c,h){var d=b.controller,i=d.rootElement,e=b.selector,f=b.handler,n=b.eventName,B=b.isGlobal;if(b.bindTarget)c=b.bindTarget,i=b.eventName,e=b.handler,b.isNativeBind?c.removeEventListener(i,e):a(c).unbind(i,e);else if(B){if(null==V(c))return;a(c).undelegate(e,n,f)}else a(i).undelegate(e,
n,f);h||(h=d.__controllerContext.boundHandlers,h.splice(a.inArray(b,h),1))}function f(a,b){p(a,function(a){a.__controllerContext.executeListeners=b})}function l(a,b,c){return function(){var h=null,d=a.__name;if(a[b])try{h=a[b]({args:a.__controllerContext.args})}catch(i){L(a,i)}h&&Q(h.done)&&Q(h.fail)?h.done(c).fail(function(){var b=ca(K,d,Aa(arguments));L(a.rootController,null,b)}):c()}}function N(a,b){p(a,function(a){if(!v(a)&&!a.__controllerContext.isDisposing){var c,h;"__init"===b?(c=J(a),h=[a.preInitPromise],
a.parentController&&h.push(a.parentController.initPromise)):"__postInit"===b?(c=g(a),h=q(a,"postInitPromise")):(c=F(a),h=q(a,"readyPromise"));Ka(h,l(a,b,c))}})}function J(a){return function(){if(!ga(a)){a.isInit=!0;var b=a.__controllerContext.initDfd;delete a.__controllerContext.templatePromise;delete a.__controllerContext.preInitDfd;delete a.__controllerContext.initDfd;var h=a.rootElement,c=[];try{var d=a.__meta;u(a,function(b,i,e){c.push(b);i=d&&d[e]&&d[e].rootElement?U(d[e].rootElement,b,a):h;
x(i,b.__controllerContext.controllerDef,b.__name);b.rootElement=i;b.view.__controller=b})}catch(i){L(a,i);return}b.resolveWith(a);ga(a)||!c.length&&function(){var b=!0;p(a.rootController,function(a){return b=a.isInit});return b}()&&N(a.rootController,"__postInit")}}}function g(a){return function(){if(!ga(a)){a.isPostInit=!0;var b=a.__controllerContext.postInitDfd;delete a.__controllerContext.postInitDfd;b.resolveWith(a);!ga(a)&&a.__controllerContext.isRoot&&(p(a,function(a,b,h){var d=!0;b&&b.__meta&&
b.__meta[h]&&(d=!1!==b.__meta[h].useHandlers);if(d){var b=a.__controllerContext.cache.bindMap,h=T(a.rootElement),i;for(i in b)for(var d=A(a,b[i],a[i]),za=0,e=d.length;za<e;za++)c(d[za],h)}}),ub(a))}}}function F(b){return function(){if(!ga(b)){b.isReady=!0;var h=b.__controllerContext.readyDfd;delete b.__controllerContext.readyDfd;h.resolveWith(b);ga(b)||b.__controllerContext.isRoot&&b.rootElement&&b.isInit&&b.isPostInit&&b.isReady&&a(b.rootElement).trigger("h5controllerready",b)}}}function S(b,h){if(!y(b))return a(b);
var c=a.trim(b);return rb.test(c)?(c=a.trim(c.substring(1,c.length-1)),a(H(c,T(h.rootElement),h))):a(h.rootElement).find(b)}function r(a,b,h,c){return{controller:a,selector:b,eventName:h,handler:c}}function t(a,b,h,c){return{controller:a,selector:b,eventName:typeof document.onmousewheel===ja?"DOMMouseScroll":h,handler:function(b){var h=b.event;null==h.wheelDelta&&h.originalEvent&&null!=h.originalEvent.wheelDelta&&(h.wheelDelta=h.originalEvent.wheelDelta);null==h.wheelDelta&&h.originalEvent&&null!=
h.originalEvent.detail&&(h.wheelDelta=40*-h.originalEvent.detail);c.call(a,b)}}}function xa(b,h,c,d){function i(a,b){for(var h in a)a.hasOwnProperty(h)&&!b[h]&&"target"!==h&&"currentTarget"!==h&&"originalEvent"!==h&&"liveFired"!==h&&(b[h]=a[h]);b.h5DelegatingEvent=a}var e=typeof document.ontouchstart!==ja;if(c!==Ma)return r(b,h,c,function(b){var h=b.event.h5DelegatingEvent.type;if("mousemove"===h||"mouseup"===h){var h=b.event,c=a(h.currentTarget).offset()||{left:0,top:0};h.offsetX=h.pageX-c.left;
h.offsetY=h.pageY-c.top}d.apply(this,arguments)});var f=a(T(b.rootElement));return function(){function n(h,c,d){return function(e){var B;a:{switch(h){case "touchstart":case "mousedown":B=Ma;break a;case "touchmove":case "mousemove":B=qb;break a;case "touchend":case "mouseup":B=Wa;break a}B=void 0}var Ta=B===Ma;if(!Ta||!g){var K=0===e.event.type.indexOf("touch");K&&ma(e.event,h);var l=new a.Event(B);i(e.event,l);var ob=e.event.target;c&&(ob=c);d&&d(l);var k=e.event.originalEvent||e.event;Ta&&-1===
a.inArray(k,sa)&&(sa=[],Ba=[]);var j=a.inArray(k,sa);-1===j&&(j=sa.push(k)-1,Ba[j]=!1);if(!Ba[j]&&(!K||g||Ta))Ba[j]=!0,a(ob).trigger(l,e.evArg),g=!0;if(e.event.currentTarget===document&&(B===Wa&&(sa=[],Ba=[]),-1!==a.inArray(k,sa)))sa.splice(j,1),Ba.splice(j,1);if(Ta&&g){l.h5DelegatingEvent.preventDefault();B=l.target;var ha=l.clientX,m=l.clientY,s=K?"touchmove":"mousemove",w=K?"touchend":"mouseup",E=n(s,B,function(a){var b=a.clientX,h=a.clientY;a.dx=b-ha;a.dy=h-m;ha=b;m=h}),P=n(w,B),L=function(a){e.event=
a;e.evArg=ya(arguments);E(e)},da=function(a){e.event=a;e.evArg=ya(arguments);P(e)},Ha=K?a(B):f;z=function(){sa=[];Ba=[];Ha.unbind(s,L);Ha.unbind(w,da);if(!K&&b.rootElement!==document){a(b.rootElement).unbind(s,L);a(b.rootElement).unbind(w,da)}};Ha.bind(s,L);Ha.bind(w,da);!K&&b.rootElement!==document&&(a(b.rootElement).bind(s,L),a(b.rootElement).bind(w,da))}else B===Wa&&(z(),g=!1)}}}function B(a){return{controller:b,selector:h,eventName:a,handler:n(a)}}var z=null,g=!1,K=[r(b,h,c,d)];e&&K.push(B("touchstart"));
K.push(B("mousedown"));return K}()}function ma(b,h){var c=b.originalEvent;if(c){var d="touchend"===h||"touchcancel"===h?c.changedTouches[0]:c.touches[0],i=d.pageX,e=d.pageY;b.pageX=c.pageX=i;b.pageY=c.pageY=e;b.screenX=c.screenX=d.screenX;b.screenY=c.screenY=d.screenY;b.clientX=c.clientX=d.clientX;b.clientY=c.clientY=d.clientY;d=b.target;if(d.ownerSVGElement)d=d.farthestViewportElement;else if(d===window||d===document)d=document.body;if(d=a(d).offset())e-=d.top,b.offsetX=c.offsetX=i-d.left,b.offsetY=
c.offsetY=e}}function ya(a){return 3>a.length?a[1]:Aa(a).slice(1)}function ea(b,h){var c=null,d=null;h&&(c=h[0],d=ya(h));var i=c;if(i&&null==i.offsetX&&null==i.offsetY&&i.pageX&&i.pageY){var e=i.target;if(e.ownerSVGElement)e=e.farthestViewportElement;else if(e===window||e===document)e=document.body;if(e=a(e).offset())i.offsetX=i.pageX-e.left,i.offsetY=i.pageY-e.top}return new C(b.controller,c,d,b.evSelector,b.evSelectorType)}function na(a){p(a,function(a){a.rootElement=null;a.view.__controller=null})}
function U(b,h,c){null==b&&d(Ua,[h.__name]);!y(b)&&"object"!==typeof b&&d(B,[h.__name]);b=c?S(b,c):a(b);0===b.length&&d(Va,[h.__name]);1<b.length&&d(qa,[h.__name]);return b.get(0)}function ub(b){var h=b.__controllerContext.managed,c=Ga.controllers;-1===a.inArray(b,c)&&!1!==h&&c.push(b);!1!==h&&a(b.rootElement).trigger("h5controllerbound",b);N(b,"__ready")}function Sa(a){ia();setTimeout(function(){N(a,"__init")},0)}function fa(a,b){p(a,function(a){var h=ia();h.resolve();a.__controllerContext.templatePromise=
h.promise();a.__controllerContext.initDfd=ia();a.initPromise=a.__controllerContext.initDfd.promise();a.__controllerContext.postInitDfd=ia();a.postInitPromise=a.__controllerContext.postInitDfd.promise();a.__controllerContext.readyDfd=ia();a.readyPromise=a.__controllerContext.readyDfd.promise();a.isInit=!1;a.isPostInit=!1;a.isReady=!1;a.__controllerContext.isUnbinding=!1;a.__controllerContext.isUnbinded=!1;a.__controllerContext.args=b})}function $(b,h){var c=null,d=h;a.isPlainObject(d)?c=d.target:d=
{};c=c?S(c,b):b.rootElement;return e.ui.indicator.call(b,c,d)}function n(a,b){var h=[],c=null;j(a,function(a){if(a[b]&&Q(a[b])){try{var d=a[b]()}catch(i){c=c||i}xb(d)&&h.push(d)}});if(c)throw c;return h}function L(a,b,h){function c(){var a=b||h||B||g;j(i,function(b){b.view&&b.view.__view&&b.view.__view.clear();if(a)b.__controllerContext.isDisposed=1;else for(var h in b)b.hasOwnProperty(h)&&(b[h]=null)});g?K.rejectWith(i,[g]):K.resolveWith(i);if(a&&(Ga.dispatchEvent({type:"lifecycleerror",detail:a,
rootController:i}),b||B))throw b||B;}function d(){g=B||ca(yb,i.__name,Aa(arguments));c()}var i=a.__controllerContext&&(a.__controllerContext.isRoot?a:a.rootController);if(i){if(!v(i)&&!i.__controllerContext.isDisposing){i.__controllerContext.isDisposing=1;try{E(i,h||b)}catch(e){b=b||e}var f,B=null;try{f=n(i,"__dispose")}catch(z){b=b||z,B=B||z}var K=i.deferred(),g=null;B?d():Ka(f,c,d,!0);return K.promise()}}else if(b)throw b;}function E(h,c){if(!ga(h)){h.__controllerContext.isUnbinding=1;eb(h,c);var d;
try{n(h,"__unbind")}catch(i){d=i}p(h,function(a){var h=a.rootElement;if(h){for(var h=T(h),c=a.__controllerContext.boundHandlers,d=0,i=c.length;d<i;d++)b(c[d],h,!0);a.__controllerContext.boundHandlers=[]}});h.__controllerContext.unbindList={};Ga.controllers=a.grep(Ga.controllers,function(a){return a!==h});h.isPostInit&&!1!==h.__controllerContext.managed&&a(h.rootElement).trigger("h5controllerunbound",h);na(h);h.__controllerContext.isUnbinded=1;if(d)throw d;}}function w(a,b){return b.view.__view.isAvailable(a)?
b.view.__view:b.parentController?w(a,b.parentController):e.core.view}function v(a){return!a.__controllerContext||a.__controllerContext.isDisposed}function ga(a){return v(a)||a.__controllerContext.isUnbinding||a.__controllerContext.isUnbinded}function eb(a,b){var h=["postInitDfd","readyDfd"],c=[];p(a,function(a){c.push(a);var h=a.__controllerContext.initDfd;h&&!Da(h)&&!Ea(h)&&h.rejectWith(a,[b])});for(var d=0,i=h.length;d<i;d++)for(var e=h[d],f=c.length-1;0<=f;f--){var B=c[f],n=B.__controllerContext[e];
n&&!Da(n)&&!Ea(n)&&n.rejectWith(B,[b])}}function oa(a,b){for(var h=a.childNodes,c=0,d=h.length;c<d;c++){var i=h[c];if(1===i.nodeType){if(i=oa(i,b))return i}else if(8===i.nodeType){var e=i.nodeValue;if(0===e.indexOf(va)){var f=e.indexOf("}");if(-1!==f&&(e=e.slice(0,f).match(/id="([A-Za-z][\w-:\.]*)"/))&&e[1]===b)return i}}}return null}function pa(a){var b=this;return function(){return a.apply(b,arguments)}}function ta(a){var b=this;return function(){var h=e.u.obj.argsToArray(arguments);h.unshift(this);
return a.apply(b,h)}}function Xa(a,b,c){function i(f){e.u.obj.getByPath("h5.core.view")||d(h);a.view.__view.load(c).done(function(){b.resolve()}).fail(function(a){var h=a.detail.error.status;f===e.settings.dynamicLoading.retryCount||0!==h&&h!==lb?setTimeout(function(){b.reject(a)},0):setTimeout(function(){i(++f)},e.settings.dynamicLoading.retryInterval)})}i(0)}function ua(b,h,c,i){var e=y(b),f=e?null:b,b=e?a.trim(b):null,h=a.trim(h),B=!e||rb.test(b),n=Oa.test(h);n&&(h=a.trim(a.trim(h.substring(1,
h.length-1))));e&&B&&(b=a.trim(b.substring(1,b.length-1)),"this"===b&&d(zb,[c.__name],{controllerDef:c}));return{selector:b,bindTarget:f,isGlobal:B,isBindRequested:n,eventName:h,propertyKey:i}}function i(){this.logicProperties=[];this.eventHandlerProperties=[];this.functionProperties=[];this.otherProperties=[];this.bindMap={};this.childControllerProperties=[]}function s(b){var h=new i,c=h.logicProperties,e=h.eventHandlerProperties,f=h.functionProperties,B=h.otherProperties,n=h.bindMap,K=h.childControllerProperties,
z={},g;for(g in b)if(-1!==g.indexOf(" ")&&Q(b[g])){e.push(g);var l=a.trim(g),j=l.lastIndexOf(" "),l=ua(l.substring(0,j),l.substring(j+1,l.length),b,g),j=l.selector,k=l.eventName,s=l.isGlobal,ha=l.isBindRequested;z[j]||(z[j]={});z[j][k]||(z[j][k]={});z[j][k][s]||(z[j][k][s]={});z[j][k][s][ha]?d(fb,[b.__name,j,k],{controllerDef:b}):z[j][k][s][ha]=1;n[g]=l}else La(g,aa)&&b[g]&&!Q(b[g])?K.push(g):La(g,Z)&&b[g]&&!Q(b[g])?c.push(g):Q(b[g])?f.push(g):B.push(g);return h}function P(){this.logicProperties=
[];this.functionProperties=[]}function Y(a,b){if(a===b)return!0;var h=gb(a),c=gb(b);if(!h&&!c)return!1;h=h?a.toArray():[a];c=c?b.toArray():[b];if(h.length!==c.length)return!1;for(var d=0,i=h.length;d<i;d++)if(h[d]!==c[d])return!1;return!0}function W(a,b){(!a||!a.rootElement)&&d(z,b)}function X(a,b){(!a||v(a))&&d(Ha,b)}function Na(b){var h=b.bindTarget,c=b.eventName,d=b.handler;h&&typeof h.nodeType!==ja||jb(h)||gb(h)?a(h).bind(c,d):!h||!h.addEventListener?b.isBindCanceled=!0:(h.addEventListener(c,
d),b.isNativeBind=!0)}function Ya(a){this.__controller=a;e.u.obj.getByPath("h5.core.view")&&(this.__view=e.core.view.createView())}function Ca(a,b,h,c,d){this.__name=b;this.__templates=null;this.rootElement=a;this.__controllerContext={executeListeners:!0,isRoot:d,boundHandlers:[],controllerDef:h};this.__controllerContext.args=c?c:null;this.isReady=this.isPostInit=this.isInit=!1;this.readyPromise=this.postInitPromise=this.initPromise=this.preInitPromise=this.parentController=this.rootController=null;
this.log=e.log.createLogger(b);this.view=new Ya(this)}function Pa(){this.rootElement=document;this.controllers=[];a(document).bind(sb,function(a,b){null==b.target&&(b.target=document);b.indicator=$(this,b);a.stopPropagation()})}function Za(){this._init()}function Qa(b,h,c,i){var e=!i||!i.isInternal,f=h.__name;(!y(f)||0===a.trim(f).length)&&d($a,null,{controllerDefObj:h});c&&!a.isPlainObject(c)&&d(ab,[f],{controllerDefObj:h});h.__controllerContext&&d(Ia,null,{controllerDefObj:h});var B=da.get(f);B||
m(e,b,h,c,f);e&&G(h,f);B||(B=s(h),da.register(f,B));e&&x(b,h,f);var n=new Ca(b?a(b).get(0):null,f,h,c,e),g=ia(),f=g.promise().fail(bb),z=ia(),K=z.promise().fail(bb),l=ia(),j=l.promise().fail(bb),k=ia(),ha=k.promise();e||ha.fail(bb);b=n.__controllerContext;b.cache=B;b.preInitDfd=g;b.initDfd=z;b.postInitDfd=l;b.readyDfd=k;n.preInitPromise=f;n.initPromise=K;n.postInitPromise=j;n.readyPromise=ha;z=0;for(K=B.logicProperties.length;z<K;z++)l=B.logicProperties[z],n[l]=Ra(h[l]);f=a.extend(!0,{},h);h=h.__templates;
z=ia();K=z.promise();h&&0<h.length?Xa(n,z,h):z.resolve();K.done(function(){!v(n)&&!n.__controllerContext.isDisposing&&g.resolveWith(n)}).fail(function(a){g.rejectWith(n,[a]);L(n,null,a)});z=0;for(K=B.childControllerProperties.length;z<K;z++)l=B.childControllerProperties[z],n[l]=Qa(null,a.extend(!0,{},f[l]),c,a.extend({isInternal:!0},i));z=0;for(K=B.eventHandlerProperties.length;z<K;z++)l=B.eventHandlerProperties[z],n[l]=D(f,l,!0);z=0;for(K=B.functionProperties.length;z<K;z++)l=B.functionProperties[z],
n[l]=D(f,l);z=0;for(K=B.otherProperties.length;z<K;z++)l=B.otherProperties[z],n[l]=f[l];if(e){var w=!1;p(n,function(a,b){try{a.__construct&&a.__construct({args:a.__controllerContext.args})}catch(h){L(n,h)}if(v(a)||a.__controllerContext.isDisposing){w=true;return false}if(a===n){a.rootController=a;a.parentController=null}else{a.parentController=b;a.rootController=b.rootController}});if(w)return null}b.managed=i&&i.managed;e&&Sa(n);return n}function Ra(b){function h(b,c){var i=b.__name;(!y(i)||0===
a.trim(i).length)&&d(hb,null,{logicDefObj:b});b.__logicContext&&d(cb,null,{logicDefObj:b});var f=da.get(i);if(!f){c&&k(b);var f=new P,n=f.functionProperties,B=f.logicProperties,z;for(z in b)b.hasOwnProperty(z)&&La(z,Z)?B.push(z):Q(b[z])&&n.push(z)}z=a.extend(!0,{},b);for(var g=f.functionProperties,n=0,B=g.length;n<B;n++){var K=g[n];z[K]=D(z,K)}z.deferred=ia;z.log=e.log.createLogger(i);z.__logicContext={logicDef:b};z.own=pa;z.ownWithOrg=ta;g=f.logicProperties;n=0;for(B=g.length;n<B;n++)K=g[n],z[K]=
h(z[K]);Q(z.__construct)&&z.__construct();da.register(i,f);return z}return h(b,!0)}var ra={SELECTOR_TYPE_LOCAL:1,SELECTOR_TYPE_GLOBAL:2,SELECTOR_TYPE_OBJECT:3},aa="Controller",Z="Logic",Ma="h5trackstart",qb="h5trackmove",Wa="h5trackend",la="rootElement",sb="triggerIndicator",rb=/^\{.*\}$/,Oa=/^\[.*\]$/,va="{h5view ",Ua=6001,Va=6003,qa=6004,$a=6006,ab=6007,Ia=6008,Fa=6009,ka=6010,wa=6011,zb=6012,fb=6013,hb=6017,cb=6018,h=6029,B=6030,K=6033,ha=6034,z=6035,Ha=6036,yb=6038,Ga,da,bb=function(){},ia=e.async.deferred,
xb=e.async.isPromise,pb=e.u.str.startsWith,La=e.u.str.endsWith,Ab=e.u.str.format,Aa=e.u.obj.argsToArray,gb=e.u.obj.isJQueryObject,sa=[],Ba=[],db="",wb=function(){var a=document.createElement("div");return typeof a.style.touchAction!==ja?(db="touchAction",!0):typeof a.style.msTouchAction!==ja?(db="msTouchAction",!0):!1}();a.extend(C.prototype,ra);a.extend(Ya.prototype,{get:function(a,b){W(this.__controller,"view#get");return w(a,this.__controller).get(a,b)},update:function(a,b,h){W(this.__controller,
"view#update");a=S(a,this.__controller);return w(b,this.__controller).update(a,b,h)},append:function(a,b,h){W(this.__controller,"view#append");a=S(a,this.__controller);return w(b,this.__controller).append(a,b,h)},prepend:function(a,b,h){W(this.__controller,"view#prepend");a=S(a,this.__controller);return w(b,this.__controller).prepend(a,b,h)},load:function(a){W(this.__controller,"view#load");return this.__view.load(a)},register:function(a,b){W(this.__controller,"view#register");this.__view.register(a,
b)},isValid:function(a){W(this.__controller,"view#isValid");return this.__view.isValid(a)},isAvailable:function(a){W(this.__controller,"view#isAvailable");return w(a,this.__controller).isAvailable(a)},clear:function(a){W(this.__controller,"view#clear");this.__view.clear(a)},getAvailableTemplates:function(){W(this.__controller,"view#getAvailableTemplates");return this.__view.getAvailableTemplates()},bind:function(b,h){W(this.__controller,"view#bind");var c=b;if(y(b)&&0===b.indexOf("h5view#")){for(var d=
oa(this.__controller.rootElement,b.slice(7)),c=d.nodeValue,c=c.slice(c.indexOf("}")+1),i=a("<div>").append(c),c=[],e=i[0].childNodes,f=0,n=e.length;f<n;f++)c.push(e[f]);i.empty();i=document.createDocumentFragment();f=0;for(n=c.length;f<n;f++)i.appendChild(c[f]);d.parentNode.insertBefore(i,d.nextSibling)}return this.__view.bind(c,h)}});a.extend(Ca.prototype,{$find:function(b){X(this,"$find");W(this,"$find");return a(this.rootElement).find(b)},deferred:function(){X(this,"deferred");return ia()},trigger:function(b,
h){X(this,"trigger");W(this,"trigger");var c=y(b)?a.Event(b):b;a(this.rootElement).trigger(c,h);return c},own:function(){X(this,"own");return pa.apply(this,Aa(arguments))},ownWithOrg:function(){X(this,"ownWithOrg");return ta.apply(this,Aa(arguments))},bind:function(a,b){X(this,"bind");this.__controllerContext.isRoot||d(6031);this.rootElement=U(a,this);this.view.__controller=this;fa(this,b?b:null);Sa(this);return this},unbind:function(){X(this,"unbind");W(this,"unbind");this.__controllerContext.isRoot||
d(6031);this.rootController||d(6037);try{E(this)}catch(a){L(this,a)}},dispose:function(){X(this,"dispose");this.__controllerContext.isRoot||d(6031);return L(this)},triggerIndicator:function(b){X(this,"triggerIndicator");W(this,"triggerIndicator");var h={indicator:null};b&&a.extend(h,b);a(this.rootElement).trigger(sb,[h]);return h.indicator},indicator:function(a){X(this,"indicator");W(this,"indicator");return $(this,a)},enableListeners:function(){X(this,"enableListeners");f(this,!0)},disableListeners:function(){X(this,
"disableListeners");f(this,!1)},throwError:function(a,b){X(this,"throwError");var h=Aa(arguments);h.unshift(null);this.throwCustomError.apply(this,h)},throwCustomError:function(a,b,h){X(this,"throwCustomError");2>arguments.length&&d(6005);var c=null;b&&y(b)?c=Error(Ab.apply(null,Aa(arguments).slice(1))):(c=Error(),c.detail=b);c.customType=a;throw c;},on:function(a,b,h){X(this,"on");W(this,"on");a=ua(a,b,this);h=A(this,a,h);a=0;for(b=h.length;a<b;a++)c(h[a],T(this.rootElement))},off:function(a,h,c){X(this,
"off");W(this,"off");for(var d=ua(a,h,this),a=this.__controllerContext.boundHandlers,i=null,e=d.bindTarget,h=d.eventName,f=d.selector,n=d.isGlobal,d=d.isBindRequested,B=0,z=a.length;B<z;B++){var g=a[B];if(e){if(Y(e,g.bindTarget)&&h===g.eventName&&g.originalHandler===c){i=g;break}}else if(f===g.selector&&n===g.isGlobal&&d===g.isBindRequested&&c===g.originalHandler){i=g;break}}i&&b(i,T(this.rootElement))}});e.mixin.eventDispatcher.mix(Pa.prototype);a.extend(Pa.prototype,{getAllControllers:function(){return this.controllers},
getControllers:function(b,h){for(var c=h&&h.deep,d=h&&h.name?R(h.name):null,i=a(b)[0],e=this.controllers,f=[],n=0,B=e.length;n<B;n++){var z=e[n];!(d&&-1===a.inArray(z.__name,d))&&z.rootElement&&(i===z.rootElement?f.push(z):c&&T(i)===T(z.rootElement)&&a.contains(i,z.rootElement)&&f.push(z))}return f}});a.extend(Za.prototype,{get:function(a){return this._cacheMap[a]},register:function(a,b){this._cacheMap[a]=b},clear:function(a){delete this._cacheMap[a]},clearAll:function(){this._cacheMap={}},_init:function(){this._cacheMap=
{}}});da=new Za;Ga=new Pa;e.u.obj.expose("h5.core",{controllerManager:Ga,definitionCacheManager:{clear:function(a){da.clear(a)},clearAll:function(){da.clearAll()}}});var vb=function(){var a={},b=new Ca(null,"a"),h;for(h in b)b.hasOwnProperty(h)&&"__name"!==h&&"__templates"!==h&&"__meta"!==h&&(a[h]=1);b=Ca.prototype;for(h in b)b.hasOwnProperty(h)&&(a[h]=null);return a}();mb.controllerInternal=Qa;e.u.obj.expose("h5.core",{controller:function(a,b,h){2>arguments.length&&d(6032);return Qa(a,b,h)},logic:Ra,
expose:function(a){var b=a.__name;b||d(6019,null,{target:a});var h=b.lastIndexOf(".");if(-1===h)window[b]=a;else{var c=b.substr(0,h),b=b.substr(h+1,b.length),h={};h[b]=a;e.u.obj.expose(c,h)}}})})();(function(){function m(a){return(a=a&&y(a)?a.match(/^(string|number|integer|boolean|any|enum|@(.+?))((\[\]){0,1})$/):null)?{elmType:a[1],dataModel:a[2],dimension:a[3]?1:0}:{}}function G(b,c){return function ha(b,h){if(!c[b])return!1;for(var d=0,i=c[b].length;d<i;d++)if(-1<a.inArray(c[b][d],h)||ha(c[b][d],
h.concat([b])))return!0;return!1}(b,[])}function k(a){return"number"===typeof a&&isNaN(a)}function x(a,b){return null==a||k(a)||"number"===typeof a||!b&&(a instanceof Number||!(!(y(a)||a instanceof String)||!a.match(/^[+\-]{0,1}[0-9]*\.{0,1}[0-9]+$/)))}function C(a,b){return null==a||"number"===typeof a&&parseInt(a)===a||!b&&(a instanceof Number&&parseInt(a)===parseFloat(a)||("string"===typeof a||a instanceof String)&&!!a.match(/^[+\-]{0,1}[0-9]+$/))}function O(b,c,e){function f(){n.push(A.call(this,
arguments));if(e)throw null;}var n=[];try{if(!a.isPlainObject(b))throw f(oa),null;la(b.name)||f(pa);var g=b.base,l=null;if(null!=g)if(!y(g)||0!==g.indexOf("@"))f(ta);else{var j=g.substring(1);c.models[j]?l=c.models[j].schema:f(Xa,j)}var k=b.schema;!l&&null==k&&f(ua);if(!l&&!a.isPlainObject(k))throw f(i),null;}catch(s){d($,null,n)}}function D(b,c,i,e){function f(){n.push(A.call(this,arguments));if(e)throw null;}"object"!==typeof b&&d(L);var n=[];try{if(c){var g=!1,l;for(l in b)b[l]&&!0===b[l].id&&
(g&&f(s),g=!0);g||f(P)}var j={},g=function(a){if(null!=a){r&&f(W,v);t.hasOwnProperty("defaultValue")&&f(Ea,v);if(null==a.on)f(X,v);else for(var c=R(a.on),d=0,i=c.length;d<i;d++)if(!b.hasOwnProperty(c[d])){f(X,v);break}"function"!==typeof a.calc&&f(Na,v);j[v]=R(a.on)}};l=function(a){r&&null==a&&(a="string");var b={};null!=a&&(y(a)?(r&&"string"!==a&&"integer"!==a&&f(Va,v),b=m(a),b.elmType?(b.dataModel&&(c||f(Ca,v,b.dataModel),i.models[b.dataModel]||f(Pa,v,b.dataModel)),"enum"===b.elmType&&null==t.enumValue&&
f(Za,v)):f(Ca,v,a)):f(Ya,v))};var w=function(b,h){if(null!=b)if(a.isPlainObject(b)){for(var c in b){var d=b[c];if(null!=d)switch(c){case "notNull":!0!==d&&!1!==d?f(Ra,v,c):r&&!d&&f(Oa,v,c,d);break;case "min":case "max":switch(h.elmType){case "integer":(y(d)||!C(d)||k(d))&&f(ra,v,c);break;case "number":(y(d)||y(d)||!x(d)||Infinity===d||-Infinity===d||k(d))&&f(ra,v,c);break;default:f(V,v,c,h.elmType)}break;case "minLength":case "maxLength":switch(h.elmType){case "string":y(d)||!C(d)||k(d)||0>d?f(ba,
v,c):r&&"maxLength"===c&&0===d&&f(Oa,v,c,d);break;default:f(V,v,c,h.elmType)}break;case "notEmpty":switch(h.elmType){case "string":!0!==d&&!1!==d?f(Ra,v,c):r&&!d&&f(Oa,v,c,d);break;default:f(V,v,c,h.elmType)}break;case "pattern":switch(h.elmType){case "string":"regexp"!==a.type(d)&&f(aa,v,c);break;default:f(V,v,c,h.elmType)}}}b.notEmpty&&0===b.maxLength&&f(Z,v,"notEmpty","maxLength");null!=b.min&&null!=b.max&&b.min>b.max&&f(Z,v,"min","max");null!=b.minLength&&null!=b.maxLength&&b.minLength>b.maxLength&&
f(Z,v,"minLength","maxLength")}else f(Qa,v)},q=function(b,h){null!=b&&("enum"!==h.elmType&&f(ca,v),(!M(b)||0===b.length||-1<a.inArray(null,b)||-1<a.inArray(void 0,b))&&f(va,v))},v;for(v in b){var t=null==b[v]?{}:b[v],r=c&&!!t.id;la(v)||f(Y,v);g(t.depend);l(t.type);var o={},p=r&&null==p?"string":t.type;y(p)&&(o=m(p));w(t.constraint,o);q(t.enumValue,o);r&&t.hasOwnProperty("defaultValue")&&f(wa,v)}for(var u in j)G(u,j)&&f(Ua,u)}catch(J){d(E,null,n)}return!0}function I(a,b){var c=[];try{for(var i in a){var f=
a[i];if(f&&(f.hasOwnProperty("defaultValue")||!f.type||!("array"===f.type||m(f.type).dimension))&&f.hasOwnProperty("defaultValue")){var e=f.defaultValue;b[i](e).length&&pushErrorReason(Da,i,e)}}return!0}catch(n){d(E,null,c)}}function H(a,b,c){var d={},i;for(i in a){var f=d,e=i,n;n=c;var g=a[i]||{},l=[],j=null,k=0,j=g.type,s=g.constraint||{};b&&g.id&&(j=j||"string",s.notNull=!0,"string"===j&&(s.notEmpty=!0));j&&(k=m(j),j=k.elmType,k=k.dimension,l.push(o(j,{manager:n,enumValue:g.enumValue})));s&&l.push(u(s));
n=p({checkFuncs:l,dimension:k});f[e]=n}return d}function u(a){return function(b){var c=[];a.notNull&&null==b&&c.push({notNull:a.notNull});a.notEmpty&&!b&&c.push({notEmpty:a.notEmpty});if(null==b)return c;null!=a.min&&b<a.min&&c.push({min:a.min});null!=a.max&&a.max<b&&c.push({max:a.max});null!=a.minLength&&b.length<a.minLength&&c.push({minLength:a.minLength});null!=a.maxLength&&a.maxLength<b.length&&c.push({maxLength:a.maxLength});null!=a.pattern&&!b.match(a.pattern)&&c.push({pattern:a.pattern});return c}}
function o(b,c){var d=[{type:b}];switch(b){case "number":return function(a,b){return x(a,b)?[]:d};case "integer":return function(a,b){return C(a,b)?[]:d};case "string":return function(a,b){return null==a||y(a)||!b&&a instanceof String?[]:d};case "boolean":return function(a,b){return null==a||"boolean"===typeof a||!b&&a instanceof Boolean?[]:d};case "enum":return function(b){var h;a:if(h=c.enumValue,k(b)){for(var b=0,i=h.length;b<i;b++)if(k(h[b])){h=!0;break a}h=!1}else h=null===b||-1<a.inArray(b,
h);return h?[]:d};case "any":return function(){return[]}}var i=b.match(/^@(.+?)$/)[1],f=c.manager;return function(a){var b=f.models[i];return!b||"object"!==typeof a&&null!=a?d:null==a||b.has(a)?[]:d}}function p(a){var b=a.checkFuncs;if(!b||0===b.length)return function(){return[]};var c=a.dimension||0;return function(a,h){function d(a,f){if(!f){for(var n=0,g=b.length;n<g;n++){var l=b[n](a,h);if(l.length)return i=i.concat(l),!1}return!0}if(null==a)return!0;if(!M(a)&&!e.core.data.isObservableArray(a))return i.push({dimension:c}),
!1;n=0;for(g=a.length;n<g;n++)if(!d(a[n],f-1))return!1;return!0}var i=[];d(a,c);return i}}function j(a,b){a._values={};a._nullProps={};for(var c in b)if(b[c]&&q(b[c].type)){var d=na();d.relatedItem=a;a._values[c]=d;a._nullProps[c]=!0}}function q(a){return!a?!1:-1!==a.indexOf("[]")}function A(){return{code:arguments[0]}}function c(b,c,i,f){function e(c){for(var c=R(l[c].depend.on),d=0,i=c.length;d<i;d++)if(-1===a.inArray(c[d],b._realProperty)&&-1!==a.inArray(c[d],g))return!1;return!0}function n(b,
c){for(var h=0,d=c.length;h<d;h++){var i=j[c[h]];if(i)for(var f=0,e=i.length;f<e;f++){var g=i[f];-1===a.inArray(g,b)&&b.push(g)}}}var g=[],l=b.schema||b._model.schema,j=b._dependencyMap,k={};for(f?g=b._dependProps.slice():n(g,R(i));0!==g.length;){for(var i=[],f=0,s=g.length;f<s;f++){var w=g[f];if(e(w)){var m=l[w].depend.calc.call(b,c);0!==b._validateItemValue(w,m,!0).length&&d(eb,[b._model?b._model.name:qa,w,m]);k[w]={oldValue:b._values[w],newValue:m};l[w]&&q(l[w].type)?m?(b._values[w].copyFrom(m),
b._nullProps[w]=!1):(b._values[w].copyFrom([]),b._nullProps[w]=!0):b._values[w]=m}else i.push(w)}n(i,g);g=i}return k}function b(a,b,c,i){for(var f in c){f in a||d(ga,[i?i.name:qa,f]);var e=c[f];if(!a[f]||!q(a[f].type)||c.hasOwnProperty(f))e=b(f,e,i&&i._idKey===f),0<e.length&&d(w,[i?i.name:qa,f],e)}}function f(b,i,f,n){var g=b.schema||b._model.schema,l=[],j;for(j in i)if(!(f&&-1!==a.inArray(j,f))){var w=b._values[j],s=i[j];if(g[j]&&g[j].depend)w!==s&&d(v,[b._model?b._model.name:qa,j]);else{var m=g[j]&&
g[j].type;q(m)&&(null==s?(s=[],b._nullProps[j]=!0):b._nullProps[j]=!1);if(m&&m.match(/string|number|integer|boolean/)){var E=s;if(M(E)){for(var E=E.slice(0),s=0,P=E.length;s<P;s++)E[s]=E[s]&&"object"===typeof E[s]?E[s]&&E[s].valueOf&&E[s].valueOf():E[s];s=E}else s=E&&"object"===typeof E&&E.valueOf?E.valueOf():E}if(null!=s&&m&&m.match(/number|integer/)&&"number"!==typeof s)if(M(s)||e.core.data.isObservableArray(s)){E=0;for(P=s.length;E<P;E++)null!=s[E]&&x(s[E])&&(s[E]=parseFloat(s[E]))}else null!=
s&&(s=parseFloat(s));if(!q(m)||!w||!w.equals(s,w))w===s||k(w)&&k(s)||(m&&-1!==m.indexOf("[]")&&e.core.data.isObservableArray(w)&&(w=w.toArray()),l.push({p:j,o:w,n:s}))}}if(l.length){i={};f=[];E=0;for(j=l.length;E<j;E++)w=l[E],g[w.p]&&q(g[w.p].type)?w.n&&b._values[w.p].copyFrom(w.n):b._values[w.p]=w.n,i[w.p]={oldValue:w.o,newValue:b.get(w.p)},f.push(w.p);g={type:!0===n?"create":"change",target:b,props:i};a.extend(i,c(b,g,f,n));return g}}function l(a){var b=a._manager,a=a.name;b._updateLogs||(b._updateLogs=
{});b._updateLogs[a]||(b._updateLogs[a]={});return b._updateLogs[a]}function N(a,b,c){if(a._manager)for(var d=l(a),i=0,f=c.length;i<f;i++){var e=c[i],n=e._values[a._idKey];d[n]||(d[n]=[]);d[n].push({type:b,item:e})}}function J(a,b){if(a._manager){var c=l(a),d=b.target._values[a._idKey];c[d]||(c[d]=[]);c[d].push({type:$a,ev:b})}}function g(b){var c={},d;for(d in b)if(b.hasOwnProperty(d)){var i=b[d]?b[d].depend:null;if(i)for(var i=R(i.on),f=0,e=i.length;f<e;f++){var n=i[f];c[n]||(c[n]=[]);-1===a.inArray(d,
c[n])&&c[n].push(d)}}return c}function F(b,c){O(b,c,!0);var d;d=(d=b.base)?c.models[d.slice(1)].schema:{};d=a.extend({},d,b.schema);D(d,!0,c,!0);var i=H(d,!0,c);I(d,i,!0);return new xa(d,b,i,c)}function S(b,c){var d=[],i=[],f=[],e;for(e in b)b[e]&&b[e].depend?i.push(e):d.push(e),b[e]&&b[e].type&&-1!==b[e].type.indexOf("[]")&&f.push(e);e=g(b);var n={},l;for(l in b){var j=b[l];if(!j||!j.depend){var s=null,s=j&&void 0!==j.defaultValue?j.defaultValue:null;n[l]=s}}return{_realProps:d,_dependProps:i,_aryProps:f,
_dependencyMap:e,_createInitialValueObj:function(b){if(!b)return a.extend({},n);var c=a.extend({},n),d;for(d in b)c[d]=b[d];return c},_validateItemValue:function(a,b,d){return c[a](b,d)}}}function r(b,c,i,f){var g=!1,l=["sort","reverse","pop","shift"],j=null;i.addEventListener("changeBefore",function(i){f&&(b._isRemoved||!f._manager)&&d(n,[b._values[f._idKey],i.method]);var s=e.u.obj.argsToArray(i.args);if(-1===a.inArray(i.method,l)){var k=!0;switch(i.method){case "splice":k=!1;s.shift();s.shift();
break;case "copyFrom":s=s[0];break;case "set":s.shift()}k&&(i=b._validateItemValue(c,s),0<i.length&&d(w,c,i))}f?(f._manager&&(i=f._manager,s=f.name,i._oldValueLogs||(i._oldValueLogs={}),i._oldValueLogs[s]||(i._oldValueLogs[s]={}),i=i._oldValueLogs[s],s=b._values[f._idKey],i[s]||(i[s]={}),i[s][c]||(i[s][c]=b._values[c].toArray())),(g=f._manager?f._manager.isInUpdate():!1)||f._manager.beginUpdate()):j=b._values[c].toArray()});i.addEventListener("change",function(a){if(!(b._isInSet||null===a.method)){var d=
{type:"change",target:b,props:{}};d.props[c]={};f?(J(f,d),g?a.stopImmediatePropagation():(f._manager._isArrayPropChangeSilentlyRequested=!0,f._manager.endUpdate(),f._manager._isArrayPropChangeSilentlyRequested=!1)):i.equals(j)||(d.props[c]={oldValue:j,newValue:b._values[c]},b.dispatchEvent(d))}})}function t(a){la(a)||d(fa);this.models={};this.name=a;this._updateLogs=null;this._isArrayPropChangeSilentlyRequested=!1}function xa(a,b,c,d){this.items={};this.size=0;this.name=b.name;this._manager=d;for(var i in a)a[i]&&
a[i].id&&(this._idKey=i);this._idType=(b=a[this._idKey].type)?"string"===b?T:Sa:T;this.schema=a;this._itemConstructor=ma(a,c,this);d.models[this.name]=this}function ma(c,d,i){function n(a){j(this,c,g,a);a=g._createInitialValueObj(a);b(c,g._validateItemValue,a,i);f(this,a,null,!0);for(var a=g._aryProps,d=0,e=a.length;d<e;d++)r(this,a[d],this.get(a[d]),i)}var g=S(c,d);i._schemaInfo=g;e.mixin.eventDispatcher.mix(n.prototype);a.extend(n.prototype,g,ab,{_model:i,_isRemoved:!1,getModel:function(){return this._isRemoved?
null:this._model}});return n}function ya(){}function ea(){this.length=0;this._src=[]}function na(){return new ea}function U(a){return a&&a.constructor===ea?!0:!1}var T="string",Sa="number",fa=15E3,$=15001,n=15005,L=15008,E=15009,w=15011,v=15012,ga=15013,eb=15016,oa=15900,pa=15901,ta=15902,Xa=15903,ua=15904,i=6,s=15800,P=15801,Y=15802,W=15803,X=15804,Na=15805,Ya=15806,Ca=15807,Pa=15808,Za=15809,Qa=15810,Ra=15811,ra=15812,V=15813,aa=15814,ba=15815,Z=15816,ca=15817,va=15818,wa=15819,Da=15820,Oa=15821,
Ea=15822,Ua=15823,Va=15824,qa="n/a",$a=2,ab={get:function(b){if(0===arguments.length)return a.extend({},this._values);var c=this._model;(c?c.schema:this.schema).hasOwnProperty(b)||d(15014,[c?c.name:qa,b]);return this._values[b]},set:function(a){var c=a;2===arguments.length&&(c={},c[arguments[0]]=arguments[1]);var i=this._model;i&&(this._isRemoved||!i._manager)&&d(n,[this._values[this._model._idKey],"set"],this);if(i)i._idKey in c&&c[i._idKey]!==this._values[i._idKey]&&d(15003,[i.name,this._idKey]),
b(i.schema,i._schemaInfo._validateItemValue,c,i);else{var e=this.validate(c);if(e)throw e;}var e=null,g=i?i._manager.isInUpdate():!1;i&&!g&&i._manager.beginUpdate();this._isInSet=!0;e=f(this,c);this._isInSet=!1;i?(e&&J(i,e),g||i._manager.endUpdate()):e&&this.dispatchEvent(e)},regardAsNull:function(a){return this._isArrayProp(a)?!0===this._nullProps[a]:null===this._values[a]},_isArrayProp:function(a){var b=this._model?this._model.schema:this.schema;return b[a]&&b[a].type&&-1<b[a].type.indexOf("[]")?
!0:!1}};e.mixin.eventDispatcher.mix(t.prototype);a.extend(t.prototype,{createModel:function(b){(!b||"object"!==typeof b)&&d($,null,[A(oa)]);if(!M(b))return this.models[b.name]?this.models[b.name]:F(b,this);var c=b.length;c||d($,null,[A(oa)]);for(var i={},f=[],e=0;e<c;e++){var n=b[e].name;if(this.models[n])w[e]=manager.models[b.name];else try{f.push(n);n=[];b[e].base&&n.push(b[e].base.substring(1));for(var g in b[e].schema){var l=b[e].schema[g];if(l){var j=l.type;j&&"@"===j.substring(0,1)&&(j=-1===
j.indexOf("[]")?j.substring(1):j.substring(1,j.length-2),n.push(j))}}i[e]={depends:n}}catch(s){d($)}}for(var w={size:0};w.size<c;){g={};l=!1;for(e=0;e<c;e++)if(!i[e].registed){for(var n=i[e].depends,j=0,k=n.length;j<k;j++)if(!this.models[n[j]]){g[n[j]]=!0;break}j===k&&(w[e]=F(b[e],this),w.size++,l=!0,i[e].registed=!0)}if(!l){var e=!0,E;for(E in g)if(-1===a.inArray(E,f)){e=!1;break}e&&d(15004);d($,null,[A(Xa,E)])}}b=[];for(e=0;e<c;e++)b.push(w[e]);return b},dropModel:function(a){if((a=y(a)?a:"object"===
typeof a?a.name:null)&&this.models[a]){var b=this.models[a];b._manager=null;delete this.models[a];return b}},isInUpdate:function(){return null!==this._updateLogs},beginUpdate:function(){this.isInUpdate()||(this._updateLogs={})},endUpdate:function(){if(this.isInUpdate()){var a=!this._isArrayPropChangeSilentlyRequested,b=this._updateLogs,c=this._oldValueLogs;this._oldValueLogs=this._updateLogs=null;var d={},i;for(i in b)if(b.hasOwnProperty(i)){var f;f=this.models[i];var e=b[i],n=[],g=[],l=[],j=[],s=
void 0;for(s in e){for(var w=e[s],E=!0,m=[],v=w.length-1;0<=v;v--){var P=w[v],L=P.type;if(L===$a)m.push(P.ev);else{a:{for(E=0;E<v;E++){var q=w[E].type;if(1===q||3===q){v=w[E];break a}}v=null}if(1===L)v&&3===v.type?n.push({id:s,oldItem:v.item,newItem:P.item}):g.push(P.item);else if(v=v&&3===v.type?v.item:v?null:P.item)j.push(v),v.dispatchEvent({type:"remove",model:f});E=!1;break}}if(E&&0<m.length){P={};for(v=m.length-1;0<=v;v--)for(var Y in m[v].props)P[Y]||(U(f.get(s).get(Y))?(L=c&&c[f.name]&&c[f.name][s]&&
c[f.name][s][Y],f.get(s).get(Y).equals(L)||(P[Y]={oldValue:L})):P[Y]={oldValue:m[v].props[Y].oldValue});v=!1;for(Y in P)L=P[Y].oldValue,w=f.get(s).get(Y),L===w||k(L)&&k(w)?delete P[Y]:(v=f.get(s).get(Y),a&&U(v)&&v.dispatchEvent({type:"change",method:null,args:null,returnValue:null}),P[Y].newValue=v,v=!0);v&&(m={type:"change",target:m[0].target,props:P},l.push(m),m.target.dispatchEvent(m))}}(f=0===g.length&&0===n.length&&0===j.length&&0===l.length?!1:{created:g,recreated:n,removed:j,changed:l})&&(d[i]=
f)}a=!1;for(i in d)a=!0,f=d[i],this.models[i].dispatchEvent({type:"itemsChange",created:f.created,recreated:f.recreated,removed:f.removed,changed:f.changed});d={type:"itemsChange",models:d};a&&this.dispatchEvent(d)}},_dataModelItemsChangeListener:function(a){var b=a.target.manager,c={};c[a.target.name]=a;b.dispatchEvent({type:"itemsChange",models:c})}});e.mixin.eventDispatcher.mix(xa.prototype);a.extend(xa.prototype,{create:function(a){this._manager||d(15006,[this.name,"create"]);var b=this.validate(a,
!0);if(b)throw b;(b=this._manager?this._manager.isInUpdate():!1)||this._manager.beginUpdate();for(var c=[],i=R(a),e=[],n=this._idKey,g=0,l=i.length;g<l;g++){var j=i[g],s=j[n],w=this._findById(s);w?(e.push(w),(s=f(w,j,[n]))&&J(this,s)):(j=new this._itemConstructor(j),this.items[s]=j,this.size++,c.push(j),e.push(j))}0<c.length&&N(this,1,c);b||this._manager.endUpdate();return M(a)?e:e[0]},validate:function(a,c){try{var i=this._idKey,f=R(a);"object"!==typeof a&&!M(a)&&d(15007);if(c)for(var e=0,n=f.length;e<
n;e++){var g=f[e],j=g[i];(""===j||null==j)&&d(15002,[this.name,i]);var l=this._schemaInfo._createInitialValueObj(g);b(this.schema,this._schemaInfo._validateItemValue,l,this)}else for(var e=0,s=f.length;e<s;e++)g=f[e],b(this.schema,this._schemaInfo._validateItemValue,g,this)}catch(w){return w}return null},get:function(a){if(M(a)||e.core.data.isObservableArray(a)){for(var b=[],c=0,d=a.length;c<d;c++)b.push(this._findById(a[c]));return b}return this._findById(a)},remove:function(a){this._manager||d(15006,
[this.name,"remove"]);var b=this._manager?this._manager.isInUpdate():!1;b||this._manager.beginUpdate();for(var c=this._idKey,i=R(a),f=[],e=[],n=0,g=i.length;n<g;n++)if(this.has(i[n])){var j=y(i[n])||C(i[n],!0)?i[n]:i[n]._values[c],l=this.items[j];delete this.items[j];this.size--;e.push(l);l._model&&(l._isRemoved=!0);f.push(l)}else e.push(null);0<f.length&&N(this,3,f);b||this._manager.endUpdate();return M(a)?e:e[0]},removeAll:function(){var a=this.toArray();0<a.length&&this.remove(a);return a},has:function(a){return y(a)||
C(a,!0)?!!this._findById(a):"object"===typeof a?null!=a&&Q(a.get)&&a===this.items[a.get(this._idKey)]:!1},getManager:function(){return this._manager},_findById:function(a){a=this.items[a];return typeof a===ja?null:a},_dispatchItemsChangeEvent:function(a){a={type:"itemsChange",created:[],recreated:[],removed:[],changed:[a]};this.dispatchEvent(a);this._manager&&(a.target=this,this._manager._dataModelItemsChangeListener(a))},toArray:function(){var a=[],b=this.items,c;for(c in b)b.hasOwnProperty(c)&&
a.push(b[c]);return a}});e.mixin.eventDispatcher.mix(ya.prototype);a.extend(ya.prototype,ab,{validate:function(a){try{var c=a;2===arguments.length&&(c={},c[arguments[0]]=arguments[1]);b(this.schema,this._validateItemValue,c)}catch(d){return d}return null}});e.mixin.eventDispatcher.mix(ea.prototype);var Ia={equals:function(a){var b=this.length;if(!M(a)&&!U(a)||a.length!==b)return!1;for(var a=U(a)?a._src:a,c=0;c<b;c++){var d=this[c],i=a[c];if(!(d===i||k(d)&&k(i)))return!1}return!0},copyFrom:function(a){null==
a&&(a=[]);a=U(a)?a._src:a;M(a)||d(15010,[0,a]);a=a.slice(0);a.unshift(0,this.length);Array.prototype.splice.apply(this,a)},get:function(a){return this[a]},set:function(a,b){this[a]=b},toArray:function(){return this.slice(0)},concat:function(){for(var a=e.u.obj.argsToArray(arguments),b=0,c=a.length;b<c;b++)U(a[b])&&(a[b]=a[b].toArray());return this.concat.apply(this,a)}},Fa="concat,join,pop,push,reverse,shift,slice,sort,splice,unshift,indexOf,lastIndexOf,every,filter,forEach,map,some,reduce,reduceRight".split(","),
ka;for(ka in Ia)Ia.hasOwnProperty(ka)&&-1===a.inArray(ka,Fa)&&Fa.push(ka);var Ja=["concat","slice","splice","filter","map"],Ka=["reverse","sort"],fb="sort,reverse,pop,shift,unshift,push,splice,copyFrom,set".split(",");ka=0;for(var hb=Fa.length;ka<hb;ka++){var cb=Fa[ka];ea.prototype[cb]=function(b){function c(){var i=d.apply(this._src,arguments);if(-1!==a.inArray(b,Ka))i=this;else if(-1!==a.inArray(b,Ja)){var f=na();f.copyFrom(i);i=f}return i}var d=Ia[b]?Ia[b]:Array.prototype[b];return-1===a.inArray(b,
fb)?c:function(){if(!this.dispatchEvent({type:"changeBefore",method:b,args:arguments})){var a=c.apply(this,arguments);this.length=this._src.length;this.dispatchEvent({type:"change",method:b,args:arguments,returnValue:a});return a}}}(cb)}e.u.obj.expose("h5.core.data",{createManager:function(a,b){la(a)||d(fa);var c=new t(a);if(null!=b){""===b&&(b="window");var i={};i[a]=c;e.u.obj.expose(b,i)}return c},createObservableArray:na,createObservableItem:function(a){D(a,!1,null,!0);var c=H(a);I(a,c,!0);var d=
new ya,c=S(a,c);j(d,a,c);d.schema=a;for(var i in c)d[i]=c[i];i=c._createInitialValueObj();b(a,c._validateItemValue,i);f(d,i,null,!0);a=0;for(c=d._aryProps.length;a<c;a++)r(d,d._aryProps[a],d.get(d._aryProps[a]));return d},isObservableArray:U,isObservableItem:function(a){return!(!a||!a.constructor||!a._validateItemValue||Q(a.getModel))},createSequence:function(b,c,d){function i(){return j}function f(){var a=j;j+=l;return a}function e(){return j.toString()}function n(){var a=j;j+=l;return a.toString()}
function g(){}var j=null!=b?b:1,l=null!=c?c:1,b=1===d?{current:e,next:n,returnType:1}:{current:i,next:f,returnType:2};b.setCurrent=function(a){j=a};a.extend(g.prototype,b);return new g},SEQ_STRING:1,SEQ_INT:2})})();(function(){function m(a,b){return!a||a.nodeType!==ba?void 0:a.getAttribute(b)}function G(a){if(!a)return null;for(var b=[],c=0,d=a.length;c<d;c++)b.push(a[c]);return b}function k(a,b,c,d){var f=[],b=R(b);if(!0===d)return x(f,a,b,c),f;for(var a=a.childNodes,d=0,e=a.length;d<e;d++)x(f,a[d],
b,c);return f}function x(a,b,c,d){if(b.nodeType===ba){for(var f=0,e=c.length;f<e;f++){var g=b.getAttribute(c[f]);if(typeof d===ja){if(null!==g){a.push(b);break}}else if(null!==g&&g==d){a.push(b);break}}if(0<b.childNodes.length){b=b.childNodes;f=0;for(e=b.length;f<e;f++)x(a,b[f],c,d)}}}function C(b,c){for(var b=R(b),d=[],e=0,g=b.length;e<g;e++){var j=b[e];if(j.nodeType===ba&&!(!0===c&&(null!=m(j,l)||null!=m(j,N))))for(var q=k(j,f,void 0,!0),t=0,r=q.length;t<r;t++){for(var o=!0,p=q[t];null!=p&&p!==
j;p=p.parentNode)if(null!=m(p,l)||null!=m(p,N)){o=!1;break}o&&d.push(q[t])}}return a(d)}function y(b,c,d){for(var f=[],e=0,g=b.length;e<g;e++){var j=b[e];if(j.nodeType===ba){if(!0===d){if(null!=j.getAttribute(c)){f.push(j);continue}if(null!=m(j,l)||null!=m(j,N))continue}for(var q=k(j,c,void 0,!1),t=0,r=q.length;t<r;t++){var p=a(q[t])[0],o=p.parentNode;(null==m(o,l)&&null==m(o,N)||o===j)&&f.push(p)}}}return a(f)}function D(a){return a&&a.addEventListener&&a.getModel&&!M(a)&&!e.core.data.isObservableArray(a)||
e.core.data.isObservableItem(a)?!0:!1}function I(a,b){for(var c=0,d=a.length;c<d;c++){var f=a[c];f.nodeType===ba&&f.setAttribute(g,b)}}function H(b,c,f){var g=U++,j=c[0];a(j).empty();if(f){!M(f)&&!e.core.data.isObservableArray(f)&&d(ea);I(c,g);b._addBindingEntry(f,j,g);e.core.data.isObservableArray(f)&&!b._isWatching(f)&&(c=function(a){b._observableArray_changeListener(a)},b._listeners[b._getContextIndex(f)]=c,f.addEventListener("change",c));var c=m(j,J),c=G(b._getSrcCtxNode(c).childNodes),l=[];b._loopElementsMap[g]=
l;for(var g=j.ownerDocument.createDocumentFragment(),k=f.get?function(a){return f.get(a)}:function(a){return f[a]},q=0,t=f.length;q<t;q++){for(var r=[],p=0,o=c.length;p<o;p++){var i=$(c[p]);r.push(i);g.appendChild(i)}l[q]=r;j.appendChild(g);u(b,r,k(q),!1,!0)}}}function u(a,b,c,f,g){b=R(b);if(f)H(a,b,c);else{f=U++;c&&(("object"!==typeof c||M(c)||e.core.data.isObservableArray(c))&&d(ea),I(b,f),a._addBindingEntry(c,b,f));var j=D(c);j&&!a._isWatching(c)&&(f=function(b){a._observableItem_changeListener(b)},
a._listeners[a._getContextIndex(c)]=f,c.addEventListener("change",f));C(b,g).each(function(){p(this,c,j)});o(a,b,c,!1,g);o(a,b,c,!0,g)}}function o(a,b,c,d,f){var e=d?"data-h5-loop-context":"data-h5-context";y(b,e,f).each(function(){var b=m(this,e),f=null;c&&(f=D(c)?c.get(b):c[b]);u(a,this,f,d)})}function p(b,c,e){for(var g=m(b,f).split(t),j=[],l=[],k=[],q=0,p=g.length;q<p;q++){var o=g[q];if(-1===o.indexOf(r))0<a.trim(o).length&&(j.push(null),l.push(null),k.push(a.trim(o)));else{var A=o.split(r),o=
a.trim(A[0]),A=a.trim(A[1]),u=null,i=xa.exec(o);i&&(u=i[1],o=/(\S+)[\s\(]/.exec(o)[1]);0<o.length&&0<A.length&&(j.push(o),l.push(u),k.push(A))}}g=b.tagName.toLowerCase();q=a(b);p=0;for(o=j.length;p<o;p++){var u=j[p],i=l[p],s=k[p],A=null;c&&(A=e?c.get(s):c[s]);null==u&&("input"===g?(u="attr",i="value"):u="text");switch(u){case "text":null==A?q.text(""):q.text(A);break;case "html":null==A?q.html(""):q.html(A);break;case "class":var u=m(b,S),s=(i=null==u)?"":" ",P=!1;A&&(P=!RegExp("\\s"+A+"\\s").test(" "+
u+" "));q[0].className=(i?"":u)+(P?s+A:"");break;case "attr":i||d(ma);"input"===g&&"value"===i?null==A?q.val(""):q.val(A):null==A?q.removeAttr(i):q.attr(i,A);break;case "style":i||d(ma);null==A?q.css(i,""):q.css(i,A);break;default:d(Q)}}}function j(a,b,c){for(var d=0,f=c.length;d<f;d++){var e=c[d];b.removeChild(e);a._removeBinding(e)}}function q(a){for(var a=a.childNodes,b=[],c=0,d=a.length;c<d;c++)b.push($(a[c]));return b}function A(a,b,c,d,f){for(var e=c.ownerDocument.createDocumentFragment(),g=
[],j=0,l=f.length;j<l;j++){var k=q(c);g[j]=k;for(var m=0,t=k.length;m<t;m++)e.appendChild(k[m]);u(a,k,f[j])}Array.prototype[d].apply(b,g);return e}function c(a,b,c,d,f,e){var g=d.length;if(0!==g){for(var l=d[0],k=l,c=1===g?c.length:k+d[1];k<c;k++){var m=f[k];m&&j(a,b,m)}f.splice(l,d[1]);if(!(2>=g)){k=f.length;k=0===k||0===l?b.firstChild:l>=k?null:f[l][0];c=e.ownerDocument.createDocumentFragment();l=[l,0];for(m=2;m<g;m++){for(var t=q(e),o=0,i=t.length;o<i;o++)c.appendChild(t[o]);u(a,t,d[m]);l.push(t)}b.insertBefore(c,
k);Array.prototype.splice.apply(f,l)}}}function b(a,b){void 0!==a.nodeType?a.nodeType===ba&&(this._parent=a.parentNode,this._targets=[a]):(this._parent=a[0].parentNode,this._targets=G(a));this._bindRootId=T++;V[this._bindRootId]=this;for(var c=[],d=0,e=this._targets.length;d<e;d++){var g=this._targets[d];if(g.nodeType===ba){g.setAttribute(F,this._bindRootId);for(var j=k(g,[l,N],void 0,!0),q=0,t=j.length;q<t;q++){var o=na++;j[q].setAttribute(J,o)}j=k(g,f,void 0,!0);q=0;for(t=j.length;q<t;q++)o=j[q],
/class\s*:/.test(m(o,f))&&""!=o.className&&o.setAttribute(S,o.className)}c.push(g.cloneNode(!0))}this._srces=c;this._loopElementsMap={};this._rootContext=b;this._usingContexts=[];this._srcToViewMap={};this._listeners={};u(this,this._targets,this._rootContext,!1,!0)}var f="data-h5-bind",l="data-h5-context",N="data-h5-loop-context",J="data-h5-dyn-ctx",g="data-h5-dyn-vid",F="data-h5-dyn-bind-root",S="data-h5-dyn-cn",r=":",t=";",xa=/\(\s*(\S+)\s*\)/,ma=7100,Q=7101,ea=7102,na=0,U=0,T=0,V={},fa={},$;(function(){var b=
document.createElement("div");b.h5Dummy="a";var c=b.cloneNode(!1),d=void 0!==c.h5Dummy;b.h5Dummy=void 0;d?(c.h5Dummy=void 0,$=function(b){var c=b.ownerDocument;return b.nodeType===ba?a(a.trim(b.outerHTML),c)[0]:b.cloneNode(!0)}):$=function(a){return a.cloneNode(!0)}})();a.extend(b.prototype,{unbind:function(){for(var a=0,b=this._targets.length;a<b;a++){var c=this._targets[a];if(c.nodeType===ba){this._removeBinding(c);c.removeAttribute(F);for(var d=k(c,S,void 0,!0),f=0,e=d.length;f<e;f++)d[f].removeAttribute(S);
c=k(c,J,void 0,!0);f=0;for(d=c.length;f<d;f++)c[f].removeAttribute(J)}}delete V[this._bindRootId]},_observableArray_changeListener:function(a){var b=this._getViewsFromSrc(a.target);if(b)for(var d in b)if(b.hasOwnProperty(d)){var f=b[d],e=this._getSrcCtxNode(m(f,J)),g=this._loopElementsMap[d];switch(a.method){case "set":c(this,f,a.target,[a.args[0],1,a.args[1]],g,e);break;case "shift":case "pop":var l=g[a.method]();l&&j(this,f,l);break;case "unshift":l=A(this,g,e,a.method,a.args);f.insertBefore(l,
f.firstChild);break;case "push":l=A(this,g,e,a.method,a.args);f.appendChild(l);break;case "splice":c(this,f,a.target,a.args,g,e);break;case "reverse":for(var l=f,k=g;l.firstChild;)l.removeChild(l.firstChild);for(var t=0,f=k.length;t<f;t++)for(var e=k[t],o=e.length-1;0<=o;o--)l.insertBefore(e[o],l.firstChild);g.reverse();break;case "sort":case "copyFrom":case null:for(var l=this._loopElementsMap,k=d,t=a.target,o=g,g=e,e=0,p=o.length;e<p;e++)j(this,f,o[e]);for(var o=f.ownerDocument.createDocumentFragment(),
p=[],e=0,r=t.length;e<r;e++){var i=q(g);p[e]=i;for(var s=0,P=i.length;s<P;s++)o.appendChild(i[s]);u(this,i,t.get(e))}f.appendChild(o);l[k]=p}}},_observableItem_changeListener:function(a){var b=this._getViewsFromSrc(a.target);if(b){var c=!1;a.target===this._rootContext&&(c=!0);var d=this,f;for(f in b)if(b.hasOwnProperty(f)){var e=b[f];C(e,c).each(function(){p(this,a.target,!0)});y(e,l).each(function(){var b=m(this,l);if(!(b in a.props))return!0;d._removeBinding(this);var c=m(this,J),c=d._getSrcCtxNode(c),
c=$(c);this.parentNode.replaceChild(c,this);u(d,c,a.props[b].newValue)});y(e,N).each(function(){var b=m(this,N);if(!(b in a.props)||a.target._isArrayProp(b))return!0;d._removeBinding(this);u(d,this,a.props[b].newValue,!0)})}}},_getSrcCtxNode:function(a){for(var b=0,c=this._srces.length;b<c;b++){var d=this._srces[b];if(m(d,J)===a)return d;d=k(d,J,a);if(0<d.length)return d[0]}return null},_isWatching:function(a){a=this._getContextIndex(a);return-1===a?!1:null!=this._listeners[a]},_getContextIndex:function(b){return a.inArray(b,
this._usingContexts)},_addBindingEntry:function(a,b,c){var d=this._getContextIndex(a);-1===d&&(this._usingContexts.push(a),d=this._usingContexts.length-1);fa[c]=a;(a=this._srcToViewMap[d])?a[c]=b:(a={},a[c]=b,this._srcToViewMap[d]=a)},_hasBindingForSrc:function(a){for(var b in a)if(a.hasOwnProperty(b))return!0;return!1},_removeBindingEntry:function(a){var b=fa[a];if(b){var c=this._getContextIndex(b);if(-1!==c){var d=this._srcToViewMap[c];d&&d[a]&&(delete d[a],this._hasBindingForSrc(d)||(d=!1,D(b)?
(b.removeEventListener("change",this._listeners[c]),d=!0):e.core.data.isObservableArray(b)&&(b.removeEventListener("change",this._listeners[c]),d=!0),d&&delete this._listeners[c],delete this._srcToViewMap[c],this._usingContexts[c]=null))}fa[a]&&delete fa[a]}},_removeBinding:function(a){if(a.nodeType===ba){var b=m(a,g);null!=b&&(this._removeBindingEntry(b),a.removeAttribute(g));for(var a=k(a,g),b=0,c=a.length;b<c;b++){var d=a[b];this._removeBindingEntry(m(d,g));d.removeAttribute(g)}}},_getViewsFromSrc:function(a){a=
this._getContextIndex(a);return-1===a?null:this._srcToViewMap[a]}});nb={createBinding:function(a,c){return new b(a,c)}}})();(function(){function m(d){return e.u.obj.isJQueryObject(d)?d:a(d)}function G(){this.__cachedTemplates={}}var k="[",x=7001,C=7002,O=7003,D=7010,I=7011,H=e.async.deferred,u={escapeHtml:function(a){return e.u.str.escapeHtml(a)}},o={MAX_CACHE:10,cache:{},cacheUrls:[],accessingUrls:{},append:function(a,d,e){this.cacheUrls.length>=this.MAX_CACHE&&this.deleteCache(this.cacheUrls[0]);
this.cache[a]={};this.cache[a].templates=d;this.cache[a].path=e;this.cacheUrls.push(a)},deleteCache:function(a,d){d||delete this.cache[a];for(var e=0,c=this.cacheUrls.length;e<c;e++)if(this.cacheUrls[e]===a){this.cacheUrls.splice(e,1);break}},getTemplateByUrls:function(j){function m(b){if(0!==b.length){var c={},f=[];b.each(function(){var b=a.trim(this.id),e=a.trim(this.innerHTML);b||d(C,null,{});try{var g=new EJS.Compiler(e,k);g.compile();c[b]=g.process;f.push(b)}catch(j){e=j.lineNumber,d(D,[e?" line:"+
e:"",j.message],{id:b,error:j,lineNo:e})}});return{compiled:c,data:{ids:f}}}}function o(b,c,d){e.ajax(c,{dataType:"text"}).done(function(c,f,e){delete l.accessingUrls[b];c=a(e.responseText).filter(function(){return this.tagName&&-1===this.tagName.indexOf("/")&&8!==this.nodeType});f=this.url;if(0<c.not('script[type="text/ejs"]').length)d.reject(ca(I,null,{url:b,path:f}));else{e=null;try{e=m(c.filter('script[type="text/ejs"]'))}catch(g){g.detail.url=b;g.detail.path=f;d.reject(g);return}var j,k;try{var o=
e.compiled;k=e.data;k.path=f;k.absoluteUrl=b;j=o;l.append(b,o,f)}catch(p){d.reject(ca(x,null,{error:p,url:b,path:f}));return}d.resolve({ret:j,data:k})}}).fail(function(a){delete l.accessingUrls[b];d.reject(ca(O,[a.status,b],{url:b,path:c,error:a}))})}for(var c={},b=[],f=[],l=this,p=function(a){var b=l.cache[a].templates;l.deleteCache(a,!0);l.cacheUrls.push(a);return b},u=0;u<j.length;u++){var g=j[u],F=Z(g);if(this.cache[F])a.extend(c,p(F)),f.push({absoluteUrl:F});else if(this.accessingUrls[F])b.push(this.accessingUrls[F]);
else{var G=e.async.deferred();b.push(this.accessingUrls[F]=G.promise());o(F,g,G)}}var r=H();e.async.when(b).done(function(){for(var b=e.u.obj.argsToArray(arguments),d=0,g=b.length;d<g;d++)a.extend(c,b[d].ret),f.push(b[d].data);r.resolve(c,f)}).fail(function(a){r.reject(a)});return r.promise()}};a.extend(G.prototype,{load:function(e){var k=H(),m=this,c=null;switch(a.type(e)){case "string":a.trim(e)||d(7004);c=[e];break;case "array":c=e;0===c.length&&d(7004);for(var e=0,b=c.length;e<b;e++)y(c[e])?a.trim(c[e])||
d(7004):d(7004);break;default:d(7004)}o.getTemplateByUrls(c).done(function(b,c){a.extend(m.__cachedTemplates,b);k.resolve(c)}).fail(function(a){k.reject(a)});return k.promise()},getAvailableTemplates:function(){var a=[],d;for(d in this.__cachedTemplates)a.push(d);return a},register:function(e,m){"string"!==a.type(m)?d(7E3,null,{id:e}):(!y(e)||!a.trim(e))&&d(C,[]);try{var o=new EJS.Compiler(m,k);o.compile();this.__cachedTemplates[e]=o.process}catch(c){o=c.lineNumber,d(D,[o?" line:"+o:"",c.message],
{id:e})}},isValid:function(a){try{return(new EJS.Compiler(a,k)).compile(),!0}catch(d){return!1}},get:function(e,k){var m=this.__cachedTemplates;(!y(e)||!a.trim(e))&&d(C);(m=m[e])||d(7005,e);var c=k?a.extend(!0,{},k):{},b=c.hasOwnProperty("_h")?new EJS.Helpers(c):new EJS.Helpers(c,{_h:u}),f=null;try{f=m.call(c,c,b)}catch(l){d(7006,l.toString(),l)}return f},update:function(a,d,e){return m(a).html(this.get(d,e))},append:function(a,d,e){return m(a).append(this.get(d,e))},prepend:function(a,d,e){return m(a).prepend(this.get(d,
e))},isAvailable:function(a){return!!this.__cachedTemplates[a]},clear:function(e){if(typeof e===ja)this.__cachedTemplates={};else{var k=null;switch(a.type(e)){case "string":k=[e];break;case "array":e.length||d(C);k=e;break;default:d(C)}for(var e=0,m=k.length;e<m;e++){var c=k[e];(!y(c)||!a.trim(c))&&d(C)}e=0;for(m=k.length;e<m;e++)delete this.__cachedTemplates[k[e]]}},bind:function(j,k){var m=null;null==j&&d(7007);M(j)?m=j:(m=a(j),0===m.length&&d(7007),m=m.toArray());(null==k||"object"!==typeof k||
M(k)||e.core.data.isObservableArray(k))&&d(7009);return nb.createBinding(m,k)}});var p=new G;p.createView=function(){return new G};a(function(){a('script[type="text/ejs"]').each(function(){var d=a.trim(this.id),e=a.trim(this.innerHTML);0!==e.length&&d&&(e=new EJS.Compiler(e,k),e.compile(),p.__cachedTemplates[d]=e.process)})});e.u.obj.expose("h5.core",{view:p})})();(function(){function d(b){var c={},f;for(f in fa){var e=a("<div></div>").addClass(b).addClass(f).appendTo("body"),g=a.camelCase(f);c[g]=
{};a.map(fa[f],function(a){c[g][a]="width"===a||"height"===a?parseInt(e.css(a).replace(/\D/g,""),10):e.css(a)});e.remove()}return c}function G(a,b,c){var a=b.createElement("v:"+a),d;for(d in c)a.style[d]=c[d];return a}function k(a,b){for(var c=[],d=a/2,f=0.8*a/2,e=360/b*Math.PI/180,g=1;g<=b;g++){var l=e*g,j=Math.cos(l),l=Math.sin(l);c.push({from:{x:d+f/2*j,y:d+f/2*l},to:{x:d+f*j,y:d+f*l}})}return c}function x(a){return function(){var b=document.body,c=document.documentElement,d=L?b:E?c:null;return d?
"Height"===a?d["client"+a]>d["scroll"+a]?d["client"+a]:d["scroll"+a]:d["client"+a]:Math.max(b["scroll"+a],c["scroll"+a],b["offset"+a],c["offset"+a],c["client"+a])}}function C(a){return function(){var b=L?document.body:document.documentElement;return window["page"+("Top"===a?"Y":"X")+"Offset"]||b["scroll"+a]}}function O(a){var b=L?document.body:document.documentElement;return U.isiOS?window["inner"+a]:b["client"+a]}function D(b){var c=a(b)[0],d=document.body,f=a("html")[0],b={top:0,left:0};if(c===
d&&E)return{top:parseFloat(f.currentStyle.paddingTop||0)+parseFloat(d.currentStyle.marginTop||0)+parseFloat(d.currentStyle.borderTop||0),left:parseFloat(f.currentStyle.paddingLeft||0)+parseFloat(d.currentStyle.marginLeft||0)+parseFloat(d.currentStyle.borderLeft||0)};"undefined"!==typeof c.getBoundingClientRect&&(b=c.getBoundingClientRect());d=L?d:document.documentElement;c=d.clientTop||0;d=d.clientLeft||0;return{top:b.top+pa()-c,left:b.left+ta()-d}}function I(){a.each(ba(arguments),function(a,b){b.bind("click dblclick touchstart touchmove touchend mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave focus focusin focusout blur change select",
function(){return!1})})}function H(a){a=aa(a)?a[0]:a;return a===window||a===document||a===document.body}function u(a){return V(T(a)).getComputedStyle(a,null)}function o(b,c){return!V(T(b)).getComputedStyle?a(b).css(c):u(b)[c]}function p(b){if(!V(T(b)).getComputedStyle)return a(b).height();var c=u(b);return b.offsetHeight-parseFloat(c.paddingTop)-parseFloat(c.paddingBottom)}function j(b){if(!V(T(b)).getComputedStyle)return a(b).width();var c=u(b);return b.offsetWidth-parseFloat(c.paddingLeft)-parseFloat(c.paddingRight)}
function q(b,c){if(!V(T(b)).getComputedStyle)return a(b).outerHeight();var d=u(b);return p(b)+parseFloat(d.paddingTop)+parseFloat(d.paddingBottom)+parseFloat(d.borderTopWidth)+parseFloat(d.borderBottomWidth)+(c?parseFloat(d.marginTop)+parseFloat(d.marginBottom):0)}function A(b,c){if(!V(T(b)).getComputedStyle)return a(b).outerWidth();var d=u(b);return j(b)+parseFloat(d.paddingLeft)+parseFloat(d.paddingRight)+parseFloat(d.borderLeftWidth)+parseFloat(d.borderRightWidth)+(c?parseFloat(d.marginLeft)+parseFloat(d.marginRight):
0)}function c(b){if(!V(T(b)).getComputedStyle)return a(b).innerHeight();var c=u(b);return p(b)+parseFloat(c.paddingTop)+parseFloat(c.paddingBottom)}function b(b){if(!V(T(b)).getComputedStyle)return a(b).innerWidth();var c=u(b);return j(b)+parseFloat(c.paddingLeft)+parseFloat(c.paddingRight)}function f(b,c,d,f){function e(){l+=g;l>d?(clearInterval(m),c.each(function(a){for(var c in b[a])this.style[c]=""}),f()):c.each(function(b){var c=j[b],d;for(d in c)c[d]+=k[b][d];a(this).css(c)})}var g=na,l=0,j=
[],k=[];c.each(function(a){var f=b[a];k[a]={};j[a]={};var e=u(c[a]),l;for(l in f)j[a][l]=parseFloat(e[l]),k[a][l]=(parseFloat(f[l])-parseFloat(e[l]))*g/d});e();var m=setInterval(e,g)}function l(a,b,c){var d=[];a.each(function(){var a=parseFloat(o(this,"opacity"));d.push({opacity:a})});a.css({opacity:0,display:"block"});f(d,a,b,c)}function N(a,b,c){var d=[];a.each(function(){d.push({opacity:0})});f(d,a,b,c)}function J(b,c){this.style=a.extend(!0,{},b);if(!c.getElementById(ma)){c.namespaces.add("v",
"urn:schemas-microsoft-com:vml");var d=c.createElement("style");c.getElementsByTagName("head")[0].appendChild(d);d.id=ma;d.setAttribute("type","text/css");d.styleSheet.cssText="v\\:stroke,v\\:line,v\\:textbox { behavior:url(#default#VML); }"}d=this.style.throbber.width;this.group=G("group",c,{width:d+"px",height:this.style.throbber.height+"px"});this.group.className=R;for(var d=k(d,this.style.throbber.lines),f=this.style.throbberLine.color,e=this.style.throbberLine.width,g=0,l=d.length;g<l;g++){var j=
d[g],m=j.from,n=j.to,j=G("line",c);j.strokeweight=e;j.strokecolor=f;j.fillcolor=f;j.from=m.x+","+m.y;j.to=n.x+","+n.y;m=G("stroke",c);m.opacity=1;j.appendChild(m);this.group.appendChild(j)}this._createPercentArea(c)}function g(b,c){var f=this,g=a(b);if(g.length){var l=H(g),g=l?a("body"):g,j=T(g[0]);if(j!==window.document&&(g[0]===j||V(j)===g[0]))g=a(j.body);var k=a.extend(!0,{},{message:"",percent:-1,block:!0,fadeIn:-1,fadeOut:-1,promises:null,theme:"a"},c);this._displayed=!1;this._throbbers=[];this._settings=
k;this._styles=a.extend(!0,{},{throbber:{roundTime:1E3,lines:12},throbberLine:{},percent:{}},d(k.theme));k.throbber&&a.extend(this._styles.throbber,k.throbber);this._isScreenLock=l;this._$target=g;this._target=1===this._$target.length?this._$target[0]:this._$target.toArray();this._scrollEventTimerId=null;this._scrollHandler=function(){f._handleScrollEvent()};this._resizeEventTimerId=null;this._resizeHandler=function(){f._handleResizeEvent()};this._redrawable=!0;this._lastPercent=-1;this._lastMessage=
null;this._fadeInTime="number"===typeof k.fadeIn?k.fadeIn:-1;this._fadeOutTime="number"===typeof k.fadeOut?k.fadeOut:-1;this._$content=a();this._$overlay=a();this._$skin=a();for(var g=e.u.str.format(Z,""===k.message?'style="display: none;"':"",k.message),l="https"===document.location.protocol?"return:false":"about:blank",n=0,o=this._$target.length;n<o;n++)this._$content=this._$content.add(a(j.createElement("div")).append(g).addClass(F).addClass(k.theme).addClass(S).css("display","none")),this._$overlay=
this._$overlay.add((k.block?a(j.createElement("div")):a()).addClass(F).addClass(k.theme).addClass(r).css("display","none")),this._$skin=this._$skin.add((E||L?a(j.createElement("iframe")):a()).attr("src",l).addClass(F).addClass(t).css("display","none"));var p=this._isScreenLock&&w?"fixed":"absolute";a.each([this._$overlay,this._$content],function(){this.css("position",p)});j=k.promises;k=function(){f.hide()};g=a.hasOwnProperty("curCSS")?"pipe":"then";M(j)?(j=a.map(j,function(a){return a&&Q(a.promise)?
a:null}),0<j.length&&wa(e.async.when(j),g,[k,k])):j&&Q(j.promise)&&wa(j,g,[k,k])}}var F="h5-indicator",S="content",r="overlay",t="skin",R="vml-root",ma="h5-vmlstyle",Z='<span class="indicator-throbber"></span><span class="indicator-message" {0}>{1}</span>',ea=500,na=13,U=e.env.ua,aa=e.u.obj.isJQueryObject,ba=e.u.obj.argsToArray,fa={throbber:["width","height"],"throbber-line":["width","color"]},$=!!document.createElement("canvas").getContext,n=function(){var a=document.createDocumentFragment().appendChild(document.createElement("div"));
a.innerHTML='<v:line strokeweight="1"/>';a=a.firstChild;a.style.behavior="url(#default#VML)";return"number"===typeof a.strokeweight}(),L="CSS1Compat"!==document.compatMode,E=U.isIE&&6>=U.browserVersion,w=!(U.isAndroidDefaultBrowser||U.isiOS&&5>U.browserVersion||E||L||U.isWindowsPhone),v=null,ga=null,ca=null,oa=null,pa=null,ta=null,la=function(){var b=document.createDocumentFragment().appendChild(document.createElement("div")),c=["Webkit","Moz","O","ms","Khtml"],d=c.length;return function(f){f=a.camelCase(f);
if(f in b.style)return!0;for(var f=f.charAt(0).toUpperCase()+f.slice(1),e=0;e<d;e++)if(c[e]+f in b.style)return!0;return!1}}(),ga=function(a){return function(){var b=document.body,c=document.documentElement;return"number"===typeof window["inner"+a]?window["inner"+a]:L?b["client"+a]:c["client"+a]}}("Height"),ca=x("Height"),oa=x("Width"),pa=C("Top"),ta=C("Left"),v=la("animationName");J.prototype={show:function(a){a&&(this.root=a,this.highlightPos=1,this.hide(),this.root.appendChild(this.group),this._run())},
hide:function(){this.root.innerHTML="";this._runId&&(clearTimeout(this._runId),this._runId=null)},_run:function(){var a=this.style.throbber.lines;if(0!==a){for(var b=this.style.throbber.roundTime,c=this.highlightPos,d=this.group.childNodes,f=0,e=d.length;f<e;f++){var g=d[f];if("textbox"!==g.nodeName){var l=f+1;g.firstChild.opacity=l==c?"1":l==c+1||l==c-1?"0.75":"0.4"}}c==a?c=0:c++;this.highlightPos=c;var j=this;this._runId=setTimeout(function(){j._run.call(j)},Math.floor(b/a))}},_createPercentArea:function(b){var c=
G("textbox",b),b=a(b.createElement("table"));b.append("<tr><td></td></tr>");var d=b.find("td");d.width(this.group.style.width);d.height(this.group.style.height);d.css("line-height",this.group.style.height);d.addClass("throbber-percent");c.appendChild(b[0]);this.group.appendChild(c)},setPercent:function(b){a(this.group).find(".throbber-percent").html(b)}};var ua=function(b,c){this.style=a.extend(!0,{},b);this.canvas=c.createElement("canvas");this.baseDiv=c.createElement("div");this.percentDiv=c.createElement("div");
var d=this.canvas,f=this.baseDiv,e=this.percentDiv;d.width=this.style.throbber.width;d.height=this.style.throbber.height;d.style.display="block";d.style.position="absolute";f.style.width=this.style.throbber.width+"px";f.style.height=this.style.throbber.height+"px";f.appendChild(d);e.style.width=this.style.throbber.width+"px";e.style.height=this.style.throbber.height+"px";e.style.lineHeight=this.style.throbber.height+"px";e.className="throbber-percent";f.appendChild(e);this.positions=k(d.width,this.style.throbber.lines)};
ua.prototype={show:function(a){a&&(this.root=a,this.highlightPos=1,this.hide(),this.root.appendChild(this.baseDiv),this._run())},hide:function(){a(this.baseDiv).remove();this._runId&&(clearTimeout(this._runId),this._runId=null)},_run:function(){var a=this.style.throbber.lines;if(0!==a){var b=this.canvas,c=b.getContext("2d"),d=this.highlightPos,f=this.positions,e=this.style.throbberLine.color,g=this.style.throbberLine.width,l=this.style.throbber.roundTime;b.width=b.width;for(var j=0,k=f.length;j<k;j++){c.beginPath();
c.strokeStyle=e;c.lineWidth=g;var m=j+1;c.globalAlpha=m==d?1:m==d+1||m==d-1?0.75:0.4;var n=f[j],m=n.from,n=n.to;c.moveTo(m.x,m.y);c.lineTo(n.x,n.y);c.stroke()}d==a?d=0:d++;this.highlightPos=d;if(v)b.className="throbber-canvas";else{var o=this;this._runId=setTimeout(function(){o._run.call(o)},Math.floor(l/a))}}},setPercent:function(a){this.percentDiv.innerHTML=a}};g.prototype={show:function(){if(this._displayed||!this._$target||0<this._$target.children("."+F).length)return this;this._displayed=!0;
for(var b=this,c=this._fadeInTime,d=function(){var c=a(window);b._isScreenLock&&(I(b._$overlay,b._$content),w||(c.bind("touchmove",b._scrollHandler),c.bind("scroll",b._scrollHandler)));c.bind("orientationchange",b._resizeHandler);c.bind("resize",b._resizeHandler)},f=0,e=this._$target.length;f<e;f++){var g=this._$target.eq(f),j=this._$content.eq(f),k=this._$skin.eq(f),m=this._$overlay.eq(f),p=o(g[0],"position");!this._isScreenLock&&"static"===p&&(g.data("before-position",p),g.data("before-zoom",o(g[0],
"zoom")),g.css({position:"relative",zoom:"1"}));p=T(g[0]);if(p=$?new ua(this._styles,p):n?new J(this._styles,p):null)b._throbbers.push(p),b.percent(this._settings.percent),p.show(j.children(".indicator-throbber")[0]);g.append(k).append(m).append(j)}f=this._$skin.toArray();Array.prototype.push.apply(f,this._$content.toArray());Array.prototype.push.apply(f,this._$overlay.toArray());f=a(f);0>c?(f.css("display","block"),d()):l(f,c,d);this._reposition();this._resizeOverlay();return this},_resizeOverlay:function(){var a,
b;if(!(this._isScreenLock&&w||0===this._$overlay.length))for(var c=0,d=this._$target.length;c<d;c++){var f=this._$content.eq(c),e=this._$overlay.eq(c);b=this._$target.eq(c);var g=this._$skin.eq(c);if(this._isScreenLock)f=oa(),b=ca();else{e.css("display","none");f.css("display","none");var l=b[0];a=l.scrollWidth;b=l.scrollHeight;if(E)a=Math.max(a,l.clientWidth),b=Math.max(b,l.clientHeight);else if(U.isIE&&"function"===typeof getComputedStyle){var l=V(T(l)).getComputedStyle(l,null),j=parseFloat(l.width)+
parseFloat(l.paddingLeft)+parseFloat(l.paddingRight);a+=j-parseInt(j)-1;l=parseFloat(l.height)+parseFloat(l.paddingTop)+parseFloat(l.paddingBottom);b+=l-parseInt(l)-1}e.css("display","block");f.css("display","block");f=a}e[0].style.width=f+"px";e[0].style.height=b+"px";if(E||L)g[0].style.width=f+"px",g[0].style.height=b+"px"}},_reposition:function(){for(var d=0,f=this._$target.length;d<f;d++){var e=this._$target.eq(d),g=this._$content.eq(d);if(this._isScreenLock){var l=ga();w?g.css("top",(l-q(g[0]))/
2+"px"):g.css("top",pa()+l/2-q(g[0])/2+"px")}else g.css("top",e.scrollTop()+(c(e[0])-q(g[0]))/2);var l=b(g[0])-j(g[0]),k=0;g.children().each(function(){var b=a(this);if("none"===o(b[0],"display"))return!0;k+=A(this,!0)});g.css("width",k+l);g.css("left",e.scrollLeft()+(b(e[0])-A(g[0]))/2)}},hide:function(){if(!this._displayed)return this;this._displayed=!1;var b=this,c=this._fadeOutTime,d=this._$skin.toArray();Array.prototype.push.apply(d,this._$content.toArray());Array.prototype.push.apply(d,this._$overlay.toArray());
for(var f=a(d),d=function(){var c=a(window);f.remove();b._isScreenLock||b._$target.each(function(b,c){var d=a(c);d.css({position:d.data("before-position"),zoom:d.data("before-zoom")});d.removeData("before-position").removeData("before-zoom")});c.unbind("touchmove",b._scrollHandler);c.unbind("scroll",b._scrollHandler);c.unbind("orientationchange",b._resizeHandler);c.unbind("resize",b._resizeHandler);b._resizeEventTimerId&&clearTimeout(b._resizeEventTimerId);b._scrollEventTimerId&&clearTimeout(b._scrollEventTimerId)},
e=0,g=this._throbbers.length;e<g;e++)this._throbbers[e].hide();0>c?(f.css("display","none"),d()):N(f,c,d);return this},percent:function(a){if("number"!==typeof a||!(0<=a&&100>=a))return this;if(!this._redrawable)return this._lastPercent=a,this;for(var b=0,c=this._throbbers.length;b<c;b++)this._throbbers[b].setPercent(a);return this},message:function(a){if(!y(a))return this;if(!this._redrawable)return this._lastMessage=a,this;this._$content.children(".indicator-message").css("display","inline-block").text(a);
this._reposition();return this},_handleScrollEvent:function(){this._scrollEventTimerId&&clearTimeout(this._scrollEventTimerId);if(this._redrawable){var a=this;this._scrollEventTimerId=setTimeout(function(){a._reposition();a._scrollEventTimerId=null},50)}},_handleResizeEvent:function(){function a(){b._resizeOverlay();b._reposition();b._redrawable=!0;b.percent(b._lastPercent);b.message(b._lastMessage);b._resizeEventTimerId=null}var b=this;this._resizeEventTimerId&&clearTimeout(this._resizeEventTimerId);
this._redrawable=!1;w||E||L?a():this._resizeEventTimerId=setTimeout(function(){a()},1E3)}};e.u.obj.expose("h5.ui",{indicator:function(b,c){return a.isPlainObject(b)?new g(b.target,b):new g(b,c)},isInView:function(b,c){var d,f,e,g,l=a(b);if(typeof c===ja)f=O("Height"),g=O("Width"),d=pa(),e=ta();else{g=a(c);if(0===g.find(l).length)return;e=D(g);d=e.top+parseInt(g.css("border-top-width"));e=e.left+parseInt(g.css("border-left-width"));f=g.innerHeight();g=g.innerWidth()}f=d+f;g=e+g;var j=D(l),k=j.top,
j=j.left,m=k+l.outerHeight(),l=j+l.outerWidth();return(d<=k&&k<f||d<m&&m<=f)&&(e<=j&&j<g||e<l&&l<=g)},scrollToTop:function(){function b(){1===window.scrollY&&(c=0);0<c&&(window.scrollTo(0,1),c--,setTimeout(b,ea))}var c=3;window.scrollTo(0,1);1!==a(window).scrollTop()&&setTimeout(b,ea)}})})();(function(){function m(){var c=a.mobile.activePage,c=c&&c[0]&&c[0].id;return y(c)&&0<c.length?c:null}function G(){var c=m();null!==c&&a(function(){O.addCSS(c);O.bindController(c)})}function k(a,b){for(var d in I)for(var e=
I[d],j=a===d,k=0,g=e.length;k<g;k++){var m=e[k];if(j)m[(b?"enable":"disable")+"Listeners"]()}for(d in H){e=H[d];j=a===d;k=0;for(g=e.length;k<g;k++)if(m=e[k],j)m[(b?"enable":"disable")+"Listeners"]()}}function x(a,b){a=a.replace(/(\.0+)+$/,"");b=b.replace(/(\.0+)+$/,"");if(a===b)return 0;for(var d=a.split("."),e=b.split("."),j=d.length,k=0;k<j;k++){if(null==e[k])return 1;var g=parseInt(d[k],10),m=parseInt(e[k],10);if(g!==m)return g<m?-1:1}return null!=e[j]?-1:0}var C,O=null,D={},I={},H={},u={},o={},
p=!1,j=!1,q=!1;e.u.obj.ns("h5.ui.jqm");e.ui.jqm.dataPrefix="h5";var A={__name:"JQMController",__ready:function(){var c=this,b=m();a(':jqmData(role="page"), :jqmData(role="dialog")').each(function(){c.loadScript(this.id)});var d=this.$find("#"+b);d.one("h5controllerready.emulatepageshow",function(){q&&d[0]===a.mobile.activePage[0]&&d.trigger("h5jqmpageshow",{prevPage:a("")})})},':jqmData(role="page"), :jqmData(role="dialog") pageinit':function(a){C||this._initPage(a.event.target.id)},':jqmData(role="page"), :jqmData(role="dialog") pagecreate':function(a){C&&
this._initPage(a.event.target.id)},_initPage:function(a){this.loadScript(a);this.addCSS(a);this.bindController(a)},"{rootElement} pageremove":function(c){a(c.event.target).trigger("h5jqmpagehide",{nextPage:a.mobile.activePage});j=!0;var c=c.event.target.id,b=I[c],d=H[c];if(b){for(var e=0,k=b.length;e<k;e++)b[e].dispose();I[c]=[]}if(d){e=0;for(k=d.length;e<k;e++)d[e].dispose();H[c]=[]}},"{rootElement} pagebeforeshow":function(a){a=a.event.target.id;this.addCSS(a);k(a,!0)},"{rootElement} pagehide":function(c){j||
a(c.event.target).trigger("h5jqmpagehide",{nextPage:c.evArg.nextPage});j=!1;c=c.event.target.id;k(c,!1);this.removeCSS(c)},"{rootElement} pageshow":function(c){var b=!1,d=a(c.event.target),e=c.evArg?c.evArg.prevPage:a("");if(c=I[d[0].id])for(var j=0,k=c.length;j<k;j++)if(!c[j].isReady){d.unbind("h5controllerready.emulatepageshow").one("h5controllerready.emulatepageshow",function(){a.mobile.activePage[0]===d[0]&&d.trigger("h5jqmpageshow",{prevPage:e})});b=!0;break}b||d.trigger("h5jqmpageshow",{prevPage:e})},
"{rootElement} h5controllerbound":function(c){c=c.evArg;if(this!==c){var b=m();null===b||-1!==a.inArray(c,I[b])||(H[b]||(H[b]=[]),H[b].push(c))}},"{rootElement} h5controllerunbound":function(c){var b=c.evArg,c=m();null!==c&&(b=a.inArray(b,H[c]),-1!==b&&H[c].splice(b,1))},loadScript:function(c){var c=a("#"+c),b=a.trim(c.data(this.getDataAttribute("script")));if(0!==b.length)return b=a.map(b.split(","),function(b){return a.trim(b)}),c=!0==c.data(this.getDataAttribute("async")),e.u.loadScript(b,{async:c})},
getDataAttribute:function(a){var b=e.ui.jqm.dataPrefix;null==b&&(b="h5");return 0!==b.length?b+"-"+a:a},bindController:function(a){var b=D[a],d=u[a];if(b&&0!==b.length){I[a]||(I[a]=[]);for(var l=I[a],j=0,k=b.length;j<k;j++){for(var g=b[j],m=!1,o=0,p=l.length;o<p;o++){var q=l[o];if(q&&q.__name===g.__name){m=!0;break}}m||I[a].push(e.core.controller("#"+a,g,d[j]))}}},addCSS:function(c){if(c=o[c])for(var b=document.getElementsByTagName("head")[0],d=b.getElementsByTagName("link"),e=d.length,j=0,k=c.length;j<
k;j++){for(var g=a.mobile.path.parseUrl(c[j]).filename,m=!1,p=0;p<e;p++)if(a.mobile.path.parseUrl(d[p].href).filename===g){m=!0;break}m||(g=document.createElement("link"),g.type="text/css",g.rel="stylesheet",g.href=c[j],b.appendChild(g))}},removeCSS:function(c){var b=o[c];if(b&&(c=m(),null!==c)){var d=o[c];a("link").filter(function(){var c=a(this).attr("href");return-1!==a.inArray(c,b)&&-1===a.inArray(c,d)}).remove()}}};e.u.obj.expose("h5.ui.jqm.manager",{init:function(){p||(p=!0,C=0<=x(a.mobile.version,
"1.4"),a(document).one("pageshow",function(){q=!0}),a(function(){O=mb.controllerInternal("body",A,null,{managed:!1});G()}))},define:function(c,b,e,j){y(c)||d(12E3,"id");null!=b&&!y(b)&&!M(b)&&d(12E3,"cssSrc");null!=e&&((y(e)||M(e))&&d(12001),(!a.isPlainObject(e)||!("__name"in e))&&d(12E3,"controllerDefObject"),null!=j&&!a.isPlainObject(j)&&d(12E3,"initParam"));o[c]||(o[c]=[]);D[c]||(D[c]=[]);u[c]||(u[c]=[]);a.merge(o[c],a.map(a.makeArray(b),function(b){return a.inArray(b,o[c])!==-1?null:b}));e&&-1===
a.inArray(e,D[c])&&(D[c].push(e),u[c].push(j));p&&null!==m()?G():this.init()}})})();(function(){function m(){x||(x=navigator.geolocation);return x}function G(a,d){this.oblateness=a;this.semiMajorAxis=d}function k(){}var x=null,C=e.env.ua;G.prototype.getOblateness=function(){return this.oblateness};G.prototype.getSemiMajorAxis=function(){return this.semiMajorAxis};var y=new G(298.257222,6378137),D=new G(299.152813,6377397.155),I=Math.PI/180;a.extend(k.prototype,{isSupported:C.isIE&&9<=C.browserVersion?
!0:!!m(),getCurrentPosition:function(a){var d=e.async.deferred();m().getCurrentPosition(function(a){d.resolve(a)},function(a){d.reject(ca(2002,null,a))},a);return d.promise()},watchPosition:function(a){function d(){}var k=e.async.deferred(),p=m().watchPosition(function(a){k.notify(a)},function(a){m().clearWatch(p);k.reject(ca(2002,null,a))},a);d.prototype.unwatch=function(){m().clearWatch(p);k.resolve()};return k.promise(new d)},getDistance:function(a,e,k,m,j){(!isFinite(a)||!isFinite(e)||!isFinite(k)||
!isFinite(m))&&d(2E3);var q=j?j:y;q instanceof G||d(2001);var j=q.getSemiMajorAxis(),x=q.getOblateness(),a=a*I,e=e*I,k=k*I,q=m*I,m=(a+k)/2,x=Math.sqrt(2*x-1)/x,x=Math.pow(x,2),c=Math.sqrt(1-x*Math.pow(Math.sin(m),2)),x=j*(1-x)/Math.pow(c,3),j=j/c,e=e-q;return Math.sqrt(Math.pow(x*(a-k),2)+Math.pow(j*Math.cos(m)*e,2))},GS_GRS80:y,GS_BESSEL:D});e.u.obj.expose("h5.api",{geo:new k})})();(function(){function m(a){if(a){var c=a.deferred;(Da(c)||Ea(c)||!a.result)&&d(p)}}function G(b,c,e){if(a.isPlainObject(b))for(var k in b){var m=
a.trim(k).replace(/ +/g," ").split(" "),g=[];""===m[0]?d(q):1===m.length?(g.push(m[0]),g.push("="),g.push("?")):/^(<=|<|>=|>|=|!=|like)$/i.test(m[1])?3===m.length&&/^like$/i.test(m[1])?(g.push(m[0]),g.push(m[1]),g.push("?"),g.push("ESCAPE"),g.push('"'+m[2]+'"')):(g.push(m[0]),g.push(m[1]),g.push("?")):d(j);c.push(g.join(" "));e.push(b[k])}}function k(){}function x(){this._multiple=!1}function C(a){this._db=a;this._df=A();this._tx=null;this._tasks=[];this._queue=[]}function O(a,c,d){this._statements=
[];this._parameters=[];this._executor=a;this._tableName=c;this._columns=M(d)?d.join(", "):"*";this._orderBy=this._where=null}function D(a,c,d){this._statements=[];this._parameters=[];this._executor=a;this._tableName=c;this._values=d?R(d):[];this._df=A();this._multiple=!0}function I(a,c,d){this._statements=[];this._parameters=[];this._executor=a;this._tableName=c;this._values=d;this._where=null}function H(a,c){this._statements=[];this._parameters=[];this._executor=a;this._tableName=c;this._where=null}
function u(a,c,d){this._statements=[];this._parameters=[];this._executor=a;this._statements.push(c);this._parameters.push(d||[])}function o(a){this._db=a}var p=3E3,j=3003,q=3011,A=e.async.deferred,c=e.u.str.format;a.extend(x.prototype,{execute:function(){return this._executor.add(this)._execute(function(a){return a[0]})}});a.extend(C.prototype,{_runTransaction:function(){return null!=this._tx},_addTask:function(a){this._tasks.push({deferred:a,result:null})},_setResult:function(a){this._getRecentTask().result=
a},_getRecentTask:function(){return this._tasks[this._tasks.length-1]},add:function(a){a instanceof x||d(3009);var c=this._getRecentTask();(!c||c.result)&&this._queue.push(a);return this},_execute:function(a){function c(){if(0===j.length){var k=a(g);d._setResult.apply(d,[k]);e.notify(k,d)}else{for(var m=j.shift(),o=m._statements,p=m._parameters,q=A().resolve().promise(),k=[],r=0,u=o.length;r<u;r++)(function(a,b){q=aa(q,function(){var c=A();d._tx.executeSql(a,b,function(a,b){k.push(m._onComplete(b));
c.resolve()});return c.promise()})})(o[r],p[r]);aa(q,function(){g.push(m._multiple?k:k[0]);c()})}}var d=this,e=this._df,j=this._queue,g=[];try{m(this._getRecentTask());this._addTask(e);for(var k=0,o=j.length;k<o;k++)j[k]._buildStatementAndParameters();this._runTransaction()?c():this._db.transaction(function(a){d._tx=a;c()},function(a){d._tx=null;for(var b=d._tasks,c=b.length-1;0<=c;c--)b[c].deferred.reject(ca(3010,["SQLDB ERROR(code="+a.code+")",a.message],a))},function(){d._tx=null;for(var a=d._tasks,
b=a.length-1;0<=b;b--){var c=a[b];c.deferred.resolve(c.result)}})}catch(p){e.reject(p)}this._df=A();return e.promise()},execute:function(){return this._execute(function(a){return a})},promise:function(){return this._df.promise()}});O.prototype=new x;a.extend(O.prototype,{where:function(b){!a.isPlainObject(b)&&!y(b)&&d(3004,["Select","where"]);this._where=b;return this},orderBy:function(b){!a.isPlainObject(b)&&!y(b)&&d(3004,["Select","orderBy"]);this._orderBy=R(b);return this},_buildStatementAndParameters:function(){var b=
"",d=this._where,b=c("SELECT {0} FROM {1}",this._columns,this._tableName);if(a.isPlainObject(d)){var e=[];G(d,e,this._parameters);b+=" WHERE "+e.join(" AND ")}else y(d)&&(b+=" WHERE "+d);M(this._orderBy)&&(b+=" ORDER BY "+this._orderBy.join(", "));this._statements.push([b]);this._parameters=[this._parameters]},_onComplete:function(a){return a.rows}});D.prototype=new x;a.extend(D.prototype,{_buildStatementAndParameters:function(){var b=this._values,d=this._statements,e=this._parameters;if(0===b.length)d.push(c("INSERT INTO {0} DEFAULT VALUES",
this._tableName)),e.push([]);else for(var j=0,k=b.length;j<k;j++){var g=b[j];if(null==g)d.push(c("INSERT INTO {0} DEFAULT VALUES",this._tableName)),e.push([]);else if(a.isPlainObject(g)){var m=[],o=[],p=[],q;for(q in g)m.push("?"),o.push(q),p.push(g[q]);d.push(c("INSERT INTO {0} ({1}) VALUES ({2})",this._tableName,o.join(", "),m.join(", ")));e.push(p)}}},_onComplete:function(a){return a.insertId}});I.prototype=new x;a.extend(I.prototype,{where:function(b){!a.isPlainObject(b)&&!y(b)&&d(3004,["Update",
"where"]);this._where=b;return this},_buildStatementAndParameters:function(){var b="",d=this._where,b=this._values,e=[],j;for(j in b)e.push(j+" = ?"),this._parameters.push(b[j]);b=c("UPDATE {0} SET {1}",this._tableName,e.join(", "));a.isPlainObject(d)?(j=[],G(d,j,this._parameters),b+=" WHERE "+j.join(" AND ")):y(d)&&(b+=" WHERE "+d);this._statements.push([b]);this._parameters=[this._parameters]},_onComplete:function(a){return a.rowsAffected}});H.prototype=new x;a.extend(H.prototype,{where:function(b){!a.isPlainObject(b)&&
!y(b)&&d(3004,["Del","where"]);this._where=b;return this},_buildStatementAndParameters:function(){var b="",d=this._where,b=c("DELETE FROM {0}",this._tableName);if(a.isPlainObject(d)){var e=[];G(d,e,this._parameters);b+=" WHERE "+e.join(" AND ")}else y(d)&&(b+=" WHERE "+d);this._statements.push([b]);this._parameters=[this._parameters]},_onComplete:function(a){return a.rowsAffected}});u.prototype=new x;a.extend(u.prototype,{_buildStatementAndParameters:function(){},_onComplete:function(a){return a}});
a.extend(o.prototype,{select:function(a,c,e){y(a)||d(3001,"select");!M(c)&&"*"!==c&&d(3005,"select");return new O(this.transaction(e),a,c)},insert:function(b,c,e){y(b)||d(3001,"insert");null!=c&&!M(c)&&!a.isPlainObject(c)&&d(3006,"insert");return new D(this.transaction(e),b,c)},update:function(b,c,e){y(b)||d(3001,"update");a.isPlainObject(c)||d(3006,"update");return new I(this.transaction(e),b,c)},del:function(a,c){y(a)||d(3001,"del");return new H(this.transaction(c),a)},sql:function(a,c,e){y(a)||
d(3007,"sql");null!=c&&!M(c)&&d(3008,"sql");return new u(this.transaction(e),a,c)},transaction:function(a){void 0!=a&&!(a instanceof C)&&d(3002,"transaction");return a?a:new C(this._db)}});a.extend(k.prototype,{isSupported:!!window.openDatabase,open:function(a,c,d,e){if(this.isSupported)return a=openDatabase(a,c,d,e),new o(a)}});e.u.obj.expose("h5.api",{sqldb:new k})})();(function(){function d(a){this._storage=a}a.extend(d.prototype,{getLength:function(){return this._storage.length},key:function(a){return this._storage.key(a)},
getItem:function(a){a=this._storage.getItem(a);return null===a?null:e.u.obj.deserialize(a)},setItem:function(a,d){this._storage.setItem(a,e.u.obj.serialize(d))},removeItem:function(a){this._storage.removeItem(a)},clear:function(){this._storage.clear()},each:function(a){for(var d=this._storage,e=0,m=d.length;e<m;e++){var y=d.key(e);a(e,y,this.getItem(y))}}});e.u.obj.expose("h5.api.storage",{isSupported:window.localStorage?function(){try{return window.localStorage.setItem("__H5_WEB_STORAGE_CHECK__",
"ok"),window.localStorage.removeItem("__H5_WEB_STORAGE_CHECK__"),!0}catch(a){return!1}}():!1,local:new d(window.localStorage),session:new d(window.sessionStorage)})})()})(jQuery); | hifive-snu/hifive-test-explorer | hifive-test-explorer/src/main/webapp/res/lib/hifive/h5.js | JavaScript | apache-2.0 | 112,101 |
import Collection from './collection';
import extend from '../utils/extend';
export default function Grouping(key, elements) {
this.key = key;
this.elements = elements;
Collection.call(this, elements);
}
extend(Grouping, Collection, {
/**
* Gets the number of elements in the Grouping.
* @returns {Number}
*/
count: function () {
return this.elements.length;
},
/**
* Creates an array from the Grouping.
* @returns {Array}
*/
toArray: function () {
return this.elements;
},
toString: function () {
return '[Grouping]';
}
}); | multiplex/multiplex.js | src/lib/collections/grouping.js | JavaScript | apache-2.0 | 620 |
define(function(require) {
/*
DEPENDENCIES
*/
var BaseDialog = require('utils/dialogs/dialog');
var TemplateHTML = require('hbs!./clone/html');
var Sunstone = require('sunstone');
var Notifier = require('utils/notifier');
var Locale = require('utils/locale');
var OpenNebulaSecurityGroup = require('opennebula/securitygroup');
/*
CONSTANTS
*/
var DIALOG_ID = require('./clone/dialogId');
var TAB_ID = require('../tabId');
/*
CONSTRUCTOR
*/
function Dialog() {
this.dialogId = DIALOG_ID;
BaseDialog.call(this);
}
Dialog.DIALOG_ID = DIALOG_ID;
Dialog.prototype = Object.create(BaseDialog.prototype);
Dialog.prototype.constructor = Dialog;
Dialog.prototype.html = _html;
Dialog.prototype.onShow = _onShow;
Dialog.prototype.setup = _setup;
return Dialog;
/*
FUNCTION DEFINITIONS
*/
function _html() {
return TemplateHTML({
'dialogId': this.dialogId
});
}
function _setup(context) {
var that = this;
context.off('invalid.fndtn.abide', '#' + DIALOG_ID + 'Form');
context.off('valid.fndtn.abide', '#' + DIALOG_ID + 'Form');
context.on('invalid.fndtn.abide', '#' + DIALOG_ID + 'Form', function(e) {
// Fix for valid event firing twice
if (e.namespace != 'abide.fndtn') { return; }
Notifier.notifyError(Locale.tr("One or more required fields are missing or malformed."));
}).on('valid.fndtn.abide', '#' + DIALOG_ID + 'Form', function(e) {
// Fix for valid event firing twice
if (e.namespace != 'abide.fndtn') { return; }
var name = $('input', this).val();
var sel_elems = Sunstone.getDataTable(TAB_ID).elements();
if (sel_elems.length > 1){
for (var i=0; i< sel_elems.length; i++)
//use name as prefix if several items selected
Sunstone.runAction('SecurityGroup.clone',
sel_elems[i],
name + OpenNebulaSecurityGroup.getName(sel_elems[i]));
} else {
Sunstone.runAction('SecurityGroup.clone',sel_elems[0],name);
}
return false;
});
context.foundation('reflow', 'abide');
return false;
}
function _onShow(context) {
var sel_elems = Sunstone.getDataTable(TAB_ID).elements();
//show different text depending on how many elements are selected
if (sel_elems.length > 1) {
$('.clone_one', context).hide();
$('.clone_several', context).show();
$('input',context).val('Copy of ');
} else {
$('.clone_one', context).show();
$('.clone_several', context).hide();
$('input',context).val('Copy of ' + OpenNebulaSecurityGroup.getName(sel_elems[0]));
}
$("input[name='name']",context).focus();
return false;
}
});
| tuxmea/one | src/sunstone/public/app/tabs/secgroups-tab/dialogs/clone.js | JavaScript | apache-2.0 | 2,737 |
/*
Siesta 3.0.1
Copyright(c) 2009-2015 Bryntum AB
http://bryntum.com/contact
http://bryntum.com/products/siesta/license
*/
/**
@class Siesta.Harness.NodeJS
@extends Siesta.Harness
Class, representing the NodeJS harness. This class reports the output from all test files to console.
This file is a reference only however, for a getting start guide and manual, please refer to <a href="#!/guide/siesta_getting_started">Getting Started Guide</a>.
Synopsys
========
var Harness,
isNode = typeof process != 'undefined' && process.pid
if (isNode) {
Harness = require('siesta');
} else {
Harness = Siesta.Harness.Browser;
}
Harness.configure({
title : 'Awesome Test Suite',
transparentEx : true,
autoCheckGlobals : true,
expectedGlobals : [
'Ext',
'Sch'
],
preload : [
"http://cdn.sencha.io/ext-4.0.2a/ext-all-debug.js",
"../awesome-project-all.js",
{
text : "console.log('preload completed')"
}
]
})
Harness.start(
// simple string - url relative to harness file
'sanity.t.js',
// test file descriptor with own configuration options
{
url : 'basic.t.js',
// replace `preload` option of harness
preload : [
"http://cdn.sencha.io/ext-4.0.6/ext-all-debug.js",
"../awesome-project-all.js"
]
},
// groups ("folders") of test files (possibly with own options)
{
group : 'Sanity',
autoCheckGlobals : false,
items : [
'data/crud.t.js',
...
]
},
...
)
Running the test suite in NodeJS
================================
To run the suite in NodeJS, launch the harness javascript file:
> node t/index.js
*/
Class('Siesta.Harness.NodeJS', {
// static
my : {
isa : Siesta.Harness,
does : Siesta.Role.ConsoleReporter,
has : {
contentManagerClass : Siesta.Content.Manager.NodeJS,
scopeProvider : 'Scope.Provider.NodeJS',
chdirToIndex : true
},
before : {
start : function () {
this.runCore = 'sequential'
if (this.chdirToIndex) {
var indexFile = process.argv[1]
var path = require('path')
process.chdir(path.dirname(indexFile))
}
}
},
methods : {
log : console.log,
exit : process.exit,
getScopeProviderConfigFor : function (desc, launchId) {
var config = this.SUPER(desc, launchId)
config.sourceURL = desc.url
return config
},
normalizeURL : function (url) {
// ref to lib in current dist (no trailing `.js`)
if (!/\.js$/.test(url)) {
url = '../lib/' + url.replace(/\./g, '/') + '.js'
}
return url
}
}
}
//eof my
})
//eof Siesta.Harness.NodeJS
| department-of-veterans-affairs/ChartReview | web-app/js/siesta-3.0.1-lite/lib/Siesta/Harness/NodeJS.js | JavaScript | apache-2.0 | 3,700 |
<script>
$(document).ready(function() {
$("#jobs_table").DataTable({
"ajax": {
'type': 'POST',
'url': "{{ url_for('api.jobs', query_str=query_str) }}",
},
"columns": [
{"data": "name"},
{"data": "last_build.status",
"defaultContent": "None"
},
{"data": "release",
"defaultContent": "None"
},
{"data": "last_build.timestamp",
"defaultContent": "None"
},
{"data": "name"},
{"data": "name"},
],
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
status = aData.last_build.status;
{% include "tables/color_result.js" -%}
columnDefs: [
{
targets:0,
render: function ( data, type, row, meta ) {
if(type === 'display'){
return $('<a>')
.attr('href', data)
.text(data)
.wrap('<div></div>')
.parent()
.html();
}
else { return data; }
}
},
{
targets:[1],
render: function ( data, type, row, meta ) {
data = '<a href="' + "{{ jenkins_url }}" + '/job/' + row['name'] + '/' + row['last_build']['number'] + '">' + row['last_build']['status'] + '</a>';
return data;
}
},
{
targets:4,
render: function ( data, type, row, meta ) {
if(type === 'display' && row[1] != 0 && (row['last_build']['status'] == 'SUCCESS' || row['last_build']['status'] == 'UNSTABLE')){
data = '<a href="' + "{{ jenkins_url }}" + '/job/' + row['name'] + '/' + row['last_build']['number'] + '/testReport' + '">Tests</a>';
}
else {
data = 'No Tests';
}
return data;
}
},
{
targets:5,
render: function ( data, type, row, meta ) {
{% if current_user.is_anonymous %}
data = '<a href="' + "{{ jenkins_url }}" + '/job/' + row['name'] + '/' + row['last_build']['number'] + '/consoleFull"><img src="{{ url_for('static', filename='images/terminal.png') }}">';
{% else %}
data = '<a href="' + "{{ jenkins_url }}" + '/job/' + row['name'] + '/' + row['last_build']['number'] + '/consoleFull"><img src="{{ url_for('static', filename='images/terminal.png') }}"> <a href="' + "{{ jenkins_url }}" + '/job/' + row['name'] + '/' + row['last_build']['number'] + '/build"><img src="{{ url_for('static' , filename='images/clock.png') }}"> <a href="' + "{{ jenkins_url }}" + '/job/' + row['name'] + '/' + row['last_build']['number'] + '/configure"><img src="{{ url_for('static', filename='images/gear.png') }}"> ';
{% endif %}
return data;
}
}
],
processing: true,
search: { "regex": true },
"lengthChange": false,
deferRender: true,
});
});
</script>
| bregman-arie/rhoci | rhoci/templates/jobs/last_added_table.js | JavaScript | apache-2.0 | 3,302 |
define([
'backbone',
'models/comment'
], function(Backbone, model){
var Collection = Backbone.Collection.extend({
model: model,
url: '/api/1/comments'
});
return new Collection(init.comments);
});
| erikeldridge/item-network | src/js/collections/comments.js | JavaScript | apache-2.0 | 215 |
var express = require('express');
var http = require('http');
var app = express();
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var router = require('./server/router');
var morgan = require('morgan');
app.use(bodyParser.urlencoded({extended: true}));
// parse application/json
app.use(bodyParser.json());
app.use(methodOverride());
app.use(morgan('dev', { format: 'dev', immediate: true }));
app.use(router());
http.createServer(app).listen(9999, function() {
console.log('Server up: http://localhost:' + 9999);
});
| Raspberrybrat/my-first-rest | index.js | JavaScript | apache-2.0 | 565 |
'use strict';
/* eslint-disable max-len */
const { extend } = require('underscore');
const lifecycleManager = require('abacus-lifecycle-manager')();
const moment = require('abacus-moment');
const { createStatsReader } = require('abacus-test-helper');
const env = {
tokenSecret: 'secret',
tokenAlgorithm: 'HS256',
abacusClientId: 'abacus-collector-client-id',
abacusClientSecret: 'abacus-collector-client-secret',
retryCount: 3
};
const port = 9501;
const hourInMillis = 3600000;
// There may be a case where the test is run at the very last moment of the month
// and until the renewer starts up, we enter into the next month, which causes our tests
// to fail. In order to avoid such a scenario, we check if we are in the last hour of the month
// and we roll back the clock of the renewer through the `ABACUS_TIME_OFFSET` env variable
// to assure that tests work as expected.
const now = moment.now();
const isLastHourOfCurrentMonth = () =>
now >
moment
.utc(now)
.endOf('month')
.subtract(1, 'hour')
.valueOf() &&
now <=
moment
.utc(now)
.endOf('month')
.valueOf();
// Use value larger then the months' length in order to force renewer to start
// independently of current date (renewer starts working only if current date
// is before "start of month + slack")
const slack = '32D';
const getEnviornmentVars = (externalSystems) => ({
ABACUS_CLIENT_ID: env.abacusClientId,
ABACUS_CLIENT_SECRET: env.abacusClientSecret,
SECURED: 'true',
AUTH_SERVER: externalSystems.cloudController.url(),
API: externalSystems.cloudController.url(),
COLLECTOR: externalSystems.abacusCollector.url(),
JWTKEY: env.tokenSecret,
JWTALGO: env.tokenAlgorithm,
RETRIES: env.retryCount,
ABACUS_TIME_OFFSET: isLastHourOfCurrentMonth() ? -hourInMillis : 0,
SLACK: slack
});
module.exports = (customEnv) => ({
env,
readStats: createStatsReader({
port,
tokenSecret: env.tokenSecret
}),
start: (externalSystemsMocks) => {
externalSystemsMocks
.cloudController
.infoService
.returnUaaAddress(externalSystemsMocks.uaaServer.url());
const renewerEnv = extend({}, process.env, getEnviornmentVars(externalSystemsMocks), customEnv);
lifecycleManager.useEnv(renewerEnv).startModules([lifecycleManager.modules.renewer]);
},
stop: lifecycleManager.stopAllStarted
});
| cloudfoundry-incubator/cf-abacus | test/integration/cf/renewer/src/test/renewer.js | JavaScript | apache-2.0 | 2,377 |
'use strict';
import React, {Component, PropTypes} from 'react';
import ReactNative, {View, Text} from 'react-native';
var Popover = require('../Popover');
var AutoHide = require('./AutoHide');
var ToptipAnimation = require('../Popover/PopoverAnimationVertical').create(
{onStartShouldSetResponder: () => false}
);
class Toptip extends AutoHide {
static propTypes = {
...AutoHide.propTypes,
text: PropTypes.string,
children: PropTypes.node,
type: PropTypes.oneOf(['success', 'warning', 'error', 'info']),
};
static contextTypes = {
uiTheme: PropTypes.object.isRequired,
};
render() {
const {
text,
duration,
type,
style,
children,
...other,
} = this.props;
const {toptip, spacing} = this.context.uiTheme;
const paddingTop = spacing.statusbarHeight;
const backgroundColor = toptip.backgroundColors[type];
const color = toptip.colors[type];
let content = children;
if(typeof text === 'string') {
content = (
<Text style={[styles.text, {color}]}>
{text}
</Text>
);
}
return (
<Popover
layerStyle={styles.layer}
{...other}
useLayerForClickAway={true}
animation={ToptipAnimation}
style={[styles.toptip, {backgroundColor, paddingTop}, style]}>
{content}
</Popover>
);
}
}
const styles = {
layer: {
right: 0,
},
toptip: {
alignSelf: 'stretch',
},
text: {
fontSize: 15,
padding: 10,
fontWeight: 'bold',
textAlign: 'center',
},
};
module.exports = Toptip;
| glinjy/react-native-apex-ui | src/Toptip/Toptip.js | JavaScript | apache-2.0 | 1,503 |
import React from 'react';
import PropTypes from 'prop-types';
import FormField from '../../components/FormField';
import TextHelp from '../../components/TextHelp';
import DomainIdField from '../../components/DomainIdField';
import PodcastEdit from './PodcastEdit';
const LibraryFormContents = (props) => {
const { className, errors, formState, session } = props;
const library = formState.object;
let podcast;
if (library.podcast) {
const url = `${window.location.origin}/${library.path || library.id}.rss`;
podcast = [
<p key="loc" className="form__text secondary">
Published at: {url}<br />
<a href={`https://validator.w3.org/feed/check.cgi?url=${encodeURIComponent(url)}`}>
Test
</a> <a href="https://help.apple.com/itc/podcasts_connect/#/itcd88ea40b9">
Submit
</a>
</p>,
<PodcastEdit key="podcast"
podcast={library.podcast}
onChange={formState.change('podcast')} />,
];
}
return (
<div className={className}>
<fieldset className="form__fields">
<FormField label="Name" error={errors.name}>
<input name="name"
value={library.name || ''}
onChange={formState.change('name')} />
</FormField>
<FormField name="text" label="Description" help={<TextHelp />}>
<textarea name="text"
value={library.text || ''}
rows={4}
onChange={formState.change('text')} />
</FormField>
<FormField name="path"
label="Url ID"
help="unique url name"
error={errors.path}>
<input name="path"
value={library.path || ''}
onChange={formState.change('path')} />
</FormField>
<DomainIdField formState={formState} session={session} />
<FormField>
<input name="podcast"
type="checkbox"
checked={library.podcast}
onChange={() =>
formState.set('podcast', library.podcast ? undefined : {})} />
<label htmlFor="podcast">podcast</label>
</FormField>
</fieldset>
{podcast}
</div>
);
};
LibraryFormContents.propTypes = {
className: PropTypes.string,
errors: PropTypes.object,
formState: PropTypes.object.isRequired,
session: PropTypes.object.isRequired,
};
LibraryFormContents.defaultProps = {
className: undefined,
errors: {},
};
export default LibraryFormContents;
| ericsoderberg/pbc-web | ui/js/pages/library/LibraryFormContents.js | JavaScript | apache-2.0 | 2,472 |
sap.ui.define([
"sap/ui/core/mvc/Controller",
"sap/ui/model/json/JSONModel",
"sap/m/MessageToast"
], function (Controller, JSONModel, MessageToast) {
"use strict";
var TABLESETTINGS = window.TABLESETTINGS;
return Controller.extend("sap.ui.table.testApps.DragAndDrop", {
onInit: function () {
var oTable = this.byId("table");
var oTreeTable = this.byId("treetable");
var oModel = new JSONModel();
oModel.setData({
listData: TABLESETTINGS.listTestData,
treeData: TABLESETTINGS.treeTestData
});
oTable.setModel(oModel);
oTreeTable.setModel(oModel);
oTable.addExtension(new sap.m.Toolbar());
TABLESETTINGS.init(oTable, function(oButton) {
oTable.getExtension()[0].addContent(oButton);
});
oTreeTable.addExtension(new sap.m.Toolbar());
// TODO: Make table settings interoperable with multi table pages
//TABLESETTINGS.init(oTreeTable, function(oButton) {
// oTreeTable.getExtension()[0].addContent(oButton);
//});
window.oTable = oTable;
window.oTreeTable = oTreeTable;
},
tableDragStart: function(oEvent) {
var oRow = oEvent.getParameter("target");
var oRowContext = oRow.getBindingContext();
var oModelProperty = oRowContext.getModel().getProperty(oRowContext.getPath());
var sStatus = oModelProperty && oModelProperty.objStatusState != null ? oModelProperty.objStatusState : "";
if (sStatus !== "Success") {
oEvent.preventDefault();
}
this.showDragStartEventInfo(oEvent, "Table");
},
tableReorderDragEnter: function(oEvent) {
var oRow = oEvent.getParameter("target");
var oRowContext = oRow.getBindingContext();
var oModelProperty = oRowContext.getModel().getProperty(oRowContext.getPath());
var sStatus = oModelProperty && oModelProperty.objStatusState != null ? oModelProperty.objStatusState : "";
if (sStatus !== "Success") {
oEvent.preventDefault();
}
this.showDragEnterEventInfo(oEvent, "Table Reorder");
},
tableReorderDrop: function(oEvent) {
this.showDropEventInfo(oEvent, "Table Reorder");
},
tableToTreeTableDragEnter: function(oEvent) {
this.showDragEnterEventInfo(oEvent, "Table to TreeTable");
},
tableToTreeTableDrop: function(oEvent) {
this.showDropEventInfo(oEvent, "Table to TreeTable");
},
treeTableDragStart: function(oEvent) {
this.showDragStartEventInfo(oEvent, "TreeTable");
},
treeTableReorderDragEnter: function(oEvent) {
this.showDragEnterEventInfo(oEvent, "TreeTable Reorder");
},
treeTableReorderDrop: function(oEvent) {
this.showDropEventInfo(oEvent, "TreeTable Reorder");
},
treeTableToTableDragEnter: function(oEvent) {
this.showDragEnterEventInfo(oEvent, "TreeTable to Table");
},
treeTableToTableDrop: function(oEvent) {
this.showDropEventInfo(oEvent, "TreeTable to Table");
},
showDragStartEventInfo: function(oEvent, sTitle) {
sap.m.MessageToast.show(
sTitle + " (" + "DragStart parameters" + ")"
+ "\nDrag target: " + oEvent.getParameter("target").getId()
+ "\nDrag session: " + (oEvent.getParameter("dragSession") ? "available" : "not available")
+ "\nBrowser event: " + oEvent.getParameter("browserEvent").type,
{
width: "25rem"
}
);
},
showDragEnterEventInfo: function(oEvent, sTitle) {
sap.m.MessageToast.show(
sTitle + " (" + "DragEnter parameters" + ")"
+ "\nDrop target: " + oEvent.getParameter("target").getId()
+ "\nDrag session: " + (oEvent.getParameter("dragSession") ? "available" : "not available")
+ "\nBrowser event: " + oEvent.getParameter("browserEvent").type,
{
width: "25rem"
}
);
},
showDropEventInfo: function(oEvent, sTitle) {
sap.m.MessageToast.show(
sTitle + " (" + "Drop parameters" + ")"
+ "\nDragged control: " + oEvent.getParameter("draggedControl").getId()
+ "\nDropped control: " + oEvent.getParameter("droppedControl").getId()
+ "\nDrop position: " + oEvent.getParameter("dropPosition")
+ "\nDrag session: " + (oEvent.getParameter("dragSession") ? "available" : "not available")
+ "\nBrowser event: " + oEvent.getParameter("browserEvent").type,
{
duration: 8000,
width: "25rem"
}
);
},
getProgress: function(sValue) {
sValue = sValue || "";
return (sValue.length * 10) % 100;
},
getRating: function(sValue) {
sValue = sValue || "";
return sValue.length % 5;
}
});
});
| cschuff/openui5 | src/sap.ui.table/test/sap/ui/table/testApps/DragAndDrop.controller.js | JavaScript | apache-2.0 | 4,396 |
/*
* Copyright 2014 Fulup Ar Foll.
*
* 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.
*
* This modele is used for HTTP like divices that do not rely on TCP session
* typical for phone application as CellTrackGTS and others.
*/
'use strict';
var Debug = require("./_Debug");
var TrackerCmd= require("../lib/_TrackerCmd");
// small object to keep track of last position in ram
function PositionObj (data) {
this.msg = parseInt (data.cmd);
this.lat = parseFloat(data.lat);
this.lon = parseFloat(data.lon);
this.sog = parseFloat(data.sog) || 0;
this.cog = parseFloat(data.cog) || 0;
this.alt = parseFloat(data.alt) || 0;
this.moved = parseInt(data.moved) || -1;
this.elapsed= parseInt(data.elapsed) || -1;
this.valid = parseInt(+data.valid);
this.acquired_at = data.acquired_at;
this.gpsdate= data.date;
}
// called from http class of adapter
function GpsdHttpClient (adapter, devid) {
this.debug = adapter.debug; // inherit debug level
this.uid = "httpclient//" + adapter.info + ":" + devid;
this.adapter = adapter;
this.gateway = adapter.gateway;
this.controller = adapter.controller;
this.socket = null; // we cannot rely on socket to talk to device
this.devid = false; // we get uid directly from device
this.name = false;
this.logged = false;
this.alarm = 0; // count alarm messages
this.count = 0; // generic counter used by file backend
this.errorcount = 0; // number of ignore messages
this.uid = "httpclient://" + this.adapter.info + ":" + this.adapter.id;
};
// Import debug method
GpsdHttpClient.prototype.Debug = Debug;
// This method is fast but very approximative for close points
// User may expect 50% of error for distance of few 100m
// nevertheless this is more than enough to optimize storage.
GpsdHttpClient.prototype.Distance = function (old, now) {
var R = 6371; // Radius of the earth in km
var dLat = (now.lat - old.lat) * Math.PI / 180; // deg2rad below
var dLon = (now.lon - old.lon) * Math.PI / 180;
var a =
0.5 - Math.cos(dLat)/2 +
Math.cos(old.lat * Math.PI / 180) * Math.cos(now.lat * Math.PI / 180) *
(1 - Math.cos(dLon))/2;
var d= R * 2 * Math.asin(Math.sqrt(a));
d= Math.round (d*1000);
this.Debug (7, "Distance devid:%s [%s] moved %dm", this.devid, this.name, d);
return (d); // return distance in meters
};
GpsdHttpClient.prototype.DummyName = function (devid) {
var devname = devid.toString();
return devname.substring(devname.length-8);
};
GpsdHttpClient.prototype.LoginDev = function(data) {
// make code simpler to read
var adapter = this.adapter;
var controller= adapter.controller;
var gateway = adapter.controller.gateway;
gateway.event.emit ("notice", "LOGIN_REQUEST", data.devid, this.uid, "");
// if we not logged do it now
if (this.logged === false) {
this.devid = data.devid;
this.class = controller.adapter.info;
//Update/Create device socket store by uid at gateway level
gateway.activeClients [this.devid] = this;
//Propose a fake name in case nothing exist
var emeifix = this.DummyName (this.devid);
this.callsign = "FX-" + emeifix;
this.model = this.devid;
if (!data.name) this.name = this.adapter.id + "-" + emeifix;
else this.name = data.name;
// ask backend to authenticate device and eventfully to change logged state to true
gateway.backend.LoginDev (this);
}
};
GpsdHttpClient.prototype.LogoutDev = function() {
var gateway = this.adapter.controller.gateway;
if (this.logged) {
delete gateway.activeClients [this.devid];
gateway.backend.LogoutDev (this);
}
};
// Action depending on data parsed by the adapter
GpsdHttpClient.prototype.ProcessData = function(data) {
// make code simpler to read
var adapter = this.adapter;
var controller= adapter.controller;
var gateway = adapter.controller.gateway;
// update lastshow to cleanup crom
this.lastshow= new Date().getTime();
switch (data.cmd) {
// This device is not register inside GpsdHttpClient Object
case TrackerCmd.GetFrom.LOGIN:
this.LoginDev (data);
break;
// Device keep alive service
case TrackerCmd.GetFrom.PING:
break;
// Standard tracking information
case TrackerCmd.GetFrom.TRACK :
var update = true; // default is do the update
data.acquired_at = new Date().getTime();
// compute distance only update backend is distance is greater than xxxm
if (this.stamp !== undefined) {
var moved = parseInt (this.Distance (this.stamp, data));
// compute elapsed time since last update
var elapsed = parseInt((data.acquired_at - this.stamp.acquired_at)/1000) ; // in seconds
var speedms = parseInt (moved/elapsed); // NEED TO BE KNOWN: with short tic speed is quicky overestimated by 100% !!!
// usefull human readable info for control console
data.moved = moved;
data.elapsed = elapsed;
// if moved less than mindist or faster than maxspeed check maxtime value
if (moved < this.controller.svcopts.mindist) {
this.Debug(2,"%d Dev=%s Data ignored moved %dm<%dm ?", this.errorcount, this.devid, moved, this.controller.svcopts.mindist);
// should we force a DB update because maxtime ?
if (elapsed < this.controller.svcopts.maxtime) update = false;
}
// if moved less than mindist or faster than maxspeed check maxtime value
if (speedms > this.controller.svcopts.maxspeed) {
this.Debug(2,"%d Dev %s Data ignored speed %dm/s >%dm/s ?", this.errorcount, this.devid, speedms, this.controller.svcopts.maxspeed);
// we only ignore maxErrorCount message, then we restart data acquisition
if (this.errorcount++ < this.controller.svcopts.maxerrors) update = false;
}
} else {
data.moved = 0;
data.elapsed = 0;
}
// update database and store current device location in object for mindist computation
if (update) { // update device last position in Ram/Database
this.stamp = new PositionObj(data);
gateway.backend.UpdatePosDev (this);
} else {
this.Debug(6,"%s Dev=%s ignored moved %dm<%dm ?", this.count, this.devid, moved, this.controller.svcopts.mindist);
this.gateway.backend.IgnorePosDev (this);
}
break;
default:
this.Debug(2, "Notice: [%s] Unknown command=[%s] Ignored", this.uid, data.cmd);
return;
break;
} // end switch
gateway.event.emit ("accept", this, data);
this.Debug (5, "Devid:[%s] Name:[%s] Cmd:[%s] Lat:%d Lon:%d Date:%s Logged=%s", this.devid, this.name, data.cmd, data.lat, data.lon, data.date, this.logged );
};
// Only LOGOUT command make sence with a TcpFeed
GpsdHttpClient.prototype.RequestAction = function(command,args){
// send command to adapter & backend
var status = this.adapter.SendCommand (this,command,args);
if (status !== 0) {
this.gateway.event.emit ("notice", "UNSUP_CMD", command, this.adapter.uid);
}
return(status);
};
module.exports = GpsdHttpClient; | fulup-bzh/GeoGate | server/lib/_HttpClient.js | JavaScript | apache-2.0 | 8,325 |
/* global suite test internalScope */
(function () {
suite('offsetPath', function () {
test('basicShapeCircle', function () {
var assertTransformInterpolation = internalScope.assertTransformInterpolation;
assertTransformInterpolation([
{'offsetPath': 'circle(10px at 0px 0px)', 'offsetDistance': '0%'},
{'offsetPath': 'circle(10px at 0px 0px)', 'offsetDistance': '100%'}],
[
{at: 0, is: 'translate3d(0px, -10px, 0px)'},
{at: 0.25, is: 'translate3d(10px, 0px, 0px) rotate(90deg)'},
{at: 0.5, is: 'translate3d(0px, 10px, 0px) rotate(180deg)'},
{at: 0.75, is: 'translate3d(-10px, 0px, 0px) rotate(-90deg)'},
{at: 1, is: 'translate3d(0px, -10px, 0px)'}
]
);
assertTransformInterpolation([
{'offsetPath': 'circle(10px at 0px 0px)', 'offsetDistance': '0px'},
{'offsetPath': 'circle(10px at 0px 0px)', 'offsetDistance': '62.83px'}],
[
{at: 0, is: 'translate3d(0px, -10px, 0px)'},
{at: 0.25, is: 'translate3d(10px, 0px, 0px) rotate(89.45deg)'},
{at: 0.5, is: 'translate3d(0.01px, 10px, 0px) rotate(180deg)'},
{at: 0.75, is: 'translate3d(-10px, 0.01px, 0px) rotate(-90deg)'},
{at: 1, is: 'translate3d(-0.01px, -10px, 0px) rotate(-0.55deg)'}
]
);
assertTransformInterpolation([
{'offsetPath': 'circle(10px at 0px 0px)', 'offsetDistance': '0%'},
{'offsetPath': 'circle(10px at 0px 0px)', 'offsetDistance': '50%'}],
[
{at: 0, is: 'translate3d(0px, -10px, 0px)'},
{at: 0.5, is: 'translate3d(10px, 0px, 0px) rotate(90deg)'},
{at: 1, is: 'translate3d(0px, 10px, 0px) rotate(180deg)'}
]
);
assertTransformInterpolation([
{'offsetPath': 'circle(10px at 0px 0px)', 'offsetDistance': '0px'},
{'offsetPath': 'circle(10px at 0px 0px)', 'offsetDistance': '31.42px'}],
[
{at: 0, is: 'translate3d(0px, -10px, 0px)'},
{at: 0.5, is: 'translate3d(10px, 0px, 0px) rotate(90deg)'},
{at: 1, is: 'translate3d(0px, 10px, 0px) rotate(179.45deg)'}
]
);
assertTransformInterpolation([
{'offsetPath': 'circle(10px at 100px 100px)', 'offsetDistance': '0%'},
{'offsetPath': 'circle(10px at 100px 100px)', 'offsetDistance': '100%'}],
[
{at: 0, is: 'translate3d(100px, 90px, 0px)'},
{at: 0.25, is: 'translate3d(110px, 100px, 0px) rotate(90deg)'},
{at: 0.5, is: 'translate3d(100px, 110px, 0px) rotate(180deg)'},
{at: 0.75, is: 'translate3d(90px, 100px, 0px) rotate(-90deg)'},
{at: 1, is: 'translate3d(100px, 90px, 0px)'}
]
);
// TODO: Support path interpolation for basic shapes.
assertTransformInterpolation([
{'offsetPath': 'circle(0px at 100px 200px)', 'offsetDistance': '1000px', 'offsetRotate': '0deg', 'offsetAnchor': '50% 50%'},
{'offsetPath': 'circle(0px at 300px 400px)', 'offsetDistance': '1000px', 'offsetRotate': '0deg', 'offsetAnchor': '50% 50%'}],
[
{at: 0, is: 'translate3d(100px, 200px, 0px)'},
{at: 1, is: 'translate3d(300px, 400px, 0px)'}
]
);
});
});
})();
| Motion-Path-Polyfill/motion-path-js | test/pathBasicShapeCircleTest.js | JavaScript | apache-2.0 | 4,232 |
/*
* Copyright (C) 2014 Xillio (support@xillio.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
| XillioQA/xill-platform-3.4 | xill-ide-core/src/main/resources/load-doc-editor.js | JavaScript | apache-2.0 | 634 |
//// [promiseIdentityWithAny2.ts]
interface IPromise<T, V> {
then<U, W>(callback: (x: T) => IPromise<U, W>): IPromise<U, W>;
}
interface Promise<T, V> {
then(callback: (x: T) => Promise<any, any>): Promise<any, any>;
}
// Error because type parameter arity doesn't match
var x: IPromise<string, number>;
var x: Promise<string, boolean>;
interface IPromise2<T, V> {
then<U, W>(callback: (x: T) => IPromise2<U, W>): IPromise2<U, W>;
}
interface Promise2<T, V> {
then<U, W>(callback: (x: T) => Promise2<string, any>): Promise2<any, any>; // Uses string instead of any!
}
// Error because string and any don't match
var y: IPromise2<string, number>;
var y: Promise2<string, boolean>;
//// [promiseIdentityWithAny2.js]
// Error because type parameter arity doesn't match
var x;
var x;
// Error because string and any don't match
var y;
var y;
| freedot/tstolua | tests/baselines/reference/promiseIdentityWithAny2.js | JavaScript | apache-2.0 | 859 |
'use strict';
/**
* Created by zhaoxueyong on 2017/1/14.
*/
angular.module('browserApp').
controller('ColuslifeCtrl', function ($scope, $http) {
$scope.countryName = "China";
var mapObj = null;
$scope.init_map = function(){
console.log("init map now");
mapObj = new AMap.Map("mapbody", {
level: 7,
building: false,
point: false
});
var marker = new AMap.Marker({
position: new AMap.LngLat(120.58, 31.335),
title: 'SuZhouLeYuan'
});
marker.setMap(mapObj);
};
$('#btnLocation').on("click", function(){
var locations = null;
if (null === locations){
$http({
method: 'GET',
url: 'http://127.0.0.1:8000/coluslife/locations',
timeout: 5
}).then(
function successCallback(response){
console.log(response.data);
locations = response.data;
for (var i = 0; i < locations.length; i++){
var loc = locations[i];
placeMarker(loc);
}
},
function errorCallback(error){
console.error(error);
});
}
});
var placeMarker = function(location){
var marker = new AMap.Marker({
position: new AMap.LngLat(location.fields.gislng, location.fields.gislat),
title: location.fields.name
});
marker.setMap(mapObj);
}
});
| ColusLife/ColusLifeDemo | Browser/app/scripts/controllers/coluslife.js | JavaScript | apache-2.0 | 1,433 |
// Copyright 2017 Joyent, Inc.
module.exports = Identity;
var assert = require('assert-plus');
var algs = require('./algs');
var crypto = require('crypto');
var Fingerprint = require('./fingerprint');
var Signature = require('./signature');
var errs = require('./errors');
var util = require('util');
var utils = require('./utils');
var asn1 = require('asn1');
/*JSSTYLED*/
var DNS_NAME_RE = /^([*]|[a-z0-9][a-z0-9\-]{0,62})(?:\.([*]|[a-z0-9][a-z0-9\-]{0,62}))*$/i;
var oids = {};
oids.cn = '2.5.4.3';
oids.o = '2.5.4.10';
oids.ou = '2.5.4.11';
oids.l = '2.5.4.7';
oids.s = '2.5.4.8';
oids.c = '2.5.4.6';
oids.sn = '2.5.4.4';
oids.dc = '0.9.2342.19200300.100.1.25';
oids.uid = '0.9.2342.19200300.100.1.1';
oids.mail = '0.9.2342.19200300.100.1.3';
var unoids = {};
Object.keys(oids).forEach(function (k) {
unoids[oids[k]] = k;
});
function Identity(opts) {
var self = this;
assert.object(opts, 'options');
assert.arrayOfObject(opts.components, 'options.components');
this.components = opts.components;
this.componentLookup = {};
this.components.forEach(function (c) {
if (c.name && !c.oid)
c.oid = oids[c.name];
if (c.oid && !c.name)
c.name = unoids[c.oid];
if (self.componentLookup[c.name] === undefined)
self.componentLookup[c.name] = [];
self.componentLookup[c.name].push(c);
});
if (this.componentLookup.cn && this.componentLookup.cn.length > 0) {
this.cn = this.componentLookup.cn[0].value;
}
assert.optionalString(opts.type, 'options.type');
if (opts.type === undefined) {
if (this.components.length === 1 &&
this.componentLookup.cn &&
this.componentLookup.cn.length === 1 &&
this.componentLookup.cn[0].value.match(DNS_NAME_RE)) {
this.type = 'host';
this.hostname = this.componentLookup.cn[0].value;
} else if (this.componentLookup.dc &&
this.components.length === this.componentLookup.dc.length) {
this.type = 'host';
this.hostname = this.componentLookup.dc.map(
function (c) {
return (c.value);
}).join('.');
} else if (this.componentLookup.uid &&
this.components.length ===
this.componentLookup.uid.length) {
this.type = 'user';
this.uid = this.componentLookup.uid[0].value;
} else if (this.componentLookup.cn &&
this.componentLookup.cn.length === 1 &&
this.componentLookup.cn[0].value.match(DNS_NAME_RE)) {
this.type = 'host';
this.hostname = this.componentLookup.cn[0].value;
} else if (this.componentLookup.uid &&
this.componentLookup.uid.length === 1) {
this.type = 'user';
this.uid = this.componentLookup.uid[0].value;
} else if (this.componentLookup.mail &&
this.componentLookup.mail.length === 1) {
this.type = 'email';
this.email = this.componentLookup.mail[0].value;
} else if (this.componentLookup.cn &&
this.componentLookup.cn.length === 1) {
this.type = 'user';
this.uid = this.componentLookup.cn[0].value;
} else {
this.type = 'unknown';
}
} else {
this.type = opts.type;
if (this.type === 'host')
this.hostname = opts.hostname;
else if (this.type === 'user')
this.uid = opts.uid;
else if (this.type === 'email')
this.email = opts.email;
else
throw (new Error('Unknown type ' + this.type));
}
}
Identity.prototype.toString = function () {
return (this.components.map(function (c) {
return (c.name.toUpperCase() + '=' + c.value);
}).join(', '));
};
/*
* These are from X.680 -- PrintableString allowed chars are in section 37.4
* table 8. Spec for IA5Strings is "1,6 + SPACE + DEL" where 1 refers to
* ISO IR #001 (standard ASCII control characters) and 6 refers to ISO IR #006
* (the basic ASCII character set).
*/
/* JSSTYLED */
var NOT_PRINTABLE = /[^a-zA-Z0-9 '(),+.\/:=?-]/;
/* JSSTYLED */
var NOT_IA5 = /[^\x00-\x7f]/;
Identity.prototype.toAsn1 = function (der, tag) {
der.startSequence(tag);
this.components.forEach(function (c) {
der.startSequence(asn1.Ber.Constructor | asn1.Ber.Set);
der.startSequence();
der.writeOID(c.oid);
/*
* If we fit in a PrintableString, use that. Otherwise use an
* IA5String or UTF8String.
*/
if (c.value.match(NOT_IA5)) {
var v = new Buffer(c.value, 'utf8');
der.writeBuffer(v, asn1.Ber.Utf8String);
} else if (c.value.match(NOT_PRINTABLE)) {
der.writeString(c.value, asn1.Ber.IA5String);
} else {
der.writeString(c.value, asn1.Ber.PrintableString);
}
der.endSequence();
der.endSequence();
});
der.endSequence();
};
function globMatch(a, b) {
if (a === '**' || b === '**')
return (true);
var aParts = a.split('.');
var bParts = b.split('.');
if (aParts.length !== bParts.length)
return (false);
for (var i = 0; i < aParts.length; ++i) {
if (aParts[i] === '*' || bParts[i] === '*')
continue;
if (aParts[i] !== bParts[i])
return (false);
}
return (true);
}
Identity.prototype.equals = function (other) {
if (!Identity.isIdentity(other, [1, 0]))
return (false);
if (other.components.length !== this.components.length)
return (false);
for (var i = 0; i < this.components.length; ++i) {
if (this.components[i].oid !== other.components[i].oid)
return (false);
if (!globMatch(this.components[i].value,
other.components[i].value)) {
return (false);
}
}
return (true);
};
Identity.forHost = function (hostname) {
assert.string(hostname, 'hostname');
return (new Identity({
type: 'host',
hostname: hostname,
components: [{name: 'cn', value: hostname}]
}));
};
Identity.forUser = function (uid) {
assert.string(uid, 'uid');
return (new Identity({
type: 'user',
uid: uid,
components: [{name: 'uid', value: uid}]
}));
};
Identity.forEmail = function (email) {
assert.string(email, 'email');
return (new Identity({
type: 'email',
email: email,
components: [{name: 'mail', value: email}]
}));
};
Identity.parseDN = function (dn) {
assert.string(dn, 'dn');
var parts = dn.split(',');
var cmps = parts.map(function (c) {
c = c.trim();
var eqPos = c.indexOf('=');
var name = c.slice(0, eqPos).toLowerCase();
var value = c.slice(eqPos + 1);
return ({name: name, value: value});
});
return (new Identity({components: cmps}));
};
Identity.parseAsn1 = function (der, top) {
var components = [];
der.readSequence(top);
var end = der.offset + der.length;
while (der.offset < end) {
der.readSequence(asn1.Ber.Constructor | asn1.Ber.Set);
var after = der.offset + der.length;
der.readSequence();
var oid = der.readOID();
var type = der.peek();
var value;
switch (type) {
case asn1.Ber.PrintableString:
case asn1.Ber.IA5String:
case asn1.Ber.OctetString:
case asn1.Ber.T61String:
value = der.readString(type);
break;
case asn1.Ber.Utf8String:
value = der.readString(type, true);
value = value.toString('utf8');
break;
case asn1.Ber.CharacterString:
case asn1.Ber.BMPString:
value = der.readString(type, true);
value = value.toString('utf16le');
break;
default:
throw (new Error('Unknown asn1 type ' + type));
}
components.push({oid: oid, value: value});
der._offset = after;
}
der._offset = end;
return (new Identity({
components: components
}));
};
Identity.isIdentity = function (obj, ver) {
return (utils.isCompatible(obj, Identity, ver));
};
/*
* API versions for Identity:
* [1,0] -- initial ver
*/
Identity.prototype._sshpkApiVersion = [1, 0];
Identity._oldVersionDetect = function (obj) {
return ([1, 0]);
};
| ionutbarau/petstore | petstore-app/src/main/resources/static/node_modules/sshpk/lib/identity.js | JavaScript | apache-2.0 | 8,545 |
// viewReportedPeptidesForProteinAllLoadedFromWebServiceTemplate.js
// Process and load data into the file viewReportedPeptidesForProteinAllLoadedFromWebServiceTemplateFragment.jsp
// Used on page viewSearchProteinAll.jsp
//////////////////////////////////
// JavaScript directive: all variables have to be declared with "var", maybe other things
"use strict";
// require full Handlebars since compiling templates
const Handlebars = require('handlebars');
// For showing Data for links (Drilldown) (Called by HTML onclick):
import { viewPsmsLoadedFromWebServiceTemplate } from 'page_js/data_pages/project_search_ids_driven_pages/common/viewPsmsLoadedFromWebServiceTemplate.js';
// Class contructor
var ViewReportedPeptidesForProteinAllLoadedFromWebServiceTemplate = function() {
var _DATA_LOADED_DATA_KEY = "dataLoaded";
var _handlebarsTemplate_peptide_protein_all_block_template = null;
var _handlebarsTemplate_peptide_protein_all_data_row_entry_template = null;
var _handlebarsTemplate_peptide_protein_all_child_row_entry_template = null;
var _psmPeptideAnnTypeIdDisplay = null;
var _psmPeptideCutoffsRootObject = null;
var _excludeLinksWith_Root = null;
var _chosenLinkTypes = undefined;
//////////////
this.setPsmPeptideCriteria = function( psmPeptideCutoffsRootObject ) {
_psmPeptideCutoffsRootObject = psmPeptideCutoffsRootObject;
};
//////////////
this.setPsmPeptideAnnTypeIdDisplay = function( psmPeptideAnnTypeIdDisplay ) {
_psmPeptideAnnTypeIdDisplay = psmPeptideAnnTypeIdDisplay;
};
//////////////
this.setExcludeLinksWith_Root = function( excludeLinksWith_Root ) {
_excludeLinksWith_Root = excludeLinksWith_Root;
};
//////////////
this.setChosenLinkTypes = function( chosenLinkTypes ) {
_chosenLinkTypes = chosenLinkTypes;
};
// ////////////
this.showHideReportedPeptides = function( params ) {
try {
var clickedElement = params.clickedElement;
var $clickedElement = $( clickedElement );
var $itemToToggle = $clickedElement.next();
if( $itemToToggle.is(":visible" ) ) {
$itemToToggle.hide();
$clickedElement.find(".toggle_visibility_expansion_span_jq").show();
$clickedElement.find(".toggle_visibility_contraction_span_jq").hide();
} else {
$itemToToggle.show();
$clickedElement.find(".toggle_visibility_expansion_span_jq").hide();
$clickedElement.find(".toggle_visibility_contraction_span_jq").show();
this.loadAndInsertReportedPeptidesIfNeeded( { $topTRelement : $itemToToggle, $clickedElement : $clickedElement } );
}
return false; // does not stop bubbling of click event
} catch( e ) {
reportWebErrorToServer.reportErrorObjectToServer( { errorException : e } );
throw e;
}
};
// ////////////
this.reloadData = function( params ) {
try {
var $htmlElement = params.$htmlElement;
var $itemToToggle = $htmlElement.next();
this.loadAndInsertReportedPeptidesIfNeeded( {
$topTRelement : $itemToToggle,
$clickedElement : $htmlElement,
reloadData : true } );
} catch( e ) {
reportWebErrorToServer.reportErrorObjectToServer( { errorException : e } );
throw e;
}
};
////////////////////////
this.loadAndInsertReportedPeptidesIfNeeded = function( params ) {
var objectThis = this;
var $topTRelement = params.$topTRelement;
var $clickedElement = params.$clickedElement;
var reloadData = params.reloadData;
if ( ! reloadData ) {
var dataLoaded = $topTRelement.data( _DATA_LOADED_DATA_KEY );
if ( dataLoaded ) {
return; // EARLY EXIT since data already loaded.
}
}
var project_search_id = $clickedElement.attr( "data-project_search_id" );
var protein_id = $clickedElement.attr( "data-protein_id" );
// Convert all attributes to empty string if null or undefined
if ( ! project_search_id ) {
project_search_id = "";
}
if ( ! protein_id ) {
protein_id = "";
}
if ( _psmPeptideCutoffsRootObject === null || _psmPeptideCutoffsRootObject === undefined ) {
throw Error( "_psmPeptideCutoffsRootObject not initialized" );
}
var psmPeptideCutoffsForProjectSearchId = _psmPeptideCutoffsRootObject.searches[ project_search_id ];
if ( psmPeptideCutoffsForProjectSearchId === undefined || psmPeptideCutoffsForProjectSearchId === null ) {
psmPeptideCutoffsForProjectSearchId = {};
// throw Error( "Getting data. Unable to get cutoff data for project_search_id: " + project_search_id );
}
var psmPeptideCutoffsForProjectSearchId_JSONString = JSON.stringify( psmPeptideCutoffsForProjectSearchId );
var psmPeptideAnnTypeDisplayPerProjectSearchId_JSONString = null;
if ( _psmPeptideAnnTypeIdDisplay ) {
var psmPeptideAnnTypeIdDisplayForProjectSearchId = _psmPeptideAnnTypeIdDisplay.searches[ project_search_id ];
if ( psmPeptideAnnTypeIdDisplayForProjectSearchId === undefined || psmPeptideAnnTypeIdDisplayForProjectSearchId === null ) {
// psmPeptideAnnTypeIdDisplayForSearchId = {};
throw Error( "Getting data. Unable to get ann type display data for project_search_id: " + project_search_id );
}
psmPeptideAnnTypeDisplayPerProjectSearchId_JSONString = JSON.stringify( psmPeptideAnnTypeIdDisplayForProjectSearchId );
}
var excludeLinksWith_Root_JSONString = undefined;
if ( _excludeLinksWith_Root ) {
excludeLinksWith_Root_JSONString = JSON.stringify( _excludeLinksWith_Root );
}
var ajaxRequestData = {
project_search_id : project_search_id,
protein_id : protein_id,
psmPeptideCutoffsForProjectSearchId : psmPeptideCutoffsForProjectSearchId_JSONString,
peptideAnnTypeDisplayPerSearch : psmPeptideAnnTypeDisplayPerProjectSearchId_JSONString,
excludeLinksWith_Root : excludeLinksWith_Root_JSONString
};
if ( _chosenLinkTypes !== null && _chosenLinkTypes !== undefined ) {
ajaxRequestData.link_type = _chosenLinkTypes;
}
$.ajax({
url : "services/data/getReportedPeptidesAllProteinsPage",
traditional: true, // Force traditional serialization of the data sent
// One thing this means is that arrays are sent as the object property instead of object property followed by "[]".
// So searchIds array is passed as "searchIds=<value>" which is what Jersey expects
data : ajaxRequestData, // The data sent as params on the URL
dataType : "json",
success : function( ajaxResponseData ) {
try {
var responseParams = {
ajaxResponseData : ajaxResponseData,
ajaxRequestData : ajaxRequestData,
$topTRelement : $topTRelement,
$clickedElement : $clickedElement
};
objectThis.loadAndInsertReportedPeptidesResponse( responseParams );
$topTRelement.data( _DATA_LOADED_DATA_KEY, true );
} catch( e ) {
reportWebErrorToServer.reportErrorObjectToServer( { errorException : e } );
throw e;
}
},
failure: function(errMsg) {
handleAJAXFailure( errMsg );
},
error : function(jqXHR, textStatus, errorThrown) {
handleAJAXError(jqXHR, textStatus, errorThrown);
}
});
};
///////////////////
this.loadAndInsertReportedPeptidesResponse = function( params ) {
var ajaxResponseData = params.ajaxResponseData;
var ajaxRequestData = params.ajaxRequestData;
var $clickedElement = params.$clickedElement;
var show_children_if_one_row = $clickedElement.attr( "show_children_if_one_row" );
var peptideAnnotationDisplayNameDescriptionList = ajaxResponseData.peptideAnnotationDisplayNameDescriptionList;
var psmAnnotationDisplayNameDescriptionList = ajaxResponseData.psmAnnotationDisplayNameDescriptionList;
var peptide_protein_alls = ajaxResponseData.searchPeptideNoLinkInfoList;
var $topTRelement = params.$topTRelement;
var $peptide_protein_all_data_container = $topTRelement.find(".child_data_container_jq");
if ( $peptide_protein_all_data_container.length === 0 ) {
throw Error( "unable to find HTML element with class 'child_data_container_jq'" );
}
$peptide_protein_all_data_container.empty();
if ( _handlebarsTemplate_peptide_protein_all_block_template === null ) {
var handlebarsSource_peptide_protein_all_block_template = $( "#peptide_protein_all_block_template" ).html();
if ( handlebarsSource_peptide_protein_all_block_template === undefined ) {
throw Error( "handlebarsSource_peptide_protein_all_block_template === undefined" );
}
if ( handlebarsSource_peptide_protein_all_block_template === null ) {
throw Error( "handlebarsSource_peptide_protein_all_block_template === null" );
}
_handlebarsTemplate_peptide_protein_all_block_template = Handlebars.compile( handlebarsSource_peptide_protein_all_block_template );
}
if ( _handlebarsTemplate_peptide_protein_all_data_row_entry_template === null ) {
var handlebarsSource_peptide_protein_all_data_row_entry_template = $( "#peptide_protein_all_data_row_entry_template" ).html();
if ( handlebarsSource_peptide_protein_all_data_row_entry_template === undefined ) {
throw Error( "handlebarsSource_peptide_protein_all_data_row_entry_template === undefined" );
}
if ( handlebarsSource_peptide_protein_all_data_row_entry_template === null ) {
throw Error( "handlebarsSource_peptide_protein_all_data_row_entry_template === null" );
}
_handlebarsTemplate_peptide_protein_all_data_row_entry_template = Handlebars.compile( handlebarsSource_peptide_protein_all_data_row_entry_template );
}
if ( _handlebarsTemplate_peptide_protein_all_child_row_entry_template === null ) {
var handlebarsSource_peptide_protein_all_child_row_entry_template = $( "#peptide_protein_all_child_row_entry_template" ).html();
if ( handlebarsSource_peptide_protein_all_child_row_entry_template === undefined ) {
throw Error( "handlebarsSource_peptide_protein_all_child_row_entry_template === undefined" );
}
if ( handlebarsSource_peptide_protein_all_child_row_entry_template === null ) {
throw Error( "handlebarsSource_peptide_protein_all_child_row_entry_template === null" );
}
_handlebarsTemplate_peptide_protein_all_child_row_entry_template = Handlebars.compile( handlebarsSource_peptide_protein_all_child_row_entry_template );
}
// Search for NumberNonUniquePSMs being set in any row
var showNumberNonUniquePSMs = false;
for ( var peptide_protein_allIndex = 0; peptide_protein_allIndex < peptide_protein_alls.length ; peptide_protein_allIndex++ ) {
var peptide_protein_all = peptide_protein_alls[ peptide_protein_allIndex ];
if ( peptide_protein_all.numNonUniquePsms !== undefined && peptide_protein_all.numNonUniquePsms !== null ) {
showNumberNonUniquePSMs = true;
break;
}
}
// create context for header row
var context = {
showNumberNonUniquePSMs : showNumberNonUniquePSMs,
peptideAnnotationDisplayNameDescriptionList : peptideAnnotationDisplayNameDescriptionList,
psmAnnotationDisplayNameDescriptionList : psmAnnotationDisplayNameDescriptionList
};
var html = _handlebarsTemplate_peptide_protein_all_block_template(context);
var $peptide_protein_all_block_template = $(html).appendTo($peptide_protein_all_data_container);
var peptide_protein_all_table_jq_ClassName = "peptide_protein_all_table_jq";
var $peptide_protein_all_table_jq = $peptide_protein_all_block_template.find("." + peptide_protein_all_table_jq_ClassName );
if ( $peptide_protein_all_table_jq.length === 0 ) {
throw Error( "unable to find HTML element with class '" + peptide_protein_all_table_jq_ClassName + "'" );
}
// Add peptide_protein_all data to the page
for ( var peptide_protein_allIndex = 0; peptide_protein_allIndex < peptide_protein_alls.length ; peptide_protein_allIndex++ ) {
var peptide_protein_all = peptide_protein_alls[ peptide_protein_allIndex ];
// wrap data in an object to allow adding more fields
var context = {
showNumberNonUniquePSMs : showNumberNonUniquePSMs,
data : peptide_protein_all,
projectSearchId : ajaxRequestData.project_search_id
};
var html = _handlebarsTemplate_peptide_protein_all_data_row_entry_template(context);
var $peptide_protein_all_entry =
$(html).appendTo($peptide_protein_all_table_jq);
// Get the number of columns of the inserted row so can set the "colspan=" in the next row
// that holds the child data
var $peptide_protein_all_entry__columns = $peptide_protein_all_entry.find("td");
var peptide_protein_all_entry__numColumns = $peptide_protein_all_entry__columns.length;
// colSpan is used as the value for "colspan=" in the <td>
var childRowHTML_Context = { colSpan : peptide_protein_all_entry__numColumns };
var childRowHTML = _handlebarsTemplate_peptide_protein_all_child_row_entry_template( childRowHTML_Context );
// Add next row for child data
$( childRowHTML ).appendTo($peptide_protein_all_table_jq);
// If only one record, click on it to show it's children
if ( show_children_if_one_row === "true" && peptide_protein_alls.length === 1 ) {
$peptide_protein_all_entry.click();
}
}
// If the function window.linkInfoOverlayWidthResizer() exists, call it to resize the overlay
if ( window.linkInfoOverlayWidthResizer ) {
window.linkInfoOverlayWidthResizer();
}
};
};
// Static Singleton Instance of Class
var viewReportedPeptidesForProteinAllLoadedFromWebServiceTemplate = new ViewReportedPeptidesForProteinAllLoadedFromWebServiceTemplate();
window.viewReportedPeptidesForProteinAllLoadedFromWebServiceTemplate = viewReportedPeptidesForProteinAllLoadedFromWebServiceTemplate;
export { viewReportedPeptidesForProteinAllLoadedFromWebServiceTemplate }
| yeastrc/proxl-web-app | proxl_web_app/front_end/src/js/page_js/data_pages/project_search_ids_driven_pages/protein_pages/viewReportedPeptidesForProteinAllLoadedFromWebServiceTemplate.js | JavaScript | apache-2.0 | 13,535 |
angular.module('n52.core.base')
.factory('styleService', ['$rootScope', 'settingsService', 'colorService', '$injector', "styleServiceStandalone",
function($rootScope, settingsService, colorService, $injector, styleServiceStandalone) {
var intervalList = settingsService.intervalList;
function createStylesInTs(ts) {
var styles, color, visible, selected, zeroScaled, groupedAxis;
if (!ts.styles) {
ts.styles = {};
}
color = ts.styles.color || ts.renderingHints && ts.renderingHints.properties.color || colorService.getColor(ts.id);
visible = true;
selected = false;
if (angular.isUndefined(ts.styles.zeroScaled)) {
zeroScaled = settingsService.defaultZeroScale;
}
if (angular.isUndefined(ts.styles.groupedAxis)) {
groupedAxis = settingsService.defaultGroupedAxis;
}
styles = styleServiceStandalone.createStyle(ts, color, zeroScaled, groupedAxis, selected, visible);
angular.merge(ts.styles, styles);
angular.forEach(ts.referenceValues, function(refValue) {
refValue.color = colorService.getRefColor(refValue.referenceValueId);
});
}
function deleteStyle(ts) {
colorService.removeColor(ts.styles.color);
angular.forEach(ts.referenceValues, function(refValue) {
colorService.removeRefColor(refValue.color);
});
}
function toggleSelection(ts) {
ts.styles.selected = !ts.styles.selected;
$rootScope.$emit('timeseriesChanged', ts.internalId);
}
function setSelection(ts, selected, quiet) {
ts.styles.selected = selected;
if (!quiet) {
$rootScope.$emit('timeseriesChanged', ts.internalId);
}
}
function toggleTimeseriesVisibility(ts) {
ts.styles.visible = !ts.styles.visible;
$rootScope.$emit('timeseriesChanged', ts.internalId);
}
function updateColor(ts, color) {
ts.styles.color = color;
$rootScope.$emit('timeseriesChanged', ts.internalId);
}
function updateZeroScaled(ts) {
ts.styles.zeroScaled = !ts.styles.zeroScaled;
if (ts.styles.groupedAxis) {
var tsSrv = $injector.get('timeseriesService');
angular.forEach(tsSrv.getAllTimeseries(), function(timeseries) {
if (timeseries.uom === ts.uom && timeseries.styles.groupedAxis) {
timeseries.styles.zeroScaled = ts.styles.zeroScaled;
}
});
}
$rootScope.$emit('timeseriesChanged', ts.internalId);
}
function updateGroupAxis(ts) {
ts.styles.groupedAxis = !ts.styles.groupedAxis;
$rootScope.$emit('timeseriesChanged', ts.internalId);
}
function updateInterval(ts, interval) {
ts.renderingHints.properties.interval = interval.caption;
ts.renderingHints.properties.value = interval.value;
$rootScope.$emit('timeseriesChanged', ts.internalId);
}
function notifyAllTimeseriesChanged() {
$rootScope.$emit('allTimeseriesChanged');
}
function triggerStyleUpdate(ts) {
$rootScope.$emit('timeseriesChanged', ts.internalId);
}
return {
createStylesInTs: createStylesInTs,
deleteStyle: deleteStyle,
notifyAllTimeseriesChanged: notifyAllTimeseriesChanged,
toggleSelection: toggleSelection,
setSelection: setSelection,
toggleTimeseriesVisibility: toggleTimeseriesVisibility,
updateColor: updateColor,
updateZeroScaled: updateZeroScaled,
updateGroupAxis: updateGroupAxis,
updateInterval: updateInterval,
intervalList: intervalList,
triggerStyleUpdate: triggerStyleUpdate
};
}
]);
| 52North/sensorweb-client-core | src/js/base/services/styleTs.js | JavaScript | apache-2.0 | 4,493 |
/**
* Slices arrays.
* @param array
* @param pos
* @returns {string}
*/
var arraySlicer = function (array, pos) {
return array.slice(0, pos).concat(array.slice(pos + 1, array.length));
};
/**
* https://en.wikipedia.org/wiki/Cosine_similarity
* https://en.wikipedia.org/wiki/Canberra_distance
* https://en.wikipedia.org/wiki/Sørensen–Dice_coefficient
* @param arr1
* @param arr2
* @returns {number}
*/
function distanceFunction(arr1, arr2) {
var INTERVAL = 70;
/*var sum1 = 0;
var sum2 = 0;
var sum3 = 0;
var canberra = 0;
var Czekanowski1 = 0;
var Czekanowski2 = 0;
*/
var intervalCount = 0;
for (var i = 0; i < arr1.length && i < arr2.length; i++) {
/*sum1 += arr1[i] * arr2[i];
sum2 += arr1[i] * arr1[i];
sum3 += arr2[i] * arr2[i];
canberra += Math.abs(arr1[i] - arr2[i]) / (arr1[i] + arr2[i]);
Czekanowski1 += (arr1[i] * arr2[i]);
Czekanowski2 += (arr1[i] * arr1[i] + arr2[i] * arr2[i]);
*/
if (Math.abs(arr1[i] - arr2[i]) > INTERVAL) {
intervalCount++;
}
}
/*var similarity = (sum1 / (Math.sqrt(sum2) * Math.sqrt(sum3)));
var distance = Math.acos(similarity) * 2 / Math.PI;
var Sørensen = (2 * Czekanowski1) / Czekanowski2;
return [similarity, distance, 1 - distance, 2 * sum1 / (sum2 + sum3), canberra, Sørensen, intervaledCount];
*/
return intervalCount;
}
function randInt(N) {
if (!N) N = Number.MAX_SAFE_INTEGER;
return Math.floor((Math.random() * Number.MAX_VALUE) % (Math.pow(10, N)));
}
if (typeof exports != "undefined") {
exports.distanceFunction = distanceFunction;
exports.randInt = randInt;
} | albertlinde/Legion | framework/shared/Utils.js | JavaScript | apache-2.0 | 1,725 |
(function () {
'use strict';
var dccModul = angular.module('workinghours', ['dcc.controller', 'dcc.factories', 'dcc.filter', 'ngCookies', 'ngRoute']);
dccModul.config(['$routeProvider', '$httpProvider', function ($routeProvider, $httpProvider) {
$routeProvider.when('/duration/new', {
templateUrl: '/partials/durationNew.html',
controller: 'DurationController'
});
$routeProvider.when('/duration/:id', {
templateUrl: '/partials/durationNew.html',
controller: 'DurationController'
});
$routeProvider.when('/login', {templateUrl: '/partials/login.html', controller: 'LoginController'});
$routeProvider.when('/adminoverview', {
templateUrl: '/partials/adminoverview.html',
controller: 'AdminOverviewController'
});
$routeProvider.when('/users/new', {templateUrl: '/partials/userNew.html', controller: 'NewUserController'});
$routeProvider.when('/checkin', {templateUrl: '/partials/checkIn.html', controller: 'CheckInController'});
$routeProvider.when('/changepassword', {
templateUrl: '/partials/changepassword.html',
controller: 'ChangePasswordController'
});
$routeProvider.otherwise({templateUrl: '/partials/overview.html', controller: 'OverviewController'});
$httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
}]);
}());
| pongo710/workinghours | src/main/resources/static/js/app.js | JavaScript | apache-2.0 | 1,470 |
/// <reference types="cypress" />
context('Waiting', () => {
beforeEach(() => {
cy.visit('https://example.cypress.io/commands/waiting')
})
// BE CAREFUL of adding unnecessary wait times.
// https://on.cypress.io/best-practices#Unnecessary-Waiting
// https://on.cypress.io/wait
it('cy.wait() - wait for a specific amount of time', () => {
cy.get('.wait-input1').type('Wait 1000ms after typing')
cy.wait(1000)
cy.get('.wait-input2').type('Wait 1000ms after typing')
cy.wait(1000)
cy.get('.wait-input3').type('Wait 1000ms after typing')
cy.wait(1000)
})
it('cy.wait() - wait for a specific route', () => {
cy.server()
// Listen to GET to comments/1
cy.route('GET', 'comments/*').as('getComment')
// we have code that gets a comment when
// the button is clicked in scripts.js
cy.get('.network-btn').click()
// wait for GET comments/1
cy.wait('@getComment').its('status').should('eq', 200)
})
})
| wesleyegberto/courses-projects | frontend/angular/Angular-JumpStart/cypress/examples/waiting.spec.js | JavaScript | apache-2.0 | 977 |
/*
* Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
*/
var global = require('./global'),
config = process.mainModule.exports.config,
commonUtils = require('../utils/common.utils'),
logutils = require('../utils/log.utils');
var serviceRespData = {};
var webuiIP = null;
function checkIfServiceRespDataExists (service, data)
{
try {
var serviceType = service['serviceType'];
var svcData = serviceRespData[serviceType]['data'][serviceType];
if (null == svcData) {
return false;
}
var svcCnt = svcData.length;
var dataCnt = data[serviceType].length;
if (svcCnt != dataCnt) {
return false;
}
for (var i = 0; i < svcCnt; i++) {
if (svcData[i]['ip-address'] !=
data[serviceType][i]['ip-address']) {
return false;
}
if (svcData[i]['port'] != data[serviceType][i]['port']) {
return false;
}
}
} catch(e) {
return false;
}
return true;
}
function storeServiceRespData (service, data)
{
if ((null == service) || (null == data) || (null == data['ttl'])) {
return;
}
var serviceType = service['serviceType'];
if (null == serviceRespData[serviceType]) {
serviceRespData[serviceType] = {};
}
if (false == checkIfServiceRespDataExists(service, data)) {
/* Log Only if change happens */
logutils.logger.debug("DiscService Response Updated by process:" +
process.pid + " " + JSON.stringify(data));
}
serviceRespData[serviceType]['service'] = service;
serviceRespData[serviceType]['data'] = data;
}
function getServiceRespDataList ()
{
return serviceRespData;
}
/* Function: getDiscServiceByServiceType
This function uses load balancing internally
Always it returns the first server IP/Port combination in the service list and
pushes that at the end, such that next time when new request comes then this
server should be requested at last, as we have already sent the request to
this server.
*/
function getDiscServiceByServiceType (serviceType)
{
if (null != serviceRespData[serviceType]) {
try {
var service =
serviceRespData[serviceType]['data'][serviceType].shift();
serviceRespData[serviceType]['data'][serviceType].push(service);
return service;
} catch(e) {
}
}
//logutils.logger.error("Unknown Service Type Request Rxed in " +
// "getDiscServiceByServiceType(): " + serviceType);
return null;
}
function getDiscServiceByApiServerType (apiServerType)
{
var service = null;
var serviceType = null;
var respObj = [];
switch (apiServerType) {
case global.label.OPS_API_SERVER:
case global.label.OPSERVER:
serviceType = global.DISC_SERVICE_TYPE_OP_SERVER;
break;
case global.label.VNCONFIG_API_SERVER:
case global.label.API_SERVER:
serviceType = global.DISC_SERVICE_TYPE_API_SERVER;
break;
case global.label.DNS_SERVER:
serviceType = global.DISC_SERVICE_TYPE_DNS_SERVER;
break;
default:
// logutils.logger.debug("Unknown Discovery Server Service Type:" +
// apiServerType);
return null;
}
return getDiscServiceByServiceType(serviceType);
}
function processDiscoveryServiceResponseMsg (msg)
{
if (null == msg) {
return;
}
msg = JSON.parse(msg.toString());
if (msg && msg['serviceResponse']) {
storeServiceRespData(msg['serviceResponse']['service'],
msg['serviceResponse']['data']);
}
}
function getServerTypeByServerName (serverName)
{
switch (serverName) {
case global.label.OPS_API_SERVER:
return global.DISC_SERVICE_TYPE_OP_SERVER;
case global.label.OPS_API_SERVER:
case global.label.VNCONFIG_API_SERVER:
return global.DISC_SERVICE_TYPE_API_SERVER;
case global.label.DNS_SERVER:
return global.DISC_SERVICE_TYPE_DNS_SERVER;
default:
return null;
}
}
function sendWebServerReadyMessage ()
{
var data = {};
data['jobType'] = global.STR_MAIN_WEB_SERVER_READY;
data = JSON.stringify(data);
var msg = {
cmd: global.STR_SEND_TO_JOB_SERVER,
reqData: data
};
process.send(msg);
}
function sendDiscSubscribeMsgToJobServer (serverType)
{
var data = {};
data['jobType'] = global.STR_DISC_SUBSCRIBE_MSG;
data['serverType'] = serverType;
data = JSON.stringify(data);
var msg = {
cmd: global.STR_SEND_TO_JOB_SERVER,
reqData: data
};
process.send(msg);
}
function sendDiscSubMessageOnDemand (apiName)
{
var myId = process.mainModule.exports['myIdentity'];
var servType = getServerTypeByServerName(apiName);
if (null == servType) {
logutils.logger.error("Unknown Discovery serviceType in " +
"sendDiscSubMessageOnDemand() : " + servType);
return;
}
if (global.service.MAINSEREVR == myId) {
sendDiscSubscribeMsgToJobServer(servType);
} else {
try {
discServ = require('../jobs/core/discoveryservice.api');
discServ.subscribeDiscoveryServiceOnDemand(servType);
} catch(e) {
logutils.logger.error('Module discoveryservice.api can not be ' +
'found');
}
}
}
function resetServicesByParams (params, apiName)
{
var serviceType = getServerTypeByServerName(apiName);
if (null == serviceType) {
return null;
}
try {
var servData = serviceRespData[serviceType]['data'][serviceType];
var servCnt = servData.length;
if (servCnt <= 1) {
/* Only one/no server, so no need to do any params update, as no other
* server available
*/
return null;
}
for (var i = 0; i < servCnt; i++) {
if ((servData[i]['ip-address'] == params['url']) &&
(servData[i]['port'] == params['port'])) {
serviceRespData[serviceType]['data'][serviceType].splice(i, 1);
break;
}
}
params['url'] =
serviceRespData[serviceType]['data'][serviceType][0]['ip-address'];
params['port'] =
serviceRespData[serviceType]['data'][serviceType][0]['port'];
} catch(e) {
logutils.logger.error("In resetServicesByParams(): exception occurred" +
" " + e);
return null;
}
return params;
}
function getDiscServiceRespDataList (req, res, appData)
{
commonUtils.handleJSONResponse(null, res, getServiceRespDataList());
}
function setWebUINodeIP (ip)
{
if (null != ip) {
webuiIP = ip;
}
}
function getWebUINodeIP (ip)
{
return webuiIP;
}
exports.resetServicesByParams = resetServicesByParams;
exports.storeServiceRespData = storeServiceRespData;
exports.getServiceRespDataList = getServiceRespDataList;
exports.getDiscServiceByApiServerType = getDiscServiceByApiServerType;
exports.getDiscServiceByServiceType = getDiscServiceByServiceType;
exports.processDiscoveryServiceResponseMsg = processDiscoveryServiceResponseMsg;
exports.sendWebServerReadyMessage = sendWebServerReadyMessage;
exports.sendDiscSubMessageOnDemand = sendDiscSubMessageOnDemand;
exports.getDiscServiceRespDataList = getDiscServiceRespDataList;
exports.setWebUINodeIP = setWebUINodeIP;
exports.getWebUINodeIP = getWebUINodeIP;
| vishnuvv/contrail-web-core | src/serverroot/common/discoveryclient.api.js | JavaScript | apache-2.0 | 7,665 |
webserver.prototype.__proto__ = require('events').EventEmitter.prototype;
webserver.prototype.server = null;
webserver.prototype.config = null;
webserver.prototype.endpoints = [];
const bodyParser = require('body-parser');
const express = require('express');
const multer = require('multer');
const formData = multer({ storage: multer.memoryStorage() });
const https = require('https');
const http = require('http');
const fs = require('fs');
/**
* Initalize a webserver with options such as SSL
* @param port
* @param options
*/
function webserver(logger, port, options) {
var self = this;
self.logger = logger;
self.port = port;
self.options = options;
self.app = express();
self.app.use(bodyParser.urlencoded({extended: true}));
self.app.set('json spaces', 2);
}
webserver.prototype.start = function (callback) {
var self = this;
if (self.HTTPserver != null && self.HTTPSserver != null)
return callback({Error: "Server is already active... Try restarting instead."});
if (self.HTTPSserver == null) {
try {
self.ssl = {};
if (self.options && self.options.hasOwnProperty("ssl")) {
// Create a service (the app object is just a callback).
// This line is from the Node.js HTTPS documentation.
if (self.options.ssl.hasOwnProperty("key") && self.options.ssl.hasOwnProperty("cert")) {
var options = {
key: self.options.ssl.key,
cert: self.options.ssl.cert
};
self.HTTPSserver = https.createServer(options, self.app).listen(443);// Create an HTTPS service identical to the HTTP service.
self.logger.log("debug", "Started SSL server on port 443.");
}
}
if (self.HTTPserver == null) {
try {
self.HTTPserver = http.createServer(self.app).listen(self.port);// Create an HTTP service.
self.logger.log("debug", "Started HTTP server on port " + self.port);
if (callback)
return callback();
} catch (e){
console.log(e);
if (callback)
return callback({Error: "Failed to start HTTP server due to " + e});
}
}
} catch (e){
console.log(e);
if (callback)
return callback({Error: "Failed to start HTTP server due to " + e});
}
} else if (self.HTTPserver == null) {
try {
self.ssl = {};
if (self.HTTPserver == null) {
try {
self.HTTPserver = http.createServer(self.app).listen(self.port);// Create an HTTP service.
self.logger.log("debug", "Started HTTP server on port " + self.port);
if (self.options && self.options.hasOwnProperty("ssl")) {
if (self.options.ssl.hasOwnProperty("key") && self.options.ssl.hasOwnProperty("cert")) {
var options = {
key: self.options.ssl.key,
cert: self.options.ssl.cert
};
self.HTTPSserver = https.createServer(options, self.app).listen(443);// Create an HTTPS service identical to the HTTP service.
self.logger.log("debug", "Started SSL server on port 443.");
}
}
} catch (e){
console.log(e);
if (callback)
return callback({Error: "Failed to start HTTP server due to " + e});
}
}
} catch (e){
console.log(e);
if (callback)
return callback({Error: "Failed to start HTTP server due to " + e});
}
}
};
webserver.prototype.addEndpoint = function (method, url, callback) {
var self = this;
self.endpoints.push({method: method, url: url, callback: callback});
switch (method.toLowerCase()) {
case 'post':
// console.log("Reg post...");
//
// var func = new Function(
// "return function " + method + "_" + url + "(req, res, next){ " +
// "console.log('Test' + self.app._router.stack);}"
// )();
self.app.post(url, formData.array(), callback);
break;
case 'get':
self.app.get(url, callback);
break;
default:
self.app.post(url, formData.array(), callback);
break;
}
};
webserver.prototype.removeEndpoint = function (method, url) {
var self = this;
console.log("Added route " + self.app._router.stack);
var routes = self.app._router.stack;
routes.forEach(removeMiddlewares);
function removeMiddlewares(route, i, routes) {
switch (route.handle.name) {
case method + "_" + url:
routes.splice(i, 1);
}
if (route.route)
route.route.stack.forEach(removeMiddlewares);
}
};
webserver.prototype.restart = function () {
var self = this;
if (self.HTTPSserver != null && self.HTTPserver != null) {
self.HTTPSserver.close();
self.HTTPserver.close();
for (var endpoint in self.endpoints)
if (self.endpoints.hasOwnProperty(endpoint))
self.addEndpoint(self.endpoints[endpoint].method, self.endpoints[endpoint].url, self.endpoints[endpoint].callback);
self.start();
}
};
module.exports = webserver;
| Undeadkillz/node-steam-bot-manager | lib/webserver.js | JavaScript | apache-2.0 | 5,757 |
scaffolder:
https://github.com/coryhouse/react-slingshot
^we wont use this though
well use: https://github.com/coryhouse/pluralsight-redux-starter
Our dev environment:
1. Automated Testign
2. Linting
3. Minification
4. Bundling
5. JSXCompilation
6. ES6 Transpilation
Babel-Polyfill:
few things babel cant do and babel-polyfill can do for es6->5
array.from, set, map, promise, generator functions etc.
Downsides: Its too large 50K but we can pull out whatever particula polyfill we want
babel-preset-react-hmre
its a babel preset that wraps up a number of other libraries and settings in a single prest
It works by wrapping your components in a custom proxy using Babel.
Proxies are classes that act just like your classes but they provide hooks for injectin new implementiaton
So when you hit save, your changes are immd8ly applied without requiring a reload
WARNINGS: experimental and doesnt reload functional components and container functions like mapStateTOprops
(I think this is embedded into react now)
npm scripts replaced gulp! cool right!
https://medium.freecodecamp.com/why-i-left-gulp-and-grunt-for-npm-scripts-3d6853dd22b8#.scjzloi78
| iitjee/SteppinsWebDev | React/Project1- React n Redux/01 Environment Setup.js | JavaScript | apache-2.0 | 1,160 |
const path = require('path');
const fs = require('fs');
const escapeRegExp = require("lodash/escapeRegExp");
require("@babel/register")({
extensions: [".es6", ".es", ".jsx", ".js", ".mjs", ".ts"],
only: [
new RegExp("^" + escapeRegExp(path.resolve(__dirname, "../../static/js")) + path.sep),
new RegExp("^" + escapeRegExp(path.resolve(__dirname, "../../static/shared/js")) + path.sep),
],
plugins: ["rewire-ts"],
});
global.assert = require('assert').strict;
global._ = require('underscore/underscore.js');
const _ = global._;
// Create a helper function to avoid sneaky delays in tests.
function immediate(f) {
return () => {
return f();
};
}
// Find the files we need to run.
const finder = require('./finder.js');
const files = finder.find_files_to_run(); // may write to console
if (files.length === 0) {
throw "No tests found";
}
// Set up our namespace helpers.
const namespace = require('./namespace.js');
global.set_global = namespace.set_global;
global.patch_builtin = namespace.set_global;
global.zrequire = namespace.zrequire;
global.stub_out_jquery = namespace.stub_out_jquery;
global.with_overrides = namespace.with_overrides;
global.window = new Proxy(global, {
set: (obj, prop, value) => namespace.set_global(prop, value),
});
global.to_$ = () => window;
// Set up stub helpers.
const stub = require('./stub.js');
global.make_stub = stub.make_stub;
global.with_stub = stub.with_stub;
// Set up fake jQuery
global.make_zjquery = require('./zjquery.js').make_zjquery;
// Set up fake blueslip
const make_blueslip = require('./zblueslip.js').make_zblueslip;
// Set up fake translation
const stub_i18n = require('./i18n.js');
// Set up Handlebars
const handlebars = require('./handlebars.js');
global.make_handlebars = handlebars.make_handlebars;
global.stub_templates = handlebars.stub_templates;
const noop = function () {};
// Set up fake module.hot
const Module = require('module');
Module.prototype.hot = {
accept: noop,
};
// Set up fixtures.
global.read_fixture_data = (fn) => {
const full_fn = path.join(__dirname, '../../zerver/tests/fixtures/', fn);
const data = JSON.parse(fs.readFileSync(full_fn, 'utf8', 'r'));
return data;
};
function short_tb(tb) {
const lines = tb.split('\n');
const i = lines.findIndex(line => line.includes('run_test') || line.includes('run_one_module'));
if (i === -1) {
return tb;
}
return lines.splice(0, i + 1).join('\n') + '\n(...)\n';
}
// Set up markdown comparison helper
global.markdown_assert = require('./markdown_assert.js');
function run_one_module(file) {
console.info('running tests for ' + file.name);
require(file.full_name);
}
global.run_test = (label, f) => {
if (files.length === 1) {
console.info(' test: ' + label);
}
f();
// defensively reset blueslip after each test.
blueslip.reset();
};
try {
files.forEach(function (file) {
set_global('location', {
hash: '#',
});
global.patch_builtin('setTimeout', noop);
global.patch_builtin('setInterval', noop);
_.throttle = immediate;
_.debounce = immediate;
set_global('blueslip', make_blueslip());
set_global('i18n', stub_i18n);
namespace.clear_zulip_refs();
run_one_module(file);
if (blueslip.reset) {
blueslip.reset();
}
namespace.restore();
});
} catch (e) {
if (e.stack) {
console.info(short_tb(e.stack));
} else {
console.info(e);
}
process.exit(1);
}
| synicalsyntax/zulip | frontend_tests/zjsunit/index.js | JavaScript | apache-2.0 | 3,606 |
/**
* $Id$
*
* @author Moxiecode
* @copyright Copyright © 2004-2006, Moxiecode Systems AB, All rights reserved.
*/
/* Import plugin specific language pack */
tinyMCE.importPluginLanguagePack('nonbreaking');
var TinyMCE_NonBreakingPlugin = {
getInfo : function() {
return {
longname : 'Nonbreaking space',
author : 'Moxiecode Systems AB',
authorurl : 'http://tinymce.moxiecode.com',
infourl : 'http://tinymce.moxiecode.com/tinymce/docs/plugin_nonbreaking.html',
version : tinyMCE.majorVersion + "." + tinyMCE.minorVersion
};
},
getControlHTML : function(cn) {
switch (cn) {
case "nonbreaking":
return tinyMCE.getButtonHTML(cn, 'lang_nonbreaking_desc', '{$pluginurl}/images/nonbreaking.gif', 'mceNonBreaking', false);
}
return "";
},
execCommand : function(editor_id, element, command, user_interface, value) {
var inst = tinyMCE.getInstanceById(editor_id), h;
switch (command) {
case "mceNonBreaking":
h = (inst.visualChars && inst.visualChars.state) ? '<span class="mceItemHiddenVisualChar">·</span>' : ' ';
tinyMCE.execInstanceCommand(editor_id, 'mceInsertContent', false, h);
return true;
}
return false;
},
handleEvent : function(e) {
var inst, h;
if (!tinyMCE.isOpera && e.type == 'keydown' && e.keyCode == 9 && tinyMCE.getParam('nonbreaking_force_tab', false)) {
inst = tinyMCE.selectedInstance;
h = (inst.visualChars && inst.visualChars.state) ? '<span class="mceItemHiddenVisualChar">···</span>' : ' ';
tinyMCE.execInstanceCommand(inst.editorId, 'mceInsertContent', false, h);
tinyMCE.cancelEvent(e);
return false;
}
return true;
}
};
tinyMCE.addPlugin("nonbreaking", TinyMCE_NonBreakingPlugin);
| WilliamGoossen/epsos-common-components.gnomonportal | webapps/ROOT/html/js/editor/tiny_mce/plugins/nonbreaking/editor_plugin_src.js | JavaScript | apache-2.0 | 1,758 |
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
(function (win) {
var cordova = require('cordova'),
Acceleration = require('cordova-plugin-device-motion.Acceleration'),
accelerometerCallback = null;
module.exports = {
start: function (successCallback, errorCallback) {
if (accelerometerCallback) {
win.removeEventListener("devicemotion", accelerometerCallback, true);
}
accelerometerCallback = function (motion) {
successCallback({
x: motion.accelerationIncludingGravity.x,
y: motion.accelerationIncludingGravity.y,
z: motion.accelerationIncludingGravity.z,
timestamp: new Date().getTime()
});
};
win.addEventListener("devicemotion", accelerometerCallback, true);
},
stop: function (successCallback, errorCallback) {
win.removeEventListener("devicemotion", accelerometerCallback, true);
accelerometerCallback = null;
}
};
require("cordova/tizen/commandProxy").add("Accelerometer", module.exports);
}(window));
| michaelrbk/showCaseCordova | plugins/cordova-plugin-device-motion/src/tizen/AccelerometerProxy.js | JavaScript | apache-2.0 | 1,957 |
import React from 'react';
let lastClicked = 0;
export default class Candidate extends React.Component {
constructor(props) {
super(props);
this.state = { wiggle: false };
this.castVote = this.castVote.bind(this);
this.wiggleDone = this.wiggleDone.bind(this);
}
componentDidMount() {
const anim = this.refs[this.props.candidate];
anim.addEventListener('animationend', this.wiggleDone);
}
componentWillUnmount() {
const anim = this.refs[this.props.candidate];
anim.removeEventListener('animationend', this.wiggleDone);
}
wiggleDone() {
this.setState({ wiggle: false });
}
castVote() {
if (new Date() - lastClicked >= 3000) {
lastClicked = Date.now();
this.props.castVote(this.props.index);
this.setState({ wiggle: true });
// console.log('vote cast');
} else {
// console.log('waiting for delay, vote not cast');
}
}
render() {
const wiggle = this.state.wiggle;
return (
<img
key={this.props.candidate}
ref={this.props.candidate}
className={wiggle ? 'candidate wiggle' : 'candidate'}
onClick={this.castVote}
src={`Image${this.props.index}.png`}
/>
);
}
}
Candidate.propTypes = {
index: React.PropTypes.number,
candidate: React.PropTypes.string,
votes: React.PropTypes.oneOfType([
React.PropTypes.number,
React.PropTypes.string,
]),
castVote: React.PropTypes.func,
};
| AdlerPlanetarium/pluto-poll | src/components/VoteCandidate.js | JavaScript | apache-2.0 | 1,473 |
/*
* Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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.
*
*/
var LifecycleAPI = {};
var LifecycleUtils = {};
(function() {
var configMap = {};
var eventMap = {};
var dataMap = {};
var lifecycleImpl = {};
var currentLifecycle;
var constants = LifecycleAPI.constants = {}; //Sgort hand reference
constants.API_ENDPOINT = 'lifecycle-api';
constants.API_LC_DEFINITION = 'lifecycle-definition-api';
constants.API_BASE = 'apiLCBase';
constants.API_CHANGE_STATE = 'apiChangeState';
constants.API_FETCH_STATE = 'apiFetchState';
constants.API_FETCH_HISTORY = 'apiFetchHistory';
constants.API_UPDATE_CHECKLIST = 'apiUpdateChecklist';
constants.UI_LIFECYCLE_SELECT_ID = '#lifecycle-selector';
constants.UI_LIFECYCLE_SELECT_BOX = 'ul.lifecycle-dropdown-menu li a';
constants.CONTAINER_SVG = 'svgContainer';
constants.CONTAINER_GRAPH = 'graphContainer';
constants.CONTAINER_LC_ACTION_AREA = 'lifecycleActionArea';
constants.CONTAINER_RENDERING_AREA = 'lifecycleRenderingArea';
constants.CONTAINER_CHECKLIST_AREA = 'lifecycleChecklistArea';
constants.CONTAINER_CHECKLIST_OVERLAY = 'lifecycleChecklistBlock';
constants.CONTAINER_LC_ACTION_OVERLAY = 'lifecycleActionOverlay';
constants.CONTAINER_HISTORY_AREA = 'lifecycleHistoryArea';
constants.CONTAINER_INFORMATION_AREA = 'lifecycleInformationArea';
constants.CONTAINER_TRANSITION_UI_AREA = 'lifecycleTransitionUIArea';
constants.CONTAINER_LC_NOTIFICATIONS_AREA = 'lifecycleNotificationsArea';
constants.CONTAINER_LC_GLOBAL_NOTIFICATIONS_AREA = 'lifecycleGlobalNotificationsArea';
constants.CONTAINER_LC_TRANSITION_INPUTS_FIELDS_AREA = 'lifecycleTransitionInputsFieldsArea';
constants.CONTAINER_LC_TRANSITION_INPUTS_ACTIONS_AREA = 'lifecycleTransitionInputsActionsArea';
constants.CONTAINER_LC_TRANSITION_INPUTS_FIELDS_FORM = 'lifecycleTRansitionInputsFieldsForm';
constants.TEMPLATE_NOTIFICATION_ERROR = 'lifecycleTemplateNotficationError';
constants.TEMPLATE_NOTIFICATION_INFO = 'lifecycleTemplateNotificationInfo';
constants.TEMPLATE_NOTIFICATION_WARN = 'lifecycleTemplateNotificationWarn';
constants.TEMPLATE_NOTIFICATION_SUCCESS = 'lifecycleTemplateNotificationSuccess';
constants.INPUT_TEXTAREA_LC_COMMENT = 'lifecycleCommentTextArea';
constants.EVENT_LC_LOAD = 'event.lc.loaded';
constants.EVENT_LC_UNLOAD = 'event.lc.unload';
constants.EVENT_FETCH_STATE_START = 'event.fetch.state.start';
constants.EVENT_FETCH_STATE_SUCCESS = 'event.fetch.state.success';
constants.EVENT_FETCH_STATE_FAILED = 'event.fetch.state.failed';
constants.EVENT_STATE_CHANGE = 'event.state.change';
constants.EVENT_ACTION_START = 'event.action.invoked';
constants.EVENT_ACTION_FAILED = 'event.action.failed';
constants.EVENT_ACTION_SUCCESS = 'event.action.success';
constants.EVENT_UPDATE_CHECKLIST_START = 'event.update.checklist.start';
constants.EVENT_UPDATE_CHECKLIST_SUCCESS = 'event.update.checklist.success';
constants.EVENT_UPDATE_CHECKLIST_FAILED = 'event.update.checklist.failed';
constants.EVENT_FETCH_HISTORY_START = 'event.fetch.history.start';
constants.EVENT_FETCH_HISTORY_SUCCESS = 'event.fetch.history.success';
constants.EVENT_FETCH_HISTORY_FAILED = 'event.fetch.history.failed';
constants.HISTORY_ACTION_TRANSITION = 'transition';
constants.HISTORY_ACTION_CHECKITEM = 'check.item';
constants.NOTIFICATION_INFO = 'info';
constants.NOTIFICATION_ERROR = 'error';
constants.NOTIFICATION_WARN = 'warn';
constants.NOTIFICATION_SUCCESS = 'success';
constants.MSG_WARN_CANNOT_CHANGE_STATE = 'msgCannotChangeState';
constants.MSG_SUCCESS_STATE_CHANGE = 'msgStateChangedSuccess';
constants.MSG_ERROR_STATE_CHANGE = 'msgStateChangeError';
constants.MSG_SUCCESS_CHECKLIST_UPDATE = 'msgChecklistUpdateSuccess';
constants.MSG_ERROR_CHECKLIST_UPDATE = 'msgChecklistUpdateError';
constants.CONTAINER_DELETE_ACTION_AREA = 'deleteActionArea';
var id = function(name) {
return '#' + name;
};
var config = function(key) {
return LifecycleAPI.configs(key);
};
var partial = function(name) {
return '/themes/' + caramel.themer + '/partials/' + name + '.hbs';
};
var renderPartial = function(partialKey, containerKey, data, fn) {
fn = fn || function() {};
var partialName = config(partialKey);
var containerName = config(containerKey);
if (!partialName) {
throw 'A template name has not been specified for template key ' + partialKey;
}
if (!containerName) {
throw 'A container name has not been specified for container key ' + containerKey;
}
var obj = {};
obj[partialName] = partial(partialName);
caramel.partials(obj, function() {
var template = Handlebars.partials[partialName](data);
$(id(containerName)).html(template);
fn(containerName);
});
};
var processCheckItems = function(stateDetails, datamodel) {
if (!stateDetails.hasOwnProperty('datamodel')) {
stateDetails.datamodel = {};
}
stateDetails.datamodel.checkItems = datamodel.item;
for (var index = 0; index < datamodel.item.length; index++) {
datamodel.item[index].checked = false;
datamodel.item[index].index = index;
}
};
var processTransitionUI = function(stateDetails, datamodel) {
if (!stateDetails.hasOwnProperty('datamodel')) {
stateDetails.datamodel = {};
}
var ui = datamodel.ui || [];
var transitions;
stateDetails.datamodel.transitionUIs = [];
if (ui.length >= 0) {
stateDetails.datamodel.transitionUIs = ui;
}
transitions = stateDetails.datamodel.transitionUIs;
for (var index = 0; index < transitions.length; index++) {
transition = transitions[index];
transition.action = transition.forEvent;
delete transition.forEvent;
}
};
var processTransitionInputs = function(stateDetails, datamodel) {
if (!stateDetails.hasOwnProperty('datamodel')) {
stateDetails.datamodel = {};
}
var transitions;
var transition;
var entry;
var executions;
var execution;
var form;
var forms;
var map;
forms = stateDetails.datamodel.transitionInputs = {};
executions = datamodel.execution || [];
for (var index = 0; index < executions.length; index++) {
execution = executions[index];
if (execution.transitionInputs) {
form = execution.transitionInputs[0];
map = forms[execution.forEvent.toLowerCase()] = {};
map.action = execution.forEvent;
map.inputs = form.input;
}
}
};
var processDataModel = function(stateDetails, datamodel) {
switch (datamodel.name) {
case 'checkItems':
processCheckItems(stateDetails, datamodel);
break;
case 'transitionUI':
processTransitionUI(stateDetails, datamodel);
break;
case 'transitionExecution':
processTransitionInputs(stateDetails, datamodel);
break;
default:
break;
}
};
var triggerEvent = function(eventName, eventCb) {
if (eventMap.hasOwnProperty(eventName)) {
eventCb = eventCb || {};
eventCallbacks = eventMap[eventName];
console.log('emiting event::' + eventName + ' [active lifecycle: ' + LifecycleAPI.currentLifecycle() + ' ]');
for (var index = 0; index < eventCallbacks.length; index++) {
eventCallbacks[index](eventCb);
}
} else {
console.log('no event listeners for event :: ' + eventName);
}
};
/**
* Converts the JSON definition returned by the lifecycles API
* into a well structured JSOn object
* @param {[type]} data [description]
* @return {[type]} [description]
*/
LifecycleUtils.buildStateMapFromDefinition = function(data) {
var definition = data.data.definition.configuration.lifecycle.scxml.state;
var initialState = data.data.definition.configuration.lifecycle.scxml.initialstate;
var stateMap = {};
var state;
var stateDetails;
var nodeCount = 0;
var datamodels;
var datamodel;
var transition;
stateMap.states = {};
stateMap.initialState = initialState ? initialState.toLowerCase() : initialState;
for (var stateKey in definition) {
stateDetails = definition[stateKey];
state = stateMap.states[stateKey] = {};
state.id = stateKey;
state.label = stateDetails.id;
state.transitions = stateDetails.transition || [];
stateDetails.datamodel = stateDetails.datamodel ? stateDetails.datamodel : [];
datamodels = stateDetails.datamodel.data || [];
//Convert the target states to lower case
for (var index = 0; index < state.transitions.length; index++) {
transition = state.transitions[index];
transition.target = transition.target.toLowerCase();
}
//Process the data model
for (var dIndex = 0; dIndex < datamodels.length; dIndex++) {
datamodel = datamodels[dIndex];
processDataModel(state, datamodel);
}
nodeCount++;
}
return stateMap;
};
/**
* Returns meta information on the current asset
* @return {[type]} [description]
*/
LifecycleUtils.currentAsset = function() {
return store.publisher.lifecycle;
};
LifecycleUtils.config = function(key) {
return LifecycleAPI.configs(key);
};
LifecycleAPI.configs = function() {
if ((arguments.length == 1) && (typeof arguments[0] == 'object')) {
configMap = arguments[0]
} else if ((arguments.length = 1) && (typeof arguments[0] == 'string')) {
return configMap[arguments[0]];
} else {
return configMap;
}
};
LifecycleAPI.event = function() {
var eventName = arguments[0];
var eventCb = arguments[1];
var eventCallbacks;
if (arguments.length === 1) {
triggerEvent(eventName, eventCb);
} else if ((arguments.length === 2) && (typeof eventCb === 'object')) {
triggerEvent(eventName, eventCb);
} else if ((arguments.length === 2) && (typeof eventCb === 'function')) {
if (!eventMap.hasOwnProperty(eventName)) {
eventMap[eventName] = [];
}
eventMap[eventName].push(eventCb);
}
};
LifecycleAPI.data = function() {
var dataKey = arguments[0];
var data = arguments[1];
if (arguments.length == 1) {
return dataMap[dataKey];
} else if (arguments.length == 2) {
dataMap[dataKey] = data;
}
};
LifecycleAPI.lifecycle = function() {
var name = arguments[0];
var impl = arguments[1];
if (arguments.length == 0) {
var currentLC = LifecycleAPI.currentLifecycle();
return LifecycleAPI.lifecycle(currentLC);
} else if ((arguments.length === 1) && (typeof name === 'string')) {
var impl = LifecycleAPI.data(name);
if (!impl) {
impl = new LifecycleImpl({
name: name
});
LifecycleAPI.data(name, impl);
}
return impl;
} else if ((arguments.length === 2) && (typeof impl === 'object')) {
//Allow method overiding
} else {
throw 'Invalid lifecycle name provided';
}
};
LifecycleAPI.currentLifecycle = function() {
if (arguments.length === 1) {
currentLifecycle = arguments[0];
} else {
return currentLifecycle;
}
};
LifecycleAPI.notify = function(msg, options) {
options = options || {};
var global = options.global ? options.global : false;
var container = constants.CONTAINER_LC_NOTIFICATIONS_AREA;
var notificationType = options.type ? options.type : constants.NOTIFICATION_INFO;
var partial = constants.TEMPLATE_NOTIFICATION_INFO;
if (global) {
container = constants.CONTAINER_LC_GLOBAL_NOTIFICATIONS_AREA;
}
switch (notificationType) {
case constants.NOTIFICATION_WARN:
partial = constants.TEMPLATE_NOTIFICATION_WARN;
break;
case constants.NOTIFICATION_ERROR:
partial = constants.TEMPLATE_NOTIFICATION_ERROR;
break;
case constants.NOTIFICATION_SUCCESS:
partial = constants.TEMPLATE_NOTIFICATION_SUCCESS;
default:
break;
}
//Clear existing content
$(id(container)).html('');
renderPartial(partial, container, {
msg: msg
}, function(container) {
$(id(container)).fadeIn(5000);
});
};
function LifecycleImpl(options) {
options = options || {};
this.lifecycleName = options.name ? options.name : null;
this.currentState = null;
this.previousState = null;
this.rawAPIDefinition = null;
this.stateMap = null;
this.dagreD3GraphObject = null;
this.renderingSite;
this.history = [];
}
LifecycleImpl.prototype.load = function() {
var promise;
if (!this.rawAPIDefinition) {
var that = this;
//Fetch the lifecycle definition
promise = $.ajax({
url: this.queryDefinition(),
success: function(data) {
that.rawAPIDefinition = data;
that.processDefinition();
that.currentState = that.stateMap.initialState;
LifecycleAPI.currentLifecycle(that.lifecycleName);
//Obtain the asset current state from the code block,if not set it to the initial state
LifecycleAPI.event(constants.EVENT_LC_LOAD, {
lifecycle: that.lifecycleName
});
that.fetchState();
},
error: function() {
alert('Failed to load definition');
}
});
} else {
LifecycleAPI.currentLifecycle(this.lifecycleName);
//If the definition is present then the lifecycle has already been loaded
LifecycleAPI.event(constants.EVENT_LC_LOAD, {
lifecycle: this.lifecycleName
});
this.fetchState();
}
};
LifecycleAPI.unloadActiveLifecycle = function() {
LifecycleAPI.event(constants.EVENT_LC_UNLOAD);
};
LifecycleImpl.prototype.resolveRenderingSite = function() {
this.renderingSite = {};
this.renderingSite.svgContainer = LifecycleAPI.configs(constants.CONTAINER_SVG);
this.renderingSite.graphContainer = LifecycleAPI.configs(constants.CONTAINER_GRAPH);
};
LifecycleImpl.prototype.processDefinition = function() {
this.stateMap = LifecycleUtils.buildStateMapFromDefinition(this.rawAPIDefinition);
};
LifecycleImpl.prototype.render = function() {
this.resolveRenderingSite();
this.renderInit();
this.fillGraphData();
this.style();
this.renderFinish();
};
LifecycleImpl.prototype.renderInit = function() {
this.dagreD3GraphObject = new dagreD3.graphlib.Graph().setGraph({});
if (!this.renderingSite) {
throw 'Unable to render lifecycle as renderingSite details has not been provided';
}
};
LifecycleImpl.prototype.renderFinish = function() {
var g = this.dagreD3GraphObject;
var svgContainer = this.renderingSite.svgContainer;
var graphContainer = this.renderingSite.graphContainer;
d3.select(svgContainer).append(graphContainer);
var svg = d3.select(svgContainer),
inner = svg.select(graphContainer);
// Set up zoom support
var zoom = d3.behavior.zoom().on("zoom", function() {
inner.attr("transform", "translate(" + d3.event.translate + ")" + "scale(" + d3.event.scale + ")");
});
svg.call(zoom);
// Create the renderer
var render = new dagreD3.render();
// Run the renderer. This is what draws the final graph.
render(inner, g);
// Center the graph
var initialScale = 1.2;
zoom.translate([($(svgContainer).width() - g.graph().width * initialScale) / 2, 20]).scale(initialScale).event(svg);
svg.attr('height', g.graph().height * initialScale + 40);
};
LifecycleImpl.prototype.fillGraphData = function() {
var state;
var transition;
var source;
var stateMap = this.stateMap;
var g = this.dagreD3GraphObject;
for (var key in stateMap.states) {
state = stateMap.states[key];
g.setNode(key, {
label: state.id.toUpperCase(),
shape: 'rect',
labelStyle: 'font-size: 12px;font-weight: lighter;fill: rgb(51, 51, 51);'
});
}
//Add the edges
for (key in stateMap.states) {
state = stateMap.states[key];
source = key;
for (var index = 0; index < state.transitions.length; index++) {
transition = state.transitions[index];
g.setEdge(source, transition.target, {
label: transition.event.toUpperCase(),
lineInterpolate: 'basis',
labelStyle: 'font-size: 12px;font-weight: lighter;fill: rgb(255, 255, 255);'
});
}
}
};
LifecycleImpl.prototype.style = function() {
var g = this.dagreD3GraphObject;
// Set some general styles
g.nodes().forEach(function(v) {
var node = g.node(v);
node.rx = node.ry = 0;
});
};
LifecycleImpl.prototype.queryDefinition = function() {
var baseURL = LifecycleAPI.configs(constants.API_LC_DEFINITION);
return caramel.context + baseURL + '/' + this.lifecycleName;
};
LifecycleImpl.prototype.urlChangeState = function(data) {
var apiBase = LifecycleUtils.config(constants.API_BASE);
var apiChangeState = LifecycleUtils.config(constants.API_CHANGE_STATE);
var asset = LifecycleUtils.currentAsset();
if ((!asset) || (!asset.id)) {
throw 'Unable to locate details about asset';
}
return caramel.url(apiBase + '/' + asset.id + apiChangeState + '?type=' + asset.type + '&lifecycle=' + this.lifecycleName + '&nextAction=' + data.nextAction);
};
LifecycleImpl.prototype.urlFetchState = function() {
var apiBase = LifecycleUtils.config(constants.API_BASE);
var apiChangeState = LifecycleUtils.config(constants.API_FETCH_STATE);
var asset = LifecycleUtils.currentAsset();
if ((!asset) || (!asset.id)) {
throw 'Unable to locate details about asset';
}
return caramel.url(apiBase + '/' + asset.id + apiChangeState + '?type=' + asset.type + '&lifecycle=' + this.lifecycleName);
};
LifecycleImpl.prototype.urlUpdateChecklist = function() {
var apiBase = LifecycleUtils.config(constants.API_BASE);
var apiUpdateChecklist = LifecycleUtils.config(constants.API_UPDATE_CHECKLIST);
var asset = LifecycleUtils.currentAsset();
if ((!asset) || (!asset.id)) {
throw 'Unable to locate details about asset';
}
return caramel.url(apiBase + '/' + asset.id + apiUpdateChecklist + '?type=' + asset.type + '&lifecycle=' + this.lifecycleName);
};
LifecycleImpl.prototype.urlFetchHistory = function() {
var apiBase = LifecycleUtils.config(constants.API_BASE);
var apiFetchHistory = LifecycleUtils.config(constants.API_FETCH_HISTORY);
var asset = LifecycleUtils.currentAsset();
if ((!asset) || (!asset.id)) {
throw 'Unable to locate details about asset';
}
return caramel.url(apiBase + '/' + asset.id + apiFetchHistory + '?type=' + asset.type + '&lifecycle=' + this.lifecycleName);
};
LifecycleImpl.prototype.checklist = function() {
var state = this.state(this.currentState);
var datamodel;
if (arguments.length === 1) {
console.log('changing checklist state');
datamodel = (state.datamodel) ? state.datamodel : (state.datamodel = {});
datamodel.checkItems = arguments[0];
} else {
datamodel = state.datamodel || {};
return datamodel.checkItems ? datamodel.checkItems : [];
}
};
/**
* This method returns the available actions of a given lifecycle state
* if required state is not provided it is assumed to be current state
* Note : as this method only returns pre-set allowed actions for the current state,
* allowed actions should be set calling setAllowedActions(actions)
*/
LifecycleImpl.prototype.actions = function() {
//Assume that a state has not been provided
var currentState = this.currentState;
if ((arguments.length === 1) && (typeof arguments[0] === 'string')) {
currentState = arguments[0];
}
var state = this.stateMap.states[currentState] || {};
var transitions = state.transitions || [];
var actions = [];
var transition;
for (var index = 0; index < transitions.length; index++) {
transition = transitions[index];
if (currentState == this.currentState) {
if (state.allowedActions && state.allowedActions[transition.event]){
actions.push(transition.event);
}
}
else {
actions.push(transition.event);
}
}
return actions;
};
LifecycleImpl.prototype.setAllowedActions = function(actions) {
var currentState = this.currentState;
var state = this.stateMap.states[currentState] || {};
state.allowedActions = actions;
return state.allowedActions;
};
LifecycleImpl.prototype.nextStateByAction = function(action, state) {
//Get tinformation about the state
var stateDetails = this.state(state);
var transitions = stateDetails.transitions || [];
var transition;
var nextState;
for (var index = 0; index < transitions.length; index++) {
transition = transitions[index];
if (transition.event.toLowerCase() === action.toLowerCase()) {
nextState = transition.target;
return nextState;
}
}
return nextState;
};
LifecycleImpl.prototype.invokeAction = function() {
var action = arguments[0];
var comment = arguments[1];
var optionalArguments = arguments[2];
var nextState;
var data = {};
if (!action) {
throw 'Attempt to invoke an action without providing the action';
return;
}
nextState = this.nextStateByAction(action, this.currentState);
if (!nextState) {
throw 'Unable to locate the next state for the given action::' + action;
}
data.nextState = nextState;
//Check if the action is one of the available actions for the current state
var availableActions = this.actions(this.currentState);
if ((availableActions.indexOf(action, 0) <= -1)) {
throw 'Attempt to invoke an action (' + action + ') which is not available for the current state : ' + this.currentState;
}
if (comment) {
data.comment = comment;
}
if (optionalArguments) {
data.arguments = optionalArguments;
}
if (arguments[0]){
data.nextAction = arguments[0];
}
//Determine the next state
LifecycleAPI.event(constants.EVENT_ACTION_START);
var that = this;
$.ajax({
url: this.urlChangeState(data),
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json',
success: function(data) {
that.previousState = that.currentState;
that.currentState = data.data.newState;
var traversableStates = data.data.traversableStates || [];
//If next states are not returned then lifecycle
//actions are not permitted
if (traversableStates.length === 0) {
that.isLCActionsPermitted = false;
}
LifecycleAPI.event(constants.EVENT_ACTION_SUCCESS);
LifecycleAPI.event(constants.EVENT_STATE_CHANGE);
that.fetchState();
},
error: function (jqXHR, textStatus, errorThrown) {
LifecycleAPI.event(constants.EVENT_ACTION_FAILED, jqXHR.responseJSON);
}
});
};
LifecycleImpl.prototype.updateChecklist = function(checklistItemIndex, checked) {
var data = {};
var entry = {};
entry.index = checklistItemIndex;
entry.checked = checked;
data.checklist = [];
data.checklist.push(entry);
LifecycleAPI.event(constants.EVENT_UPDATE_CHECKLIST_START);
var that = this;
$.ajax({
type: 'POST',
url: this.urlUpdateChecklist(),
data: JSON.stringify(data),
contentType: 'application/json',
success: function() {
//Update the internal check list items
LifecycleAPI.event(constants.EVENT_UPDATE_CHECKLIST_SUCCESS);
that.fetchState();
},
error: function() {
LifecycleAPI.event(constants.EVENT_UPDATE_CHECKLIST_FAILED);
}
});
};
LifecycleImpl.prototype.fetchState = function() {
LifecycleAPI.event(constants.EVENT_FETCH_STATE_START);
var that = this;
$.ajax({
url: this.urlFetchState(),
success: function(data) {
var data = data.data;
that.previousState = that.currentState;
if (!data.id) {
LifecycleAPI.event(constants.EVENT_FETCH_STATE_FAILED);
return;
}
that.currentState = data.id.toLowerCase();
that.isLCActionsPermitted = data.isLCActionsPermitted;
that.isDeletable = data.isDeletable;
for (var index = 0; index < data.checkItems.length; index++) {
data.checkItems[index].index = index;
}
that.checklist(data.checkItems);
that.setAllowedActions(data.approvedActions);
LifecycleAPI.event(constants.EVENT_FETCH_STATE_SUCCESS);
},
error: function() {
LifecycleAPI.event(constants.EVENT_FETCH_STATE_FAILED);
}
})
};
LifecycleImpl.prototype.userPermited = function() {
return this.isLCActionsPermitted;
};
LifecycleImpl.prototype.processHistory = function(data) {
console.log('### Processing history ###');
var entry;
var historyEntry;
this.history = [];
for (var index = 0; index < data.length; index++) {
entry = data[index];
historyEntry = {};
historyEntry.state = entry.state;
historyEntry.timestamp = entry.timestamp;
historyEntry.user = entry.user;
historyEntry.actionType = constants.HISTORY_ACTION_CHECKITEM;
historyEntry.comment = entry.comment;
historyEntry.hasComment = false;
if (historyEntry.comment) {
historyEntry.hasComment = true;
}
historyEntry.dateOfTransition = entry.dateofTransition;
//Check if it is a state change
if (entry.targetState) {
historyEntry.targetState = entry.targetState;
historyEntry.actionType = constants.HISTORY_ACTION_TRANSITION;
}
this.history.push(historyEntry);
}
};
LifecycleImpl.prototype.fetchHistory = function() {
LifecycleAPI.event(constants.EVENT_FETCH_HISTORY_START);
var that = this;
$.ajax({
url: this.urlFetchHistory(),
success: function(data) {
var data = data.data || [];
// that.history = []; //Reset the history
// for (var index = 0; index < data.length; index++) {
// that.history.push(data[index]);
// }
that.processHistory(data);
LifecycleAPI.event(constants.EVENT_FETCH_HISTORY_SUCCESS);
},
error: function() {
LifecycleAPI.event(constants.EVENT_FETCH_HISTORY_FAILED);
}
})
};
LifecycleImpl.prototype.nextStates = function() {
//Assume that a state has not been provided
var currentState = this.currentState;
if ((arguments.length === 1) && (typeof arguments[0] === 'string')) {
currentState = arguments[0];
}
var state = this.stateMap.states[currentState] || {};
var transitions = state.transitions || [];
var transition;
var states = [];
for (var index = 0; index < transitions.length; index++) {
transition = transitions[index];
states.push(transition.target);
}
return states;
};
LifecycleImpl.prototype.state = function(name) {
return this.stateMap.states[name];
};
LifecycleImpl.prototype.stateNode = function(name) {
return this.dagreD3GraphObject.node(name);
};
LifecycleImpl.prototype.changeState = function(nextState) {
this.currentState = nextState;
LifecycleAPI.event(constants.EVENT_STATE_CHANGE);
};
LifecycleImpl.prototype.transitionUIs = function() {
var state = this.currentState;
var action;
var stateDetails;
var transition;
var transitionMappedToAction;
var transitionUI;
if (arguments.length === 1) {
state = arguments[0];
}
if (arguments.length === 2) {
action = arguments[1];
}
stateDetails = this.state(state) || {};
transitionUIs = (stateDetails.datamodel) ? stateDetails.datamodel.transitionUIs : [];
if (!action) {
return transitionUIs;
}
if (!transitionUIs) {
return [];
}
//Find the transition UI for the provided action
for (var index = 0; index < transitionUIs.length; index++) {
transition = transitionUIs[index];
if (transition.action.toLowerCase() === action.toLowerCase()) {
transitionMappedToAction = transition;
}
}
return transitionMappedToAction;
};
LifecycleImpl.prototype.transitionInputs = function(action) {
var currentState = this.currentState;
var state = this.state(currentState);
var stateDataModel = state.datamodel || {};
var transitionInputs = stateDataModel.transitionInputs || {};
var targetAction = action.toLowerCase();
if (transitionInputs.hasOwnProperty(targetAction)) {
return transitionInputs[targetAction];
}
return null;
// return {
// "action": "Promote",
// "inputs": [{
// "name": "id",
// "type": "text"
// }]
// };
};
LifecycleImpl.prototype.highlightCurrentState = function() {
var currentStateNode = this.stateNode(this.currentState);
var previousStateNode;
selectNode(currentStateNode.elem);
if ((this.previousState) && (this.previousState !== this.currentState)) {
previousStateNode = this.stateNode(this.previousState);
unselectNode(previousStateNode.elem);
}
};
var selectNode = function(elem) {
var rect = $(elem).find('rect');
rect.css('fill', '#3a9ecf');
rect.css('stroke', '#3a9ecf');
};
var unselectNode = function(elem) {
var rect = $(elem).find('rect');
rect.css('fill', '#f9f9f9');
rect.css('stroke', '#f9f9f9');
};
}()); | udarakr/carbon-store | apps/publisher/themes/default/js/lifecycle/lifecycle-core.js | JavaScript | apache-2.0 | 33,881 |
/*
* Copyright © 2014 NoNumber All Rights Reserved
* License http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
(function($){$(document).ready(function(){if(typeof(window['nn_sliders_use_hash'])!="undefined"){nnSliders={show:function(id,scroll,ignoreparents){var openparents=0;var $el=$('#'+id);if(!ignoreparents){$el.closest('.nn_sliders').closest('.accordion-body').each(function(i,parent){if(!$(parent).hasClass('in')){nnSliders.show(parent.id,0);openparents=1;}});}
if(openparents){nnSliders.show(id,scroll,1);}else{if(!$el.hasClass('in')){$el.collapse({toggle:true,parent:$el.parent().parent()});if(!$el.hasClass('in')){$el.collapse('toggle');}}else{}
$el.focus();}},};$('.nn_sliders > .accordion-group > .accordion-body').on('show show.bs.collapse',function(e){$(this).parent().addClass('active');e.stopPropagation();});$('.nn_sliders > .accordion-group > .accordion-body').on('hidden hidden.bs.collapse',function(e){$(this).parent().removeClass('active');e.stopPropagation();});if(nn_sliders_use_hash){if(window.location.hash){var id=window.location.hash.replace('#','');if(id.indexOf("&")==-1&&id.indexOf("=")==-1&&$('#'+id+'.accordion-body').length>0){if(!nn_sliders_urlscroll){$('html,body').animate({scrollTop:0});}
nnSliders.show(id,nn_sliders_urlscroll);}}
$('.nn_sliders > .accordion-group > .accordion-body').on('show show.bs.collapse',function(e){var id=this.id
this.id='';window.location.hash=id;this.id=id;e.stopPropagation();});}
if(window.location.hash){var id=window.location.hash.replace('#','');var $el=$('a[name="'+id+'"][data-toggle!="collapse"]');if($el){var hasparents=0;$el.closest('.nn_sliders').closest('.accordion-body').each(function(i,parent){if(!$(parent).hasClass('in')){nnSliders.show(parent.id,0);hasparents=1;}});if(hasparents){setTimeout(function(){$('html,body').animate({scrollTop:$el.offset().top});},500);}}}}});})(jQuery);function openAllSliders(){(function($){$('.nn_sliders').each(function(e,el){id=$(el).find('.accordion-body').first().attr('id');nnSliders.show(id);});})(jQuery);}
function closeAllSliders(){(function($){$('.nn_sliders').each(function(e,el){id=$(el).find('.accordion-body').first().attr('id');var $el=$('#'+id);$el.collapse('hide');});})(jQuery);} | cmaere/lwb | templates/protostar/media/sliders/js/script.min.js | JavaScript | apache-2.0 | 2,217 |
/*global QUnit */
sap.ui.define([
"sap/ui/qunit/QUnitUtils",
"sap/ui/qunit/utils/createAndAppendDiv",
"sap/ui/ux3/NavigationBar",
"sap/ui/thirdparty/jquery",
"sap/ui/ux3/NavigationItem"
], function(qutils, createAndAppendDiv, NavigationBar, jQuery, NavigationItem) {
"use strict";
// prepare DOM
createAndAppendDiv("uiArea1").style.marginTop = "10px";
var styleElement = document.createElement("style");
styleElement.textContent =
".sapUiUx3NavBarArrow {" +
" /* Enable testing of the arrow, even though it is not used outside the shell in BC */" +
" display: inline-block !important;" +
"}";
document.head.appendChild(styleElement);
var expectedItemId;
function eventHandler(oEvent) {
var itemId = oEvent.getParameter("itemId");
QUnit.config.current.assert.equal(itemId, expectedItemId, "the item ID should be the one of the clicked item: " + expectedItemId);
var item = oEvent.getParameter("item");
QUnit.config.current.assert.ok(item, "item should be given as well");
QUnit.config.current.assert.equal(item.getId(), expectedItemId, "the item's ID should be the one of the clicked item: " + expectedItemId);
}
var oCtrl = new NavigationBar("n1", {select:eventHandler});
oCtrl.placeAt("uiArea1");
QUnit.test("Initial Check", function(assert) {
assert.ok(oCtrl, "NavBar should exist after creating");
var oDomRef = window.document.getElementById("n1");
assert.ok(oDomRef, "NavBar root element should exist in the page");
});
var item1 = new NavigationItem({text:"Item 1"});
var item2 = new NavigationItem({text:"Item 2", href:"http://item2.org/"});
var item3 = new NavigationItem({text:"Item 3"});
QUnit.test("Add Items", function(assert) {
oCtrl.addItem(item1);
oCtrl.addItem(item2);
oCtrl.addItem(item3);
sap.ui.getCore().applyChanges();
var oDomRef = item1.getDomRef();
assert.ok(oDomRef, "Item element should exist in the page");
assert.equal(jQuery(oDomRef).text(), "Item 1", "Item 1 text should be written to the page");
var $list = oCtrl.$("list");
assert.equal($list.children().length, 5, "3 items plus the selection arrow plus dummy should be in the NavigationBar");
assert.equal($list.children(":eq(3)").text(), "Item 3", "The text of the third item should be rendered inside the NavigationBar");
var $items = jQuery(".sapUiUx3NavBarItem");
assert.equal($items.length, 4, "3 items plus the dummy should be in the page");
assert.equal($items[2].getAttribute("href"), "http://item2.org/", "item 2 should have a URL set as href");
assert.equal($items[3].getAttribute("href"), "#", "item 3 should have no URL set as href");
});
QUnit.test("Select Item", function(assert) {
oCtrl.setSelectedItem(item2);
assert.equal(oCtrl.getSelectedItem(), item2.getId(), "item 2 should be selected");
var $selItems = jQuery(".sapUiUx3NavBarItemSel");
assert.equal($selItems.length, 1, "1 item should be selected");
assert.equal($selItems.children()[0].id, item2.getId(), "DOM element marked as selected should be the one with the same ID as the selected item");
});
var firstPos;
QUnit.test("Selection Arrow", function(assert) {
var done = assert.async();
var arrow = oCtrl.getDomRef("arrow");
assert.ok(arrow, "there should be one selection arrow");
setTimeout(function(){
var item = item2.getDomRef();
var left = item.offsetLeft;
var width = item.offsetWidth;
var right = left + 3 * width / 5;
left = left + 2 * width / 5;
var arrowPos = arrow.offsetLeft + (arrow.offsetWidth / 2);
firstPos = arrowPos;
assert.ok(arrowPos > left && arrowPos < right, "arrow position (" + arrowPos
+ ") should be around the center of the selected item (between " + left + " and " + right + ")");
done();
}, 600);
});
QUnit.test("Selection Arrow Animation", function(assert) {
var done = assert.async();
oCtrl.setSelectedItem(item3);
var arrow = oCtrl.getDomRef("arrow");
setTimeout(function(){
var arrowPos = arrow.offsetLeft + (arrow.offsetWidth / 2);
assert.ok(arrowPos > firstPos, "arrow should have moved to the right a bit in the middle of the animation (from " + firstPos + ", now " + arrowPos + ")");
setTimeout(function() {
var newArrowPos = arrow.offsetLeft + (arrow.offsetWidth / 2);
var item = item3.getDomRef();
var left = item.offsetLeft;
var width = item.offsetWidth;
var right = left + 3 * width / 5;
left = left + 2 * width / 5;
assert.ok(newArrowPos > arrowPos, "arrow should have moved further to the right after the animation (from " + arrowPos + ", now " + newArrowPos + ")");
assert.ok(newArrowPos > left && newArrowPos < right, "arrow position (" + newArrowPos
+ ") should be around the center of the newly selected item (between " + left + " and " + right + ")");
done();
}, 400);
}, 300);
});
QUnit.test("Item selection (mouse)", function(assert) {
var done = assert.async();
assert.expect(5); // including event handler
var oldSel = oCtrl.getSelectedItem();
assert.equal(oldSel, item3.getId(), "item 3 should be selected"); // make sure previous selection is right
// click first item
var target = item1.getDomRef();
expectedItemId = item1.getId();
qutils.triggerMouseEvent(target, "click");
// wait selection animation to be finished
setTimeout(function(){
var newSel = oCtrl.getSelectedItem();
assert.equal(newSel, item1.getId(), "item 1 should be selected after clicking it"); // make sure selection is right after clicking
done();
}, 600);
});
QUnit.test("Render With Association", function(assert) {
oCtrl.removeAllItems();
sap.ui.getCore().applyChanges();
var $list = oCtrl.$("list");
assert.equal($list.children().length, 2, "no items except for dummy and arrow should be in the NavigationBar");
oCtrl.addAssociatedItem(item1);
oCtrl.addAssociatedItem(item2);
oCtrl.addAssociatedItem(item3);
sap.ui.getCore().applyChanges();
var oDomRef = item1.getDomRef();
assert.ok(oDomRef, "Item element should exist in the page");
assert.equal(jQuery(oDomRef).text(), "Item 1", "Item 1 text should be written to the page");
$list = oCtrl.$("list");
assert.equal($list.children().length, 5, "3 items plus dummy plus the selection arrow should be in the NavigationBar");
assert.equal($list.children(":eq(3)").text(), "Item 3", "The text of the third item should be rendered inside the NavigationBar");
});
QUnit.test("isSelectedItemValid", function(assert) {
oCtrl.setSelectedItem(item1);
var valid = oCtrl.isSelectedItemValid();
assert.equal(valid, true, "item1 is a valid selection");
oCtrl.setSelectedItem("item4");
valid = oCtrl.isSelectedItemValid();
assert.equal(valid, false, "the ID 'item4' is not a valid selection");
oCtrl.setSelectedItem(item1.getId());
valid = oCtrl.isSelectedItemValid();
assert.equal(valid, true, "the ID 'item1' is a valid selection");
});
QUnit.test("enabaling the overflowItemsToUppercase", function (assert) {
var oOverflowMenu = oCtrl._getOverflowMenu();
assert.strictEqual(oCtrl.getOverflowItemsToUpperCase(), false, "the property is disabled by default");
oCtrl.setOverflowItemsToUpperCase(true);
sap.ui.getCore().applyChanges();
assert.strictEqual(oOverflowMenu.hasStyleClass("sapUiUx3NavBarUpperCaseText"), true, "the items in the menu are uppercased");
oCtrl.setOverflowItemsToUpperCase(false);
sap.ui.getCore().applyChanges();
assert.strictEqual(oOverflowMenu.hasStyleClass("sapUiUx3NavBarUpperCaseText"), false, "the items in the menu are with their original case");
});
QUnit.test("Overflow", function(assert) {
var done = assert.async();
jQuery(document.getElementById("uiArea1")).css("width", "80px");
setTimeout(function(){
assert.equal(isForwardVisible(), true, "forward arrow should be visible");
assert.equal(isForwardEnabled(), true, "forward arrow should be enabled");
assert.equal(isBackVisible(), true, "back arrow should be visible");
assert.equal(isBackEnabled(), false, "back arrow should not be enabled");
jQuery(document.getElementById("uiArea1")).css("width", "800px");
setTimeout(function(){
assert.equal(isForwardVisible(), false, "forward arrow should not be visible");
assert.equal(isBackVisible(), false, "back arrow should not be visible");
oCtrl.addAssociatedItem(new NavigationItem({text:"Item with some quite long text to cause overflow 4"}));
oCtrl.addAssociatedItem(new NavigationItem({text:"Item with some quite long text to cause overflow 5"}));
setTimeout(function(){
assert.equal(isForwardVisible(), true, "forward arrow should be visible");
assert.equal(isForwardEnabled(), true, "forward arrow should be enabled");
assert.equal(isBackVisible(), true, "back arrow should not be visible");
assert.equal(isBackEnabled(), false, "back arrow should not be enabled");
done();
}, 500);
}, 500);
}, 500);
});
QUnit.test("Scrolling + Overflow", function(assert) {
var done = assert.async();
assert.equal(oCtrl.getDomRef("list").scrollLeft, 0, "list should not be scrolled initially");
// click first item
var target = oCtrl.$("off");
qutils.triggerMouseEvent(target, "click");
setTimeout(function(){
assert.equal(isForwardVisible(), true, "forward arrow should be visible");
assert.equal(isBackVisible(), true, "back arrow should be visible");
assert.ok(oCtrl.getDomRef("list").scrollLeft != 0, "list should be scrolled now");
// scroll to end
qutils.triggerMouseEvent(target, "click");
setTimeout(function(){
assert.equal(isForwardVisible(), true, "forward arrow should be visible");
assert.equal(isForwardEnabled(), false, "forward arrow should not be enabled");
assert.equal(isBackVisible(), true, "back arrow should be visible");
assert.equal(isBackEnabled(), true, "back arrow should be enabled");
// scroll to the beginning again
target = oCtrl.getDomRef("ofb");
qutils.triggerMouseEvent(target, "click");
setTimeout(function(){
qutils.triggerMouseEvent(target, "click");
setTimeout(function(){
assert.equal(isForwardVisible(), true, "forward arrow should be visible");
assert.equal(isForwardEnabled(), true, "forward arrow should be enabled");
assert.equal(isBackVisible(), true, "back arrow should be visible");
assert.equal(isBackEnabled(), false, "back arrow shouldnot be enabled");
assert.equal(oCtrl.getDomRef("list").scrollLeft, 0, "list should not be scrolled now");
done();
}, 600);
}, 600);
}, 600);
}, 600);
});
function isForwardVisible() {
return oCtrl.$("off").is(":visible");
}
function isBackVisible() {
return oCtrl.$("ofb").is(":visible");
}
function isForwardEnabled() {
return oCtrl.$("off").is(":visible") && oCtrl.$().hasClass("sapUiUx3NavBarScrollForward");
}
function isBackEnabled() {
return oCtrl.$("ofb").is(":visible") && oCtrl.$().hasClass("sapUiUx3NavBarScrollBack");
}
}); | SAP/openui5 | src/sap.ui.ux3/test/sap/ui/ux3/qunit/NavigationBar.qunit.js | JavaScript | apache-2.0 | 10,944 |
ace.define("ace/ext/menu_tools/overlay_page",[], function(require, exports, module) {
'use strict';
var dom = require("../../lib/dom");
var cssText = "#ace_settingsmenu, #kbshortcutmenu {\
background-color: #F7F7F7;\
color: black;\
box-shadow: -5px 4px 5px rgba(126, 126, 126, 0.55);\
padding: 1em 0.5em 2em 1em;\
overflow: auto;\
position: absolute;\
margin: 0;\
bottom: 0;\
right: 0;\
top: 0;\
z-index: 9991;\
cursor: default;\
}\
.ace_dark #ace_settingsmenu, .ace_dark #kbshortcutmenu {\
box-shadow: -20px 10px 25px rgba(126, 126, 126, 0.25);\
background-color: rgba(255, 255, 255, 0.6);\
color: black;\
}\
.ace_optionsMenuEntry:hover {\
background-color: rgba(100, 100, 100, 0.1);\
transition: all 0.3s\
}\
.ace_closeButton {\
background: rgba(245, 146, 146, 0.5);\
border: 1px solid #F48A8A;\
border-radius: 50%;\
padding: 7px;\
position: absolute;\
right: -8px;\
top: -8px;\
z-index: 100000;\
}\
.ace_closeButton{\
background: rgba(245, 146, 146, 0.9);\
}\
.ace_optionsMenuKey {\
color: darkslateblue;\
font-weight: bold;\
}\
.ace_optionsMenuCommand {\
color: darkcyan;\
font-weight: normal;\
}\
.ace_optionsMenuEntry input, .ace_optionsMenuEntry button {\
vertical-align: middle;\
}\
.ace_optionsMenuEntry button[ace_selected_button=true] {\
background: #e7e7e7;\
box-shadow: 1px 0px 2px 0px #adadad inset;\
border-color: #adadad;\
}\
.ace_optionsMenuEntry button {\
background: white;\
border: 1px solid lightgray;\
margin: 0px;\
}\
.ace_optionsMenuEntry button:hover{\
background: #f0f0f0;\
}";
dom.importCssString(cssText, "settings_menu.css", false);
module.exports.overlayPage = function overlayPage(editor, contentElement, callback) {
var closer = document.createElement('div');
var ignoreFocusOut = false;
function documentEscListener(e) {
if (e.keyCode === 27) {
close();
}
}
function close() {
if (!closer) return;
document.removeEventListener('keydown', documentEscListener);
closer.parentNode.removeChild(closer);
if (editor) {
editor.focus();
}
closer = null;
callback && callback();
}
function setIgnoreFocusOut(ignore) {
ignoreFocusOut = ignore;
if (ignore) {
closer.style.pointerEvents = "none";
contentElement.style.pointerEvents = "auto";
}
}
closer.style.cssText = 'margin: 0; padding: 0; ' +
'position: fixed; top:0; bottom:0; left:0; right:0;' +
'z-index: 9990; ' +
(editor ? 'background-color: rgba(0, 0, 0, 0.3);' : '');
closer.addEventListener('click', function(e) {
if (!ignoreFocusOut) {
close();
}
});
document.addEventListener('keydown', documentEscListener);
contentElement.addEventListener('click', function (e) {
e.stopPropagation();
});
closer.appendChild(contentElement);
document.body.appendChild(closer);
if (editor) {
editor.blur();
}
return {
close: close,
setIgnoreFocusOut: setIgnoreFocusOut
};
};
});
ace.define("ace/ext/modelist",[], function(require, exports, module) {
"use strict";
var modes = [];
function getModeForPath(path) {
var mode = modesByName.text;
var fileName = path.split(/[\/\\]/).pop();
for (var i = 0; i < modes.length; i++) {
if (modes[i].supportsFile(fileName)) {
mode = modes[i];
break;
}
}
return mode;
}
var Mode = function(name, caption, extensions) {
this.name = name;
this.caption = caption;
this.mode = "ace/mode/" + name;
this.extensions = extensions;
var re;
if (/\^/.test(extensions)) {
re = extensions.replace(/\|(\^)?/g, function(a, b){
return "$|" + (b ? "^" : "^.*\\.");
}) + "$";
} else {
re = "^.*\\.(" + extensions + ")$";
}
this.extRe = new RegExp(re, "gi");
};
Mode.prototype.supportsFile = function(filename) {
return filename.match(this.extRe);
};
var supportedModes = {
ABAP: ["abap"],
ABC: ["abc"],
ActionScript:["as"],
ADA: ["ada|adb"],
Alda: ["alda"],
Apache_Conf: ["^htaccess|^htgroups|^htpasswd|^conf|htaccess|htgroups|htpasswd"],
Apex: ["apex|cls|trigger|tgr"],
AQL: ["aql"],
AsciiDoc: ["asciidoc|adoc"],
ASL: ["dsl|asl|asl.json"],
Assembly_x86:["asm|a"],
AutoHotKey: ["ahk"],
BatchFile: ["bat|cmd"],
C_Cpp: ["cpp|c|cc|cxx|h|hh|hpp|ino"],
C9Search: ["c9search_results"],
Cirru: ["cirru|cr"],
Clojure: ["clj|cljs"],
Cobol: ["CBL|COB"],
coffee: ["coffee|cf|cson|^Cakefile"],
ColdFusion: ["cfm"],
Crystal: ["cr"],
CSharp: ["cs"],
Csound_Document: ["csd"],
Csound_Orchestra: ["orc"],
Csound_Score: ["sco"],
CSS: ["css"],
Curly: ["curly"],
D: ["d|di"],
Dart: ["dart"],
Diff: ["diff|patch"],
Dockerfile: ["^Dockerfile"],
Dot: ["dot"],
Drools: ["drl"],
Edifact: ["edi"],
Eiffel: ["e|ge"],
EJS: ["ejs"],
Elixir: ["ex|exs"],
Elm: ["elm"],
Erlang: ["erl|hrl"],
Forth: ["frt|fs|ldr|fth|4th"],
Fortran: ["f|f90"],
FSharp: ["fsi|fs|ml|mli|fsx|fsscript"],
FSL: ["fsl"],
FTL: ["ftl"],
Gcode: ["gcode"],
Gherkin: ["feature"],
Gitignore: ["^.gitignore"],
Glsl: ["glsl|frag|vert"],
Gobstones: ["gbs"],
golang: ["go"],
GraphQLSchema: ["gql"],
Groovy: ["groovy"],
HAML: ["haml"],
Handlebars: ["hbs|handlebars|tpl|mustache"],
Haskell: ["hs"],
Haskell_Cabal: ["cabal"],
haXe: ["hx"],
Hjson: ["hjson"],
HTML: ["html|htm|xhtml|vue|we|wpy"],
HTML_Elixir: ["eex|html.eex"],
HTML_Ruby: ["erb|rhtml|html.erb"],
INI: ["ini|conf|cfg|prefs"],
Io: ["io"],
Jack: ["jack"],
Jade: ["jade|pug"],
Java: ["java"],
JavaScript: ["js|jsm|jsx"],
JSON: ["json"],
JSON5: ["json5"],
JSONiq: ["jq"],
JSP: ["jsp"],
JSSM: ["jssm|jssm_state"],
JSX: ["jsx"],
Julia: ["jl"],
Kotlin: ["kt|kts"],
LaTeX: ["tex|latex|ltx|bib"],
Latte: ["latte"],
LESS: ["less"],
Liquid: ["liquid"],
Lisp: ["lisp"],
LiveScript: ["ls"],
LogiQL: ["logic|lql"],
LSL: ["lsl"],
Lua: ["lua"],
LuaPage: ["lp"],
Lucene: ["lucene"],
Makefile: ["^Makefile|^GNUmakefile|^makefile|^OCamlMakefile|make"],
Markdown: ["md|markdown"],
Mask: ["mask"],
MATLAB: ["matlab"],
Maze: ["mz"],
MediaWiki: ["wiki|mediawiki"],
MEL: ["mel"],
MIPS: ["s|asm"],
MIXAL: ["mixal"],
MUSHCode: ["mc|mush"],
MySQL: ["mysql"],
Nginx: ["nginx|conf"],
Nim: ["nim"],
Nix: ["nix"],
NSIS: ["nsi|nsh"],
Nunjucks: ["nunjucks|nunjs|nj|njk"],
ObjectiveC: ["m|mm"],
OCaml: ["ml|mli"],
Pascal: ["pas|p"],
Perl: ["pl|pm"],
pgSQL: ["pgsql"],
PHP: ["php|inc|phtml|shtml|php3|php4|php5|phps|phpt|aw|ctp|module"],
PHP_Laravel_blade: ["blade.php"],
Pig: ["pig"],
Powershell: ["ps1"],
Praat: ["praat|praatscript|psc|proc"],
Prisma: ["prisma"],
Prolog: ["plg|prolog"],
Properties: ["properties"],
Protobuf: ["proto"],
Puppet: ["epp|pp"],
Python: ["py"],
QML: ["qml"],
R: ["r"],
Raku: ["raku|rakumod|rakutest|p6|pl6|pm6"],
Razor: ["cshtml|asp"],
RDoc: ["Rd"],
Red: ["red|reds"],
RHTML: ["Rhtml"],
RST: ["rst"],
Ruby: ["rb|ru|gemspec|rake|^Guardfile|^Rakefile|^Gemfile"],
Rust: ["rs"],
SASS: ["sass"],
SCAD: ["scad"],
Scala: ["scala|sbt"],
Scheme: ["scm|sm|rkt|oak|scheme"],
Scrypt: ["scrypt"],
SCSS: ["scss"],
SH: ["sh|bash|^.bashrc"],
SJS: ["sjs"],
Slim: ["slim|skim"],
Smarty: ["smarty|tpl"],
Smithy: ["smithy"],
snippets: ["snippets"],
Soy_Template:["soy"],
Space: ["space"],
SQL: ["sql"],
SQLServer: ["sqlserver"],
Stylus: ["styl|stylus"],
SVG: ["svg"],
Swift: ["swift"],
Tcl: ["tcl"],
Terraform: ["tf", "tfvars", "terragrunt"],
Tex: ["tex"],
Text: ["txt"],
Textile: ["textile"],
Toml: ["toml"],
TSX: ["tsx"],
Twig: ["twig|swig"],
Typescript: ["ts|typescript|str"],
Vala: ["vala"],
VBScript: ["vbs|vb"],
Velocity: ["vm"],
Verilog: ["v|vh|sv|svh"],
VHDL: ["vhd|vhdl"],
Visualforce: ["vfp|component|page"],
Wollok: ["wlk|wpgm|wtest"],
XML: ["xml|rdf|rss|wsdl|xslt|atom|mathml|mml|xul|xbl|xaml"],
XQuery: ["xq"],
YAML: ["yaml|yml"],
Zeek: ["zeek|bro"],
Django: ["html"]
};
var nameOverrides = {
ObjectiveC: "Objective-C",
CSharp: "C#",
golang: "Go",
C_Cpp: "C and C++",
Csound_Document: "Csound Document",
Csound_Orchestra: "Csound",
Csound_Score: "Csound Score",
coffee: "CoffeeScript",
HTML_Ruby: "HTML (Ruby)",
HTML_Elixir: "HTML (Elixir)",
FTL: "FreeMarker",
PHP_Laravel_blade: "PHP (Blade Template)",
Perl6: "Perl 6",
AutoHotKey: "AutoHotkey / AutoIt"
};
var modesByName = {};
for (var name in supportedModes) {
var data = supportedModes[name];
var displayName = (nameOverrides[name] || name).replace(/_/g, " ");
var filename = name.toLowerCase();
var mode = new Mode(filename, displayName, data[0]);
modesByName[filename] = mode;
modes.push(mode);
}
module.exports = {
getModeForPath: getModeForPath,
modes: modes,
modesByName: modesByName
};
});
ace.define("ace/ext/themelist",[], function(require, exports, module) {
"use strict";
var themeData = [
["Chrome" ],
["Clouds" ],
["Crimson Editor" ],
["Dawn" ],
["Dreamweaver" ],
["Eclipse" ],
["GitHub" ],
["IPlastic" ],
["Solarized Light"],
["TextMate" ],
["Tomorrow" ],
["Xcode" ],
["Kuroir"],
["KatzenMilch"],
["SQL Server" ,"sqlserver" , "light"],
["Ambiance" ,"ambiance" , "dark"],
["Chaos" ,"chaos" , "dark"],
["Clouds Midnight" ,"clouds_midnight" , "dark"],
["Dracula" ,"" , "dark"],
["Cobalt" ,"cobalt" , "dark"],
["Gruvbox" ,"gruvbox" , "dark"],
["Green on Black" ,"gob" , "dark"],
["idle Fingers" ,"idle_fingers" , "dark"],
["krTheme" ,"kr_theme" , "dark"],
["Merbivore" ,"merbivore" , "dark"],
["Merbivore Soft" ,"merbivore_soft" , "dark"],
["Mono Industrial" ,"mono_industrial" , "dark"],
["Monokai" ,"monokai" , "dark"],
["Nord Dark" ,"nord_dark" , "dark"],
["One Dark" ,"one_dark" , "dark"],
["Pastel on dark" ,"pastel_on_dark" , "dark"],
["Solarized Dark" ,"solarized_dark" , "dark"],
["Terminal" ,"terminal" , "dark"],
["Tomorrow Night" ,"tomorrow_night" , "dark"],
["Tomorrow Night Blue" ,"tomorrow_night_blue" , "dark"],
["Tomorrow Night Bright","tomorrow_night_bright" , "dark"],
["Tomorrow Night 80s" ,"tomorrow_night_eighties" , "dark"],
["Twilight" ,"twilight" , "dark"],
["Vibrant Ink" ,"vibrant_ink" , "dark"]
];
exports.themesByName = {};
exports.themes = themeData.map(function(data) {
var name = data[1] || data[0].replace(/ /g, "_").toLowerCase();
var theme = {
caption: data[0],
theme: "ace/theme/" + name,
isDark: data[2] == "dark",
name: name
};
exports.themesByName[name] = theme;
return theme;
});
});
ace.define("ace/ext/options",[], function(require, exports, module) {
"use strict";
require("./menu_tools/overlay_page");
var dom = require("../lib/dom");
var oop = require("../lib/oop");
var config = require("../config");
var EventEmitter = require("../lib/event_emitter").EventEmitter;
var buildDom = dom.buildDom;
var modelist = require("./modelist");
var themelist = require("./themelist");
var themes = { Bright: [], Dark: [] };
themelist.themes.forEach(function(x) {
themes[x.isDark ? "Dark" : "Bright"].push({ caption: x.caption, value: x.theme });
});
var modes = modelist.modes.map(function(x){
return { caption: x.caption, value: x.mode };
});
var optionGroups = {
Main: {
Mode: {
path: "mode",
type: "select",
items: modes
},
Theme: {
path: "theme",
type: "select",
items: themes
},
"Keybinding": {
type: "buttonBar",
path: "keyboardHandler",
items: [
{ caption : "Ace", value : null },
{ caption : "Vim", value : "ace/keyboard/vim" },
{ caption : "Emacs", value : "ace/keyboard/emacs" },
{ caption : "Sublime", value : "ace/keyboard/sublime" },
{ caption : "VSCode", value : "ace/keyboard/vscode" }
]
},
"Font Size": {
path: "fontSize",
type: "number",
defaultValue: 12,
defaults: [
{caption: "12px", value: 12},
{caption: "24px", value: 24}
]
},
"Soft Wrap": {
type: "buttonBar",
path: "wrap",
items: [
{ caption : "Off", value : "off" },
{ caption : "View", value : "free" },
{ caption : "margin", value : "printMargin" },
{ caption : "40", value : "40" }
]
},
"Cursor Style": {
path: "cursorStyle",
items: [
{ caption : "Ace", value : "ace" },
{ caption : "Slim", value : "slim" },
{ caption : "Smooth", value : "smooth" },
{ caption : "Smooth And Slim", value : "smooth slim" },
{ caption : "Wide", value : "wide" }
]
},
"Folding": {
path: "foldStyle",
items: [
{ caption : "Manual", value : "manual" },
{ caption : "Mark begin", value : "markbegin" },
{ caption : "Mark begin and end", value : "markbeginend" }
]
},
"Soft Tabs": [{
path: "useSoftTabs"
}, {
ariaLabel: "Tab Size",
path: "tabSize",
type: "number",
values: [2, 3, 4, 8, 16]
}],
"Overscroll": {
type: "buttonBar",
path: "scrollPastEnd",
items: [
{ caption : "None", value : 0 },
{ caption : "Half", value : 0.5 },
{ caption : "Full", value : 1 }
]
}
},
More: {
"Atomic soft tabs": {
path: "navigateWithinSoftTabs"
},
"Enable Behaviours": {
path: "behavioursEnabled"
},
"Wrap with quotes": {
path: "wrapBehavioursEnabled"
},
"Enable Auto Indent": {
path: "enableAutoIndent"
},
"Full Line Selection": {
type: "checkbox",
values: "text|line",
path: "selectionStyle"
},
"Highlight Active Line": {
path: "highlightActiveLine"
},
"Show Invisibles": {
path: "showInvisibles"
},
"Show Indent Guides": {
path: "displayIndentGuides"
},
"Persistent HScrollbar": {
path: "hScrollBarAlwaysVisible"
},
"Persistent VScrollbar": {
path: "vScrollBarAlwaysVisible"
},
"Animate scrolling": {
path: "animatedScroll"
},
"Show Gutter": {
path: "showGutter"
},
"Show Line Numbers": {
path: "showLineNumbers"
},
"Relative Line Numbers": {
path: "relativeLineNumbers"
},
"Fixed Gutter Width": {
path: "fixedWidthGutter"
},
"Show Print Margin": [{
path: "showPrintMargin"
}, {
ariaLabel: "Print Margin",
type: "number",
path: "printMarginColumn"
}],
"Indented Soft Wrap": {
path: "indentedSoftWrap"
},
"Highlight selected word": {
path: "highlightSelectedWord"
},
"Fade Fold Widgets": {
path: "fadeFoldWidgets"
},
"Use textarea for IME": {
path: "useTextareaForIME"
},
"Merge Undo Deltas": {
path: "mergeUndoDeltas",
items: [
{ caption : "Always", value : "always" },
{ caption : "Never", value : "false" },
{ caption : "Timed", value : "true" }
]
},
"Elastic Tabstops": {
path: "useElasticTabstops"
},
"Incremental Search": {
path: "useIncrementalSearch"
},
"Read-only": {
path: "readOnly"
},
"Copy without selection": {
path: "copyWithEmptySelection"
},
"Live Autocompletion": {
path: "enableLiveAutocompletion"
}
}
};
var OptionPanel = function(editor, element) {
this.editor = editor;
this.container = element || document.createElement("div");
this.groups = [];
this.options = {};
};
(function() {
oop.implement(this, EventEmitter);
this.add = function(config) {
if (config.Main)
oop.mixin(optionGroups.Main, config.Main);
if (config.More)
oop.mixin(optionGroups.More, config.More);
};
this.render = function() {
this.container.innerHTML = "";
buildDom(["table", {role: "presentation", id: "controls"},
this.renderOptionGroup(optionGroups.Main),
["tr", null, ["td", {colspan: 2},
["table", {role: "presentation", id: "more-controls"},
this.renderOptionGroup(optionGroups.More)
]
]],
["tr", null, ["td", {colspan: 2}, "version " + config.version]]
], this.container);
};
this.renderOptionGroup = function(group) {
return Object.keys(group).map(function(key, i) {
var item = group[key];
if (!item.position)
item.position = i / 10000;
if (!item.label)
item.label = key;
return item;
}).sort(function(a, b) {
return a.position - b.position;
}).map(function(item) {
return this.renderOption(item.label, item);
}, this);
};
this.renderOptionControl = function(key, option) {
var self = this;
if (Array.isArray(option)) {
return option.map(function(x) {
return self.renderOptionControl(key, x);
});
}
var control;
var value = self.getOption(option);
if (option.values && option.type != "checkbox") {
if (typeof option.values == "string")
option.values = option.values.split("|");
option.items = option.values.map(function(v) {
return { value: v, name: v };
});
}
if (option.type == "buttonBar") {
control = ["div", {role: "group", "aria-labelledby": option.path + "-label"}, option.items.map(function(item) {
return ["button", {
value: item.value,
ace_selected_button: value == item.value,
'aria-pressed': value == item.value,
onclick: function() {
self.setOption(option, item.value);
var nodes = this.parentNode.querySelectorAll("[ace_selected_button]");
for (var i = 0; i < nodes.length; i++) {
nodes[i].removeAttribute("ace_selected_button");
nodes[i].setAttribute("aria-pressed", false);
}
this.setAttribute("ace_selected_button", true);
this.setAttribute("aria-pressed", true);
}
}, item.desc || item.caption || item.name];
})];
} else if (option.type == "number") {
control = ["input", {type: "number", value: value || option.defaultValue, style:"width:3em", oninput: function() {
self.setOption(option, parseInt(this.value));
}}];
if (option.ariaLabel) {
control[1]["aria-label"] = option.ariaLabel;
} else {
control[1].id = key;
}
if (option.defaults) {
control = [control, option.defaults.map(function(item) {
return ["button", {onclick: function() {
var input = this.parentNode.firstChild;
input.value = item.value;
input.oninput();
}}, item.caption];
})];
}
} else if (option.items) {
var buildItems = function(items) {
return items.map(function(item) {
return ["option", { value: item.value || item.name }, item.desc || item.caption || item.name];
});
};
var items = Array.isArray(option.items)
? buildItems(option.items)
: Object.keys(option.items).map(function(key) {
return ["optgroup", {"label": key}, buildItems(option.items[key])];
});
control = ["select", { id: key, value: value, onchange: function() {
self.setOption(option, this.value);
} }, items];
} else {
if (typeof option.values == "string")
option.values = option.values.split("|");
if (option.values) value = value == option.values[1];
control = ["input", { type: "checkbox", id: key, checked: value || null, onchange: function() {
var value = this.checked;
if (option.values) value = option.values[value ? 1 : 0];
self.setOption(option, value);
}}];
if (option.type == "checkedNumber") {
control = [control, []];
}
}
return control;
};
this.renderOption = function(key, option) {
if (option.path && !option.onchange && !this.editor.$options[option.path])
return;
var path = Array.isArray(option) ? option[0].path : option.path;
this.options[path] = option;
var safeKey = "-" + path;
var safeId = path + "-label";
var control = this.renderOptionControl(safeKey, option);
return ["tr", {class: "ace_optionsMenuEntry"}, ["td",
["label", {for: safeKey, id: safeId}, key]
], ["td", control]];
};
this.setOption = function(option, value) {
if (typeof option == "string")
option = this.options[option];
if (value == "false") value = false;
if (value == "true") value = true;
if (value == "null") value = null;
if (value == "undefined") value = undefined;
if (typeof value == "string" && parseFloat(value).toString() == value)
value = parseFloat(value);
if (option.onchange)
option.onchange(value);
else if (option.path)
this.editor.setOption(option.path, value);
this._signal("setOption", {name: option.path, value: value});
};
this.getOption = function(option) {
if (option.getValue)
return option.getValue();
return this.editor.getOption(option.path);
};
}).call(OptionPanel.prototype);
exports.OptionPanel = OptionPanel;
});
ace.define("ace/ext/settings_menu",[], function(require, exports, module) {
"use strict";
var OptionPanel = require("./options").OptionPanel;
var overlayPage = require('./menu_tools/overlay_page').overlayPage;
function showSettingsMenu(editor) {
if (!document.getElementById('ace_settingsmenu')) {
var options = new OptionPanel(editor);
options.render();
options.container.id = "ace_settingsmenu";
overlayPage(editor, options.container);
options.container.querySelector("select,input,button,checkbox").focus();
}
}
module.exports.init = function() {
var Editor = require("../editor").Editor;
Editor.prototype.showSettingsMenu = function() {
showSettingsMenu(this);
};
};
}); (function() {
ace.require(["ace/ext/settings_menu"], function(m) {
if (typeof module == "object" && typeof exports == "object" && module) {
module.exports = m;
}
});
})();
| SAP/openui5 | src/sap.ui.codeeditor/src/sap/ui/codeeditor/js/ace/ext-settings_menu.js | JavaScript | apache-2.0 | 26,258 |
var NAVTREEINDEX37 =
{
"a03349.html":[3,0,174],
"a03349.html#a30f34b2cebac981b0ff2be7508b2537a":[3,0,174,3],
"a03349.html#a6a98c1ea78a5041690c98cd3010df4a1":[3,0,174,2],
"a03349.html#abdebedb1f3f9fd43f04e051ae965bd6e":[3,0,174,0],
"a03349.html#adebb3f6f6beb03a3402690a71a59d24b":[3,0,174,1],
"a03353.html":[3,0,175],
"a03353.html#a0cca2a22516e27216964b067cb1a6df2":[3,0,175,3],
"a03353.html#a66a0ca38ab62204054f37012c5c0e6cf":[3,0,175,1],
"a03353.html#a986272921cee3b7c07b6dbcadf019299":[3,0,175,2],
"a03353.html#ac474c586d6955dee98c7f9b8d82c98ad":[3,0,175,0],
"a03357.html":[3,0,90],
"a03357.html#a14c8bc85d7a5b7aadb9f7381a9d8a79f":[3,0,90,3],
"a03357.html#a4f7f1fa96fa8036921324f18149f1d99":[3,0,90,0],
"a03357.html#a9c4fe92191563c1c7d9de407205ef269":[3,0,90,1],
"a03357.html#ab312944a59a3fb7ca9587c1b52e45b42":[3,0,90,2],
"a03361.html":[3,0,91],
"a03361.html#a3d2c98342635f4828640467d9887f79b":[3,0,91,1],
"a03361.html#aa7ac5a5a67f6c8e96b58dbbd3442413c":[3,0,91,2],
"a03361.html#ab3d27a2fb9628e19f8735ad448b3f35b":[3,0,91,3],
"a03361.html#ae5ec0b7ad2a8171a5670a5d7c34efd2e":[3,0,91,0],
"a03365.html":[3,0,18],
"a03365.html#a425a521875a76859fa202ae9a883de90":[3,0,18,2],
"a03365.html#a56a84ab3130603d607a5f6f8afe54e57":[3,0,18,1],
"a03365.html#a82f583a9a400f0213940e4738e7c5ea9":[3,0,18,3],
"a03365.html#aee9a2cbb3181f53c89031a326e7241d5":[3,0,18,0],
"a03369.html":[3,0,19],
"a03369.html#a12d74829266feaa68bc4bcf23f88cbef":[3,0,19,0],
"a03369.html#a528685ec14d9b2c4910f06b3e1219694":[3,0,19,3],
"a03369.html#a9a940697c49d399ab50b3f66a7874f64":[3,0,19,1],
"a03369.html#aa9e163cc145cacb0d7b99693aa55390b":[3,0,19,2],
"a03373.html":[3,0,186],
"a03373.html#a19271a0ba55764590eb3e04ebc10e564":[3,0,186,1],
"a03373.html#a5196d91d2a4d6151483dfc4870c3b4e5":[3,0,186,2],
"a03373.html#a5c6e14d91d9dc9818955d6822e2eda2c":[3,0,186,3],
"a03373.html#a951fb093f95d70a75ea9edf1dc0961c9":[3,0,186,0],
"a03377.html":[3,0,187],
"a03377.html#ac748c14438638e16b8f4cb69babf1487":[3,0,187,0],
"a03377.html#ae7fcb454625e73af49fff3de977739a2":[3,0,187,1],
"a03377.html#af3667314f23108d3c29a63e0ceb7bae8":[3,0,187,2],
"a03377.html#af5759e92c89b085067826cd4ac95f334":[3,0,187,3],
"a03381.html":[3,0,102],
"a03381.html#a63e6bfe69d96846506f6417acfe692e4":[3,0,102,1],
"a03381.html#aa0cabfc2c7b8ea8e1fa1a3995b7ec061":[3,0,102,0],
"a03381.html#acef59bf4ed8831016f10994a26a076bc":[3,0,102,3],
"a03381.html#ad5a71441d5bcb7e8cd2f6fca9cbe4b9a":[3,0,102,2],
"a03385.html":[3,0,103],
"a03385.html#a26c08c9c74991884fef7824ef93c4e8c":[3,0,103,3],
"a03385.html#aa0f82c02bd2aa5024b7e39af2283d0c6":[3,0,103,1],
"a03385.html#aa49bf3b4903c8b67c1be7b8efab80237":[3,0,103,0],
"a03385.html#ab0c5a90349beb55e438a3f6e486da881":[3,0,103,2],
"a03389.html":[3,0,30],
"a03389.html#a391ea790c4910329bc2665a3d025a70e":[3,0,30,0],
"a03389.html#a3fb857746d36e7c7b77ff4c134dfb30f":[3,0,30,2],
"a03389.html#a6f51ccde52c6effa9f98c8edb3839325":[3,0,30,1],
"a03389.html#ae714dcb8a3d1bd06e537f1687a7ea24a":[3,0,30,3],
"a03393.html":[3,0,31],
"a03393.html#a0016ff0279fab699177e5edff67cde4d":[3,0,31,3],
"a03393.html#a0c2fcd514358c62227566b2d4e49c23a":[3,0,31,2],
"a03393.html#a28ba3d9716c422d685f1b0a34025f8a3":[3,0,31,0],
"a03393.html#a500f592fe0ce96149ddd1592603d8475":[3,0,31,1],
"a03397.html":[3,0,198],
"a03397.html#a0a98853a83fe76b20e1b771bb4337c97":[3,0,198,0],
"a03397.html#a1e1be95923a52bac37f1c95a35aa6c7f":[3,0,198,3],
"a03397.html#a8405b629d5ee53a11d1d11682fe3e5cb":[3,0,198,2],
"a03397.html#a9c569b1f2caa921328ae44bbf5e4cd6b":[3,0,198,1],
"a03401.html":[3,0,199],
"a03401.html#a3adda388f60409ec2ae571321a531941":[3,0,199,0],
"a03401.html#a8234026895783c91fc3918814761d82b":[3,0,199,2],
"a03401.html#aace1f3007f6bdfe942b4d963be5042f9":[3,0,199,1],
"a03401.html#af25b39da0d9c21e08e5697f4e30cb09f":[3,0,199,3],
"a03405.html":[3,0,114],
"a03405.html#a119f24b9b7d12add27eed15b4d8e3a88":[3,0,114,2],
"a03405.html#a21be599b0891087af0f29d5f24b5fd99":[3,0,114,0],
"a03405.html#a414c7fd1cdbff059c9c5f1131a72781e":[3,0,114,1],
"a03405.html#a93682ed2df536ff9875a9a21a41ed0ae":[3,0,114,3],
"a03409.html":[3,0,115],
"a03409.html#a34bafcdf1bce80e38a65b74b56c17a16":[3,0,115,0],
"a03409.html#a62502243a6aef84a757f774b5c2544be":[3,0,115,2],
"a03409.html#ac26e659a44de51b2be12b778cbdb2a6b":[3,0,115,3],
"a03409.html#ae14fe6cd1894f13d5ddd8651d852e8a2":[3,0,115,1],
"a03413.html":[3,0,42],
"a03413.html#a4244779f77c3fa662ba1c212a3aead25":[3,0,42,1],
"a03413.html#a5914769e543782882e46a58598ea8f04":[3,0,42,2],
"a03413.html#aa1f0cd63e3fbab60c2e0e2b14698745f":[3,0,42,3],
"a03413.html#aba070705a38fe7504e69cedd50c705ce":[3,0,42,0],
"a03417.html":[3,0,43],
"a03417.html#ac51b84aecb5bb4514eb55a52443ebadf":[3,0,43,3],
"a03417.html#ad053a9a8de88e9a2e5a2a5f51f4d07fc":[3,0,43,0],
"a03417.html#aee2834bc9dafbfc6a874840224c31021":[3,0,43,2],
"a03417.html#af77e42794a2208c7ac8af6cb0eee9d86":[3,0,43,1],
"a03421.html":[3,0,210],
"a03421.html#a10a49db7c5bef9d8de201eb25adeb0f7":[3,0,210,3],
"a03421.html#a87b460bfd426534c18674a2514c8217e":[3,0,210,1],
"a03421.html#abedb9157163de17e84b3f0f274f22956":[3,0,210,2],
"a03421.html#adba071ddcd13d1c92dabf1378e2b4cec":[3,0,210,0],
"a03425.html":[3,0,211],
"a03425.html#a3c6f5be8dea6b7f72654ab63eba0614e":[3,0,211,2],
"a03425.html#a79c0a207b47e053b338b64d6a22fcae8":[3,0,211,0],
"a03425.html#ac6e5176d9fd9ec42bf01c36287c56159":[3,0,211,1],
"a03425.html#ae93a1d3b9acf52a15844c99e8f792718":[3,0,211,3],
"a03429.html":[3,0,126],
"a03429.html#a2f958ede6897454ca4c01e4ea648c1b7":[3,0,126,2],
"a03429.html#a517b719d3c4900d4760cb833045b8826":[3,0,126,3],
"a03429.html#ac33f9f3b17ad7aeda49d5948138b7471":[3,0,126,0],
"a03429.html#adf9412b9aaf6a5faa5ec389198034bc3":[3,0,126,1],
"a03433.html":[3,0,127],
"a03433.html#a29f8006400de42d45ee46d38d817804e":[3,0,127,2],
"a03433.html#a882eb5f896fbcb5f68236411f4c52c92":[3,0,127,3],
"a03433.html#aa1d2f923d058af37e4a2f0e152006c64":[3,0,127,0],
"a03433.html#ae06656eb6ca005f8e9a1ae5082eedc50":[3,0,127,1],
"a03437.html":[3,0,54],
"a03437.html#a099d8ba06c8d2308099dbb100333e387":[3,0,54,1],
"a03437.html#a3eafab2d508e54e50a53ef091b86a3d6":[3,0,54,2],
"a03437.html#a5a6dc489db05720779034162b527114b":[3,0,54,3],
"a03437.html#a70e40ea8a648d89f902ce9d912303fc0":[3,0,54,0],
"a03441.html":[3,0,55],
"a03441.html#a49ce36f70d683db8f37c93510dab4f49":[3,0,55,3],
"a03441.html#a664c162cbc9d6560b4282283ffe56a72":[3,0,55,1],
"a03441.html#a9ed95a585443cf2429fe9d3901dacc37":[3,0,55,2],
"a03441.html#acac9a83ab6d9dfc9345124fc44ee8255":[3,0,55,0],
"a03445.html":[3,0,222],
"a03445.html#a492b6350ac21cb53a52c629f1343a475":[3,0,222,2],
"a03445.html#aa2e4b47576f8c38b37860407610b6bc5":[3,0,222,0],
"a03445.html#aba6b6f9d3ef09907daa3f605e87b9c32":[3,0,222,3],
"a03445.html#abffbdd0c8d243f1a907925b1b2c4b099":[3,0,222,1],
"a03449.html":[3,0,223],
"a03449.html#a656e469d80975fd0b367c9c1a9c8f2af":[3,0,223,0],
"a03449.html#a8bbfa1b1315a9dc8aa29787c2689fb1c":[3,0,223,3],
"a03449.html#ab9a361eec303413d3042d3ca68de692d":[3,0,223,1],
"a03449.html#ae3dc94deaf4a6d01a67bbaa0101e2d4c":[3,0,223,2],
"a03453.html":[3,0,138],
"a03453.html#a57526cc4b1831417e8e49cdc80101200":[3,0,138,3],
"a03453.html#ab75f14d698de7f19a9c08bbbcfafac15":[3,0,138,0],
"a03453.html#ac86cd5e2b8ca7ce8f0a2dfee6415dc4e":[3,0,138,2],
"a03453.html#afb6853d3cbd3e5c96ab5279c9427e295":[3,0,138,1],
"a03457.html":[3,0,139],
"a03457.html#a1101b23e8b3e72c79a037faf638ee75a":[3,0,139,1],
"a03457.html#a19dc2979e3678d7d9409b8412de58a67":[3,0,139,0],
"a03457.html#a1d8904c42a738afa2da87e6ec0d429b0":[3,0,139,3],
"a03457.html#a452ab4e2cce76dd2ae1d8309fcf06fc8":[3,0,139,2],
"a03461.html":[3,0,66],
"a03461.html#a7beb5dac27d4c8984580ac5be0c9df50":[3,0,66,2],
"a03461.html#ab28c4a85e1d739e3d815701819287139":[3,0,66,1],
"a03461.html#ac6be7f9d630c6c5655e09a6ed77dc8fa":[3,0,66,0],
"a03461.html#ae5720faaf090f900c0ce4bd28aa66cbc":[3,0,66,3],
"a03465.html":[3,0,67],
"a03465.html#a1a68c2d7dc0d62586e65970138996284":[3,0,67,3],
"a03465.html#a20c820b3a67b2d0ed8831984636b682a":[3,0,67,0],
"a03465.html#a2f6f6fe8f53e35a187749c2b13d9fc79":[3,0,67,1],
"a03465.html#a79ca58d4db1e73c70ddea6f8c1b20c7c":[3,0,67,2],
"a03469.html":[3,0,234],
"a03469.html#a17998e7b94332ee95d07345955d50912":[3,0,234,2],
"a03469.html#a21c218010d64311c4beee852d9bc4c06":[3,0,234,3],
"a03469.html#a2fcf702adb2633072ddb675685332972":[3,0,234,0],
"a03469.html#ad83c29e2000299e75a53cc8db096ca79":[3,0,234,1],
"a03473.html":[3,0,235],
"a03473.html#a2bb99c54acda13878a7db0d74a358e86":[3,0,235,3],
"a03473.html#a77c75751e2b27b73cc03735cd4c6cb3f":[3,0,235,1],
"a03473.html#aa5ac3c78a9e7b393ceb2a38895a22d0a":[3,0,235,2],
"a03473.html#ad6491af353c670dadefd6f4f6dfaa3ea":[3,0,235,0],
"a03477.html":[3,0,150],
"a03477.html#a5852a81a66a9d1c51dd2d3b235636e78":[3,0,150,0],
"a03477.html#ad5e562ef6f6aecff758c5a98c8c74ab7":[3,0,150,3],
"a03477.html#adf6112b2cb543a94c0d3bfd57ed6aad3":[3,0,150,1],
"a03477.html#aec1b480e3018f29ecbb6eb1a641f81f1":[3,0,150,2],
"a03481.html":[3,0,151],
"a03481.html#a068dff747fbc555cf55c0bfe3409a64c":[3,0,151,2],
"a03481.html#a5576d395de768c5a8d9e51a5fa040cef":[3,0,151,0],
"a03481.html#a66a656b92a72e6dc74bf03934c3542ff":[3,0,151,1],
"a03481.html#ad80b1e2faa86f396a492e72d8f76fa42":[3,0,151,3],
"a03485.html":[3,0,78],
"a03485.html#a10cb24ff98784fbf28e3a6aa79e4d38a":[3,0,78,0],
"a03485.html#a6186e2626916c80ca73fc091c42da2ea":[3,0,78,1],
"a03485.html#a95d0d0f408a4ca3ddeab7dd2b064d1d1":[3,0,78,2],
"a03485.html#a9d05e6e22e7cfe9ba8a8ba2306e6029e":[3,0,78,3],
"a03489.html":[3,0,79],
"a03489.html#a2740e0564250ff67fc5cd076a6ebf8a3":[3,0,79,0],
"a03489.html#ac5db2e71c08be861ebc1f7ea7c41a4bf":[3,0,79,3],
"a03489.html#af0832b75493efa579bc4096821746aa8":[3,0,79,1],
"a03489.html#af11a8115f9507e2bae9bcde030b7ac14":[3,0,79,2],
"a03493.html":[3,0,246],
"a03493.html#a622fc0b01d90f5d5e56f8b9d7b18c229":[3,0,246,3],
"a03493.html#a92c1c34246959a0f4d6ce4857dac3e61":[3,0,246,2],
"a03493.html#ab8cf7f238ac672c538524211c4ef73a6":[3,0,246,1],
"a03493.html#ac5f54ddeb93aa4d0311663afefb443c7":[3,0,246,0],
"a03497.html":[3,0,247],
"a03497.html#a2f3be1437cbb85971204d99ee11f0d51":[3,0,247,1],
"a03497.html#a97451d873d238f3ace8a1258e4e1cf4c":[3,0,247,2],
"a03497.html#aa4e7144d515e7531e920f1e195d84e9a":[3,0,247,3],
"a03497.html#acd65959efbbac5d199fd791e859da500":[3,0,247,0],
"a03501.html":[3,0,162],
"a03501.html#a598fd1bb0286d3df913a4edacbb6390c":[3,0,162,1],
"a03501.html#a75780e5fcf7f25b7a74d18264fbaf724":[3,0,162,2],
"a03501.html#ac5795e0de7c5fec2140c4429c6f1f51b":[3,0,162,3],
"a03501.html#aeb11f70b48e24c048c3883886f3843f5":[3,0,162,0],
"a03505.html":[3,0,163],
"a03505.html#a11066b00029633a549855097a86e2565":[3,0,163,2],
"a03505.html#a14b49668aa20cb477b658c77163dd5f3":[3,0,163,3],
"a03505.html#a3b3d7bac0431616caf1d12e5b188b2ec":[3,0,163,0],
"a03505.html#ad83860a0559a0537f5a401daf192974d":[3,0,163,1],
"a03509.html":[3,0,8],
"a03509.html#a87314cfe5cd68f08bf4432a7f5100512":[3,0,8,1],
"a03509.html#aa448aea48ce5fc89703c79774de537b7":[3,0,8,2],
"a03509.html#aad522994559151e53fc0a0852388fad4":[3,0,8,3],
"a03509.html#abc1d0fb0a4a44b6693759fb6b783b3fd":[3,0,8,0],
"a03513.html":[3,0,9],
"a03513.html#a26e0a0db87bf986fdf01dcbdc84ae3b8":[3,0,9,3],
"a03513.html#a3167abb81be5929dde60241b40355525":[3,0,9,0],
"a03513.html#a63c6fbc3f6f0d0f556705f93b1bac036":[3,0,9,2],
"a03513.html#ae8f65611aab0fb942d30596848b918a0":[3,0,9,1],
"a03517.html":[3,0,176],
"a03517.html#a08ea4be8cd069ca3fca3d8577eea513f":[3,0,176,0],
"a03517.html#a0b7cf796de97e66219796720b03a4f9c":[3,0,176,3],
"a03517.html#a8c699ea0187a5c38586caaca15f23962":[3,0,176,2],
"a03517.html#aa84b42d5170cfacc9defecbddfcf5249":[3,0,176,1],
"a03521.html":[3,0,177],
"a03521.html#aa9ead758212d88f69047e9539623e678":[3,0,177,1],
"a03521.html#ab19740d8e098ad67f7750b24823ef687":[3,0,177,0],
"a03521.html#ac306903f85909c23a19dc6119cfac42a":[3,0,177,3],
"a03521.html#ad9bd8f42a4b007c527393cd3045c7138":[3,0,177,2],
"a03525.html":[3,0,92],
"a03525.html#a0b476e9e0187e2fd102e02b2ff3fed47":[3,0,92,0],
"a03525.html#a2b64224633731cbd4523d48a988d481a":[3,0,92,1],
"a03525.html#a338fb1f7a1680bc92f5ad8881ddb9522":[3,0,92,2],
"a03525.html#ad8f45eedc4f82728b0d7505564a9ffe6":[3,0,92,3],
"a03529.html":[3,0,93],
"a03529.html#a66e6bebe0863957f666c1679daa828a5":[3,0,93,2],
"a03529.html#a83ae7b79f4cd08c2dc07d1b19d03eade":[3,0,93,3],
"a03529.html#af9c27894b23469e295c862b59202b5f4":[3,0,93,0],
"a03529.html#afba36d87e574a73b4d825014503350df":[3,0,93,1],
"a03533.html":[3,0,20],
"a03533.html#a08dd4d6fcc1da9406d8096065fc8ea75":[3,0,20,0],
"a03533.html#a164cccc0e3f524440846217eceaa11e8":[3,0,20,2],
"a03533.html#aa726f021c58a80e0f37efd7d8e613386":[3,0,20,3],
"a03533.html#af5a8f1d11ac3da3db8f4ba7344434191":[3,0,20,1],
"a03537.html":[3,0,21],
"a03537.html#a1c95a8f32274aa4858613610d3b9123d":[3,0,21,0],
"a03537.html#a201e982a46b577efa258d73da49caa5a":[3,0,21,3],
"a03537.html#a61e01176f3b8ad1558fffac0d3399232":[3,0,21,2],
"a03537.html#ab1c53503a257bee00190ab4875723dbe":[3,0,21,1],
"a03541.html":[3,0,188],
"a03541.html#a8749d3942ed5ea31643d81ad5ef3413f":[3,0,188,2],
"a03541.html#a89152ffe845df71ca1efa07cd3442f55":[3,0,188,0],
"a03541.html#aca472f0390178c41834e46223efd862e":[3,0,188,3],
"a03541.html#acf4612daa06ecc59d05310921d4d82c1":[3,0,188,1],
"a03545.html":[3,0,189],
"a03545.html#a375dc887a36b83d670078cab8e284ddf":[3,0,189,0],
"a03545.html#a7430f1b7a8b4541df4c99c8310494aff":[3,0,189,2],
"a03545.html#aa6c66df4706cea674b68e6633cd00ecf":[3,0,189,1],
"a03545.html#afc982a45376a2d614fb509cbbfa7df56":[3,0,189,3]
};
| stweil/tesseract-ocr.github.io | 4.00.00dev/navtreeindex37.js | JavaScript | apache-2.0 | 13,365 |
// Changes XML to JSON
exports.xml2json = function(xml){
return xmlToJson(xml);
};
function xmlToJson(xml) {
// Create the return object
var obj = {};
if (xml.nodeType == 1) { // element
// do attributes
if (xml.attributes.length > 0) {
obj["@attributes"] = {};
for (var j = 0; j < xml.attributes.length; j++) {
var attribute = xml.attributes.item(j);
obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
}
}
} else if (xml.nodeType == 3) { // text
obj = xml.nodeValue;
}
// do children
if (xml.hasChildNodes()) {
for(var i = 0; i < xml.childNodes.length; i++) {
var item = xml.childNodes.item(i);
var nodeName = item.nodeName;
if (typeof(obj[nodeName]) == "undefined") {
obj[nodeName] = xmlToJson(item);
} else {
if (typeof(obj[nodeName].push) == "undefined") {
var old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(xmlToJson(item));
}
}
}
return obj;
}; | aremox/RadioAdaja | app/lib/xmlToJson.js | JavaScript | apache-2.0 | 991 |
/* =============================================================
* bootstrap-collapse.js v2.2.2
* http://twitter.github.com/bootstrap/javascript.html#collapse
* =============================================================
* Copyright 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============================================================ */
!function ($) {
"use strict"; // jshint ;_;
/* COLLAPSE PUBLIC CLASS DEFINITION
* ================================ */
var Collapse = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, $.fn.collapse.defaults, options)
if (this.options.parent) {
this.$parent = $(this.options.parent)
}
this.options.toggle && this.toggle()
}
Collapse.prototype = {
constructor: Collapse
, dimension: function () {
var hasWidth = this.$element.hasClass('width')
return hasWidth ? 'width' : 'height'
}
, show: function () {
var dimension
, scroll
, actives
, hasData
if (this.transitioning) return
dimension = this.dimension()
scroll = $.camelCase(['scroll', dimension].join('-'))
actives = this.$parent && this.$parent.find('> .accordion-group > .in')
if (actives && actives.length) {
hasData = actives.data('collapse')
if (hasData && hasData.transitioning) return
actives.collapse('hide')
hasData || actives.data('collapse', null)
}
this.$element[dimension](0)
this.transition('addClass', $.Event('show'), 'shown')
$.support.transition && this.$element[dimension](this.$element[0][scroll])
}
, hide: function () {
var dimension
if (this.transitioning) return
dimension = this.dimension()
this.reset(this.$element[dimension]())
this.transition('removeClass', $.Event('hide'), 'hidden')
this.$element[dimension](0)
}
, reset: function (size) {
var dimension = this.dimension()
this.$element
.removeClass('collapse')
[dimension](size || 'auto')
[0].offsetWidth
this.$element[size !== null ? 'addClass' : 'removeClass']('collapse')
return this
}
, transition: function (method, startEvent, completeEvent) {
var that = this
, complete = function () {
if (startEvent.type == 'show') that.reset()
that.transitioning = 0
that.$element.trigger(completeEvent)
}
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
this.transitioning = 1
this.$element[method]('in')
$.support.transition && this.$element.hasClass('collapse') ?
this.$element.one($.support.transition.end, complete) :
complete()
}
, toggle: function () {
this[this.$element.hasClass('in') ? 'hide' : 'show']()
}
}
/* COLLAPSE PLUGIN DEFINITION
* ========================== */
var old = $.fn.collapse
$.fn.collapse = function (option) {
return this.each(function () {
var $this = $(this)
, data = $this.data('collapse')
, options = typeof option == 'object' && option
if (!data) $this.data('collapse', (data = new Collapse(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.collapse.defaults = {
toggle: true
}
$.fn.collapse.Constructor = Collapse
/* COLLAPSE NO CONFLICT
* ==================== */
$.fn.collapse.noConflict = function () {
$.fn.collapse = old
return this
}
/* COLLAPSE DATA-API
* ================= */
$(document).on('click.collapse.data-api', '[data-toggle=collapse]', function (e) {
var $this = $(this), href
, target = $this.attr('data-target')
|| e.preventDefault()
|| (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7
, option = $(target).data('collapse') ? 'toggle' : $this.data()
$this[$(target).hasClass('in') ? 'addClass' : 'removeClass']('collapsed')
$(target).collapse(option)
})
}(window.jQuery);
| michaelcouck/ikube | code/war/src/main/webapp/assets/javascripts/bootstrap/bootstrap-collapse.js | JavaScript | apache-2.0 | 4,620 |
import {
GET_COMMENTS,
GET_COMMENT,
SUBMIT_VOTE_COMMENT,
DELETE_COMMENT,
EDIT_COMMENT,
ADD_COMMENT,
} from '../actions';
import _ from 'lodash';
function commentsReducer(state = {}, action) {
switch (action.type) {
case GET_COMMENTS:
let comments = _.mapKeys(
_.orderBy(action.payload.data, 'voteScore', 'desc'),
'id',
);
return {
...state,
...comments,
};
case GET_COMMENT:
return action.payload.data;
case SUBMIT_VOTE_COMMENT:
let {id, option} = action.payload;
let newScore =
option === 'upVote' ? state[id].voteScore + 1 : state[id].voteScore - 1;
return {
...state,
[id]: {...state[id], voteScore: newScore},
};
case DELETE_COMMENT:
return _.omit(state, [action.payload]);
case EDIT_COMMENT:
return state;
case ADD_COMMENT:
return state;
default:
return state;
}
}
export default commentsReducer;
| rtaibah/readable | src/reducers/Comments.js | JavaScript | apache-2.0 | 989 |
/**
* @license Copyright 2017 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.
*/
/*
* @fileoverview This audit determines if the images used are sufficiently larger
* than JPEG compressed images without metadata at quality 85.
*/
'use strict';
const ByteEfficiencyAudit = require('./byte-efficiency-audit');
const URL = require('../../lib/url-shim');
const IGNORE_THRESHOLD_IN_BYTES = 4096;
class UsesOptimizedImages extends ByteEfficiencyAudit {
/**
* @return {!AuditMeta}
*/
static get meta() {
return {
name: 'uses-optimized-images',
description: 'Optimize images',
informative: true,
helpText: 'Optimized images load faster and consume less cellular data. ' +
'[Learn more](https://developers.google.com/web/tools/lighthouse/audits/optimize-images).',
requiredArtifacts: ['OptimizedImages', 'devtoolsLogs'],
};
}
/**
* @param {{originalSize: number, webpSize: number, jpegSize: number}} image
* @param {string} type
* @return {{bytes: number, percent: number}}
*/
static computeSavings(image, type) {
const bytes = image.originalSize - image[type + 'Size'];
const percent = 100 * bytes / image.originalSize;
return {bytes, percent};
}
/**
* @param {!Artifacts} artifacts
* @return {!Audit.HeadingsResult}
*/
static audit_(artifacts) {
const images = artifacts.OptimizedImages;
const failedImages = [];
const results = [];
images.forEach(image => {
if (image.failed) {
failedImages.push(image);
return;
} else if (/(jpeg|bmp)/.test(image.mimeType) === false ||
image.originalSize < image.jpegSize + IGNORE_THRESHOLD_IN_BYTES) {
return;
}
const url = URL.elideDataURI(image.url);
const jpegSavings = UsesOptimizedImages.computeSavings(image, 'jpeg');
results.push({
url,
fromProtocol: image.fromProtocol,
isCrossOrigin: !image.isSameOrigin,
preview: {url: image.url, mimeType: image.mimeType, type: 'thumbnail'},
totalBytes: image.originalSize,
wastedBytes: jpegSavings.bytes,
});
});
let debugString;
if (failedImages.length) {
const urls = failedImages.map(image => URL.getURLDisplayName(image.url));
debugString = `Lighthouse was unable to decode some of your images: ${urls.join(', ')}`;
}
const headings = [
{key: 'preview', itemType: 'thumbnail', text: ''},
{key: 'url', itemType: 'url', text: 'URL'},
{key: 'totalKb', itemType: 'text', text: 'Original'},
{key: 'potentialSavings', itemType: 'text', text: 'Potential Savings'},
];
return {
debugString,
results,
headings,
};
}
}
module.exports = UsesOptimizedImages;
| tkadlec/lighthouse | lighthouse-core/audits/byte-efficiency/uses-optimized-images.js | JavaScript | apache-2.0 | 3,287 |
function drawCanvas() {
var canvas = document.getElementById('canvas-container');
var context = canvas.getContext("2d");
var grd = context.createLinearGradient(0,0,170,0);
grd.addColorStop(0,"red");
grd.addColorStop(0.5,"blue");
grd.addColorStop(1,"green");
context.fillStyle = grd;
context.lineWidth = 50;
context.lineJoin="round";
context.beginPath();
context.arc(100,100,50,0,1.5*Math.PI);
context.closePath();
context.stroke();
context.fill();
}
$(function() {
drawCanvas();
}); | hongqingbin/hongqingbin.github.io | javascripts/app/journey-of-h5.js | JavaScript | apache-2.0 | 543 |
var dataCacheName = 'Jblog-v1';
var cacheName = 'Jblog-1';
var filesToCache = [
'/',
'/index.html'
];
self.addEventListener('install', function(e) {
console.log('[ServiceWorker] Install');
e.waitUntil(
caches.open(cacheName).then(function(cache) {
console.log('[ServiceWorker] Caching app shell');
return cache.addAll(filesToCache);
})
);
});
self.addEventListener('activate', function(e) {
console.log('[ServiceWorker] Activate');
e.waitUntil(
caches.keys().then(function(keyList) {
return Promise.all(keyList.map(function(key) {
if (key !== cacheName && key !== dataCacheName) {
console.log('[ServiceWorker] Removing old cache', key);
return caches.delete(key);
}
}));
})
);
return self.clients.claim();
});
self.addEventListener('fetch', function(e) {
console.log('[Service Worker] Fetch', e.request.url);
e.respondWith(
caches.match(e.request).then(function(response) {
return response || fetch(e.request);
})
);
});
| cfaddict/jhipster-course | jblog/src/main/webapp/sw.js | JavaScript | apache-2.0 | 1,152 |
/**
* Created with JetBrains WebStorm.
* User: k-nkgwj
* Date: 13/01/21
* Time: 3:29
* To change this template use File | Settings | File Templates.
*/
var OutputBox = (function () {
function OutputBox(selector) {
this.jqueryObject = $(selector);
this.enabled = true;
}
OutputBox.prototype.message = function (subject, body) {
if (!this.enabled) {
return;
}
$(this.jqueryObject).prepend($('<p>').addClass('message').append(
$('<span>').addClass('message-subject').html(subject)
).append(
$('<span>').addClass('message-body').html(body)
));
};
OutputBox.prototype.log = function (msg) {
if (!this.enabled) {
return;
}
$(this.jqueryObject).prepend($('<p>').addClass('system-log').html(Array.apply(null, arguments).join('')));
};
return OutputBox;
})();
| nkgwj/hub_test | js/outputbox.js | JavaScript | apache-2.0 | 879 |
/*
AngularJS v1.2.8-build.2085+sha.1b0718b
(c) 2010-2014 Google, Inc. http://angularjs.org
License: MIT
*/
(function(h,e,A){'use strict';function u(w,q,k){return{restrict:"ECA",terminal:!0,priority:400,transclude:"element",link:function(a,c,b,f,n){function y(){l&&(l.$destroy(),l=null);g&&(k.leave(g),g=null)}function v(){var b=w.current&&w.current.locals;if(e.isDefined(b&&b.$template)){var b=a.$new(),f=w.current;g=n(b,function(d){k.enter(d,null,g||c,function(){!e.isDefined(t)||t&&!a.$eval(t)||q()});y()});l=f.scope=b;l.$emit("$viewContentLoaded");l.$eval(h)}else y()}var l,g,t=b.autoscroll,h=b.onload||"";
a.$on("$routeChangeSuccess",v);v()}}}function z(e,h,k){return{restrict:"ECA",priority:-400,link:function(a,c){var b=k.current,f=b.locals;c.html(f.$template);var n=e(c.contents());b.controller&&(f.$scope=a,f=h(b.controller,f),b.controllerAs&&(a[b.controllerAs]=f),c.data("$ngControllerController",f),c.children().data("$ngControllerController",f));n(a)}}}h=e.module("ngRoute",["ng"]).provider("$route",function(){function h(a,c){return e.extend(new (e.extend(function(){},{prototype:a})),c)}function q(a,
e){var b=e.caseInsensitiveMatch,f={originalPath:a,regexp:a},h=f.keys=[];a=a.replace(/([().])/g,"\\$1").replace(/(\/)?:(\w+)([\?|\*])?/g,function(a,e,b,c){a="?"===c?c:null;c="*"===c?c:null;h.push({name:b,optional:!!a});e=e||"";return""+(a?"":e)+"(?:"+(a?e:"")+(c&&"(.+?)"||"([^/]+)")+(a||"")+")"+(a||"")}).replace(/([\/$\*])/g,"\\$1");f.regexp=RegExp("^"+a+"$",b?"i":"");return f}var k={};this.when=function(a,c){k[a]=e.extend({reloadOnSearch:!0},c,a&&q(a,c));if(a){var b="/"==a[a.length-1]?a.substr(0,
a.length-1):a+"/";k[b]=e.extend({redirectTo:a},q(b,c))}return this};this.otherwise=function(a){this.when(null,a);return this};this.$get=["$rootScope","$location","$routeParams","$q","$injector","$http","$templateCache","$sce",function(a,c,b,f,n,q,v,l){function g(){var d=t(),m=r.current;if(d&&m&&d.$$route===m.$$route&&e.equals(d.pathParams,m.pathParams)&&!d.reloadOnSearch&&!x)m.params=d.params,e.copy(m.params,b),a.$broadcast("$routeUpdate",m);else if(d||m)x=!1,a.$broadcast("$routeChangeStart",d,m),
(r.current=d)&&d.redirectTo&&(e.isString(d.redirectTo)?c.path(u(d.redirectTo,d.params)).search(d.params).replace():c.url(d.redirectTo(d.pathParams,c.path(),c.search())).replace()),f.when(d).then(function(){if(d){var a=e.extend({},d.resolve),c,b;e.forEach(a,function(d,c){a[c]=e.isString(d)?n.get(d):n.invoke(d)});e.isDefined(c=d.template)?e.isFunction(c)&&(c=c(d.params)):e.isDefined(b=d.templateUrl)&&(e.isFunction(b)&&(b=b(d.params)),b=l.getTrustedResourceUrl(b),e.isDefined(b)&&(d.loadedTemplateUrl=
b,c=q.get(b,{cache:v}).then(function(a){return a.data})));e.isDefined(c)&&(a.$template=c);return f.all(a)}}).then(function(c){d==r.current&&(d&&(d.locals=c,e.copy(d.params,b)),a.$broadcast("$routeChangeSuccess",d,m))},function(c){d==r.current&&a.$broadcast("$routeChangeError",d,m,c)})}function t(){var a,b;e.forEach(k,function(f,k){var p;if(p=!b){var s=c.path();p=f.keys;var l={};if(f.regexp)if(s=f.regexp.exec(s)){for(var g=1,q=s.length;g<q;++g){var n=p[g-1],r="string"==typeof s[g]?decodeURIComponent(s[g]):
s[g];n&&r&&(l[n.name]=r)}p=l}else p=null;else p=null;p=a=p}p&&(b=h(f,{params:e.extend({},c.search(),a),pathParams:a}),b.$$route=f)});return b||k[null]&&h(k[null],{params:{},pathParams:{}})}function u(a,c){var b=[];e.forEach((a||"").split(":"),function(a,d){if(0===d)b.push(a);else{var e=a.match(/(\w+)(.*)/),f=e[1];b.push(c[f]);b.push(e[2]||"");delete c[f]}});return b.join("")}var x=!1,r={routes:k,reload:function(){x=!0;a.$evalAsync(g)}};a.$on("$locationChangeSuccess",g);return r}]});h.provider("$routeParams",
function(){this.$get=function(){return{}}});h.directive("ngView",u);h.directive("ngView",z);u.$inject=["$route","$anchorScroll","$animate"];z.$inject=["$compile","$controller","$route"]})(window,window.angular);
| LuukvE/PieChecker | client/scripts/libs/angular-route.min.js | JavaScript | apache-2.0 | 3,862 |
wesabe.provide("fi-scripts.com.citibank.mfa", {
dispatch: function() {
if (page.present(e.mfa.indicator)) {
action.answerSecurityQuestions();
return false;
}
},
actions: {
},
elements: {
mfa: {
indicator: [
'//*[has-class("jrspageHeader")][contains(string(.), "Authorization Required")]',
'//form[@action="/US/JRS/mfa/cq/ValidateCQ.do"]',
],
cin: [ // ATM/Debit Card # (CIN)
'//input[@type="text"][@name="cin"]',
],
pin: [ // PIN
'//input[@type="password"][@name="pin"]',
],
continueButton: [
'//input[@type="image"][contains(@src, "cont_btn")]',
'//input[@type="submit" or @type="image"]',
],
},
security: {
questions: [
'//form[contains(@action, "mfa")]//*[has-class("jrsnoteText")]/b/text()',
],
answers: [
'//form[contains(@action, "mfa")]//input[@type="text" or @type="password"]',
],
continueButton: [
'//input[@type="image"][contains(@src, "cont_btn")]',
'//input[@type="submit" or @type="image"]',
],
},
},
});
| wesabe/ssu | application/chrome/content/wesabe/fi-scripts/com/citibank/mfa.js | JavaScript | apache-2.0 | 1,139 |
const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CopyWebpackPlugin = require('copy-webpack-plugin');
var babelOptions = {
presets: [
["@babel/preset-env", {
"targets": {
"browsers": ["last 2 versions"]
},
"modules": false,
"useBuiltIns": "usage",
"corejs": 3,
// This saves around 4KB in minified bundle (not gzipped)
// "loose": true,
}]
],
};
var commonPlugins = [
new HtmlWebpackPlugin({
filename: './index.html',
template: './src/index.html'
})
];
module.exports = (env, options) => {
// If no mode has been defined, default to `development`
if (options.mode === undefined)
options.mode = "development";
var isProduction = options.mode === "production";
console.log("Bundling for " + (isProduction ? "production" : "development") + "...");
return {
devtool: undefined,
mode: options.mode,
entry: {
demo: [
"@babel/polyfill",
'./src/App.fs.js',
'./src/scss/main.scss'
]
},
output: {
path: path.join(__dirname, './output'),
filename: isProduction ? '[name].[chunkhash].js' : '[name].js'
},
plugins: isProduction ?
commonPlugins.concat([
new MiniCssExtractPlugin({
filename: 'style.css'
}),
new CopyWebpackPlugin({
patterns: [
{ from: './static' }
]
})
])
: commonPlugins.concat([
new webpack.HotModuleReplacementPlugin(),
]),
devServer: {
contentBase: './static/',
publicPath: "/",
port: 8080,
hot: true,
inline: true
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: babelOptions
},
},
{
test: /\.(sass|scss|css)$/,
use: [
isProduction
? MiniCssExtractPlugin.loader
: 'style-loader',
'css-loader',
'sass-loader',
],
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)(\?.*$|$)/,
use: ["file-loader"]
}
]
}
};
}
| MangelMaxime/Fulma | templates/Content/webpack.config.js | JavaScript | apache-2.0 | 3,089 |
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// MODULES //
var bench = require( '@stdlib/bench' );
var fromCodePoint = require( '@stdlib/string/from-code-point' );
var pkg = require( './../package.json' ).name;
var toJSON = require( './../lib' );
// MAIN //
bench( pkg, function benchmark( b ) {
var err;
var o;
var i;
err = new Error( 'beep' );
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
err.message = 'be-'+fromCodePoint( (i%25)+97 )+' -ep';
o = toJSON( err );
if ( typeof o !== 'object' ) {
b.fail( 'should return an object' );
}
}
b.toc();
if ( typeof o !== 'object' ) {
b.fail( 'should return an object' );
}
b.pass( 'benchmark finished' );
b.end();
});
| stdlib-js/stdlib | lib/node_modules/@stdlib/error/to-json/benchmark/benchmark.js | JavaScript | apache-2.0 | 1,283 |
describe('adbutler adapter tests', function () {
var expect = require('chai').expect;
var adapter = require('modules/adbutlerBidAdapter');
var adLoader = require('src/adloader');
var bidmanager = require('src/bidmanager');
describe('creation of bid url', function () {
var stubLoadScript;
beforeEach(function () {
stubLoadScript = sinon.stub(adLoader, 'loadScript');
});
afterEach(function () {
stubLoadScript.restore();
});
if (typeof ($$PREBID_GLOBAL$$._bidsReceived) === 'undefined') {
$$PREBID_GLOBAL$$._bidsReceived = [];
}
if (typeof ($$PREBID_GLOBAL$$._bidsRequested) === 'undefined') {
$$PREBID_GLOBAL$$._bidsRequested = [];
}
if (typeof ($$PREBID_GLOBAL$$._adsReceived) === 'undefined') {
$$PREBID_GLOBAL$$._adsReceived = [];
}
it('should be called', function () {
var params = {
bidderCode: 'adbutler',
bids: [
{
bidId: '3c9408cdbf2f68',
sizes: [[300, 250]],
bidder: 'adbutler',
params: {
accountID: '167283',
zoneID: '210093'
},
requestId: '10b327aa396609',
placementCode: '/123456/header-bid-tag-1'
}
]
};
adapter().callBids(params);
sinon.assert.called(stubLoadScript);
});
it('should populate the keyword', function() {
var params = {
bidderCode: 'adbutler',
bids: [
{
bidId: '3c9408cdbf2f68',
sizes: [[300, 250]],
bidder: 'adbutler',
params: {
accountID: '167283',
zoneID: '210093',
keyword: 'fish'
},
requestId: '10b327aa396609',
placementCode: '/123456/header-bid-tag-1'
}
]
};
adapter().callBids(params);
var requestURI = stubLoadScript.getCall(0).args[0];
expect(requestURI).to.have.string(';kw=fish;');
});
it('should use custom domain string', function() {
var params = {
bidderCode: 'adbutler',
bids: [
{
bidId: '3c9408cdbf2f68',
sizes: [[300, 250]],
bidder: 'adbutler',
params: {
accountID: '107878',
zoneID: '86133',
domain: 'servedbyadbutler.com.dan.test'
},
requestId: '10b327aa396609',
placementCode: '/123456/header-bid-tag-1'
}
]
};
adapter().callBids(params);
var requestURI = stubLoadScript.getCall(0).args[0];
expect(requestURI).to.have.string('.dan.test');
});
});
describe('bid responses', function() {
it('should return complete bid response', function() {
var stubAddBidResponse = sinon.stub(bidmanager, 'addBidResponse');
var params = {
bidderCode: 'adbutler',
bidder: 'adbutler',
bids: [
{
bidId: '3c94018cdbf2f68-1',
sizes: [[300, 250]],
bidder: 'adbutler',
params: {
accountID: '167283',
zoneID: '210093',
},
requestId: '10b327aa396609',
placementCode: '/123456/header-bid-tag-1'
}
]
};
var response = {
status: 'SUCCESS',
account_id: 167283,
zone_id: 210093,
cpm: 1.5,
width: 300,
height: 250,
place: 0
};
adapter().callBids(params);
var adUnits = new Array();
var unit = new Object();
unit.bids = params.bids;
unit.code = '/123456/header-bid-tag-1';
unit.sizes = [[300, 250]];
adUnits.push(unit);
if (typeof ($$PREBID_GLOBAL$$._bidsRequested) === 'undefined') {
$$PREBID_GLOBAL$$._bidsRequested = [params];
} else {
$$PREBID_GLOBAL$$._bidsRequested.push(params);
}
$$PREBID_GLOBAL$$.adUnits = adUnits;
$$PREBID_GLOBAL$$.adbutlerCB(response);
var bidPlacementCode1 = stubAddBidResponse.getCall(0).args[0];
var bidObject1 = stubAddBidResponse.getCall(0).args[1];
expect(bidPlacementCode1).to.equal('/123456/header-bid-tag-1');
expect(bidObject1.getStatusCode()).to.equal(1);
expect(bidObject1.bidderCode).to.equal('adbutler');
expect(bidObject1.cpm).to.equal(1.5);
expect(bidObject1.width).to.equal(300);
expect(bidObject1.height).to.equal(250);
stubAddBidResponse.restore();
});
it('should return empty bid response', function() {
var stubAddBidResponse = sinon.stub(bidmanager, 'addBidResponse');
var params = {
bidderCode: 'adbutler',
bids: [
{
bidId: '3c9408cdbf2f68-2',
sizes: [[300, 250]],
bidder: 'adbutler',
params: {
accountID: '167283',
zoneID: '210085',
},
requestId: '10b327aa396609',
placementCode: '/123456/header-bid-tag-1'
}
]
};
var response = {
status: 'NO_ELIGIBLE_ADS',
zone_id: 210085,
width: 728,
height: 90,
place: 0
};
adapter().callBids(params);
var adUnits = new Array();
var unit = new Object();
unit.bids = params.bids;
unit.code = '/123456/header-bid-tag-1';
unit.sizes = [[300, 250]];
adUnits.push(unit);
if (typeof ($$PREBID_GLOBAL$$._bidsRequested) === 'undefined') {
$$PREBID_GLOBAL$$._bidsRequested = [params];
} else {
$$PREBID_GLOBAL$$._bidsRequested.push(params);
}
$$PREBID_GLOBAL$$.adUnits = adUnits;
$$PREBID_GLOBAL$$.adbutlerCB(response);
var bidPlacementCode1 = stubAddBidResponse.getCall(0).args[0];
var bidObject1 = stubAddBidResponse.getCall(0).args[1];
expect(bidPlacementCode1).to.equal('/123456/header-bid-tag-1');
expect(bidObject1.getStatusCode()).to.equal(2);
expect(bidObject1.bidderCode).to.equal('adbutler');
stubAddBidResponse.restore();
});
it('should return empty bid response on incorrect size', function() {
var stubAddBidResponse = sinon.stub(bidmanager, 'addBidResponse');
var params = {
bidderCode: 'adbutler',
bids: [
{
bidId: '3c9408cdbf2f68-3',
sizes: [[300, 250]],
bidder: 'adbutler',
params: {
accountID: '167283',
zoneID: '210085',
},
requestId: '10b327aa396609',
placementCode: '/123456/header-bid-tag-1'
}
]
};
var response = {
status: 'SUCCESS',
account_id: 167283,
zone_id: 210085,
cpm: 1.5,
width: 728,
height: 90,
place: 0
};
adapter().callBids(params);
var adUnits = new Array();
var unit = new Object();
unit.bids = params.bids;
unit.code = '/123456/header-bid-tag-1';
unit.sizes = [[300, 250]];
adUnits.push(unit);
if (typeof ($$PREBID_GLOBAL$$._bidsRequested) === 'undefined') {
$$PREBID_GLOBAL$$._bidsRequested = [params];
} else {
$$PREBID_GLOBAL$$._bidsRequested.push(params);
}
$$PREBID_GLOBAL$$.adUnits = adUnits;
$$PREBID_GLOBAL$$.adbutlerCB(response);
var bidObject1 = stubAddBidResponse.getCall(0).args[1];
expect(bidObject1.getStatusCode()).to.equal(2);
stubAddBidResponse.restore();
});
it('should return empty bid response with CPM too low', function() {
var stubAddBidResponse = sinon.stub(bidmanager, 'addBidResponse');
var params = {
bidderCode: 'adbutler',
bids: [
{
bidId: '3c9408cdbf2f68-4',
sizes: [[300, 250]],
bidder: 'adbutler',
params: {
accountID: '167283',
zoneID: '210093',
minCPM: '5.00'
},
requestId: '10b327aa396609',
placementCode: '/123456/header-bid-tag-1'
}
]
};
var response = {
status: 'SUCCESS',
account_id: 167283,
zone_id: 210093,
cpm: 1.5,
width: 300,
height: 250,
place: 0
};
adapter().callBids(params);
var adUnits = new Array();
var unit = new Object();
unit.bids = params.bids;
unit.code = '/123456/header-bid-tag-1';
unit.sizes = [[300, 250]];
adUnits.push(unit);
if (typeof ($$PREBID_GLOBAL$$._bidsRequested) === 'undefined') {
$$PREBID_GLOBAL$$._bidsRequested = [params];
} else {
$$PREBID_GLOBAL$$._bidsRequested.push(params);
}
$$PREBID_GLOBAL$$.adUnits = adUnits;
$$PREBID_GLOBAL$$.adbutlerCB(response);
var bidObject1 = stubAddBidResponse.getCall(0).args[1];
expect(bidObject1.getStatusCode()).to.equal(2);
stubAddBidResponse.restore();
});
it('should return empty bid response with CPM too high', function() {
var stubAddBidResponse = sinon.stub(bidmanager, 'addBidResponse');
var params = {
bidderCode: 'adbutler',
bids: [
{
bidId: '3c9408cdbf2f68-5',
sizes: [[300, 250]],
bidder: 'adbutler',
params: {
accountID: '167283',
zoneID: '210093',
maxCPM: '1.00'
},
requestId: '10b327aa396609',
placementCode: '/123456/header-bid-tag-1'
}
]
};
var response = {
status: 'SUCCESS',
account_id: 167283,
zone_id: 210093,
cpm: 1.5,
width: 300,
height: 250,
place: 0
};
adapter().callBids(params);
var adUnits = new Array();
var unit = new Object();
unit.bids = params.bids;
unit.code = '/123456/header-bid-tag-1';
unit.sizes = [[300, 250]];
adUnits.push(unit);
if (typeof ($$PREBID_GLOBAL$$._bidsRequested) === 'undefined') {
$$PREBID_GLOBAL$$._bidsRequested = [params];
} else {
$$PREBID_GLOBAL$$._bidsRequested.push(params);
}
$$PREBID_GLOBAL$$.adUnits = adUnits;
$$PREBID_GLOBAL$$.adbutlerCB(response);
var bidObject1 = stubAddBidResponse.getCall(0).args[1];
expect(bidObject1.getStatusCode()).to.equal(2);
stubAddBidResponse.restore();
});
});
describe('ad code', function() {
it('should be populated', function() {
var stubAddBidResponse = sinon.stub(bidmanager, 'addBidResponse');
var params = {
bidderCode: 'adbutler',
bids: [
{
bidId: '3c9408cdbf2f68-6',
sizes: [[300, 250]],
bidder: 'adbutler',
params: {
accountID: '167283',
zoneID: '210093'
},
requestId: '10b327aa396609',
placementCode: '/123456/header-bid-tag-1'
}
]
};
var response = {
status: 'SUCCESS',
account_id: 167283,
zone_id: 210093,
cpm: 1.5,
width: 300,
height: 250,
place: 0,
ad_code: '<img src="http://image.source.com/img" alt="" title="" border="0" width="300" height="250">'
};
adapter().callBids(params);
var adUnits = new Array();
var unit = new Object();
unit.bids = params.bids;
unit.code = '/123456/header-bid-tag-1';
unit.sizes = [[300, 250]];
adUnits.push(unit);
if (typeof ($$PREBID_GLOBAL$$._bidsRequested) === 'undefined') {
$$PREBID_GLOBAL$$._bidsRequested = [params];
} else {
$$PREBID_GLOBAL$$._bidsRequested.push(params);
}
$$PREBID_GLOBAL$$.adUnits = adUnits;
$$PREBID_GLOBAL$$.adbutlerCB(response);
var bidObject1 = stubAddBidResponse.getCall(0).args[1];
expect(bidObject1.getStatusCode()).to.equal(1);
expect(bidObject1.ad).to.have.length.above(1);
stubAddBidResponse.restore();
});
it('should contain tracking pixels', function() {
var stubAddBidResponse = sinon.stub(bidmanager, 'addBidResponse');
var params = {
bidderCode: 'adbutler',
bids: [
{
bidId: '3c9408cdbf2f68-7',
sizes: [[300, 250]],
bidder: 'adbutler',
params: {
accountID: '167283',
zoneID: '210093'
},
requestId: '10b327aa396609',
placementCode: '/123456/header-bid-tag-1'
}
]
};
var response = {
status: 'SUCCESS',
account_id: 167283,
zone_id: 210093,
cpm: 1.5,
width: 300,
height: 250,
place: 0,
ad_code: '<img src="http://image.source.com/img" alt="" title="" border="0" width="300" height="250">',
tracking_pixels: [
'http://tracking.pixel.com/params=info'
]
};
adapter().callBids(params);
var adUnits = new Array();
var unit = new Object();
unit.bids = params.bids;
unit.code = '/123456/header-bid-tag-1';
unit.sizes = [[300, 250]];
adUnits.push(unit);
if (typeof ($$PREBID_GLOBAL$$._bidsRequested) === 'undefined') {
$$PREBID_GLOBAL$$._bidsRequested = [params];
} else {
$$PREBID_GLOBAL$$._bidsRequested.push(params);
}
$$PREBID_GLOBAL$$.adUnits = adUnits;
$$PREBID_GLOBAL$$.adbutlerCB(response);
var bidObject1 = stubAddBidResponse.getCall(0).args[1];
expect(bidObject1.getStatusCode()).to.equal(1);
expect(bidObject1.ad).to.have.string('http://tracking.pixel.com/params=info');
stubAddBidResponse.restore();
});
});
});
| jbAdyoulike/Prebid.js | test/spec/modules/adbutlerBidAdapter_spec.js | JavaScript | apache-2.0 | 13,858 |
/**
* Copyright 2015 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.
*/
import {AmpDocSingle} from '../../src/service/ampdoc-impl';
import {
Viewport,
ViewportBindingDef,
ViewportBindingNatural_,
ViewportBindingNaturalIosEmbed_,
parseViewportMeta,
stringifyViewportMeta,
updateViewportMetaString,
} from '../../src/service/viewport-impl';
import {getStyle} from '../../src/style';
import {installPlatformService} from '../../src/service/platform-impl';
import {installTimerService} from '../../src/service/timer-impl';
import {installViewerService} from '../../src/service/viewer-impl';
import {loadPromise} from '../../src/event-helper';
import {setParentWindow} from '../../src/service';
import {toggleExperiment} from '../../src/experiments';
import {vsyncFor} from '../../src/vsync';
import * as sinon from 'sinon';
describe('Viewport', () => {
let sandbox;
let clock;
let viewport;
let binding;
let viewer;
let viewerMock;
let windowApi;
let ampdoc;
let viewerViewportHandler;
let updatedPaddingTop;
let viewportSize;
let vsyncTasks;
beforeEach(() => {
sandbox = sinon.sandbox.create();
clock = sandbox.useFakeTimers();
viewerViewportHandler = undefined;
viewer = {
isEmbedded: () => false,
getPaddingTop: () => 19,
onViewportEvent: handler => {
viewerViewportHandler = handler;
},
requestFullOverlay: () => {},
cancelFullOverlay: () => {},
postScroll: sandbox.spy(),
};
viewerMock = sandbox.mock(viewer);
windowApi = {
document: {
documentElement: {
style: {},
classList: {
add: function() {},
},
},
},
location: {},
navigator: window.navigator,
setTimeout: window.setTimeout,
clearTimeout: window.clearTimeout,
requestAnimationFrame: fn => window.setTimeout(fn, 16),
};
ampdoc = new AmpDocSingle(windowApi);
installTimerService(windowApi);
installPlatformService(windowApi);
installViewerService(windowApi);
binding = new ViewportBindingDef();
viewportSize = {width: 111, height: 222};
binding.getSize = () => {
return {width: viewportSize.width, height: viewportSize.height};
};
binding.getScrollTop = () => 17;
binding.getScrollLeft = () => 0;
updatedPaddingTop = undefined;
binding.updatePaddingTop = paddingTop => updatedPaddingTop = paddingTop;
viewport = new Viewport(ampdoc, binding, viewer);
viewport.fixedLayer_ = {update: () => {
return {then: callback => callback()};
}};
viewport.getSize();
// Use window since Animation by default will use window.
const vsync = vsyncFor(window);
vsyncTasks = [];
sandbox.stub(vsync, 'canAnimate').returns(true);
sandbox.stub(vsync, 'createAnimTask', (unusedContextNode, task) => {
return () => {
vsyncTasks.push(task);
};
});
});
afterEach(() => {
expect(vsyncTasks.length).to.equal(0);
viewerMock.verify();
sandbox.restore();
});
function runVsync() {
const tasks = vsyncTasks.slice(0);
vsyncTasks = [];
tasks.forEach(function(task) {
const state = {};
if (task.measure) {
task.measure(state);
}
task.mutate(state);
});
}
it('should pass through size and scroll', () => {
expect(viewport.getPaddingTop()).to.equal(19);
expect(updatedPaddingTop).to.equal(19);
expect(viewport.getSize().width).to.equal(111);
expect(viewport.getSize().height).to.equal(222);
expect(viewport.getTop()).to.equal(17);
expect(viewport.getRect().left).to.equal(0);
expect(viewport.getRect().top).to.equal(17);
expect(viewport.getRect().width).to.equal(111);
expect(viewport.getRect().height).to.equal(222);
});
it('should cache result for getRect()', () => {
assert.strictEqual(viewport.getRect(), viewport.getRect());
});
it('should invalidate getRect() cache after scroll', () => {
expect(viewport.getRect().top).to.equal(17);
// Scroll vertically.
binding.getScrollTop = () => 44;
viewport.scroll_();
expect(viewport.getRect().top).to.equal(44);
});
it('should invalidate getRect() cache after resize', () => {
expect(viewport.getRect().width).to.equal(111);
// Resize horizontally.
viewportSize.width = 112;
viewport.resize_();
expect(viewport.getRect().width).to.equal(112);
});
it('should not relayout on height resize', () => {
let changeEvent = null;
viewport.onChanged(event => {
changeEvent = event;
});
viewportSize.height = 223;
viewport.resize_();
expect(changeEvent).to.not.equal(null);
expect(changeEvent.relayoutAll).to.equal(false);
expect(changeEvent.velocity).to.equal(0);
});
it('should relayout on width resize', () => {
let changeEvent = null;
viewport.onChanged(event => {
changeEvent = event;
});
viewportSize.width = 112;
viewport.resize_();
expect(changeEvent).to.not.equal(null);
expect(changeEvent.relayoutAll).to.equal(true);
expect(changeEvent.velocity).to.equal(0);
});
it('should defer change event until fixed layer is complete', () => {
let changeEvent = null;
viewport.onChanged(event => {
changeEvent = event;
});
let fixedResolver;
const fixedPromise = new Promise(resolve => fixedResolver = resolve);
viewport.fixedLayer_ = {update: () => fixedPromise};
viewportSize.width = 112;
viewport.resize_();
expect(changeEvent).to.be.null;
fixedResolver();
return fixedPromise.then(() => {
expect(changeEvent).to.not.be.null;
});
});
it('should update padding when changed only', () => {
// Shouldn't call updatePaddingTop since it hasn't changed.
let bindingMock = sandbox.mock(binding);
viewerViewportHandler({paddingTop: 19});
bindingMock.verify();
// Should call updatePaddingTop.
bindingMock = sandbox.mock(binding);
viewport.fixedLayer_ = {updatePaddingTop: () => {}};
bindingMock.expects('updatePaddingTop').withArgs(0, true, 19).once();
viewerViewportHandler({paddingTop: 0});
bindingMock.verify();
});
it('should update padding for fixed layer', () => {
// Should call updatePaddingTop.
const bindingMock = sandbox.mock(binding);
bindingMock.expects('updatePaddingTop').withArgs(0, true, 19).once();
viewport.fixedLayer_ = {updatePaddingTop: () => {}};
const fixedLayerMock = sandbox.mock(viewport.fixedLayer_);
fixedLayerMock.expects('updatePaddingTop').withArgs(0).once();
viewerViewportHandler({paddingTop: 0});
bindingMock.verify();
fixedLayerMock.verify();
});
it('should update viewport when entering lightbox mode', () => {
viewport.vsync_ = {mutate: callback => callback()};
viewerMock.expects('requestFullOverlay').once();
const disableTouchZoomStub = sandbox.stub(viewport, 'disableTouchZoom');
const hideFixedLayerStub = sandbox.stub(viewport, 'hideFixedLayer');
const bindingMock = sandbox.mock(binding);
bindingMock.expects('updateLightboxMode').withArgs(true).once();
viewport.enterLightboxMode();
bindingMock.verify();
expect(disableTouchZoomStub.callCount).to.equal(1);
expect(hideFixedLayerStub.callCount).to.equal(1);
});
it('should update viewport when leaving lightbox mode', () => {
viewport.vsync_ = {mutate: callback => callback()};
viewerMock.expects('cancelFullOverlay').once();
const restoreOriginalTouchZoomStub = sandbox.stub(viewport,
'restoreOriginalTouchZoom');
const showFixedLayerStub = sandbox.stub(viewport, 'showFixedLayer');
const bindingMock = sandbox.mock(binding);
bindingMock.expects('updateLightboxMode').withArgs(false).once();
viewport.leaveLightboxMode();
bindingMock.verify();
expect(restoreOriginalTouchZoomStub.callCount).to.equal(1);
expect(showFixedLayerStub.callCount).to.equal(1);
});
it('should call binding.updateViewerViewport', () => {
const bindingMock = sandbox.mock(binding);
bindingMock.expects('updateViewerViewport').once();
viewerViewportHandler({paddingTop: 19});
bindingMock.verify();
});
it('should send scroll events', () => {
// 0 -> 6 -> 12 -> 16 -> 18
// scroll-10 scroll-20 scroll-30 2nd anim frame scroll-40
// when there's no scroll
expect(viewport.scrollAnimationFrameThrottled_).to.be.false;
expect(viewer.postScroll.callCount).to.equal(0);
// scroll to 10
viewport.getScrollTop = () => 10;
viewport.sendScrollMessage_();
expect(viewport.scrollAnimationFrameThrottled_).to.be.true;
expect(viewer.postScroll.callCount).to.equal(0);
// 6 ticks later, still during first animation frame
clock.tick(6);
expect(viewport.scrollAnimationFrameThrottled_).to.be.true;
// scroll to 20
viewport.getScrollTop = () => 20;
viewport.sendScrollMessage_();
expect(viewport.scrollAnimationFrameThrottled_).to.be.true;
expect(viewer.postScroll.callCount).to.equal(0);
// 6 ticks later, still during first animation frame
clock.tick(6);
expect(viewport.scrollAnimationFrameThrottled_).to.be.true;
// scroll to 30
viewport.getScrollTop = () => 30;
viewport.sendScrollMessage_();
expect(viewport.scrollAnimationFrameThrottled_).to.be.true;
expect(viewer.postScroll.callCount).to.equal(0);
// 6 ticks later, second animation frame starts
clock.tick(6);
expect(viewport.scrollAnimationFrameThrottled_).to.be.false;
expect(viewer.postScroll.callCount).to.equal(1);
expect(viewer.postScroll.withArgs(30).calledOnce).to.be.true;
// scroll to 40
viewport.getScrollTop = () => 40;
viewport.sendScrollMessage_();
expect(viewport.scrollAnimationFrameThrottled_).to.be.true;
expect(viewer.postScroll.callCount).to.equal(1);
});
it('should defer scroll events', () => {
let changeEvent = null;
let eventCount = 0;
viewport.onChanged(event => {
changeEvent = event;
eventCount++;
});
// when there's no scroll
expect(viewport.scrollTracking_).to.be.false;
// expect(changeEvent).to.equal(null);
expect(viewer.postScroll.callCount).to.equal(0);
// time 0: scroll to 34
// raf for viewer.postScroll, delay 36 ticks till raf for throttledScroll_
binding.getScrollTop = () => 34;
viewport.scroll_();
expect(viewport.scrollTracking_).to.be.true;
viewport.scroll_();
viewport.scroll_();
expect(changeEvent).to.equal(null);
expect(viewport.scrollTracking_).to.be.true;
clock.tick(8);
expect(changeEvent).to.equal(null);
clock.tick(8);
// time 16: scroll to 35
// call viewer.postScroll, raf for viewer.postScroll
expect(changeEvent).to.equal(null);
expect(viewer.postScroll.callCount).to.equal(1);
binding.getScrollTop = () => 35;
viewport.scroll_();
clock.tick(16);
// time 32: scroll to 35
// call viewer.postScroll, raf for viewer.postScroll
viewport.scroll_();
expect(changeEvent).to.equal(null);
expect(viewport.scrollTracking_).to.be.true;
expect(viewer.postScroll.callCount).to.equal(2);
// time 36:
// raf for throttledScroll_
clock.tick(16);
// time 48: scroll to 35
// call viewer.postScroll, call throttledScroll_
// raf for viewer.postScroll
// delay 36 ticks till raf for throttledScroll_
expect(viewport.scrollTracking_).to.be.false;
viewport.scroll_();
expect(changeEvent).to.not.equal(null);
expect(changeEvent.relayoutAll).to.equal(false);
expect(changeEvent.velocity).to.be.closeTo(0.020833, 1e-4);
expect(eventCount).to.equal(1);
expect(viewport.scrollTracking_).to.be.true;
expect(viewer.postScroll.callCount).to.equal(3);
changeEvent = null;
clock.tick(16);
// time 64:
// call viewer.postScroll
expect(viewer.postScroll.callCount).to.equal(4);
clock.tick(20);
// time 84:
// raf for throttledScroll_
clock.tick(16);
// time 100:
// call throttledScroll_
expect(changeEvent).to.not.equal(null);
expect(changeEvent.relayoutAll).to.equal(false);
expect(viewport.scrollTracking_).to.be.false;
expect(changeEvent.velocity).to.be.equal(0);
expect(eventCount).to.equal(2);
});
it('should update scroll pos and reset cache', () => {
const bindingMock = sandbox.mock(binding);
bindingMock.expects('setScrollTop').withArgs(117).once();
viewport.setScrollTop(117);
expect(viewport./*OK*/scrollTop_).to.be.null;
});
it('should change scrollTop for scrollIntoView and respect padding', () => {
const element = document.createElement('div');
const bindingMock = sandbox.mock(binding);
bindingMock.expects('getLayoutRect').withArgs(element)
.returns({top: 111}).once();
bindingMock.expects('setScrollTop').withArgs(111 - /* padding */ 19).once();
viewport.scrollIntoView(element);
bindingMock.verify();
});
it('should change scrollTop for animateScrollIntoView and respect ' +
'padding', () => {
const element = document.createElement('div');
const bindingMock = sandbox.mock(binding);
bindingMock.expects('getLayoutRect').withArgs(element)
.returns({top: 111}).once();
bindingMock.expects('setScrollTop').withArgs(111 - /* padding */ 19).once();
const duration = 1000;
const promise = viewport.animateScrollIntoView(element, 1000).then(() => {
bindingMock.verify();
});
clock.tick(duration);
runVsync();
return promise;
});
it('should not change scrollTop for animateScrollIntoView', () => {
const element = document.createElement('div');
const bindingMock = sandbox.mock(binding);
bindingMock.expects('getLayoutRect').withArgs(element)
.returns({top: 111}).once();
viewport.paddingTop_ = 0;
sandbox.stub(viewport, 'getScrollTop').returns(111);
bindingMock.expects('setScrollTop').withArgs(111).never();
const duration = 1000;
const promise = viewport.animateScrollIntoView(element, 1000).then(() => {
bindingMock.verify();
});
clock.tick(duration);
runVsync();
return promise;
});
it('should send cached scroll pos to getLayoutRect', () => {
const element = document.createElement('div');
const bindingMock = sandbox.mock(binding);
viewport.scrollTop_ = 111;
viewport.scrollLeft_ = 222;
bindingMock.expects('getLayoutRect').withArgs(element, 222, 111)
.returns('sentinel').once();
expect(viewport.getLayoutRect(element)).to.equal('sentinel');
});
it('should deletegate scrollWidth', () => {
const bindingMock = sandbox.mock(binding);
bindingMock.expects('getScrollWidth').withArgs().returns(111).once();
expect(viewport.getScrollWidth()).to.equal(111);
});
it('should deletegate scrollHeight', () => {
const bindingMock = sandbox.mock(binding);
bindingMock.expects('getScrollHeight').withArgs().returns(117).once();
expect(viewport.getScrollHeight()).to.equal(117);
});
it('should not set pan-y w/o experiment', () => {
// TODO(dvoytenko, #4894): Cleanup the experiment.
viewer.isEmbedded = () => true;
toggleExperiment(windowApi, 'pan-y', false);
viewport = new Viewport(ampdoc, binding, viewer);
expect(windowApi.document.documentElement.style['touch-action'])
.to.not.exist;
});
it('should not set pan-y when not embedded', () => {
// TODO(dvoytenko, #4894): Cleanup the experiment.
viewer.isEmbedded = () => false;
toggleExperiment(windowApi, 'pan-y', true);
viewport = new Viewport(ampdoc, binding, viewer);
expect(windowApi.document.documentElement.style['touch-action'])
.to.not.exist;
});
it('should set pan-y with experiment', () => {
// TODO(dvoytenko, #4894): Cleanup the experiment.
viewer.isEmbedded = () => true;
toggleExperiment(windowApi, 'pan-y', true);
viewport = new Viewport(ampdoc, binding, viewer);
expect(windowApi.document.documentElement.style['touch-action'])
.to.equal('pan-y');
});
it('should add class to HTML element with make-body-block experiment', () => {
viewer.isEmbedded = () => true;
toggleExperiment(windowApi, 'make-body-block', true);
const docElement = windowApi.document.documentElement;
const addStub = sandbox.stub(docElement.classList, 'add');
viewport = new Viewport(ampdoc, binding, viewer);
expect(addStub).to.be.calledWith('-amp-make-body-block');
});
describe('for child window', () => {
let viewport;
let bindingMock;
let iframe;
let iframeWin;
let ampdoc;
beforeEach(() => {
ampdoc = new AmpDocSingle(window);
viewport = new Viewport(ampdoc, binding, viewer);
bindingMock = sandbox.mock(binding);
iframe = document.createElement('iframe');
const html = '<div id="one"></div>';
let promise;
if ('srcdoc' in iframe) {
iframe.srcdoc = html;
promise = loadPromise(iframe);
document.body.appendChild(iframe);
} else {
iframe.src = 'about:blank';
document.body.appendChild(iframe);
const childDoc = iframe.contentWindow.document;
childDoc.open();
childDoc.write(html);
childDoc.close();
promise = Promise.resolve();
}
return promise.then(() => {
iframeWin = iframe.contentWindow;
setParentWindow(iframeWin, window);
});
});
afterEach(() => {
if (iframe.parentElement) {
iframe.parentElement.removeChild(iframe);
}
bindingMock.verify();
});
it('should calculate child window element rect via parent', () => {
viewport.scrollLeft_ = 0;
viewport.scrollTop_ = 0;
const element = iframeWin.document.createElement('div');
iframeWin.document.body.appendChild(element);
bindingMock.expects('getLayoutRect')
.withExactArgs(element, 0, 0)
.returns({left: 20, top: 10}).once();
bindingMock.expects('getLayoutRect')
.withExactArgs(iframe, 0, 0)
.returns({left: 211, top: 111}).once();
const rect = viewport.getLayoutRect(element);
expect(rect.left).to.equal(211 + 20);
expect(rect.top).to.equal(111 + 10);
});
it('should offset child window element with parent scroll pos', () => {
viewport.scrollLeft_ = 200;
viewport.scrollTop_ = 100;
const element = iframeWin.document.createElement('div');
iframeWin.document.body.appendChild(element);
bindingMock.expects('getLayoutRect')
.withExactArgs(element, 0, 0)
.returns({left: 20, top: 10}).once();
bindingMock.expects('getLayoutRect')
.withExactArgs(iframe, 200, 100)
.returns({left: 211, top: 111}).once();
const rect = viewport.getLayoutRect(element);
expect(rect.left).to.equal(211 + 20);
expect(rect.top).to.equal(111 + 10);
});
});
});
describe('Viewport META', () => {
describe('parseViewportMeta', () => {
it('should accept null or empty strings', () => {
expect(parseViewportMeta(null)).to.be.empty;
});
it('should parse single key-value', () => {
expect(parseViewportMeta('width=device-width')).to.deep.equal({
'width': 'device-width',
});
});
it('should parse two key-values', () => {
expect(parseViewportMeta('width=device-width,minimum-scale=1')).to.deep
.equal({
'width': 'device-width',
'minimum-scale': '1',
});
});
it('should parse empty value', () => {
expect(parseViewportMeta('width=device-width,minimal-ui')).to.deep.equal({
'width': 'device-width',
'minimal-ui': '',
});
expect(parseViewportMeta('minimal-ui,width=device-width')).to.deep.equal({
'width': 'device-width',
'minimal-ui': '',
});
});
it('should return last dupe', () => {
expect(parseViewportMeta('width=100,width=200')).to.deep.equal({
'width': '200',
});
});
it('should ignore extra delims', () => {
expect(parseViewportMeta(',,,width=device-width,,,,minimum-scale=1,,,'))
.to.deep.equal({
'width': 'device-width',
'minimum-scale': '1',
});
});
it('should support semicolon', () => {
expect(parseViewportMeta('width=device-width;minimum-scale=1'))
.to.deep.equal({
'width': 'device-width',
'minimum-scale': '1',
});
});
it('should support mix of comma and semicolon', () => {
expect(parseViewportMeta('width=device-width,minimum-scale=1;test=3;'))
.to.deep.equal({
'width': 'device-width',
'minimum-scale': '1',
'test': '3',
});
});
it('should ignore extra mix delims', () => {
expect(parseViewportMeta(',,;;,width=device-width;;,minimum-scale=1,,;'))
.to.deep.equal({
'width': 'device-width',
'minimum-scale': '1',
});
});
});
describe('stringifyViewportMeta', () => {
it('should stringify empty', () => {
expect(stringifyViewportMeta({})).to.equal('');
});
it('should stringify single key-value', () => {
expect(stringifyViewportMeta({'width': 'device-width'}))
.to.equal('width=device-width');
});
it('should stringify two key-values', () => {
const res = stringifyViewportMeta({
'width': 'device-width',
'minimum-scale': '1',
});
expect(res == 'width=device-width,minimum-scale=1' ||
res == 'minimum-scale=1,width=device-width')
.to.be.true;
});
it('should stringify empty values', () => {
const res = stringifyViewportMeta({
'width': 'device-width',
'minimal-ui': '',
});
expect(res == 'width=device-width,minimal-ui' ||
res == 'minimal-ui,width=device-width')
.to.be.true;
});
});
describe('updateViewportMetaString', () => {
it('should do nothing with empty values', () => {
expect(updateViewportMetaString(
'', {})).to.equal('');
expect(updateViewportMetaString(
'width=device-width', {})).to.equal('width=device-width');
});
it('should add a new value', () => {
expect(updateViewportMetaString(
'', {'minimum-scale': '1'})).to.equal('minimum-scale=1');
expect(parseViewportMeta(updateViewportMetaString(
'width=device-width', {'minimum-scale': '1'})))
.to.deep.equal({
'width': 'device-width',
'minimum-scale': '1',
});
});
it('should replace the existing value', () => {
expect(parseViewportMeta(updateViewportMetaString(
'width=device-width,minimum-scale=2', {'minimum-scale': '1'})))
.to.deep.equal({
'width': 'device-width',
'minimum-scale': '1',
});
});
it('should delete the existing value', () => {
expect(parseViewportMeta(updateViewportMetaString(
'width=device-width,minimum-scale=1', {'minimum-scale': undefined})))
.to.deep.equal({
'width': 'device-width',
});
});
it('should ignore delete for a non-existing value', () => {
expect(parseViewportMeta(updateViewportMetaString(
'width=device-width', {'minimum-scale': undefined})))
.to.deep.equal({
'width': 'device-width',
});
});
it('should do nothing if values did not change', () => {
expect(updateViewportMetaString(
'width=device-width,minimum-scale=1', {'minimum-scale': '1'}))
.to.equal('width=device-width,minimum-scale=1');
});
});
describe('TouchZoom', () => {
let sandbox;
let clock;
let viewport;
let binding;
let viewer;
let viewerMock;
let windowApi;
let ampdoc;
let originalViewportMetaString, viewportMetaString;
let viewportMeta;
let viewportMetaSetter;
beforeEach(() => {
sandbox = sinon.sandbox.create();
clock = sandbox.useFakeTimers();
viewer = {
isEmbedded: () => false,
getPaddingTop: () => 0,
onViewportEvent: () => {},
isIframed: () => false,
};
viewerMock = sandbox.mock(viewer);
originalViewportMetaString = 'width=device-width,minimum-scale=1';
viewportMetaString = originalViewportMetaString;
viewportMeta = Object.create(null);
viewportMetaSetter = sandbox.spy();
Object.defineProperty(viewportMeta, 'content', {
get: () => viewportMetaString,
set: value => {
viewportMetaSetter(value);
viewportMetaString = value;
},
});
windowApi = {
document: {
documentElement: {
style: {},
classList: {
add: function() {},
},
},
querySelector: selector => {
if (selector == 'meta[name=viewport]') {
return viewportMeta;
}
return undefined;
},
},
navigator: window.navigator,
setTimeout: window.setTimeout,
clearTimeout: window.clearTimeout,
location: {},
};
ampdoc = new AmpDocSingle(windowApi);
installTimerService(windowApi);
installPlatformService(windowApi);
installViewerService(windowApi);
binding = new ViewportBindingDef();
viewport = new Viewport(ampdoc, binding, viewer);
});
afterEach(() => {
sandbox.restore();
});
it('should initialize original viewport meta', () => {
viewport.getViewportMeta_();
expect(viewport.originalViewportMetaString_).to.equal(viewportMetaString);
expect(viewportMetaSetter.callCount).to.equal(0);
});
it('should disable TouchZoom', () => {
viewport.disableTouchZoom();
expect(viewportMetaSetter.callCount).to.equal(1);
expect(viewportMetaString).to.have.string('maximum-scale=1');
expect(viewportMetaString).to.have.string('user-scalable=no');
});
it('should ignore disable TouchZoom if already disabled', () => {
viewportMetaString = 'width=device-width,minimum-scale=1,' +
'maximum-scale=1,user-scalable=no';
viewport.disableTouchZoom();
expect(viewportMetaSetter.callCount).to.equal(0);
});
it('should ignore disable TouchZoom if embedded', () => {
viewerMock.expects('isIframed').returns(true).atLeast(1);
viewport.disableTouchZoom();
expect(viewportMetaSetter.callCount).to.equal(0);
});
it('should restore TouchZoom', () => {
viewport.disableTouchZoom();
expect(viewportMetaSetter.callCount).to.equal(1);
expect(viewportMetaString).to.have.string('maximum-scale=1');
expect(viewportMetaString).to.have.string('user-scalable=no');
viewport.restoreOriginalTouchZoom();
expect(viewportMetaSetter.callCount).to.equal(2);
expect(viewportMetaString).to.equal(originalViewportMetaString);
});
it('should reset TouchZoom; zooming state unknown', () => {
viewport.resetTouchZoom();
expect(viewportMetaSetter.callCount).to.equal(1);
expect(viewportMetaString).to.have.string('maximum-scale=1');
expect(viewportMetaString).to.have.string('user-scalable=no');
clock.tick(1000);
expect(viewportMetaSetter.callCount).to.equal(2);
expect(viewportMetaString).to.equal(originalViewportMetaString);
});
it('should ignore reset TouchZoom if not currently zoomed', () => {
windowApi.document.documentElement.clientHeight = 500;
windowApi.innerHeight = 500;
viewport.resetTouchZoom();
expect(viewportMetaSetter.callCount).to.equal(0);
});
it('should proceed with reset TouchZoom if currently zoomed', () => {
windowApi.document.documentElement.clientHeight = 500;
windowApi.innerHeight = 300;
viewport.resetTouchZoom();
expect(viewportMetaSetter.callCount).to.equal(1);
});
it('should ignore reset TouchZoom if embedded', () => {
viewerMock.expects('isIframed').returns(true).atLeast(1);
viewport.resetTouchZoom();
expect(viewportMetaSetter.callCount).to.equal(0);
});
});
});
describe('ViewportBindingNatural', () => {
let sandbox;
let windowMock;
let binding;
let windowApi;
let documentElement;
let documentBody;
let windowEventHandlers;
let viewer;
let viewerMock;
beforeEach(() => {
sandbox = sinon.sandbox.create();
const WindowApi = function() {};
windowEventHandlers = {};
WindowApi.prototype.addEventListener = function(eventType, handler) {
windowEventHandlers[eventType] = handler;
};
windowApi = new WindowApi();
documentElement = {
style: {},
};
documentBody = {
style: {},
};
windowApi.document = {
documentElement,
body: documentBody,
defaultView: windowApi,
};
windowApi.navigator = {userAgent: ''};
windowMock = sandbox.mock(windowApi);
installPlatformService(windowApi);
viewer = {
isEmbedded: () => false,
getPaddingTop: () => 19,
onViewportEvent: () => {},
requestFullOverlay: () => {},
cancelFullOverlay: () => {},
postScroll: sandbox.spy(),
};
viewerMock = sandbox.mock(viewer);
binding = new ViewportBindingNatural_(windowApi, viewer);
});
afterEach(() => {
windowMock.verify();
viewerMock.verify();
sandbox.restore();
});
it('should setup overflow:visible on body', () => {
expect(documentBody.style.overflow).to.equal('visible');
});
it('should NOT require fixed layer transferring', () => {
expect(binding.requiresFixedLayerTransfer()).to.be.false;
});
it('should subscribe to scroll and resize events', () => {
expect(windowEventHandlers['scroll']).to.not.equal(undefined);
expect(windowEventHandlers['resize']).to.not.equal(undefined);
});
it('should update padding', () => {
windowApi.document = {
documentElement: {style: {}},
};
binding.updatePaddingTop(31);
expect(windowApi.document.documentElement.style.paddingTop).to
.equal('31px');
});
it('should calculate size', () => {
windowApi.innerWidth = 111;
windowApi.innerHeight = 222;
windowApi.document = {
documentElement: {
clientWidth: 333,
clientHeight: 444,
},
};
let size = binding.getSize();
expect(size.width).to.equal(111);
expect(size.height).to.equal(222);
delete windowApi.innerWidth;
delete windowApi.innerHeight;
size = binding.getSize();
expect(size.width).to.equal(333);
expect(size.height).to.equal(444);
});
it('should calculate scrollTop from scrollElement', () => {
windowApi.pageYOffset = 11;
windowApi.document = {
scrollingElement: {
scrollTop: 17,
},
};
expect(binding.getScrollTop()).to.equal(17);
});
it('should calculate scrollWidth from scrollElement', () => {
windowApi.pageYOffset = 11;
windowApi.document = {
scrollingElement: {
scrollWidth: 117,
},
};
expect(binding.getScrollWidth()).to.equal(117);
});
it('should calculate scrollHeight from scrollElement', () => {
windowApi.pageYOffset = 11;
windowApi.document = {
scrollingElement: {
scrollHeight: 119,
},
};
expect(binding.getScrollHeight()).to.equal(119);
});
it('should update scrollTop on scrollElement', () => {
windowApi.pageYOffset = 11;
windowApi.document = {
scrollingElement: {
scrollTop: 17,
},
};
binding.setScrollTop(21);
expect(windowApi.document.scrollingElement./*OK*/scrollTop).to.equal(21);
});
it('should fallback scrollTop to pageYOffset', () => {
windowApi.pageYOffset = 11;
windowApi.document = {scrollingElement: {}};
expect(binding.getScrollTop()).to.equal(11);
});
it('should offset client rect for layout', () => {
windowApi.pageXOffset = 100;
windowApi.pageYOffset = 200;
windowApi.document = {scrollingElement: {}};
const el = {
getBoundingClientRect: () => {
return {left: 11.5, top: 12.5, width: 13.5, height: 14.5};
},
};
const rect = binding.getLayoutRect(el);
expect(rect.left).to.equal(112); // round(100 + 11.5)
expect(rect.top).to.equal(213); // round(200 + 12.5)
expect(rect.width).to.equal(14); // round(13.5)
expect(rect.height).to.equal(15); // round(14.5)
});
it('should offset client rect for layout and position passed in', () => {
windowApi.pageXOffset = 1000;
windowApi.pageYOffset = 2000;
windowApi.document = {scrollingElement: {}};
const el = {
getBoundingClientRect: () => {
return {left: 11.5, top: 12.5, width: 13.5, height: 14.5};
},
};
const rect = binding.getLayoutRect(el, 100, 200);
expect(rect.left).to.equal(112); // round(100 + 11.5)
expect(rect.top).to.equal(213); // round(200 + 12.5)
expect(rect.width).to.equal(14); // round(13.5)
expect(rect.height).to.equal(15); // round(14.5)
});
});
describe('ViewportBindingNaturalIosEmbed', () => {
let sandbox;
let windowMock;
let binding;
let windowApi;
let windowEventHandlers;
let bodyEventListeners;
let bodyChildren;
beforeEach(() => {
sandbox = sinon.sandbox.create();
const WindowApi = function() {};
windowEventHandlers = {};
bodyEventListeners = {};
bodyChildren = [];
WindowApi.prototype.addEventListener = function(eventType, handler) {
windowEventHandlers[eventType] = handler;
};
windowApi = new WindowApi();
windowApi.innerWidth = 555;
windowApi.document = {
readyState: 'complete',
documentElement: {style: {}},
body: {
scrollWidth: 777,
scrollHeight: 999,
style: {},
appendChild: child => {
bodyChildren.push(child);
},
addEventListener: (eventType, handler) => {
bodyEventListeners[eventType] = handler;
},
},
createElement: tagName => {
return {
tagName,
id: '',
style: {},
scrollIntoView: sandbox.spy(),
};
},
};
windowMock = sandbox.mock(windowApi);
binding = new ViewportBindingNaturalIosEmbed_(windowApi);
return Promise.resolve();
});
afterEach(() => {
windowMock.verify();
sandbox.restore();
});
it('should require fixed layer transferring', () => {
expect(binding.requiresFixedLayerTransfer()).to.be.true;
});
it('should subscribe to resize events on window, scroll on body', () => {
expect(windowEventHandlers['resize']).to.not.equal(undefined);
expect(windowEventHandlers['scroll']).to.equal(undefined);
expect(bodyEventListeners['scroll']).to.not.equal(undefined);
});
it('should always have scrollWidth equal window.innerWidth', () => {
expect(binding.getScrollWidth()).to.equal(555);
});
it('should setup document for embed scrolling', () => {
const documentElement = windowApi.document.documentElement;
const body = windowApi.document.body;
expect(documentElement.style.overflowY).to.equal('auto');
expect(documentElement.style.webkitOverflowScrolling).to.equal('touch');
expect(body.style.overflowX).to.equal('hidden');
expect(body.style.overflowY).to.equal('auto');
expect(body.style.webkitOverflowScrolling).to.equal('touch');
expect(body.style.position).to.equal('absolute');
expect(body.style.top).to.equal(0);
expect(body.style.left).to.equal(0);
expect(body.style.right).to.equal(0);
expect(body.style.bottom).to.equal(0);
expect(bodyChildren.length).to.equal(3);
expect(bodyChildren[0].id).to.equal('-amp-scrollpos');
expect(bodyChildren[0].style.position).to.equal('absolute');
expect(bodyChildren[0].style.top).to.equal(0);
expect(bodyChildren[0].style.left).to.equal(0);
expect(bodyChildren[0].style.width).to.equal(0);
expect(bodyChildren[0].style.height).to.equal(0);
expect(bodyChildren[0].style.visibility).to.equal('hidden');
expect(bodyChildren[1].id).to.equal('-amp-scrollmove');
expect(bodyChildren[1].style.position).to.equal('absolute');
expect(bodyChildren[1].style.top).to.equal(0);
expect(bodyChildren[1].style.left).to.equal(0);
expect(bodyChildren[1].style.width).to.equal(0);
expect(bodyChildren[1].style.height).to.equal(0);
expect(bodyChildren[1].style.visibility).to.equal('hidden');
expect(bodyChildren[2].id).to.equal('-amp-endpos');
expect(bodyChildren[2].style.position).to.be.undefined;
expect(bodyChildren[2].style.top).to.be.undefined;
expect(bodyChildren[2].style.width).to.equal(0);
expect(bodyChildren[2].style.height).to.equal(0);
expect(bodyChildren[2].style.visibility).to.equal('hidden');
});
it('should update border on BODY', () => {
windowApi.document = {
body: {style: {}},
};
binding.updatePaddingTop(31);
expect(windowApi.document.body.style.borderTop).to
.equal('31px solid transparent');
});
it('should update border in lightbox mode', () => {
windowApi.document = {
body: {style: {}},
};
binding.updatePaddingTop(31);
expect(windowApi.document.body.style.borderTop).to
.equal('31px solid transparent');
expect(windowApi.document.body.style.borderTopStyle).to.be.undefined;
binding.updateLightboxMode(true);
expect(windowApi.document.body.style.borderTopStyle).to.equal('none');
binding.updateLightboxMode(false);
expect(windowApi.document.body.style.borderTopStyle).to.equal('solid');
expect(windowApi.document.body.style.borderBottomStyle).to.not.equal(
'solid');
expect(windowApi.document.body.style.borderLeftStyle).to.not.equal('solid');
expect(windowApi.document.body.style.borderRightStyle).to.not.equal(
'solid');
});
it('should calculate size', () => {
windowApi.innerWidth = 111;
windowApi.innerHeight = 222;
const size = binding.getSize();
expect(size.width).to.equal(111);
expect(size.height).to.equal(222);
});
it('should calculate scrollTop from scrollpos element', () => {
bodyChildren[0].getBoundingClientRect = () => {
return {top: -17, left: -11};
};
binding.onScrolled_();
expect(binding.getScrollTop()).to.equal(17);
});
it('should calculate scrollTop from scrollpos element with padding', () => {
bodyChildren[0].getBoundingClientRect = () => {
return {top: 0, left: -11};
};
binding.updatePaddingTop(10);
binding.onScrolled_();
// scrollTop = - BCR.top + paddingTop
expect(binding.getScrollTop()).to.equal(10);
});
it('should calculate scrollHeight from scrollpos/endpos elements', () => {
bodyChildren[0].getBoundingClientRect = () => {
return {top: -17, left: -11};
};
bodyChildren[2].getBoundingClientRect = () => {
return {top: 100, left: -11};
};
expect(binding.getScrollHeight()).to.equal(117);
});
it('should offset client rect for layout', () => {
bodyChildren[0].getBoundingClientRect = () => {
return {top: -200, left: -100};
};
binding.onScrolled_();
const el = {
getBoundingClientRect: () => {
return {left: 11.5, top: 12.5, width: 13.5, height: 14.5};
},
};
const rect = binding.getLayoutRect(el);
expect(rect.left).to.equal(112); // round(100 + 11.5)
expect(rect.top).to.equal(213); // round(200 + 12.5)
expect(rect.width).to.equal(14); // round(13.5)
expect(rect.height).to.equal(15); // round(14.5)
});
it('should set scroll position via moving element', () => {
const moveEl = bodyChildren[1];
binding.setScrollTop(10);
expect(getStyle(moveEl, 'transform')).to.equal('translateY(10px)');
expect(moveEl.scrollIntoView.callCount).to.equal(1);
expect(moveEl.scrollIntoView.firstCall.args[0]).to.equal(true);
});
it('should set scroll position via moving element with padding', () => {
binding.updatePaddingTop(19);
const moveEl = bodyChildren[1];
binding.setScrollTop(10);
// transform = scrollTop - paddingTop
expect(getStyle(moveEl, 'transform')).to.equal('translateY(-9px)');
expect(moveEl.scrollIntoView.callCount).to.equal(1);
expect(moveEl.scrollIntoView.firstCall.args[0]).to.equal(true);
});
it('should adjust scroll position when scrolled to 0', () => {
const posEl = bodyChildren[0];
posEl.getBoundingClientRect = () => {return {top: 0, left: 0};};
const moveEl = bodyChildren[1];
const event = {preventDefault: sandbox.spy()};
binding.adjustScrollPos_(event);
expect(getStyle(moveEl, 'transform')).to.equal('translateY(1px)');
expect(moveEl.scrollIntoView.callCount).to.equal(1);
expect(moveEl.scrollIntoView.firstCall.args[0]).to.equal(true);
expect(event.preventDefault.callCount).to.equal(1);
});
it('should adjust scroll position when scrolled to 0 w/padding', () => {
binding.updatePaddingTop(10);
const posEl = bodyChildren[0];
posEl.getBoundingClientRect = () => {return {top: 10, left: 0};};
const moveEl = bodyChildren[1];
const event = {preventDefault: sandbox.spy()};
binding.adjustScrollPos_(event);
// transform = 1 - updatePadding
expect(getStyle(moveEl, 'transform')).to.equal('translateY(-9px)');
expect(moveEl.scrollIntoView.callCount).to.equal(1);
expect(moveEl.scrollIntoView.firstCall.args[0]).to.equal(true);
expect(event.preventDefault.callCount).to.equal(1);
});
it('should adjust scroll position when scrolled to 0; w/o event', () => {
const posEl = bodyChildren[0];
posEl.getBoundingClientRect = () => {return {top: 0, left: 0};};
const moveEl = bodyChildren[1];
binding.adjustScrollPos_();
expect(moveEl.scrollIntoView.callCount).to.equal(1);
});
it('should NOT adjust scroll position when scrolled away from 0', () => {
const posEl = bodyChildren[0];
posEl.getBoundingClientRect = () => {return {top: -10, left: 0};};
const moveEl = bodyChildren[1];
const event = {preventDefault: sandbox.spy()};
binding.adjustScrollPos_(event);
expect(moveEl.scrollIntoView.callCount).to.equal(0);
expect(event.preventDefault.callCount).to.equal(0);
});
it('should NOT adjust scroll position when overscrolled', () => {
const posEl = bodyChildren[0];
posEl.getBoundingClientRect = () => {return {top: 10, left: 0};};
const moveEl = bodyChildren[1];
const event = {preventDefault: sandbox.spy()};
binding.adjustScrollPos_(event);
expect(moveEl.scrollIntoView.callCount).to.equal(0);
expect(event.preventDefault.callCount).to.equal(0);
});
});
| devjsun/amphtml | test/functional/test-viewport.js | JavaScript | apache-2.0 | 43,477 |
'use strict';
/**
* Requirements
* @ignore
*/
const Filter = require('./Filter.js').Filter;
const PathesConfiguration = require('../../model/configuration/PathesConfiguration.js').PathesConfiguration;
const assertParameter = require('../../utils/assert.js').assertParameter;
const pathes = require('../../utils/pathes.js');
const fs = require('fs');
const templateString = require('es6-template-strings');
/**
* @memberOf nunjucks.filter
*/
class SvgViewBoxFilter extends Filter
{
/**
* @inheritDocs
*/
constructor(pathesConfiguration, basePath)
{
super();
this._name = 'svgViewBox';
// Check params
assertParameter(this, 'pathesConfiguration', pathesConfiguration, true, PathesConfiguration);
// Assign options
this._basePath = basePath || '/';
this._pathesConfiguration = pathesConfiguration;
}
/**
* @inheritDocs
*/
static get className()
{
return 'nunjucks.filter/SvgViewBoxFilter';
}
/**
* @inheritDocs
*/
static get injections()
{
return { 'parameters': [PathesConfiguration, 'nunjucks.filter/SvgViewBoxFilter.basePath'] };
}
/**
* @type {String}
*/
get basePath()
{
return this._basePath;
}
/**
* @returns {String}
*/
getBasePath(globals)
{
let result = this._basePath;
if (this.environment &&
this.environment.buildConfiguration)
{
result = this.environment.buildConfiguration.get('filters.svgPath', this._basePath);
}
return templateString(result, globals.location || {});
}
/**
* @type {model.configuration.PathesConfiguration}
*/
get pathesConfiguration()
{
return this._pathesConfiguration;
}
/**
* @inheritDocs
*/
filter(value)
{
const scope = this;
return function(value)
{
let result = '0 0 0 0';
const globals = scope.getGlobals(this);
const filename = pathes.concat(scope.pathesConfiguration.sites, scope.getBasePath(globals), value + '.svg');
if (fs.existsSync(filename))
{
const icon = fs.readFileSync(filename, { encoding: 'utf8' });
const viewbox = icon.match(/viewBox="([^"]*)"/i);
if (viewbox && viewbox[1])
{
result = viewbox[1];
}
}
else
{
scope.logger.warn('Could not locate svg <' + filename + '>');
}
return scope.applyCallbacks(result, arguments);
};
}
}
/**
* Exports
* @ignore
*/
module.exports.SvgViewBoxFilter = SvgViewBoxFilter;
| entoj/entoj-system | source/nunjucks/filter/SvgViewBoxFilter.js | JavaScript | apache-2.0 | 2,791 |
import { expect } from 'chai';
import { spec, resetInvibes, stubDomainOptions } from 'modules/invibesBidAdapter';
describe('invibesBidAdapter:', function () {
const BIDDER_CODE = 'invibes';
const PLACEMENT_ID = '12345';
const ENDPOINT = '//bid.videostep.com/Bid/VideoAdContent';
const SYNC_ENDPOINT = '//k.r66net.com/GetUserSync';
let bidRequests = [
{
bidId: 'b1',
bidder: BIDDER_CODE,
bidderRequestId: 'r1',
params: {
placementId: PLACEMENT_ID
},
adUnitCode: 'test-div',
auctionId: 'a1',
sizes: [
[300, 250],
[400, 300],
[125, 125]
],
transactionId: 't1'
}, {
bidId: 'b2',
bidder: BIDDER_CODE,
bidderRequestId: 'r2',
params: {
placementId: 'abcde'
},
adUnitCode: 'test-div',
auctionId: 'a2',
sizes: [
[300, 250],
[400, 300]
],
transactionId: 't2'
}
];
let StubbedPersistence = function(initialValue) {
var value = initialValue;
return {
load: function () {
let str = value || '';
try {
return JSON.parse(str);
} catch (e) { }
},
save: function (obj) {
value = JSON.stringify(obj);
}
}
};
beforeEach(function () {
resetInvibes();
document.cookie = '';
this.cStub1 = sinon.stub(console, 'info');
});
afterEach(function () {
this.cStub1.restore();
});
describe('isBidRequestValid:', function () {
context('valid bid request:', function () {
it('returns true when bidder params.placementId is set', function() {
const validBid = {
bidder: BIDDER_CODE,
params: {
placementId: PLACEMENT_ID
}
}
expect(spec.isBidRequestValid(validBid)).to.be.true;
})
});
context('invalid bid request:', function () {
it('returns false when no params', function () {
const invalidBid = {
bidder: BIDDER_CODE
}
expect(spec.isBidRequestValid(invalidBid)).to.be.false;
});
it('returns false when placementId is not set', function() {
const invalidBid = {
bidder: BIDDER_CODE,
params: {
id: '5'
}
}
expect(spec.isBidRequestValid(invalidBid)).to.be.false;
});
it('returns false when bid response was previously received', function() {
const validBid = {
bidder: BIDDER_CODE,
params: {
placementId: PLACEMENT_ID
}
}
top.window.invibes.bidResponse = { prop: 'prop' };
expect(spec.isBidRequestValid(validBid)).to.be.false;
});
});
});
describe('buildRequests', function () {
it('sends bid request to ENDPOINT via GET', function () {
const request = spec.buildRequests(bidRequests);
expect(request.url).to.equal(ENDPOINT);
expect(request.method).to.equal('GET');
});
it('sends cookies with the bid request', function () {
const request = spec.buildRequests(bidRequests);
expect(request.options.withCredentials).to.equal(true);
});
it('has location, html id, placement and width/height', function () {
const request = spec.buildRequests(bidRequests, { auctionStart: Date.now() });
const parsedData = request.data;
expect(parsedData.location).to.exist;
expect(parsedData.videoAdHtmlId).to.exist;
expect(parsedData.vId).to.exist;
expect(parsedData.width).to.exist;
expect(parsedData.height).to.exist;
});
it('has capped ids if local storage variable is correctly formatted', function () {
localStorage.ivvcap = '{"9731":[1,1768600800000]}';
const request = spec.buildRequests(bidRequests, { auctionStart: Date.now() });
expect(request.data.capCounts).to.equal('9731=1');
});
it('does not have capped ids if local storage variable is incorrectly formatted', function () {
localStorage.ivvcap = ':[1,1574334216992]}';
const request = spec.buildRequests(bidRequests, { auctionStart: Date.now() });
expect(request.data.capCounts).to.equal('');
});
it('does not have capped ids if local storage variable is expired', function () {
localStorage.ivvcap = '{"9731":[1,1574330064104]}';
const request = spec.buildRequests(bidRequests, { auctionStart: Date.now() });
expect(request.data.capCounts).to.equal('');
});
it('sends query string params from localstorage 1', function () {
localStorage.ivbs = JSON.stringify({ bvci: 1 });
const request = spec.buildRequests(bidRequests, { auctionStart: Date.now() });
expect(request.data.bvci).to.equal(1);
});
it('sends query string params from localstorage 2', function () {
localStorage.ivbs = JSON.stringify({ invibbvlog: true });
const request = spec.buildRequests(bidRequests, { auctionStart: Date.now() });
expect(request.data.invibbvlog).to.equal(true);
});
it('does not send query string params from localstorage if unknwon', function () {
localStorage.ivbs = JSON.stringify({ someparam: true });
const request = spec.buildRequests(bidRequests, { auctionStart: Date.now() });
expect(request.data.someparam).to.be.undefined;
});
it('sends all Placement Ids', function () {
const request = spec.buildRequests(bidRequests);
expect(JSON.parse(request.data.bidParamsJson).placementIds).to.contain(bidRequests[0].params.placementId);
expect(JSON.parse(request.data.bidParamsJson).placementIds).to.contain(bidRequests[1].params.placementId);
});
it('uses cookies', function () {
global.document.cookie = 'ivNoCookie=1';
let request = spec.buildRequests(bidRequests);
expect(request.data.lId).to.be.undefined;
});
it('doesnt send the domain id if not graduated', function () {
global.document.cookie = 'ivbsdid={"id":"dvdjkams6nkq","cr":1522929537626,"hc":1}';
let request = spec.buildRequests(bidRequests);
expect(request.data.lId).to.not.exist;
});
it('try to graduate but not enough count - doesnt send the domain id', function () {
global.document.cookie = 'ivbsdid={"id":"dvdjkams6nkq","cr":1521818537626,"hc":0}';
let bidderRequest = { gdprConsent: { vendorData: { vendorConsents: { 436: true } } } };
let request = spec.buildRequests(bidRequests, bidderRequest);
expect(request.data.lId).to.not.exist;
});
it('try to graduate but not old enough - doesnt send the domain id', function () {
let bidderRequest = { gdprConsent: { vendorData: { vendorConsents: { 436: true } } } };
global.document.cookie = 'ivbsdid={"id":"dvdjkams6nkq","cr":' + Date.now() + ',"hc":5}';
let request = spec.buildRequests(bidRequests, bidderRequest);
expect(request.data.lId).to.not.exist;
});
it('graduate and send the domain id', function () {
let bidderRequest = { gdprConsent: { vendorData: { vendorConsents: { 436: true } } } };
stubDomainOptions(new StubbedPersistence('{"id":"dvdjkams6nkq","cr":1521818537626,"hc":7}'));
let request = spec.buildRequests(bidRequests, bidderRequest);
expect(request.data.lId).to.exist;
});
it('send the domain id if already graduated', function () {
let bidderRequest = { gdprConsent: { vendorData: { vendorConsents: { 436: true } } } };
stubDomainOptions(new StubbedPersistence('{"id":"f8zoh044p9oi"}'));
let request = spec.buildRequests(bidRequests, bidderRequest);
expect(request.data.lId).to.exist;
expect(top.window.invibes.dom.tempId).to.exist;
});
it('send the domain id after replacing it with new format', function () {
let bidderRequest = { gdprConsent: { vendorData: { vendorConsents: { 436: true } } } };
stubDomainOptions(new StubbedPersistence('{"id":"f8zoh044p9oi.8537626"}'));
let request = spec.buildRequests(bidRequests, bidderRequest);
expect(request.data.lId).to.exist;
expect(top.window.invibes.dom.tempId).to.exist;
});
it('dont send the domain id if consent declined', function () {
let bidderRequest = { gdprConsent: { vendorData: { vendorConsents: { 436: false } } } };
stubDomainOptions(new StubbedPersistence('{"id":"f8zoh044p9oi.8537626"}'));
let request = spec.buildRequests(bidRequests, bidderRequest);
expect(request.data.lId).to.not.exist;
expect(top.window.invibes.dom.tempId).to.not.exist;
});
it('dont send the domain id if no consent', function () {
let bidderRequest = { };
stubDomainOptions(new StubbedPersistence('{"id":"f8zoh044p9oi.8537626"}'));
let request = spec.buildRequests(bidRequests, bidderRequest);
expect(request.data.lId).to.not.exist;
expect(top.window.invibes.dom.tempId).to.not.exist;
});
it('try to init id but was already loaded on page - does not increment the id again', function () {
let bidderRequest = { gdprConsent: { vendorData: { vendorConsents: { 436: true } } } };
global.document.cookie = 'ivbsdid={"id":"dvdjkams6nkq","cr":1521818537626,"hc":0}';
let request = spec.buildRequests(bidRequests, bidderRequest);
request = spec.buildRequests(bidRequests, bidderRequest);
expect(request.data.lId).to.not.exist;
expect(top.window.invibes.dom.tempId).to.exist;
});
});
describe('interpretResponse', function () {
let response = {
Ads: [{
BidPrice: 0.5,
VideoExposedId: 123
}],
BidModel: {
BidVersion: 1,
PlacementId: '12345',
AuctionStartTime: Date.now(),
CreativeHtml: '<!-- Creative -->'
}
};
let expectedResponse = [{
requestId: bidRequests[0].bidId,
cpm: 0.5,
width: 400,
height: 300,
creativeId: 123,
currency: 'EUR',
netRevenue: true,
ttl: 300,
ad: `<html>
<head><script type='text/javascript'>inDapIF=true;</script></head>
<body style='margin : 0; padding: 0;'>
<!-- Creative -->
</body>
</html>`
}];
context('when the response is not valid', function () {
it('handles response with no bids requested', function () {
let emptyResult = spec.interpretResponse({ body: response });
expect(emptyResult).to.be.empty;
});
it('handles empty response', function () {
let emptyResult = spec.interpretResponse(null, { bidRequests });
expect(emptyResult).to.be.empty;
});
it('handles response with bidding is not configured', function () {
let emptyResult = spec.interpretResponse({ body: { Ads: [{ BidPrice: 1 }] } }, { bidRequests });
expect(emptyResult).to.be.empty;
});
it('handles response with no ads are received', function () {
let emptyResult = spec.interpretResponse({ body: { BidModel: { PlacementId: '12345' }, AdReason: 'No ads' } }, { bidRequests });
expect(emptyResult).to.be.empty;
});
it('handles response with no ads are received - no ad reason', function () {
let emptyResult = spec.interpretResponse({ body: { BidModel: { PlacementId: '12345' } } }, { bidRequests });
expect(emptyResult).to.be.empty;
});
it('handles response when no placement Id matches', function () {
let emptyResult = spec.interpretResponse({ body: { BidModel: { PlacementId: '123456' }, Ads: [{ BidPrice: 1 }] } }, { bidRequests });
expect(emptyResult).to.be.empty;
});
it('handles response when placement Id is not present', function () {
let emptyResult = spec.interpretResponse({ BidModel: { }, Ads: [{ BidPrice: 1 }] }, { bidRequests });
expect(emptyResult).to.be.empty;
});
});
context('when the response is valid', function () {
it('responds with a valid bid', function () {
top.window.invibes.setCookie('a', 'b', 370);
top.window.invibes.setCookie('c', 'd', 0);
let result = spec.interpretResponse({ body: response }, { bidRequests });
expect(Object.keys(result[0])).to.have.members(Object.keys(expectedResponse[0]));
});
it('responds with a valid bid and uses logger', function () {
localStorage.InvibesDEBUG = true;
let result = spec.interpretResponse({ body: response }, { bidRequests });
expect(Object.keys(result[0])).to.have.members(Object.keys(expectedResponse[0]));
});
it('does not make multiple bids', function () {
localStorage.InvibesDEBUG = false;
let result = spec.interpretResponse({ body: response }, { bidRequests });
let secondResult = spec.interpretResponse({ body: response }, { bidRequests });
expect(secondResult).to.be.empty;
});
});
});
describe('getUserSyncs', function () {
it('returns an iframe if enabled', function () {
let response = spec.getUserSyncs({iframeEnabled: true});
expect(response.type).to.equal('iframe');
expect(response.url).to.include(SYNC_ENDPOINT);
});
it('returns an iframe with params if enabled', function () {
top.window.invibes.optIn = 1;
global.document.cookie = 'ivvbks=17639.0,1,2';
let response = spec.getUserSyncs({ iframeEnabled: true });
expect(response.type).to.equal('iframe');
expect(response.url).to.include(SYNC_ENDPOINT);
expect(response.url).to.include('optIn');
expect(response.url).to.include('ivvbks');
expect(response.url).to.include('ivbsdid');
});
it('returns undefined if iframe not enabled ', function () {
let response = spec.getUserSyncs({ iframeEnabled: false });
expect(response).to.equal(undefined);
});
});
});
| olafbuitelaar/Prebid.js | test/spec/modules/invibesBidAdapter_spec.js | JavaScript | apache-2.0 | 13,759 |
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('@angular/core');
var router_1 = require('@angular/router');
var hero_service_1 = require('../../services/hero.service');
var HeroeList = (function () {
function HeroeList(router, heroService) {
this.router = router;
this.heroService = heroService;
this.title = "Tour of Heroes";
}
HeroeList.prototype.ngOnInit = function () {
this.getHeroes();
};
HeroeList.prototype.getHeroes = function () {
var _this = this;
this.heroService.getHeroes().then(function (heroes) { return _this.heroes = heroes; });
};
HeroeList.prototype.add = function (name) {
var _this = this;
name = name.trim();
if (!name) {
return;
}
this.heroService.create(name)
.then(function (hero) {
_this.heroes.push(hero);
_this.selectedHero = null;
});
};
HeroeList.prototype.delete = function (hero) {
var _this = this;
this.heroService
.delete(hero.id)
.then(function () {
_this.heroes = _this.heroes.filter(function (h) { return h !== hero; });
if (_this.selectedHero === hero) {
_this.selectedHero = null;
}
});
};
HeroeList.prototype.onSelect = function (hero) {
this.selectedHero = hero;
};
HeroeList.prototype.gotoDetail = function () {
this.router.navigate(['/detail', this.selectedHero.id]);
};
HeroeList = __decorate([
core_1.Component({
moduleId: module.id,
selector: 'heroe-list',
providers: [hero_service_1.HeroService],
templateUrl: 'heroe-list.html',
styleUrls: ['heroe-list.css']
}),
__metadata('design:paramtypes', [router_1.Router, hero_service_1.HeroService])
], HeroeList);
return HeroeList;
}());
exports.HeroeList = HeroeList;
//# sourceMappingURL=heroe-list.component.js.map | llarreta/larretasources | AngularCommons/app/Components/heroes-list/heroe-list.component.js | JavaScript | apache-2.0 | 2,759 |
var express = require('express');
var https = require('https');
var http = require('http');
var url = require('url');
var bodyParser = require('body-parser');
var request = require('request') ;
//var publicRouter = express.Router();
module.exports = function (publicRouter,vcapServices) {
publicRouter.use(bodyParser.json());
publicRouter.route('/')
.get(function (req, res, next) {
console.log('GET request for /');
res.render('index',
{ title : 'Home' }
);
});
// Testing for Silverpop Engage ./sptest/mid1234
publicRouter.route('/sptest/:muid')
.get(function (req, res, next) {
console.log('GET for muid',req.params.muid);
if (!req.params.muid) {
console.log( 'Incomplete testsp params',req.params);
return res.status(403).send('Missing muid')
}
res.render('sptest',{title: 'Special 10% Loan', mobileid: req.params.muid});
});
// Generating Push event for dla exit entry
publicRouter.route('/sptest')
.post(function (req, res, next) {
console.log('POST sptest',req.body);
if (!req.body.muid || !req.body.channelid) {
console.log( 'Incomplete testsp payload',req.body);
return res.status(403).send('Missing muid or channeld')
}
var lat =req.body.lat.substring(0,7) ;
var lon = req.body.lon ;
var muid =req.body.muid ;
var channelid =req.body.channelid ;
var appKey =req.body.appkey ;
var store ;
var contentid ;
if (lat =="32.1291") { // in real life this should be a combination of lat and lon
store ='A';
contentid ="ca9a2aa5-2874-4d20-944b-65c16349d6db"
} else {
store ='B';
contentid ="b968615e-1da5-4ad7-bf80-57e256169f49"
}
console.log('lat',lat,'store',store);
var body =getJson (appKey, muid,channelid,store,contentid);
//res.render('sptest',{title: 'Page title', mobileid: muid,channel:channelid});
function getOauthToken() {
getNewToken(function (err, token) {
if (err) {
console.log('Err:',err,'Token:',token);
return res.status(401).send(err);
} else { // sucess
console.log('Token',token);
var options = {
uri: 'https://api0.silverpop.com/rest/channels/push/sends',
method: 'POST',
headers: {
"Content-Type": "application/json"
},
auth: {
'bearer': token
},
json: body
};
request(options, function (error, response, body) {
if (!error && response.statusCode == 202) {
return res.status(202).send(response.headers);
} else {
console.log('Error in push api',error) ;
return res.status(response.statusCode).send(response.body)
}
});
}
});
}
getOauthToken();
});
// Static page. Engage use iframe directing to this page.
publicRouter.route('/sptest-iframe')
.get(function (req, res, next) {
res.render('sptest-iframe',{});
});
// called by push url
publicRouter.route('/sptest-dynamic/:store')
.get(function (req, res, next) {
console.log('GET for sptest-dynamin for store',req.params.store);
if (!req.params.store) {
console.log( 'Incomplete sptest-dynamic params',req.params);
return res.status(403).send('Missing store')
}
res.render('sptest-dynamic',{store: req.params.store});
});
// refresh token
publicRouter.route('/getoken')
.get(function (req, res, next) {
console.log('GET token request',req.body);
function getOauthToken() {
getNewToken(function (err, token) {
if (err) {
console.log('Err:',err,'Token:',token);
return res.status(401).send(err);
} else { // sucess
console.log('Token',token);
return res.status(200).send(token);
}
});
}
getOauthToken();
});
function getNewToken(callback) {
var urlParams ='https://api0.silverpop.com/oauth/token?'+getRefreshTokenParams ();
//console.log('urlparams',urlParams);
var options = {
uri: urlParams,
method: 'POST',
headers: {
"Content-Type": "application/json"
}
};
request(options, function (error, response, body) {
if (!error ) {
//console.log('OK body:',body) ;
if (body ) {
var bodyParse = JSON.parse(body)
if (bodyParse.error) {
console.log(bodyParse);
callback (bodyParse.error,null);
} else { // got new token
callback (null,bodyParse.access_token); // success
}
} else {
console.log('error body is null',response);
callback( 'Null body returned',null);
}
} else {
console.log('Error in push api',error) ;
callback (error, null) ;
}
});
};
function getJson (appkey,muid,channelid,store,contId) {
var mid ='"'+muid+'"';
var cid ='"'+channelid+'"';
var akey ='"'+appkey+'"';
var contentid ='"'+contId+'"';
// URL Push
/*var demoJson ='{"channelQualifiers": [ '+akey+' ], "content": { "simple": { "apns": '+
'{ "aps": { "alert": "Special Sale for Store '+store+'", "sound":"default", "badge": 3 }, "notification-action": { "type": "url", "name": "open url",'+
' "value": "https://mcedemo.mybluemix.net/sptest-dynamic/'+ store+'" } } } }, "contacts": [ { "channel": { "appKey": '+akey+','+
' "userId":'+mid+', "channelId":'+cid+'} } ] }'; */
// Rich push to specific page
var demoJson ='{"channelQualifiers": [ '+akey+' ], "content": { "contentId":'+contentid+'}, "contacts": [ { "channel": { "appKey": '+akey+','+
' "userId":'+mid+', "channelId":'+cid+'} } ],"campaignName": "push06march2017" }';
// console.log('return',JSON.stringify(demoJson) );
return(JSON.parse(demoJson));
}
// get json for token
function getRefreshTokenParams () {
var client_id ='&client_id='+vcapServices.client_id;
var client_secret ='&client_secret='+vcapServices.client_secret;
var refresh_token ='&refresh_token='+vcapServices.refresh_token;
var params ='grant_type=refresh_token'+client_id+client_secret+refresh_token ;
return(params);
}
}
//module.exports = publicRouter; | giladm/mcedemo | routes/publicRouter.js | JavaScript | apache-2.0 | 7,077 |
import React from "react";
import { Link } from "react-router";
import Loader from "../../core/Loader";
import DataComponent from "../base/DataComponent";
import DataError from "../base/DataError";
import ResourceAction from "./../base/ResourceAction";
import history from "../../history";
/**
* @author Niklas Keller
*/
class NotificationDetail extends DataComponent {
getDataUri() {
return "notifications/" + this.props.params.id;
}
componentWillReceiveProps(next) {
let oldId = this.props.params.id;
let newId = next.params.id;
if (oldId !== newId) {
this.fetchData();
}
}
render() {
let content = null;
if (this.state.loaded) {
if (this.state.failed) {
content = (
<DataError />
);
} else {
let emails = this.state.data.emails.map((item) => (
<li><code>{item}</code></li>
));
emails = (
<ul>
{emails}
</ul>
);
content = (
<div>
<div className="actions">
<Link to={this.props.location.pathname + "/edit"} className="action">
<i className="fa fa-pencil icon"/>
Edit
</Link>
<ResourceAction icon="trash" method="DELETE" uri={"notifications/" + this.props.params.id}
onClick={() => window.confirm("Do you really want to delete this notification?")}
onSuccess={() => history.replaceState(null, "/notifications")}
onError={(e) => {
let error = typeof e === "object" && "data" in e ? e.data.detail : "Unknown error.";
window.alert("Deletion failed. " + error);
}}
backend={this.props.backend}>
Delete
</ResourceAction>
</div>
<h1>Notification: {this.state.data.name}</h1>
<label className="input-label">Description</label>
<pre>{this.state.data.description}</pre>
<label className="input-label">SQL Query</label>
<pre>{this.state.data.query}</pre>
<label className="input-label">Check Period</label>
<div>Checked every <code>{this.state.data.checkPeriod}</code> seconds.</div>
<label className="input-label">E-Mails</label>
<div>{emails}</div>
<label className="input-label">Send Once</label>
<div>{this.state.data.sendOnce.value ? "Yes, will be sent once and then be deleted." : "No, will be sent on every change."}</div>
</div>
);
}
}
return (
<Loader loaded={this.state.loaded} className="loader">
{content}
</Loader>
);
}
}
export default NotificationDetail; | coolcrowd/control-ui | src/js/components/notifications/NotificationDetail.js | JavaScript | apache-2.0 | 3,477 |
/**
* @license
* Copyright 2016 The Lovefield Project 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.
*/
const chalk = require('chalk');
const spawn = require('child_process').spawn;
const diff = require('diff');
const fs = require('fs-extra');
const gulp = require('gulp');
const change = require('gulp-change');
const format = require('gulp-clang-format').format;
const debug = require('gulp-debug');
const mocha = require('gulp-mocha');
const sourcemaps = require('gulp-sourcemaps');
const transform = require('gulp-transform');
const tslint = require('gulp-tslint');
const tsc = require('gulp-typescript');
const merge = require('merge2');
const nopt = require('nopt');
const path = require('path');
const thru = require('through2');
const Files = {
LIB: 'lib/**/*.ts',
SPEC: 'example/spec/*.ts',
TESTING: 'testing/**/*.ts',
TESTS: 'tests/**/*.ts'
};
const Dir = {
DEF: 'def',
DIST: 'dist',
LIB: 'lib',
OUTPUT: 'out',
SPEC: 'example/spec',
TESTING: 'testing',
TESTS: 'tests'
};
const TSCONFIG = 'tsconfig.json';
function releaseFilter(contents) {
const START_TOKEN = '/// #if DEBUG';
const END_TOKEN = '/// #endif';
let data = contents;
if (contents.includes(START_TOKEN)) {
let lines = contents.split('\n');
let includeLine = true;
data = lines.filter((line) => {
if (line.includes(START_TOKEN)) {
includeLine = false;
} else if (line.includes(END_TOKEN)) {
includeLine = true;
}
return includeLine;
}).join('\n');
}
return data;
}
function doBuild(srcs, defs, outs, filter, override) {
let tsProject = tsc.createProject(TSCONFIG, override);
let tsResult = gulp.src(srcs)
.pipe(transform(filter, {encoding: 'utf8'}))
.pipe(sourcemaps.init())
.pipe(debug())
.pipe(tsProject(tsc.reporter.defaultReporter()))
.on('error', (err) => { process.exit(1); });
return merge([
tsResult.dts.pipe(gulp.dest(defs)),
tsResult.js
.pipe(sourcemaps.write())
.pipe(gulp.dest(outs))
]);
}
function getFilter() {
let knownOpts = {
'mode': ['debug', 'release'],
};
let opts = nopt(knownOpts, null, process.argv, 2);
return (opts.mode == 'release') ? releaseFilter : (x) => x;
}
function build(srcs, defs, outs) {
let filter = getFilter();
doBuild(srcs, defs, outs, filter, {});
}
function prettyPrint(patch) {
if (patch.hunks.length) {
console.log(chalk.yellow('===== ' + patch.oldFileName));
patch.hunks.forEach((hunk) => {
let numberOld = hunk.oldStart;
let numberNew = hunk.newStart;
hunk.lines.forEach((line) => {
if (line[0] == '-') {
console.log(chalk.bgRed(numberOld + ' ' + line));
numberOld++;
} else if (line[0] == '+') {
console.log(chalk.bgGreen(numberNew + ' ' + line));
numberNew++;
} else {
console.log(numberOld + ' ' + line);
numberOld++;
numberNew++;
}
});
});
console.log();
}
}
function checkFormat() {
let stream = thru.obj(function(file, enc, done) {
if (file.isBuffer()) {
let original = fs.readFileSync(file.path, 'utf8');
let formatted = file.contents.toString();
let patch = diff.structuredPatch(file.path, null, original, formatted);
prettyPrint(patch);
} else {
console.error('Not supported');
process.exit(1);
}
// Make sure the file goes through the next gulp plugin.
this.push(file);
done();
});
return stream;
}
gulp.task('default', () => {
let log = console.log;
log('Usage:');
log('gulp build: build all libraries and tests');
log('gulp clean: remove all intermediate files');
log('gulp debug: run mocha debug');
log('gulp dist: create dist package');
log('gulp gen: generate and validate spec examples');
log('gulp test: run mocha tests');
log('gulp format_check: check files against clang-format')
log('gulp lint: run tslint against code');
log('');
log('Options:');
log(' --grep <pattern>: Mocha grep, can be used with debug/dev_test/test');
log(' --mode <debug|release>: Choose build mode');
});
gulp.task('build_lib', () => {
build(Files.LIB,
path.join(Dir.OUTPUT, Dir.DEF),
path.join(Dir.OUTPUT, Dir.LIB));
});
gulp.task('build_testing', () => {
build(Files.TESTING,
path.join(Dir.OUTPUT, Dir.DEF),
path.join(Dir.OUTPUT, Dir.TESTING));
});
gulp.task('build_tests', ['build_lib', 'build_testing'], () => {
build(Files.TESTS,
path.join(Dir.OUTPUT, Dir.DEF),
path.join(Dir.OUTPUT, Dir.TESTS));
});
gulp.task('format_check', () => {
gulp.src([Files.LIB, Files.TESTS, Files.SPEC])
.pipe(format())
.pipe(checkFormat());
});
function handleIntermediate(content) {
const START_TOKEN = '///// @@start';
const END_TOKEN = '///// @@end';
const SKIP_TOKEN = 'exports.';
let lines = content.split('\n');
let started = false;
let ended = false;
let results = lines.filter(line => {
if (ended) return false;
if (!started) {
if (line.startsWith(START_TOKEN)) {
started = true;
}
return false;
}
if (line.startsWith(END_TOKEN)) {
ended = true;
return false;
}
return true;
});
return results
.map(line => {
return line.startsWith(SKIP_TOKEN) ? '' : line;
})
.join('\n');
}
gulp.task('gen', () => {
let tsProject = tsc.createProject(TSCONFIG, {
"declaration": false,
"removeComments": false
});
gulp.src(Files.SPEC)
.pipe(debug())
.pipe(tsProject(tsc.reporter.defaultReporter()))
.on('error', (err) => { process.exit(1); })
.js
.pipe(change(handleIntermediate))
.pipe(gulp.dest(path.join(Dir.OUTPUT, Dir.SPEC)));
});
gulp.task('lint', () => {
gulp.src([Files.LIB, Files.TESTS, Files.SPEC])
.pipe(tslint({formatter: 'stylish'}))
.pipe(tslint.report({
summarizeFailureOutput: true
}));
});
gulp.task('build', ['build_tests'], () => {
});
gulp.task('dist', () => {
let cwd = process.cwd();
let targetLib = path.resolve(path.join(__dirname, Dir.OUTPUT, Dir.LIB));
let targetDef = path.resolve(path.join(__dirname, Dir.OUTPUT, Dir.DEF));
process.chdir(path.resolve(__dirname, Dir.DIST));
if (!fs.existsSync(Dir.LIB)) {
fs.symlinkSync(targetLib, Dir.LIB);
}
if (!fs.existsSync(Dir.DEF)) {
fs.symlinkSync(targetDef, Dir.DEF);
}
process.chdir(cwd);
});
function getGrepPattern() {
let knownOpts = { 'grep': String };
let opts = nopt(knownOpts, null, process.argv, 2);
return opts.grep ? opts.grep : undefined;
}
gulp.task('test', () => {
let mochaOptions = {
reporter: 'spec',
require: ['source-map-support/register'],
grep: getGrepPattern()
};
gulp.src('out/tests/**/*.js', {read: false})
.pipe(mocha(mochaOptions));
});
gulp.task('debug', () => {
let grepPattern = getGrepPattern();
let nodeDebug = 'node';
let mochaCmd =
path.resolve(__dirname, 'node_modules/mocha/bin/mocha');
let commandLine = [
'--inspect',
mochaCmd,
'debug',
'--no-timeouts',
'--require', '"source-map-support/register"',
'--recursive', '"out/tests/**/*.js"'];
if (grepPattern) {
commandLine.push('--grep');
commandLine.push(grepPattern);
}
console.log('Run this command line in your shell:');
console.log('node', commandLine.join(' '));
});
gulp.task('clean', () => {
fs.removeSync(Dir.OUTPUT);
});
| arthurhsu/rdb-polyfill | gulpfile.js | JavaScript | apache-2.0 | 8,013 |
'use strict';
const _ = require('lodash');
const config = require('../../../common/config');
const CONST = require('../../../common/constants');
const errors = require('../../../common/errors');
const logger = require('../../../common/logger');
const jwt = require('../jwt');
const utils = require('../../../common/utils');
const cf = require('../../../data-access-layer/cf');
const DirectorManager = require('./DirectorManager');
const cloudController = cf.cloudController;
const Conflict = errors.Conflict;
const DeploymentAlreadyLocked = errors.DeploymentAlreadyLocked;
const DeploymentAttemptRejected = errors.DeploymentAttemptRejected;
function AsyncServiceInstanceOperationInProgress(err) {
const response = _.get(err, 'error', {});
return response.code === 60016 || response.error_code === 'CF-AsyncServiceInstanceOperationInProgress';
}
function DeploymentLocked(err) {
const response = _.get(err, 'error', {});
const description = _.get(response, 'description', '');
return description.indexOf(CONST.OPERATION_TYPE.LOCK) > 0 && response.error_code === 'CF-ServiceBrokerRequestRejected';
}
function DeploymentStaggered(err) {
const response = _.get(err, 'error', {});
const description = _.get(response, 'description', '');
return description.indexOf(CONST.FABRIK_OPERATION_STAGGERED) > 0 && description.indexOf(CONST.FABRIK_OPERATION_COUNT_EXCEEDED) > 0 && response.error_code === 'CF-ServiceBrokerRequestRejected';
}
class ServiceFabrikOperation {
constructor(name, opts) {
this.name = name;
this.guid = undefined;
opts = opts || {};
this.bearer = opts.bearer;
this.username = opts.username;
this.useremail = opts.useremail;
this.arguments = opts.arguments || {};
this.isOperationSync = opts.isOperationSync ? true : false;
this.runImmediately = opts.runImmediately;
if (opts.instance_id) {
this.instanceId = opts.instance_id;
} else if (opts.deployment) {
this.instanceId = _.nth(DirectorManager.parseDeploymentName(opts.deployment), 2);
}
}
toJSON() {
return _.pick(this, 'name', 'guid', 'username', 'useremail', 'arguments');
}
getResult() {
return _.pick(this, 'name', 'guid');
}
getToken() {
return utils
.uuidV4()
.then(guid => _.set(this, 'guid', guid))
.then(() => jwt.sign(this.toJSON(), config.password));
}
updateServiceInstance(token) {
const options = {
parameters: {
'service-fabrik-operation': token
}
};
if (this.runImmediately) {
options.parameters._runImmediately = this.runImmediately;
}
options.isOperationSync = this.isOperationSync;
if (this.bearer) {
options.auth = {
bearer: this.bearer
};
}
return cloudController.updateServiceInstance(this.instanceId, options);
}
invoke() {
return this
.getToken()
.then(token => this.updateServiceInstance(token))
.then(() => this.getResult())
.catch(AsyncServiceInstanceOperationInProgress, err => {
const message = _.get(err.error, 'description', 'Async service instance operation in progress');
throw new Conflict(message);
})
.catch(DeploymentStaggered, err => {
logger.info('Deployment operation not proceeding due to rate limit exceeded', err.message);
throw new DeploymentAttemptRejected(this.deployment || this.instanceId);
})
.catch(DeploymentLocked, err => {
// Sample error description is
// Service broker error: Service Instance abcdefgh-abcd-abcd-abcd-abcdefghijkl __Locked__ at Mon Sep 10 2018 11:17:01 GMT+0000 (UTC) for backup
const description = _.get(err, 'error.description', '');
const lookupString = 'error: ';
const startIdx = description.indexOf(lookupString);
let lockMsg;
if (startIdx !== -1) {
lockMsg = description.substring(startIdx + lookupString.length);
}
logger.info(`Lock message : ${lockMsg}`);
throw new DeploymentAlreadyLocked(this.instanceId, undefined, lockMsg);
});
}
handle(req, res) {
if (_.isObject(req.user)) {
this.username = req.user.name;
this.useremail = req.user.email || '';
}
return this
.invoke()
.then(body => res
.status(202)
.send(body)
);
}
}
module.exports = ServiceFabrikOperation; | sauravmndl/service-fabrik-broker | broker/lib/fabrik/ServiceFabrikOperation.js | JavaScript | apache-2.0 | 4,373 |
var searchData=
[
['undefined_5fband',['UNDEFINED_BAND',['../a01181.html#a9efc501b4bfd07c8e00e55bbb5f28690',1,'blkocc.h']]],
['uni_5fmax_5flegal_5futf32',['UNI_MAX_LEGAL_UTF32',['../a00614.html#a98a2f50a1ca513613316ffd384dd1bfb',1,'unichar.cpp']]],
['unichar_5flen',['UNICHAR_LEN',['../a00617.html#a902bc40c9d89802bc063afe30ce9e708',1,'unichar.h']]],
['unlikely_5fnum_5ffeat',['UNLIKELY_NUM_FEAT',['../a00659.html#a17b4f36c5132ab55beb280e0cc233228',1,'adaptmatch.cpp']]],
['unlv_5fext',['UNLV_EXT',['../a00221.html#aa14fc11aa7528cfededa3d19c18901f1',1,'blread.cpp']]],
['unusedclassidin',['UnusedClassIdIn',['../a00749.html#a3e7ae3ffbac606326937a4c701aeeaf2',1,'intproto.h']]],
['unz_5fbadzipfile',['UNZ_BADZIPFILE',['../a01565.html#a3fcc1d41cbea304ce10286ce99577625',1,'unzip.h']]],
['unz_5fbufsize',['UNZ_BUFSIZE',['../a01562.html#ac88907609a3408a8ee6544287b6c9880',1,'unzip.c']]],
['unz_5fcrcerror',['UNZ_CRCERROR',['../a01565.html#ae9155f504a5db40587b390f9e487c303',1,'unzip.h']]],
['unz_5fend_5fof_5flist_5fof_5ffile',['UNZ_END_OF_LIST_OF_FILE',['../a01565.html#ac55ed190d07021ce9bc1bf34b91dcae9',1,'unzip.h']]],
['unz_5feof',['UNZ_EOF',['../a01565.html#a0438887aea4e1c58e1b3955838a907f3',1,'unzip.h']]],
['unz_5ferrno',['UNZ_ERRNO',['../a01565.html#aae99fb3e34ea9f78ca8ba4a716f86e68',1,'unzip.h']]],
['unz_5finternalerror',['UNZ_INTERNALERROR',['../a01565.html#a813da146afcb179d57e948bf6871799b',1,'unzip.h']]],
['unz_5fmaxfilenameinzip',['UNZ_MAXFILENAMEINZIP',['../a01562.html#a97ef86322b25dcc3d0fc5eb50d386b54',1,'unzip.c']]],
['unz_5fok',['UNZ_OK',['../a01565.html#ada043545f95ccd4dae93fa44d95e39a8',1,'unzip.h']]],
['unz_5fparamerror',['UNZ_PARAMERROR',['../a01565.html#aca983831f4d25e504d544eb07f48e39b',1,'unzip.h']]],
['update_5fedge_5fwindow',['update_edge_window',['../a01703.html#a3a90c5459659abe9227ab93d20042630',1,'plotedges.h']]]
];
| stweil/tesseract-ocr.github.io | 4.00.00dev/search/defines_15.js | JavaScript | apache-2.0 | 1,888 |
/* global QUnit, sinon */
sap.ui.define([
"sap/ui/mdc/Table",
"sap/ui/mdc/table/Column",
"sap/ui/mdc/library",
"../../QUnitUtils",
"../../util/createAppEnvironment",
"sap/ui/fl/write/api/ControlPersonalizationWriteAPI",
"sap/ui/core/Core",
"sap/ui/core/library",
"sap/ui/model/odata/v4/ODataModel",
"sap/ui/model/Filter",
"sap/ui/base/ManagedObjectObserver"
], function(
Table,
Column,
Library,
MDCQUnitUtils,
createAppEnvironment,
ControlPersonalizationWriteAPI,
Core,
coreLibrary,
ODataModel,
Filter,
ManagedObjectObserver
) {
"use strict";
var TableType = Library.TableType;
sap.ui.define("odata.v4.TestDelegate", [
"sap/ui/mdc/odata/v4/TableDelegate"
], function(TableDelegate) {
var TestDelegate = Object.assign({}, TableDelegate);
TestDelegate.updateBindingInfo = function(oMDCTable, oBindingInfo) {
TableDelegate.updateBindingInfo.apply(this, arguments);
oBindingInfo.path = "/ProductList";
};
return TestDelegate;
});
Core.loadLibrary("sap.ui.fl");
var sTableView1 =
'<mvc:View xmlns:mvc="sap.ui.core.mvc" xmlns:m="sap.m" xmlns="sap.ui.mdc" xmlns:mdcTable="sap.ui.mdc.table">' +
'<Table p13nMode="Group,Aggregate" id="myTable" delegate=\'\{ name : "odata.v4.TestDelegate" \}\'>' +
'<columns><mdcTable:Column id="myTable--column0" header="column 0" dataProperty="Name">' +
'<m:Text text="{Name}" id="myTable--text0" /></mdcTable:Column>' +
'<mdcTable:Column id="myTable--column1" header="column 1" dataProperty="Country">' +
'<m:Text text="{Country}" id="myTable--text1" /></mdcTable:Column>' +
'<mdcTable:Column header="column 2" dataProperty="name_country"> ' +
'<m:Text text="{Name}" id="myTable--text2" /></mdcTable:Column></columns> ' +
'</Table></mvc:View>';
var sTableView2 =
'<mvc:View xmlns:mvc="sap.ui.core.mvc" xmlns:m="sap.m" xmlns="sap.ui.mdc" xmlns:mdcTable="sap.ui.mdc.table">' +
'<Table p13nMode="Group,Aggregate" id="myTable" delegate=\'\{ name : "odata.v4.TestDelegate" \}\'>' +
'<columns>' +
'<mdcTable:Column header="column 2" dataProperty="name_country"> ' +
'<m:Text text="{Name}" id="myTable--text2" /></mdcTable:Column></columns> ' +
'</Table></mvc:View>';
function createColumnStateIdMap(oTable, aStates) {
var mState = {};
oTable.getColumns().forEach(function(oColumn, iIndex) {
mState[oColumn.getId() + "-innerColumn"] = aStates[iIndex];
});
return mState;
}
function poll(fnCheck, iTimeout) {
return new Promise(function(resolve, reject) {
if (fnCheck()) {
resolve();
return;
}
var iRejectionTimeout = setTimeout(function() {
clearInterval(iCheckInterval);
reject("Polling timeout");
}, iTimeout == null ? 100 : iTimeout);
var iCheckInterval = setInterval(function() {
if (fnCheck()) {
clearTimeout(iRejectionTimeout);
clearInterval(iCheckInterval);
resolve();
}
}, 10);
});
}
function waitForBindingInfo(oTable, iTimeout) {
return poll(function() {
var oInnerTable = oTable._oTable;
return oInnerTable && oInnerTable.getBindingInfo(oTable._getStringType() === "Table" ? "rows" : "items");
}, iTimeout);
}
QUnit.module("Initialization", {
afterEach: function() {
if (this.oTable) {
this.oFetchProperties.restore();
this.oFetchPropertyExtensions.restore();
this.oFetchPropertiesForBinding.restore();
this.oFetchPropertyExtensionsForBinding.restore();
this.oTable.destroy();
}
},
initTable: function(mSettings) {
if (this.oTable) {
this.oTable.destroy();
}
this.oTable = new Table(Object.assign({
delegate: {
name: "odata.v4.TestDelegate"
}
}, mSettings));
return this.oTable.awaitControlDelegate().then(function(oDelegate) {
this.oFetchProperties = sinon.spy(oDelegate, "fetchProperties");
this.oFetchPropertyExtensions = sinon.spy(oDelegate, "fetchPropertyExtensions");
this.oFetchPropertiesForBinding = sinon.spy(oDelegate, "fetchPropertiesForBinding");
this.oFetchPropertyExtensionsForBinding = sinon.spy(oDelegate, "fetchPropertyExtensionsForBinding");
return this.oTable._fullyInitialized();
}.bind(this)).then(function() {
return this.oTable;
}.bind(this));
},
assertFetchPropertyCalls: function(assert, iProperties, iPropertyExtensions, iPropertiesForBinding, oPropertyExtensionsForBinding) {
assert.equal(this.oFetchProperties.callCount, iProperties, "Delegate.fetchProperties calls");
assert.equal(this.oFetchPropertyExtensions.callCount, iPropertyExtensions, "Delegate.fetchPropertyExtensions calls");
assert.equal(this.oFetchPropertiesForBinding.callCount, iPropertiesForBinding, "Delegate.fetchPropertiesForBinding calls");
assert.equal(this.oFetchPropertyExtensionsForBinding.callCount, oPropertyExtensionsForBinding, "Delegate.fetchPropertyExtensionsForBinding calls");
}
});
QUnit.test("GridTable; Grouping and aggregation disabled", function(assert) {
return this.initTable().then(function(oTable) {
assert.notOk(oTable._oTable.getDependents().find(function(oDependent) {
return oDependent.isA("sap.ui.table.plugins.V4Aggregation");
}), "V4Aggregation plugin is not added to the inner table");
this.assertFetchPropertyCalls(assert, 1, 1, 0, 0);
}.bind(this));
});
QUnit.test("GridTable; Grouping and aggregation enabled", function(assert) {
return this.initTable({
p13nMode: ["Group", "Aggregate"]
}).then(function(oTable) {
var oPlugin = oTable._oTable.getDependents()[0];
assert.ok(oPlugin.isA("sap.ui.table.plugins.V4Aggregation"), "V4Aggregation plugin is added to the inner table");
assert.ok(oPlugin.isActive(), "V4Aggregation plugin is active");
var oGroupHeaderFormatter = sinon.spy(oTable.getControlDelegate(), "formatGroupHeader");
oPlugin.getGroupHeaderFormatter()("MyContext", "MyProperty");
assert.ok(oGroupHeaderFormatter.calledOnceWithExactly(oTable, "MyContext", "MyProperty"), "Call Delegate.formatGroupHeader");
oGroupHeaderFormatter.restore();
this.assertFetchPropertyCalls(assert, 2, 2, 1, 1);
}.bind(this));
});
QUnit.test("ResponsiveTable; Grouping and aggregation disabled", function(assert) {
return this.initTable({
type: TableType.ResponsiveTable
}).then(function(oTable) {
assert.notOk(oTable._oTable.getDependents().find(function(oDependent) {
return oDependent.isA("sap.ui.table.plugins.V4Aggregation");
}), "V4Aggregation plugin is not added to the inner table");
this.assertFetchPropertyCalls(assert, 1, 1, 0, 0);
}.bind(this));
});
QUnit.test("ResponsiveTable; Grouping and aggregation enabled", function(assert) {
return this.initTable({
type: TableType.ResponsiveTable,
p13nMode: ["Group", "Aggregate"]
}).then(function(oTable) {
assert.notOk(oTable._oTable.getDependents().find(function(oDependent) {
return oDependent.isA("sap.ui.table.plugins.V4Aggregation");
}), "V4Aggregation plugin is not added to the inner table");
this.assertFetchPropertyCalls(assert, 1, 1, 0, 0);
}.bind(this));
});
QUnit.module("Change table settings", {
beforeEach: function() {
return this.initTable();
},
afterEach: function() {
this.restoreFetchPropertyMethods();
if (this.oTable) {
this.oTable.destroy();
}
},
initTable: function(mSettings) {
if (this.oTable) {
this.oTable.destroy();
}
this.restoreFetchPropertyMethods();
this.oTable = new Table(Object.assign({
delegate: {
name: "odata.v4.TestDelegate"
},
p13nMode: ["Group", "Aggregate"]
}, mSettings));
return this.oTable.awaitControlDelegate().then(function(oDelegate) {
this.oFetchProperties = sinon.spy(oDelegate, "fetchProperties");
this.oFetchPropertyExtensions = sinon.spy(oDelegate, "fetchPropertyExtensions");
this.oFetchPropertiesForBinding = sinon.spy(oDelegate, "fetchPropertiesForBinding");
this.oFetchPropertyExtensionsForBinding = sinon.spy(oDelegate, "fetchPropertyExtensionsForBinding");
return this.oTable._fullyInitialized();
}.bind(this)).then(function() {
return this.oTable;
}.bind(this));
},
assertFetchPropertyCalls: function(assert, iProperties, iPropertyExtensions, iPropertiesForBinding, oPropertyExtensionsForBinding) {
assert.equal(this.oFetchProperties.callCount, iProperties, "Delegate.fetchProperties calls");
assert.equal(this.oFetchPropertyExtensions.callCount, iPropertyExtensions, "Delegate.fetchPropertyExtensions calls");
assert.equal(this.oFetchPropertiesForBinding.callCount, iPropertiesForBinding, "Delegate.fetchPropertiesForBinding calls");
assert.equal(this.oFetchPropertyExtensionsForBinding.callCount, oPropertyExtensionsForBinding, "Delegate.fetchPropertyExtensionsForBinding calls");
},
resetFetchPropertyCalls: function() {
this.oFetchProperties.reset();
this.oFetchPropertyExtensions.reset();
this.oFetchPropertiesForBinding.reset();
this.oFetchPropertyExtensionsForBinding.reset();
},
restoreFetchPropertyMethods: function() {
if (this.oFetchProperties) {
this.oFetchProperties.restore();
this.oFetchPropertyExtensions.restore();
this.oFetchPropertiesForBinding.restore();
this.oFetchPropertyExtensionsForBinding.restore();
}
}
});
QUnit.test("Type", function(assert) {
var that = this;
var oOldPlugin = that.oTable._oTable.getDependents()[0];
this.resetFetchPropertyCalls();
this.oTable.setType(TableType.ResponsiveTable);
return this.oTable._fullyInitialized().then(function() {
assert.notOk(that.oTable._oTable.getDependents().find(function(oDependent) {
return oDependent.isA("sap.ui.table.plugins.V4Aggregation");
}), "V4Aggregation plugin is not added to the inner table");
that.assertFetchPropertyCalls(assert, 0, 0, 0, 0);
that.resetFetchPropertyCalls();
that.oTable.setType(TableType.Table);
return that.oTable._fullyInitialized();
}).then(function() {
var oPlugin = that.oTable._oTable.getDependents()[0];
assert.ok(oPlugin.isA("sap.ui.table.plugins.V4Aggregation"), "V4Aggregation plugin is added to the inner table");
assert.ok(oPlugin.isActive(), "V4Aggregation plugin is active");
assert.notEqual(oPlugin, oOldPlugin, "V4Aggregation plugin is not the same instance");
assert.ok(oOldPlugin.bIsDestroyed, "Old V4Aggregation plugin is destroyed");
var oGroupHeaderFormatter = sinon.spy(that.oTable.getControlDelegate(), "formatGroupHeader");
oPlugin.getGroupHeaderFormatter()("MyContext", "MyProperty");
assert.ok(oGroupHeaderFormatter.calledOnceWithExactly(that.oTable, "MyContext", "MyProperty"), "Call Delegate.formatGroupHeader");
oGroupHeaderFormatter.restore();
that.assertFetchPropertyCalls(assert, 0, 0, 0, 0);
});
});
QUnit.test("GridTable; p13nMode", function(assert) {
var oPlugin = this.oTable._oTable.getDependents()[0];
this.resetFetchPropertyCalls();
this.oTable.setP13nMode();
assert.ok(oPlugin.isA("sap.ui.table.plugins.V4Aggregation"), "V4Aggregation plugin is added to the inner table");
assert.notOk(oPlugin.isActive(), "V4Aggregation plugin is not active");
assert.equal(oPlugin, this.oTable._oTable.getDependents()[0], "V4Aggregation plugin is the same instance");
this.assertFetchPropertyCalls(assert, 0, 0, 0, 0);
this.oTable.setP13nMode(["Group"]);
assert.ok(oPlugin.isA("sap.ui.table.plugins.V4Aggregation"), "V4Aggregation plugin is added to the inner table");
assert.ok(oPlugin.isActive(), "V4Aggregation plugin is active");
assert.equal(oPlugin, this.oTable._oTable.getDependents()[0], "V4Aggregation plugin is the same instance");
this.assertFetchPropertyCalls(assert, 0, 0, 0, 0);
});
QUnit.test("GridTable; Initial activation of analytical p13n modes", function(assert) {
var that = this;
return this.initTable({
p13nMode: []
}).then(function() {
that.resetFetchPropertyCalls();
that.oTable.setP13nMode(["Group"]);
assert.notOk(that.oTable._oTable.getDependents().find(function(oDependent) {
return oDependent.isA("sap.ui.table.plugins.V4Aggregation");
}), "V4Aggregation plugin is not yet added to the inner table");
return new Promise(function(resolve) {
new ManagedObjectObserver(function(oChange) {
oChange.child.setPropertyInfos = resolve;
}).observe(that.oTable._oTable, {
aggregations: ["dependents"]
});
});
}).then(function() {
var oPlugin = that.oTable._oTable.getDependents()[0];
assert.ok(oPlugin.isA("sap.ui.table.plugins.V4Aggregation"), "V4Aggregation plugin is added to the inner table");
assert.ok(oPlugin.isActive(), "V4Aggregation plugin is active");
var oGroupHeaderFormatter = sinon.spy(that.oTable.getControlDelegate(), "formatGroupHeader");
oPlugin.getGroupHeaderFormatter()("MyContext", "MyProperty");
assert.ok(oGroupHeaderFormatter.calledOnceWithExactly(that.oTable, "MyContext", "MyProperty"), "Call Delegate.formatGroupHeader");
oGroupHeaderFormatter.restore();
that.assertFetchPropertyCalls(assert, 1, 1, 1, 1);
});
});
QUnit.module("Basic functionality with JsControlTreeModifier", {
before: function() {
MDCQUnitUtils.stubPropertyInfos(Table.prototype, [{
name: "Name",
label: "Name",
path: "Name",
groupable: true
}, {
name: "Country",
label: "Country",
path: "Country",
groupable: true
}, {
name: "name_country",
label: "Complex Title & Description",
propertyInfos: ["Name", "Country"]
}, {
name: "Value",
label: "Value",
path: "Value",
sortable: false,
filterable: false
}]);
MDCQUnitUtils.stubPropertyExtension(Table.prototype, {
Name: {
defaultAggregate: {}
},
Country: {
defaultAggregate: {}
}
});
},
beforeEach: function() {
return this.createTestObjects().then(function() {
return this.oTable.getEngine().getModificationHandler().waitForChanges({
element: this.oTable
});
}.bind(this));
},
afterEach: function() {
this.destroyTestObjects();
},
after: function() {
MDCQUnitUtils.restorePropertyInfos(Table.prototype);
MDCQUnitUtils.restorePropertyExtension(Table.prototype);
},
createTestObjects: function() {
return createAppEnvironment(sTableView1, "Table").then(function(mCreatedApp){
this.oView = mCreatedApp.view;
this.oUiComponentContainer = mCreatedApp.container;
this.oUiComponentContainer.placeAt("qunit-fixture");
Core.applyChanges();
this.oTable = this.oView.byId('myTable');
ControlPersonalizationWriteAPI.restore({
selector: this.oTable
});
}.bind(this));
},
destroyTestObjects: function() {
this.oUiComponentContainer.destroy();
}
});
QUnit.test("Allowed analytics on column header and tableDelegate API's", function(assert) {
var fColumnPressSpy = sinon.spy(this.oTable, "_onColumnPress");
var oResourceBundle = Core.getLibraryResourceBundle("sap.ui.mdc");
var oTable = this.oTable;
var oPlugin;
var fSetAggregationSpy;
this.oTable.addColumn(new Column({
header: "Value",
dataProperty: "Value",
template: new Text({text: "Value"})
}));
return oTable._fullyInitialized().then(function() {
oTable._oTable.fireEvent("columnSelect", {
column: oTable._oTable.getColumns()[3]
});
return oTable._fullyInitialized().then(function() {
assert.notOk(oTable._oPopover, "ColumnHeaderPopover not created");
fColumnPressSpy.resetHistory();
});
}).then(function() {
oPlugin = oTable._oTable.getDependents()[0];
fSetAggregationSpy = sinon.spy(oPlugin, "setAggregationInfo");
oTable.setAggregateConditions({
Country: {}
});
oTable.rebind();
assert.ok(fSetAggregationSpy.calledOnceWithExactly({
visible: ["Name", "Country", "Value"],
groupLevels: [],
grandTotal: ["Country"],
subtotals: ["Country"],
columnState: createColumnStateIdMap(oTable, [
{subtotals: false, grandTotal: false},
{subtotals: true, grandTotal: true},
{subtotals: true, grandTotal: true},
{subtotals: false, grandTotal: false}
]),
search: undefined
}), "Plugin#setAggregationInfo call");
oTable._oTable.fireEvent("columnSelect", {
column: oTable._oTable.getColumns()[0]
});
assert.ok(fColumnPressSpy.calledOnce, "First Column pressed");
return oTable._fullyInitialized();
}).then(function() {
assert.strictEqual(oTable._oPopover.getItems()[0].getLabel(), oResourceBundle.getText("table.SETTINGS_GROUP"),
"The first column has group menu item");
assert.strictEqual(oTable._oPopover.getItems()[1].getLabel(), oResourceBundle.getText("table.SETTINGS_TOTALS"),
"The first column has aggregate menu item");
return new Promise(function(resolve) {
oTable._oPopover.getAggregation("_popover").attachAfterClose(function() {
oTable._oTable.fireEvent("columnSelect", {
column: oTable._oTable.getColumns()[2]
});
resolve();
});
oTable._oPopover.getAggregation("_popover").close();
}).then(function() {
return oTable._fullyInitialized();
});
}).then(function() {
assert.strictEqual(fColumnPressSpy.callCount, 2, "Third Column pressed");
assert.strictEqual(oTable._oPopover.getItems()[0].getItems().length,2, "The last column has complex property with list of two items");
fSetAggregationSpy.reset();
oTable.setGroupConditions({
groupLevels: [
{
"name": "Name"
}
]
});
oTable.rebind();
assert.ok(fSetAggregationSpy.calledOnceWithExactly({
visible: ["Name", "Country", "Value"],
groupLevels: ["Name"],
grandTotal: ["Country"],
subtotals: ["Country"],
columnState: createColumnStateIdMap(oTable, [
{subtotals: false, grandTotal: false},
{subtotals: true, grandTotal: true},
{subtotals: true, grandTotal: true},
{subtotals: false, grandTotal: false}
]),
search: undefined
}), "Plugin#setAggregationInfo call");
fSetAggregationSpy.reset();
oTable.insertColumn(new Column({
id: "cl"
}), 2);
oTable.rebind();
assert.ok(fSetAggregationSpy.calledOnceWithExactly({
visible: ["Name", "Country", "Value"],
groupLevels: ["Name"],
grandTotal: ["Country"],
subtotals: ["Country"],
columnState: createColumnStateIdMap(oTable, [
{subtotals: false, grandTotal: false},
{subtotals: true, grandTotal: true},
{subtotals: false, grandTotal: false},
{subtotals: true, grandTotal: true},
{subtotals: false, grandTotal: false}
]),
search: undefined
}), "Plugin#setAggregationInfo call");
fSetAggregationSpy.restore();
});
});
QUnit.test("Grouping enabled on column press", function(assert) {
var oTable = this.oTable;
var done = assert.async();
var fColumnPressSpy = sinon.spy(oTable, "_onColumnPress");
oTable._fullyInitialized().then(function() {
var oInnerColumn = oTable._oTable.getColumns()[0];
oTable._oTable.fireEvent("columnSelect", {
column: oInnerColumn
});
assert.ok(fColumnPressSpy.calledOnce, "First column pressed");
fColumnPressSpy.restore();
oTable._fullyInitialized().then(function() {
var oPlugin = oTable._oTable.getDependents()[0];
var fSetAggregationSpy = sinon.spy(oPlugin, "setAggregationInfo");
var oDelegate = oTable.getControlDelegate();
var fnRebind = oDelegate.rebind;
oDelegate.rebind = function () {
fnRebind.apply(this, arguments);
assert.ok(fSetAggregationSpy.calledOnceWithExactly({
visible: ["Name", "Country"],
groupLevels: ["Name"],
grandTotal: [],
subtotals: [],
columnState: createColumnStateIdMap(oTable, [
{subtotals: false, grandTotal: false},
{subtotals: false, grandTotal: false},
{subtotals: false, grandTotal: false}
]),
search: undefined
}), "Plugin#setAggregationInfo call");
fSetAggregationSpy.restore();
oDelegate.rebind = fnRebind;
done();
};
oTable._oPopover.getAggregation("_popover").getContent()[0].getContent()[0].firePress();
});
});
});
QUnit.test("Aggregation enabled on column press", function(assert) {
var oTable = this.oTable;
var fColumnPressSpy = sinon.spy(oTable, "_onColumnPress");
var done = assert.async();
oTable._fullyInitialized().then(function() {
var oInnerSecondColumn = oTable._oTable.getColumns()[1];
oTable._oTable.fireEvent("columnSelect", {
column: oInnerSecondColumn
});
assert.ok(fColumnPressSpy.calledOnce, "First Column pressed");
fColumnPressSpy.restore();
oTable._fullyInitialized().then(function() {
var oDelegate = oTable.getControlDelegate();
var oPlugin = oTable._oTable.getDependents()[0];
var fSetAggregationSpy = sinon.spy(oPlugin, "setAggregationInfo");
var fnRebind = oDelegate.rebind;
oDelegate.rebind = function () {
fnRebind.apply(this, arguments);
assert.ok(fSetAggregationSpy.calledOnceWithExactly({
visible: ["Name", "Country"],
groupLevels: [],
grandTotal: ["Country"],
subtotals: ["Country"],
columnState: createColumnStateIdMap(oTable, [
{subtotals: false, grandTotal: false},
{subtotals: true, grandTotal: true},
{subtotals: true, grandTotal: true}
]),
search: undefined
}), "Plugin#setAggregationInfo call");
fSetAggregationSpy.restore();
oDelegate.rebind = fnRebind;
done();
};
oTable._oPopover.getAggregation("_popover").getContent()[0].getContent()[1].firePress();
});
});
});
QUnit.test("Grouping and Aggregation on two columns", function(assert) {
var oTable = this.oTable;
var fColumnPressSpy = sinon.spy(oTable, "_onColumnPress");
var done = assert.async();
oTable._fullyInitialized().then(function() {
var oInnerColumn = oTable._oTable.getColumns()[0];
oTable._oTable.fireEvent("columnSelect", {
column: oInnerColumn
});
assert.ok(fColumnPressSpy.calledOnce, "First Column pressed");
oTable._fullyInitialized().then(function() {
var oDelegate = oTable.getControlDelegate();
var oPlugin = oTable._oTable.getDependents()[0];
var fSetAggregationSpy = sinon.spy(oPlugin, "setAggregationInfo");
var fnRebind = oDelegate.rebind;
var oInnerSecondColumn = oTable._oTable.getColumns()[1];
oDelegate.rebind = function () {
fnRebind.apply(this, arguments);
assert.ok(fSetAggregationSpy.calledOnceWithExactly({
visible: ["Name", "Country"],
groupLevels: ["Name"],
grandTotal: [],
subtotals: [],
columnState: createColumnStateIdMap(oTable, [
{subtotals: false, grandTotal: false},
{subtotals: false, grandTotal: false},
{subtotals: false, grandTotal: false}
]),
search: undefined
}), "Plugin#setAggregationInfo call");
fColumnPressSpy.restore();
fSetAggregationSpy.restore();
oDelegate.rebind = fnRebind;
new Promise(function(resolve) {
oTable._oPopover.getAggregation("_popover").attachAfterClose(function() {
oTable._oTable.fireEvent("columnSelect", {
column: oInnerSecondColumn
});
resolve();
});
oTable._oPopover.getAggregation("_popover").close();
}).then(function() {
return oTable._fullyInitialized();
}).then(function() {
var oDelegate = oTable.getControlDelegate();
var oPlugin = oTable._oTable.getDependents()[0];
var fSetAggregationSpy = sinon.spy(oPlugin, "setAggregationInfo");
var fnRebind = oDelegate.rebind;
oDelegate.rebind = function () {
fnRebind.apply(this, arguments);
assert.ok(fSetAggregationSpy.calledOnceWithExactly({
visible: ["Name", "Country"],
groupLevels: ["Name"],
grandTotal: ["Country"],
subtotals: ["Country"],
columnState: createColumnStateIdMap(oTable, [
{subtotals: false, grandTotal: false},
{subtotals: true, grandTotal: true},
{subtotals: true, grandTotal: true}
]),
search: undefined
}), "Plugin#setAggregationInfo call");
fColumnPressSpy.restore();
fSetAggregationSpy.restore();
oDelegate.rebind = fnRebind;
done();
};
oTable._oPopover.getAggregation("_popover").getContent()[0].getContent()[1].firePress();
});
};
oTable._oPopover.getAggregation("_popover").getContent()[0].getContent()[0].firePress();
});
});
});
QUnit.test("Grouping and forced aggregation", function(assert) {
var oTable = this.oTable;
var oDelegate;
var oPlugin;
var fSetAggregationSpy;
var fnRebind;
function openColumnMenu(oColumn) {
oTable._oTable.fireEvent("columnSelect", {
column: oColumn
});
// The popover is created async.
return oTable._fullyInitialized();
}
return oTable._fullyInitialized().then(function() {
oDelegate = oTable.getControlDelegate();
oPlugin = oTable._oTable.getDependents()[0];
fSetAggregationSpy = sinon.spy(oPlugin, "setAggregationInfo");
fnRebind = oDelegate.rebind;
return openColumnMenu(oTable._oTable.getColumns()[0]);
}).then(function() {
return new Promise(function(resolve) {
oDelegate.rebind = function() {
fnRebind.apply(this, arguments);
assert.ok(fSetAggregationSpy.calledOnceWithExactly({
visible: ["Name", "Country"],
groupLevels: ["Name"],
grandTotal: [],
subtotals: [],
columnState: createColumnStateIdMap(oTable, [
{subtotals: false, grandTotal: false},
{subtotals: false, grandTotal: false},
{subtotals: false, grandTotal: false}
]),
search: undefined
}), "Plugin#setAggregationInfo call");
fSetAggregationSpy.reset();
oDelegate.rebind = fnRebind;
resolve();
};
oTable._oPopover.getAggregation("_popover").getContent()[0].getContent()[0].firePress();
});
}).then(function() {
return openColumnMenu(oTable._oTable.getColumns()[0]);
}).then(function() {
return new Promise(function(resolve) {
oDelegate.rebind = function() {
fnRebind.apply(this, arguments);
assert.ok(fSetAggregationSpy.calledOnceWithExactly({
visible: ["Name", "Country"],
groupLevels: [],
grandTotal: ["Name"],
subtotals: ["Name"],
columnState: createColumnStateIdMap(oTable, [
{subtotals: true, grandTotal: true},
{subtotals: false, grandTotal: false},
{subtotals: true, grandTotal: true}
]),
search: undefined
}), "Plugin#setAggregationInfo call");
fSetAggregationSpy.reset();
oDelegate.rebind = fnRebind;
resolve();
};
oTable._oPopover.getAggregation("_popover").getContent()[0].getContent()[1].firePress();
Core.byId(oTable.getId() + "-messageBox").getButtons()[0].firePress();
});
});
});
QUnit.test("Sorting restriction", function(assert) {
var oTable = this.oTable;
return oTable._fullyInitialized().then(function() {
var sMessage = Core.getLibraryResourceBundle("sap.ui.mdc").getText("table.PERSONALIZATION_DIALOG_SORT_RESTRICTION");
var oState;
var oValidationState;
oState = {items: [{name: "Name"}, {name: "name_country"}]};
oValidationState = oTable.validateState(oState, "Sort");
assert.strictEqual(oValidationState.validation, coreLibrary.MessageType.None, "No sorted properties: Validation result");
assert.strictEqual(oValidationState.message, undefined, "No sorted properties: Message text");
oState = {sorters: [{name: "Name"}, {name: "Country"}]};
oValidationState = oTable.validateState(oState, "Sort");
assert.strictEqual(oValidationState.validation, coreLibrary.MessageType.Information,
"Sorted properties and no visible columns: Validation result");
assert.strictEqual(oValidationState.message, sMessage,
"Sorted properties and no visible columns: Message text");
oState = {
items: [{name: "Name"}, {name: "Country"}, {name: "name_country"}],
sorters: [{name: "Name"}, {name: "Country"}]
};
oValidationState = oTable.validateState(oState, "Sort");
assert.strictEqual(oValidationState.validation, coreLibrary.MessageType.None, "All sorted properties visible: Validation result");
assert.strictEqual(oValidationState.message, undefined, "All sorted properties visible: Message text");
oState = {
items: [{name: "Name"}],
sorters: [{name: "Country"}]
};
oValidationState = oTable.validateState(oState, "Sort");
assert.strictEqual(oValidationState.validation, coreLibrary.MessageType.Information, "Sorted property invisible: Validation result");
assert.strictEqual(oValidationState.message, sMessage, "Sorted property invisible: Message text");
oState = {
items: [{name: "Name"}, {name: "name_country"}],
sorters: [{name: "Country"}]
};
oValidationState = oTable.validateState(oState, "Sort");
assert.strictEqual(oValidationState.validation, coreLibrary.MessageType.None,
"Sorted property is part of a visible complex property: Validation result");
assert.strictEqual(oValidationState.message, undefined,
"Sorted property is part of a visible complex property: Message text");
oTable.setP13nMode();
oState = {
items: [{name: "Name"}],
sorters: [{name: "Country"}]
};
oValidationState = oTable.validateState(oState, "Sort");
assert.strictEqual(oValidationState.validation, coreLibrary.MessageType.None,
"Sorted property invisible and analytical features not enabled: Validation result");
assert.strictEqual(oValidationState.message, undefined,
"Sorted property invisible and analytical features not enabled: Message text");
});
});
QUnit.test("Group restriction", function(assert) {
var oTable = this.oTable;
return oTable._fullyInitialized().then(function() {
var oDelegate = oTable.getControlDelegate();
var oResourceBundle = Core.getLibraryResourceBundle("sap.ui.mdc");
var oState, oValidationState;
oState = {
items: [{name: "Name"}, {name: "Country"}, {name: "name_country"}]
};
oValidationState = oTable.validateState(oState, "Group");
assert.equal(oValidationState.validation, coreLibrary.MessageType.None, "No message");
assert.equal(oValidationState.message, undefined, "Message text is not defined");
oState = {
items: [{name: "Name"}],
aggregations: { Name : {}}
};
oValidationState = oTable.validateState(oState, "Group");
assert.equal(oValidationState.validation, coreLibrary.MessageType.Information,
"Information message, Grouping and aggreagtion can't be used simulatneously");
assert.equal(oValidationState.message, oResourceBundle.getText("table.PERSONALIZATION_DIALOG_GROUP_RESTRICTION", "Name"),
"Message text is correct");
oState = {
items: [{name: "Name"}, {name: "name_country"}],
sorters: [{name: "Country"}]
};
oValidationState = oDelegate.validateState(oTable, oState);
assert.equal(oValidationState.validation, coreLibrary.MessageType.None,
"No message, the sorted property is not visible but part of a visible complex property");
assert.equal(oValidationState.message, undefined, "Message text is undefined");
oState = {};
oValidationState = oDelegate.validateState(oTable, oState);
assert.equal(oValidationState.validation, coreLibrary.MessageType.None,
"No message because oState.items is undefined");
assert.equal(oValidationState.message, undefined, "Message text is undefined");
});
});
QUnit.test("Column restriction", function(assert) {
var oTable = this.oTable;
return oTable._fullyInitialized().then(function() {
var oResourceBundle = Core.getLibraryResourceBundle("sap.ui.mdc");
var oState, oValidationState;
oState = {
items: [{name: "Name"}, {name: "Country"}, {name: "name_country"}]
};
oValidationState = oTable.validateState(oState, "Column");
assert.equal(oValidationState.validation, coreLibrary.MessageType.None, "No message");
assert.equal(oValidationState.message, undefined, "Message text is not defined");
oState = {
items: [{name: "Country"}],
aggregations: { Name : {}}
};
oValidationState = oTable.validateState(oState, "Column");
assert.equal(oValidationState.validation, coreLibrary.MessageType.Information,
"Information message, Cannot remove column when the total is showed for the column");
assert.equal(oValidationState.message, oResourceBundle.getText("table.PERSONALIZATION_DIALOG_TOTAL_RESTRICTION"),
"Message text is correct");
oState = {
items: [{name: "Name"}],
sorters: [{name: "Country"}]
};
oValidationState = oTable.validateState(oState, "Column");
assert.equal(oValidationState.validation, coreLibrary.MessageType.Information,
"Information message, Cannot remove column when the sorters is applied for the column");
assert.equal(oValidationState.message, oResourceBundle.getText("table.PERSONALIZATION_DIALOG_SORT_RESTRICTION", "Name"),
"Message text is correct");
oState = {
items: [{name: "Country"}],
sorters: [{name: "Name"}],
aggregations: { Name : {}}
};
oValidationState = oTable.validateState(oState, "Column");
assert.equal(oValidationState.validation, coreLibrary.MessageType.Information,
"Information message, Cannot remove column when the sorters and totals is shown for the column");
assert.equal(oValidationState.message, oResourceBundle.getText("table.PERSONALIZATION_DIALOG_TOTAL_RESTRICTION") + "\n" +
oResourceBundle.getText("table.PERSONALIZATION_DIALOG_SORT_RESTRICTION", "Name"),
"Message text is correct");
oState = {};
oValidationState = oTable.validateState(oState, "Column");
assert.equal(oValidationState.validation, coreLibrary.MessageType.None,
"No message because oState.items is undefined");
assert.equal(oValidationState.message, undefined, "Message text is undefined");
});
});
QUnit.module("Tests with specific propertyInfos and extensions for binding", {
before: function() {
MDCQUnitUtils.stubPropertyInfos(Table.prototype, [{
name: "Name",
label: "Name",
path: "Name",
groupable: true
}, {
name: "Country",
label: "Country",
path: "Country",
groupable: true
}, {
name: "Value",
label: "Value",
path: "Value"
}, {
name: "name_country",
label: "Complex Title & Description",
propertyInfos: ["Name"]
}]);
MDCQUnitUtils.stubPropertyInfosForBinding(Table.prototype, [{
name: "Name",
label: "Name",
path: "Name",
groupable: true
}, {
name: "Country",
label: "Country",
path: "Country",
groupable: true
}, {
name: "Value",
label: "Value",
path: "Value"
}, {
name: "name_country",
label: "Complex Title & Description",
propertyInfos: ["Name", "Country", "Value"]
}]);
MDCQUnitUtils.stubPropertyExtensionsForBinding(Table.prototype, {
Value: {
defaultAggregate: {}
}
});
},
beforeEach: function() {
return this.createTestObjects().then(function() {
return this.oTable.getEngine().getModificationHandler().waitForChanges({
element: this.oTable
});
}.bind(this));
},
afterEach: function() {
this.destroyTestObjects();
},
after: function() {
MDCQUnitUtils.restorePropertyInfos(Table.prototype);
MDCQUnitUtils.restorePropertyInfosForBinding(Table.prototype);
MDCQUnitUtils.restorePropertyExtensionsForBinding(Table.prototype);
},
createTestObjects: function() {
return createAppEnvironment(sTableView2, "Table").then(function(mCreatedApp){
this.oView = mCreatedApp.view;
this.oUiComponentContainer = mCreatedApp.container;
this.oUiComponentContainer.placeAt("qunit-fixture");
Core.applyChanges();
this.oTable = this.oView.byId('myTable');
ControlPersonalizationWriteAPI.restore({
selector: this.oTable
});
}.bind(this));
},
destroyTestObjects: function() {
this.oUiComponentContainer.destroy();
}
});
QUnit.test("Check column header for analytics buttons", function(assert) {
var fColumnPressSpy = sinon.spy(this.oTable, "_onColumnPress");
var oResourceBundle = Core.getLibraryResourceBundle("sap.ui.mdc");
var oTable = this.oTable;
return oTable._fullyInitialized().then(function() {
var oFirstInnerColumn = oTable._oTable.getColumns()[0];
oTable._oTable.fireEvent("columnSelect", {
column: oFirstInnerColumn
});
assert.ok(fColumnPressSpy.calledOnce, "First Column pressed");
return oTable._fullyInitialized();
}).then(function() {
assert.strictEqual(oTable._oPopover.getItems()[0].getLabel(), oResourceBundle.getText("table.SETTINGS_GROUP"),
"The first column has group menu item");
assert.equal(oTable._oPopover.getItems().length, 1, "The first column doesn't have an aggregate menu item");
});
});
QUnit.test("Apply group on column header", function(assert) {
var oTable = this.oTable;
var done = assert.async();
var fColumnPressSpy = sinon.spy(oTable, "_onColumnPress");
oTable._fullyInitialized().then(function() {
var oInnerColumn = oTable._oTable.getColumns()[0];
oTable._oTable.fireEvent("columnSelect", {
column: oInnerColumn
});
assert.ok(fColumnPressSpy.calledOnce, "First column pressed");
fColumnPressSpy.restore();
oTable._fullyInitialized().then(function() {
var oPlugin = oTable._oTable.getDependents()[0];
var fSetAggregationSpy = sinon.spy(oPlugin, "setAggregationInfo");
var oDelegate = oTable.getControlDelegate();
var fnRebind = oDelegate.rebind;
oDelegate.rebind = function () {
fnRebind.apply(this, arguments);
assert.ok(fSetAggregationSpy.calledOnceWithExactly({
visible: ["Name", "Country","Value"],
groupLevels: ["Name"],
grandTotal: [],
subtotals: [],
columnState: createColumnStateIdMap(oTable, [
{subtotals: false, grandTotal: false},
{subtotals: true, grandTotal: true}
]),
search: undefined
}), "Plugin#setAggregationInfo call");
fSetAggregationSpy.restore();
oDelegate.rebind = fnRebind;
done();
};
var fTableGroupSpy = sinon.spy(oTable, "_onCustomGroup");
oTable._oPopover.getAggregation("_popover").getContent()[0].getContent()[0].firePress();
assert.ok(fTableGroupSpy.calledOnce, "Column group triggered");
if (!fTableGroupSpy.calledOnce) {
done(); // rebind won't be called in this case, so we need to end the test here
}
});
});
});
QUnit.module("Column state to plugin", {
before: function() {
MDCQUnitUtils.stubPropertyInfos(Table.prototype, [
{name: "CountryKey", path: "Country", label: "CountryKey", groupable: true, text: "CountryText"},
{name: "CountryText", path: "CountryText", label: "CountryText", groupable: true},
{name: "CountryKeyAndText", label: "CountryKey+CountryText", propertyInfos: ["CountryKey", "CountryText"]},
{name: "SalesAmount", path: "SalesAmount", label: "SalesAmount", unit: "Currency"},
{name: "Currency", path: "Currency", label: "Currency", groupable: true},
{name: "SalesAmountAndCurrency", label: "SalesAmount+Currency", propertyInfos: ["SalesAmount", "Currency"]},
{name: "SalesAmountAndRegion", label: "SalesAmount+Region", propertyInfos: ["SalesAmount", "Region"]},
{name: "CurrencyAndRegion", label: "Currency+Region", propertyInfos: ["Currency", "Region"]},
{name: "Region", path: "Region", label: "Region", groupable: true},
{name: "RegionText", path: "RegionText", label: "RegionText", groupable: true},
{name: "SalesAmountInLocalCurrency", path: "SalesAmountInLocalCurrency", label: "SalesAmountInLocalCurrency"},
{
name: "SalesAmountAndSalesAmountInLocalCurrency",
label: "SalesAmountAndSalesAmountInLocalCurrency",
propertyInfos: ["SalesAmount", "SalesAmountInLocalCurrency"]
},
{name: "RegionAndRegionText", label: "Region+RegionText", propertyInfos: ["Region", "RegionText"]}
]);
MDCQUnitUtils.stubPropertyExtension(Table.prototype, {
SalesAmount: {defaultAggregate: {}},
Currency: {defaultAggregate: {}}
});
},
beforeEach: function() {
return this.createTestObjects().then(function() {
this.oTable.destroyColumns();
this.oTable.addColumn(new Column({
header: "CountryKey",
dataProperty: "CountryKey",
template: new Text({text: "CountryKey"})
}));
this.oTable.addColumn(new Column({
header: "CountryText",
dataProperty: "CountryText",
template: new Text({text: "CountryText"})
}));
this.oTable.addColumn(new Column({
header: "CountryKey+CountryText",
dataProperty: "CountryKeyAndText",
template: new Text({text: "CountryKey CountryText"})
}));
this.oTable.addColumn(new Column({
header: "SalesAmount",
dataProperty: "SalesAmount",
template: new Text({text: "SalesAmount"})
}));
this.oTable.addColumn(new Column({
header: "Currency",
dataProperty: "Currency",
template: new Text({text: "Currency"})
}));
this.oTable.addColumn(new Column({
header: "SalesAmount+Currency",
dataProperty: "SalesAmountAndCurrency",
template: new Text({text: "SalesAmount Currency"})
}));
this.oTable.addColumn(new Column({
header: "SalesAmount+Region",
dataProperty: "SalesAmountAndRegion",
template: new Text({text: "SalesAmount Region"})
}));
this.oTable.addColumn(new Column({
header: "Currency+Region",
dataProperty: "CurrencyAndRegion",
template: new Text({text: "Currency Region"})
}));
this.oTable.addColumn(new Column({
header: "SalesAmount+SalesAmountInLocalCurrency",
dataProperty: "SalesAmountAndSalesAmountInLocalCurrency",
template: new Text({text: "SalesAmount SalesAmountInLocalCurrency"})
}));
this.oTable.addColumn(new Column({
header: "Region+RegionText",
dataProperty: "RegionAndRegionText",
template: new Text({text: "Region RegionText"})
}));
return this.oTable.getEngine().getModificationHandler().waitForChanges({
element: this.oTable
});
}.bind(this));
},
afterEach: function() {
this.destroyTestObjects();
},
after: function() {
MDCQUnitUtils.restorePropertyInfos(Table.prototype);
MDCQUnitUtils.restorePropertyExtension(Table.prototype);
},
createTestObjects: function() {
return createAppEnvironment(sTableView2, "Table").then(function(mCreatedApp){
this.oView = mCreatedApp.view;
this.oUiComponentContainer = mCreatedApp.container;
this.oUiComponentContainer.placeAt("qunit-fixture");
Core.applyChanges();
this.oTable = this.oView.byId('myTable');
ControlPersonalizationWriteAPI.restore({
selector: this.oTable
});
}.bind(this));
},
destroyTestObjects: function() {
this.oUiComponentContainer.destroy();
}
});
QUnit.test("Aggregate", function(assert) {
var oTable = this.oTable;
return oTable._fullyInitialized().then(function() {
var oPlugin = oTable._oTable.getDependents()[0];
var oSetAggregation = sinon.spy(oPlugin, "setAggregationInfo");
oTable.setAggregateConditions({
SalesAmount: {}
});
oTable.rebind();
assert.ok(oSetAggregation.calledOnceWithExactly({
visible: ["CountryKey", "CountryText", "SalesAmount", "Currency", "Region", "SalesAmountInLocalCurrency", "RegionText"],
groupLevels: [],
grandTotal: ["SalesAmount"],
subtotals: ["SalesAmount"],
columnState: createColumnStateIdMap(oTable, [
{subtotals: false, grandTotal: false},
{subtotals: false, grandTotal: false},
{subtotals: false, grandTotal: false},
{subtotals: true, grandTotal: true},
{subtotals: true, grandTotal: true},
{subtotals: true, grandTotal: true},
{subtotals: true, grandTotal: true},
{subtotals: true, grandTotal: true},
{subtotals: true, grandTotal: true},
{subtotals: false, grandTotal: false}
]),
search: undefined
}), "Plugin#setAggregationInfo call");
});
});
QUnit.test("Group", function(assert) {
var oTable = this.oTable;
return oTable._fullyInitialized().then(function() {
var oPlugin = oTable._oTable.getDependents()[0];
var oSetAggregation = sinon.spy(oPlugin, "setAggregationInfo");
oTable.setGroupConditions({
groupLevels: [{
name: "CountryKey"
}]
});
oTable.rebind();
assert.ok(oSetAggregation.calledOnceWithExactly({
visible: ["CountryKey", "CountryText", "SalesAmount", "Currency", "Region", "SalesAmountInLocalCurrency", "RegionText"],
groupLevels: ["CountryKey"],
grandTotal: [],
subtotals: [],
columnState: createColumnStateIdMap(oTable, [
{subtotals: false, grandTotal: false},
{subtotals: false, grandTotal: false},
{subtotals: false, grandTotal: false},
{subtotals: false, grandTotal: false},
{subtotals: false, grandTotal: false},
{subtotals: false, grandTotal: false},
{subtotals: false, grandTotal: false},
{subtotals: false, grandTotal: false},
{subtotals: false, grandTotal: false},
{subtotals: false, grandTotal: false}
]),
search: undefined
}), "Plugin#setAggregationInfo call");
});
});
QUnit.test("Group and aggregate", function(assert) {
var oTable = this.oTable;
return oTable._fullyInitialized().then(function() {
var oPlugin = oTable._oTable.getDependents()[0];
var oSetAggregation = sinon.spy(oPlugin, "setAggregationInfo");
oTable.setGroupConditions({
groupLevels: [{
name: "CountryKey"
}]
});
oTable.setAggregateConditions({
SalesAmount: {}
});
oTable.rebind();
assert.ok(oSetAggregation.calledOnceWithExactly({
visible: ["CountryKey", "CountryText", "SalesAmount", "Currency", "Region", "SalesAmountInLocalCurrency", "RegionText"],
groupLevels: ["CountryKey"],
grandTotal: ["SalesAmount"],
subtotals: ["SalesAmount"],
columnState: createColumnStateIdMap(oTable, [
{subtotals: false, grandTotal: false},
{subtotals: false, grandTotal: false},
{subtotals: false, grandTotal: false},
{subtotals: true, grandTotal: true},
{subtotals: true, grandTotal: true},
{subtotals: true, grandTotal: true},
{subtotals: true, grandTotal: true},
{subtotals: true, grandTotal: true},
{subtotals: true, grandTotal: true},
{subtotals: false, grandTotal: false}
]),
search: undefined
}), "Plugin#setAggregationInfo call");
});
});
QUnit.test("Transformation Search", function(assert) {
var done = assert.async();
var oTable = this.oTable;
return oTable._fullyInitialized().then(function() {
var fnOriginalUpdateBindingInfo = oTable.getControlDelegate().updateBindingInfo;
oTable.getControlDelegate().updateBindingInfo = function(oTable, oBindingInfo) {
fnOriginalUpdateBindingInfo(oTable, oBindingInfo);
oBindingInfo.parameters["$search"] = "Name";
};
return waitForBindingInfo(oTable);
}).then(function() {
var oPlugin = oTable._oTable.getDependents()[0];
var oBindRowsSpy = sinon.spy(oTable._oTable, "bindRows");
var oSetAggregation = sinon.spy(oPlugin, "setAggregationInfo");
oTable.setGroupConditions({ groupLevels: [{ name: "CountryKey" }] }).rebind();
var oBinding = oTable._oTable.getBindingInfo("rows");
assert.notOk(oBinding.parameters["$search"], "$search has been removed from oBinding");
assert.ok(oBindRowsSpy.calledWithExactly(oBinding), "BindRows of inner table called with oBindingInfo without $search parameter");
assert.ok(oSetAggregation.calledOnceWithExactly({
visible: ["CountryKey", "CountryText", "SalesAmount", "Currency", "Region", "SalesAmountInLocalCurrency", "RegionText"],
groupLevels: ["CountryKey"],
grandTotal: [],
subtotals: [],
columnState: createColumnStateIdMap(oTable, [
{subtotals: false, grandTotal: false},
{subtotals: false, grandTotal: false},
{subtotals: false, grandTotal: false},
{subtotals: false, grandTotal: false},
{subtotals: false, grandTotal: false},
{subtotals: false, grandTotal: false},
{subtotals: false, grandTotal: false},
{subtotals: false, grandTotal: false},
{subtotals: false, grandTotal: false},
{subtotals: false, grandTotal: false}
]),
search: "Name"
}), "Plugin#setAggregationInfo call");
done();
});
});
QUnit.module("v4.TableDelegate#updateBinding", {
before: function() {
MDCQUnitUtils.stubPropertyInfos(Table.prototype, [{
name: "Name",
path: "Name",
label: "Name",
sortable: true,
groupable: true,
filterable: true
}]);
},
beforeEach: function() {
this.oTable = new Table({
autoBindOnInit: false,
p13nMode: ["Column", "Sort", "Filter", "Group", "Aggregate"],
delegate: {
name: "odata.v4.TestDelegate",
payload: {
collectionPath: "/ProductList"
}
}
}).setModel(new ODataModel({
synchronizationMode: "None",
serviceUrl: "serviceUrl/",
operationMode: "Server"
}));
return this.oTable._fullyInitialized().then(function() {
this.oTable.bindRows();
this.oInnerTable = this.oTable._oTable;
this.oRowBinding = this.oTable.getRowBinding();
this.oSetAggregationSpy = sinon.spy(this.oInnerTable.getDependents()[0], "setAggregationInfo");
this.oRebindSpy = sinon.spy(this.oTable.getControlDelegate(), "rebind");
this.oChangeParametersSpy = sinon.spy(this.oRowBinding, "changeParameters");
this.oFilterSpy = sinon.spy(this.oRowBinding, "filter");
this.oSortSpy = sinon.spy(this.oRowBinding, "sort");
}.bind(this));
},
afterEach: function() {
this.oTable.destroy();
this.oSetAggregationSpy.restore();
this.oRebindSpy.restore();
this.oChangeParametersSpy.restore();
this.oFilterSpy.restore();
this.oSortSpy.restore();
},
after: function() {
MDCQUnitUtils.restorePropertyInfos(Table.prototype);
}
});
QUnit.test("Sort", function(assert) {
this.oTable.setSortConditions({ sorters: [{ name: "Name", descending: false }] })._rebind();
assert.ok(this.oSortSpy.firstCall.calledWithExactly(this.oTable._getSorters()));
this.oTable.setSortConditions({ sorters: [{ name: "Name", descending: true }] })._rebind();
assert.ok(this.oSortSpy.secondCall.calledWithExactly(this.oTable._getSorters()));
this.oTable.setSortConditions()._rebind();
assert.equal(this.oSortSpy.callCount, 3);
assert.equal(this.oRebindSpy.callCount, 0);
});
QUnit.test("Filter", function(assert) {
var aFilters = [new Filter("Name", "EQ", "a")];
var oUpdateBindingInfoStub = sinon.stub(this.oTable.getControlDelegate(), "updateBindingInfo");
oUpdateBindingInfoStub.callsFake(function (oMDCTable, oBindingInfo) {
oUpdateBindingInfoStub.wrappedMethod.apply(this, arguments);
var oMetadataInfo = oMDCTable.getPayload();
oBindingInfo.path = oMetadataInfo.collectionPath;
oBindingInfo.filters = aFilters;
});
this.oTable._rebind();
assert.ok(this.oFilterSpy.firstCall.calledWithExactly(aFilters, "Application"));
oUpdateBindingInfoStub.restore();
this.oTable._rebind();
assert.ok(this.oFilterSpy.secondCall.calledWithExactly([], "Application"));
assert.equal(this.oRebindSpy.callCount, 0);
});
QUnit.test("Group", function(assert) {
this.oTable.setGroupConditions({ groupLevels: [{ name: "Name" }] })._rebind();
assert.ok(this.oSetAggregationSpy.firstCall.calledWithMatch({ groupLevels: [ "Name" ] }));
this.oTable.setGroupConditions()._rebind();
assert.ok(this.oSetAggregationSpy.secondCall.calledWithMatch( { groupLevels: [] }));
assert.equal(this.oRebindSpy.callCount, 0);
});
QUnit.test("Aggregates", function(assert) {
this.oTable.setAggregateConditions({ Name: {} })._rebind();
assert.ok(this.oSetAggregationSpy.firstCall.calledWithMatch({
grandTotal: [ "Name" ],
subtotals: [ "Name" ]
}));
this.oTable.setAggregateConditions()._rebind();
assert.ok(this.oSetAggregationSpy.secondCall.calledWithMatch( { grandTotal: [], subtotals: [] }));
assert.equal(this.oRebindSpy.callCount, 0);
});
QUnit.test("Parameters", function(assert) {
var oUpdateBindingInfoStub = sinon.stub(this.oTable.getControlDelegate(), "updateBindingInfo");
oUpdateBindingInfoStub.onCall(0).callsFake(function (oMDCTable, oBindingInfo) {
oUpdateBindingInfoStub.wrappedMethod.apply(this, arguments);
var oMetadataInfo = oMDCTable.getPayload();
oBindingInfo.path = oMetadataInfo.collectionPath;
oBindingInfo.parameters.$search = "x";
});
oUpdateBindingInfoStub.onCall(1).callsFake(function (oMDCTable, oBindingInfo) {
oUpdateBindingInfoStub.wrappedMethod.apply(this, arguments);
var oMetadataInfo = oMDCTable.getPayload();
oBindingInfo.path = oMetadataInfo.collectionPath;
oBindingInfo.parameters.$search = undefined;
});
oUpdateBindingInfoStub.onCall(2).callsFake(function (oMDCTable, oBindingInfo) {
oUpdateBindingInfoStub.wrappedMethod.apply(this, arguments);
var oMetadataInfo = oMDCTable.getPayload();
oBindingInfo.path = oMetadataInfo.collectionPath;
oBindingInfo.parameters.$$canonicalPath = true;
});
this.oTable._rebind();
assert.equal(this.oChangeParametersSpy.callCount, 1);
this.oTable._rebind();
assert.equal(this.oChangeParametersSpy.callCount, 2);
assert.equal(this.oRebindSpy.callCount, 0);
this.oTable._rebind();
assert.equal(this.oRebindSpy.callCount, 1);
oUpdateBindingInfoStub.restore();
});
QUnit.test("Add Column", function(assert) {
this.oTable.insertColumn(new Column());
this.oTable._rebind();
assert.equal(this.oChangeParametersSpy.callCount, 0);
assert.equal(this.oFilterSpy.callCount, 0);
assert.equal(this.oSortSpy.callCount, 0);
assert.equal(this.oSetAggregationSpy.callCount, 1);
assert.equal(this.oRebindSpy.callCount, 1);
});
QUnit.test("Change path", function(assert) {
var oUpdateBindingInfoStub = sinon.stub(this.oTable.getControlDelegate(), "updateBindingInfo");
oUpdateBindingInfoStub.onCall(1).callsFake(function (oMDCTable, oBindingInfo) {
oUpdateBindingInfoStub.wrappedMethod.apply(this, arguments);
oBindingInfo.path = oBindingInfo.path + "something_else";
});
this.oTable._rebind();
this.oRebindSpy.resetHistory();
this.oTable._rebind();
assert.equal(this.oRebindSpy.callCount, 1, "Changing the path forces a rebind");
oUpdateBindingInfoStub.restore();
});
});
| SAP/openui5 | src/sap.ui.mdc/test/sap/ui/mdc/qunit/odata/v4/TableDelegate.qunit.js | JavaScript | apache-2.0 | 54,115 |
/**
* This is the controller file for "TodoDetail"
*
* @class Controller.TodoDetail
* @author Steven House
* @email steven.m.house@gmail.com
*/
var args = arguments[0] || {};
var itemId = args.itemId || "";
// Include logging utility
var log = Alloy.Globals.log;
var args = arguments[0] || {};
var id = args.id;
var todo = Alloy.Collections.ToDo;
var todoJSON = todo.toJSON();
var todoItem = _.first(_.where(todoJSON, {name: itemId}));
todoItem = JSON.parse(todoJSON);
//var todoItem = todo.findWhere({ name: itemId });
//var todoItem = _.first(todo.where({ name: itemId }));
//var todoItemJSON = todoItem.toJSON();
log.info('[TodoDetail] : Opened Item', todoItem);
var moment = require('moment');
var galleryExists = false;
init();
/**
* Start the controller running
* @method init
* @return
*/
function init() {
setupNav();
addEventListeners();
//alert(todoItem.name);
var name = todoItem.name;
//$.labelTitle.text = todoItem.name.toUpperCase();
//$.labelTitle.text = todoItem.get("name");
/*
if (isDone()) {
log.debug('[TodoDetail] : Initializing : Completed');
$.viewDone.height = 44;
//$.viewPhoto.height = 0;
$.addClass($.viewDone, 'bgDarkGreen');
}
if (hasReminder()) {
log.debug('[TodoDetail] : Initializing : Completed');
$.viewAptTime.height = 44;
$.viewScheduleApt.height = 0;
$.addClass($.viewScheduleApt, 'bgDarkGreen');
var reminderDate = todoItem.get('reminderDateTime');
var dateText = moment.utc(reminderDate).fromNow();
$.labelReminder.text = dateText;
// + reminderDate;
}
if (hasPhoto()) {
createGallery();
galleryExists = true;
}
*/
// @TODO Figure out why this is needed. The nav widget should handle it
//$.windowTodoDetail.open();
}
/**
* Setup the Nav Bar
* @method setupNav
*/
function setupNav() {
if (Alloy.isTablet) {
return;
}
}
/**
* Add event listeners for the ListView.
* @method addEventListeners
* @return
*/
function addEventListeners() {
// Mark as Done
$.viewDone.addEventListener('click', done);
// Set Reminder
$.viewScheduleApt.addEventListener('click', setReminder);
// Capture a photo
$.viewPhoto.addEventListener('click', captureImage);
}
/**
* Handles the done click event listener
* @method done
* @return
*/
function done() {
log.event({
type: 'todo',
action: 'completed',
description: todoItem.get('name'),
eventId: todoItem.get('name')
});
$.addClass($.viewDone, 'bgDarkGreen');
//$.viewDone.height = 0;
//$.viewPhoto.height = 44;
todoItem.set({
complete: true,
completedDateTime: new Date().toISOString()
});
todoItem.save();
}
/**
* Description
* @method isDone
* @return CallExpression
*/
function isDone() {
return todoItem.get('status');
}
/**
* Checks if item has reminder and changes UI based on this
* @method hasReminder
*/
function hasReminder() {
return todoItem.get('reminderDateTime');
}
/**
* Checks if item has reminder and changes UI based on this
* @method hasReminder
*/
function hasPhoto() {
return todoItem.get('hasPhoto');
}
/**
* Invoke the calendar module to set a date
* @method setReminder
* @return
*/
function setReminder() {
log.debug('[TodoDetail] : setReminder');
if (Ti.Platform.osname === 'android') {
var now = new Date();
var month = now.getUTCMonth() + 1;
var day = now.getUTCDate();
var year = now.getUTCFullYear();
var Dialogs = require("yy.tidialogs");
// Create the dialog
// value property is priority
var picker = Dialogs.createDatePicker({
okButtonTitle: 'Set', // <-- optional, default "Done"
cancelButtonTitle: 'Cancel', // <-- optional, default "Cancel"
value: new Date(), // <-- optional
day: day, // <-- optional
month: month, // <-- optional - java/javascript month, i.e. August
year: year // <-- optional
});
// Add the click listener
picker.addEventListener('click',function(e){
if (!e.cancel) {
saveDate(e.value);
} else {
// Android Cancel Date
}
});
// Cancel listener
picker.addEventListener('cancel', function() {
Ti.API.info("dialog was cancelled");
});
// open it
picker.show();
}
// iOS will use different date picker
else {
$.viewRow.height = 0;
var calendar = require('ti.sq');
var now = new Date();
var month = now.getUTCMonth() + 1;
var day = now.getUTCDate();
var year = now.getUTCFullYear();
var minYear = year - 1;
var maxYear = year + 1;
var calValue = {
month: month,
day: day,
year: year
};
var calMin = {
month: month,
day: day,
year: minYear
};
var calMax = {
month: month,
day: day,
year: maxYear
};
var calendarView = calendar.createView({
height: Ti.UI.FILL,
width: Ti.UI.FILL,
top: 0,
left: 10,
right: 10,
//bottom: 65,
pagingEnabled: true,
value: {
month: month,
day: day,
year: year
},
min: {
month: month,
day: 1,
year: year
},
max: {
month: month,
day: day,
year: maxYear
}
});
$.viewMain.add(calendarView);
calendarView.addEventListener('dateChanged', function(d) {
var opts = {
options: ['Yep!', 'Changed my mind'],
selectedIndex: 0,
destructive: 0,
title: 'Set A Reminder for ' + calendarView.value.month +
'/' + calendarView.value.day + '/' +
calendarView.value.year + ' ?'
};
var dialog = Ti.UI.createOptionDialog(opts);
dialog.show();
dialog.addEventListener('click', function(e) {
if (e.index == 0) {
saveDate(d.dateValue);
} else {
//Alloy.Globals.toast.show("Reminder cancelled");
alert("Reminder cancelled");
}
$.viewMain.remove(calendarView);
});
$.viewRow.height = Ti.UI.FILL;
});
}
}
/**
* @method saveDate
*/
function saveDate(d) {
log.debug("[TodoDetail] Set a reminder for : dateChanged = ", d);
var moment = require('moment');
log.event({
type: 'todo',
action: 'set a reminder for',
description: todoItem.get('name') + " " + moment(d).fromNow(),
eventId: todoItem.get('name')
});
todoItem.set({ reminderDateTime: d });
todoItem.save();
//Alloy.Globals.toast.show("Reminder set!");
alert("Reminder set!");
}
/**
* This invokes the camera
* @method captureImage
* @return
*/
function captureImage() {
log.debug('[TodoDetail] : captureImage');
var camera = require('Camera');
camera.captureImage({success: savePhoto});
}
/**
* Save a photo to the SD card
* @method savePhoto
*/
function savePhoto(image) {
if (image.mediaType == Ti.Media.MEDIA_TYPE_PHOTO) {
log.event({
type: 'todo',
action: 'captured',
description: 'an image for' + todoItem.get('name'),
eventId: todoItem.get('name')
});
log.debug('[TodoDetail] : captureImage : Camera Success, image = ', image);
// This part should be skipped to the existing function
var imageDir = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'todo');
if (!imageDir.exists()) {
imageDir.createDirectory();
}
// Add +1 to the existing photoCount
var photoCount = todoItem.get('photoCount') + 1;
var file = Ti.Filesystem.getFile(imageDir.resolve(), itemId +
photoCount + '.png');
log.debug("[TodoDetail] : Saving image to = ", imageDir.resolve() +
itemId + photoCount + '.png');
// Write to storage
file.write(image.media);
todoItem.set({
hasPhoto: true,
photoCount: photoCount
});
todoItem.save();
log.debug('[TodoDetail] : Saved image to this location : ',
file.nativePath);
updateGallery();
} else {
alert('We are only supporting images at the moment.');
todoItem.set({
hasVideo: true
});
todoItem.save();
}
}
/**
* This returns an imageView created from the file system
* @method getPictureView
* @param {photoCount}
* @param {width}
* @param {height}
* @return {Object} imageView
*/
function getPictureView(photoCount, width, height) {
log.debug('[TodoDetail] : getPictureView : photoCount = ',
photoCount + ", width = " + width + ", height = " + height);
// Create the directory if it doesn't exist
var imageDir = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'todo');
var file = Ti.Filesystem.getFile(imageDir.resolve(), itemId + photoCount + '.png');
if (!file.exists()) {
log.warn(
'[TodoDetail] : No saved pictures found. Should not see this'
);
return false;
} else {
var image = file.read();
log.info('[TodoDetail] : Retrieved saved picture : ',
image);
var imageView = Ti.UI.createImageView({
image: image,
width: width,
height: height,
borderColor: "white"
});
//$.viewMain.add(imageView);
return imageView;
}
}
/**
* Create Gallery of photos / videos
* @method createGallery
*/
function createGallery() {
log.debug('[TodoDetail] : createGallery() : image number = ', todoItem.get('photoCount'));
galleryExists = true;
var photoCount = todoItem.get('photoCount');
var images = [];
var columns = 0;
// Bail if no photos
if (photoCount < 1) {
log.debug("[TodoDetail] : createGallery : photoCount === 0");
return false;
} else if (photoCount == 1) {
columns = 1;
} else if (photoCount == 2) {
columns = 2;
} else {
columns = 3;
}
$.tdg.init({
columns: columns,
space: 5,
delayTime: 500,
gridBackgroundColor: '#e1e1e1',
itemBackgroundColor: '#9fcd4c',
itemBorderColor: '#6fb442',
itemBorderWidth: 0,
itemBorderRadius: 3
});
// For each photo count create a photo
_(photoCount).times(function(n) {
//THIS IS THE DATA THAT WE WANT AVAILABLE FOR THIS ITEM WHEN onItemClick OCCURS
var itemData = {
caption: 'Test'
};
var imageView = getPictureView(n + 1, 150, 150);
//NOW WE PUSH TO THE ARRAY THE VIEW AND THE DATA
images.push({
view: imageView,
data: itemData
});
});
//ADD ALL THE ITEMS TO THE GRID
$.tdg.addGridItems(images);
$.tdg.setOnItemClick(function(e){
alert('Selected Item: ' + JSON.stringify(e, null, 4));
});
}
/**
* Update the gallery and add a menu item
* @method updateGallery
*/
function updateGallery() {
log.debug("[TodoDetail] : Updating Gallery");
// If gallery doesn't exist create it
if (!galleryExists) {
createGallery();
return
}
// If gallery does exist add the first item
var imageView = getPictureView(1, 150, 150);
$.tdg.addGridItems({
view: imageView,
data: {
caption: 'Test'
}
});
}
| titanium-forks/shouse.To-Do | app/controllers/TodoListDetail.js | JavaScript | apache-2.0 | 12,178 |
// Here will be compiled design document
DESIGNS=false;
| itteco/tadagraph | core/_attachments/js/static.js | JavaScript | apache-2.0 | 56 |
/**
* author: Shawn
* time : 2017/8/15 17:19
* desc :
*/
var testJar = require('./testJar');
for (let i = 0; i < 10; i++) {
testJar.tt();
}
// testJar.tt();
// testJar.tt();
// testJar.tt();
| SethWen/NodejsLearning | fixbugs/test.js | JavaScript | apache-2.0 | 204 |
/**
* Created by Rory on 12/14/2015.
*/
Template.MessagesPage.helpers({
getMessages: function () {
if (Meteor.user()) {
return Messages.find({owner:Meteor.user().username});
}
},
getSender: function () {
return {username:this.sender};
},
getTextbook: function () {
return {_title:this.title};
},
isSellMessage: function () {
if(this.offerType === "sell" && !this.acceptMessage) {
return true;
}
else {
return false;
}
},
isAcceptSellMessage: function () {
if(this.offerType === "sell" && this.acceptMessage) {
return true;
}
else {
return false;
}
},
isBuyMessage: function () {
if(this.offerType === "buy" && !this.acceptMessage) {
return true;
}
else {
return false;
}
},
isAcceptBuyMessage: function () {
if(this.offerType === "buy" && this.acceptMessage) {
return true;
}
else {
return false;
}
}
}); | textbookmania/LightSteelBlue | app/client/templates/pages/Messages/MessagesPage.js | JavaScript | apache-2.0 | 968 |
import React from 'react';
import { action } from '@storybook/addon-actions';
import MultiColumnList from '../MultiColumnList';
import Button from '../../Button';
import { asyncGenerate } from './service';
export default class ClickableRows extends React.Component {
constructor() {
super();
this.state = {
data: [],
};
this.requestMore(2, 0);
}
requestMore = async (amount, index) => {
const newData = await asyncGenerate(amount, index, 1000);
this.setState(curState => ({
data: [...curState.data, ...newData]
}));
}
onRowClick = (e, i) => { // eslint-disable-line no-unused-vars
const act = action(`clicked row ${i.index}!`);
act({ row: i });
}
onRowActionClick = (e, i) => {
e.stopPropagation();
const act = action(`clicked button in row ${i}!`);
act();
// console.log('clicked button!');
}
formatter = {
actions: ({ index }) => (<Button onClick={(e) => this.onRowActionClick(e, index)}>{`Row ${index} action`}</Button>),
}
render() {
const columnWidths = {
'title': '100px'
};
return (
<div style={{ width: '800px', height:'400px' }}>
<p>Check out the actions tab below to see logged row clicks and row action clicks.</p>
<MultiColumnList
contentData={this.state.data}
columnWidths={columnWidths}
visibleColumns={['index', 'title', 'date', 'email', 'actions']}
onRowClick={this.onRowClick}
formatter={this.formatter}
height={400}
virtualize
onNeedMoreData={this.requestMore}
/>
</div>
);
}
}
| folio-org/stripes-components | lib/MultiColumnList/stories/ClickableRows.js | JavaScript | apache-2.0 | 1,633 |
'use strict';
module.exports = require('../lib/server'); | nolanlawson/socket-pouch | server/index.js | JavaScript | apache-2.0 | 57 |
var structofp12__experimenter__stats__header =
[
[ "exp_type", "structofp12__experimenter__stats__header.html#a460441be714bfea09fad329cbf887740", null ],
[ "experimenter", "structofp12__experimenter__stats__header.html#a26a1cc494706c82c3d8a1a79faf82463", null ]
]; | vladn-ma/vladn-ovs-doc | doxygen/ovs_all/html/structofp12__experimenter__stats__header.js | JavaScript | apache-2.0 | 272 |
function validateUser(req){
return (req.session.hasOwnProperty('user')&&req.session.user.length!=0);
}
module.exports = {
index:function(req,res,next){
if(validateUser(req)){
next()
}else{
res.render('login',{params:req.params,session:req.session});
}
}
}; | Courseplusplus/Courseplusplus | teacher_server/controllers/auth/index.js | JavaScript | apache-2.0 | 317 |
'use strict';
/**
* This file exports the main roles AnalyticsBackend uses which are:
* 'developer', 'teacher' and 'student'.
*
* Also indicates the anonymous routes used by the gleaner-tracker module to
* send data to the collector server.
*/
exports.app = {
roles: [
{
roles: 'student',
allows: [
{
resources: [
'/games/public',
'/games/:gameId/versions',
'/games/:gameId/versions/:versionId',
'/games/:gameId/versions/:versionId/sessions/my',
'/sessions/:sessionId/results'
],
permissions: [
'get'
]
},
{
resources: [
'/sessions/:sessionId'
],
permissions: [
'put',
'get'
]
}
]
},
{
roles: 'teacher',
allows: [
{
resources: [
'/games/public',
'/games/:gameId/versions',
'/games/:gameId/versions/:versionId',
'/games/:gameId/versions/:versionId/sessions/my',
'/sessions/:sessionId/results'
],
permissions: [
'get'
]
},
{
resources: [
'/sessions/:sessionId',
'/sessions/:sessionId/remove',
'/sessions/:sessionId/results/:resultsId'
],
permissions: [
'*'
]
},
{
resources: [
'/games/:gameId/versions/:versionId/sessions',
'/sessions/:sessionId/event/:event'
],
permissions: [
'post'
]
}
]
},
{
roles: 'developer',
allows: [
{
resources: [
'/games/my',
'/games/:gameId',
'/games/:gameId/versions',
'/games/:gameId/versions/:versionId'
],
permissions: [
'*'
]
},
{
resources: [
'/games/:gameId/versions/:versionId/sessions',
'/sessions/:sessionId'
],
permissions: [
'get'
]
},
{
resources: [
'/games'
],
permissions: [
'post'
]
}
]
}
],
anonymous: [
'/collector/start/:trackingCode',
'/collector/track'
],
autoroles: [
'student',
'teacher',
'developer'
]
}; | manuel-freire/rage-analytics-backend | a-backend-roles.js | JavaScript | apache-2.0 | 3,452 |
// The island of misfit toys... for functions
var path = require('path'),
fs = require('fs'),
colors = require('colors'),
crypto = require('crypto'),
util = require('util'),
wrench = require('wrench'),
jsonlint = require('jsonlint'),
resolve = require('resolve'),
paths = require('global-paths'),
logger = require('./logger'),
tiapp = require('./tiapp'),
XMLSerializer = require("xmldom").XMLSerializer,
DOMParser = require("xmldom").DOMParser,
_ = require("./lib/alloy/underscore")._,
CONST = require('./common/constants'),
sourceMapper = require('./commands/compile/sourceMapper');
var NODE_ACS_REGEX = /^ti\.cloud\..+?\.js$/;
exports.XML = {
getNodeText: function(node) {
if (!node) { return ''; }
var serializer = new XMLSerializer(),
str = '';
for (var c = 0; c < node.childNodes.length; c++) {
if (node.childNodes[c].nodeType === 3) {
str += serializer.serializeToString(node.childNodes[c]);
}
}
return str.replace(/\&/g,'&');
},
getElementsFromNodes: function(nodeList) {
var elems = [];
if (nodeList && nodeList.length) {
for (var i = 0, l = nodeList.length; i < l; i++) {
var node = nodeList.item(i);
if (node.nodeType === 1) {
elems.push(node);
}
}
}
return elems;
},
parseFromString: function(string) {
var doc;
try {
var errorHandler = {};
errorHandler.error = errorHandler.fatalError = function(m) {
exports.die(['Error parsing XML file.'].concat((m || '').split(/[\r\n]/)));
};
errorHandler.warn = errorHandler.warning = function(m) {
// ALOY-840: die on unclosed XML tags
// xmldom hardcodes this as a warning with the string message 'unclosed xml attribute'
// even when it's a tag that's unclosed
if(m.indexOf('unclosed xml attribute') === -1) {
logger.warn((m || '').split(/[\r\n]/));
} else {
m = m.replace('unclosed xml attribute', 'Unclosed XML tag or attribute');
exports.die(['Error parsing XML file.'].concat((m || '').split(/[\r\n]/)));
}
};
doc = new DOMParser({errorHandler:errorHandler,locator:{}}).parseFromString(string);
} catch (e) {
exports.die('Error parsing XML file.', e);
}
return doc;
},
parseFromFile: function(filename) {
var xml = fs.readFileSync(filename,'utf8');
return exports.XML.parseFromString(xml);
},
createEmptyNode: function(name, ns) {
var str = '<' + name + (ns ? ' ns="' + ns + '"' : '') + '></' + name + '>';
return exports.XML.parseFromString(str).documentElement;
},
getAlloyFromFile: function(filename) {
var doc = exports.XML.parseFromFile(filename);
var docRoot = doc.documentElement;
// Make sure the markup has a top-level <Alloy> tag
if (docRoot.nodeName !== CONST.ROOT_NODE) {
exports.die([
'Invalid view file "' + filename + '".',
'All view markup must have a top-level <Alloy> tag'
]);
}
return docRoot;
},
toString: function(node) {
return (new XMLSerializer()).serializeToString(node);
},
previousSiblingElement: function(node) {
if (!node || !node.previousSibling || node.previousSibling === null) {
return null;
} else if (node.previousSibling.nodeType === 1) {
return node.previousSibling;
} else {
return exports.XML.previousSiblingElement(node.previousSibling);
}
}
};
exports.readTemplate = function(name) {
return fs.readFileSync(path.join(__dirname,'template',name),'utf8');
};
exports.evaluateTemplate = function(name, o) {
return _.template(exports.readTemplate(name), o);
};
exports.getAndValidateProjectPaths = function(argPath, opts) {
opts = opts || {};
var projectPath = path.resolve(argPath);
// See if we got the "app" path or the project path as an argument
projectPath = fs.existsSync(path.join(projectPath,'..','tiapp.xml')) ?
path.join(projectPath,'..') : projectPath;
// Assign paths objects
var paths = {
project: projectPath,
app: path.join(projectPath,'app'),
indexBase: path.join(CONST.DIR.CONTROLLER,CONST.NAME_DEFAULT + '.' + CONST.FILE_EXT.CONTROLLER)
};
paths.index = path.join(paths.app,paths.indexBase);
paths.assets = path.join(paths.app,'assets');
paths.resources = path.join(paths.project,'Resources');
paths.resourcesAlloy = path.join(paths.resources,'alloy');
// validate project and "app" paths
if (!fs.existsSync(paths.project)) {
exports.die('Titanium project path does not exist at "' + paths.project + '".');
} else if (!fs.existsSync(path.join(paths.project,'tiapp.xml'))) {
exports.die('Invalid Titanium project path (no tiapp.xml) at "' + paths.project + '"');
} else if (!fs.existsSync(paths.app)) {
exports.die('Alloy "app" directory does not exist at "' + paths.app + '"');
} else if (!fs.existsSync(paths.index) && (opts.command !== CONST.COMMANDS.GENERATE)) {
exports.die('Alloy "app" directory has no "' + paths.indexBase + '" file at "' + paths.index + '".');
}
// TODO: https://jira.appcelerator.org/browse/TIMOB-14683
// Resources/app.js must be present, even if not used
var appjs = path.join(paths.resources, 'app.js');
if (!fs.existsSync(appjs)) {
wrench.mkdirSyncRecursive(paths.resources, 0755);
fs.writeFileSync(appjs, '');
}
return paths;
};
exports.createErrorOutput = function(msg, e) {
var errs = [msg || 'An unknown error occurred'];
var posArray = [];
if (e) {
var line = e.line || e.lineNumber;
if (e.message) { errs.push(e.message.split('\n')); }
if (line) { posArray.push('line ' + line); }
if (e.col) { posArray.push('column ' + e.col); }
if (e.pos) { posArray.push('position ' + e.pos); }
if (posArray.length) { errs.push(posArray.join(', ')); }
// add the stack trace if we don't get anything good
if (errs.length < 2) { errs.unshift(e.stack); }
} else {
errs.unshift(e.stack);
}
return errs;
};
exports.updateFiles = function(srcDir, dstDir, opts) {
opts = opts || {};
opts.rootDir = opts.rootDir || dstDir;
var copiedFiles = [];
if (!fs.existsSync(srcDir)) {
return;
}
logger.trace('SRC_DIR=' + srcDir);
if (!fs.existsSync(dstDir)) {
wrench.mkdirSyncRecursive(dstDir, 0755);
}
// don't process XML/controller files inside .svn folders (ALOY-839)
var excludeRegex = new RegExp('(?:^|[\\/\\\\])(?:' + CONST.EXCLUDED_FILES.join('|') + ')(?:$|[\\/\\\\])');
var ordered = [];
_.each(wrench.readdirSyncRecursive(srcDir), function(file) {
var src = path.join(srcDir,file);
var dst = path.join(dstDir,file);
if (excludeRegex.test(src)) {
return;
}
// make sure the file exists and that it is not filtered
if (!fs.existsSync(src) ||
(opts.filter && opts.filter.test(file)) ||
(opts.exceptions && _.contains(opts.exceptions, file)) ||
(opts.restrictionPath && src !== opts.restrictionPath)) {
return;
}
// if this is the current platform-specific folder, adjust the dst path
var parts = file.split(/[\/\\]/);
if (opts.titaniumFolder && parts[0] === opts.titaniumFolder) {
if(opts.type && opts.type !== 'ASSETS' && parts[0] === 'iphone') {
// don't copy files in lib/iphone or vendor/iphone
return;
}
dst = path.join(dstDir, parts.slice(1).join('/'));
ordered.push({ src:src, dst:dst });
} else if(opts.titaniumFolder&& opts.titaniumFolder === 'iphone' && opts.type && opts.type !== 'ASSETS' && parts[0] === 'ios') {
// copy files in lib/ios and vendor/ios
dst = path.join(dstDir, parts.slice(1).join('/'));
ordered.push({ src:src, dst:dst });
} else {
ordered.unshift({ src:src, dst:dst });
}
});
_.each(ordered, function(o) {
var src = o.src;
var dst = o.dst;
var srcStat = fs.statSync(src);
if (fs.existsSync(dst)) {
var dstStat = fs.statSync(dst);
if (!dstStat.isDirectory()) {
// copy file in if it is a JS file or if its mtime is
// greater than the one in Resources
if (path.extname(src) === '.js' || opts.themeChanged || opts.isNew ||
srcStat.mtime.getTime() > dstStat.mtime.getTime()) {
logger.trace('Copying ' +
path.join('SRC_DIR', path.relative(srcDir, src)).yellow + ' --> ' +
path.relative(opts.rootDir, dst).yellow);
exports.copyFileSync(src, dst);
copiedFiles.push(path.relative(path.join(opts.rootDir, 'Resources'), dst));
}
}
} else {
if (srcStat.isDirectory()) {
logger.trace('Creating directory ' + path.relative(opts.rootDir, dst).yellow);
wrench.mkdirSyncRecursive(dst, 0755);
} else {
logger.trace('Copying ' + path.join('SRC_DIR', path.relative(srcDir, src)).yellow +
' --> ' + path.relative(opts.rootDir, dst).yellow);
exports.copyFileSync(src, dst);
copiedFiles.push(path.relative(path.join(opts.rootDir, 'Resources'), dst));
}
}
if(!srcStat.isDirectory() && opts.createSourceMap && path.extname(src) === '.js') {
var tpath = path.join(opts.rootDir,'build','map','Resources',(opts.compileConfig.alloyConfig.platform === 'ios' ? 'iphone' : opts.compileConfig.alloyConfig.platform),'alloy');
var target = {
filename: path.join(tpath, path.basename(src)),
filepath: path.dirname(dst),
template: dst
},
data = {
'__MAPMARKER_NONCONTROLLER__': {
filename: src,
filepath: path.dirname(src),
}
};
sourceMapper.generateSourceMap({
target: target,
data: data,
origFile: {
filename: src,
filepath: path.dirname(src)
}
}, opts.compileConfig);
}
});
logger.trace('');
return copiedFiles;
};
exports.getWidgetDirectories = function(appDir) {
var configPath = path.join(appDir, 'config.json');
var appWidgets = [];
if (fs.existsSync(configPath)) {
try {
var content = fs.readFileSync(configPath,'utf8');
appWidgets = jsonlint.parse(content).dependencies;
} catch (e) {
exports.die('Error parsing "config.json"', e);
}
}
var dirs = [];
var collections = [];
var widgetPaths = [];
widgetPaths.push(path.join(__dirname,'..','widgets'));
widgetPaths.push(path.join(appDir,'widgets'));
_.each(widgetPaths, function(widgetPath) {
if (fs.existsSync(widgetPath)) {
var wFiles = fs.readdirSync(widgetPath);
for (var i = 0; i < wFiles.length; i++) {
var wDir = path.join(widgetPath,wFiles[i]);
if (fs.statSync(wDir).isDirectory() &&
_.indexOf(fs.readdirSync(wDir), 'widget.json') !== -1) {
var collection = parseManifestAsCollection(path.join(wDir, 'widget.json'));
collections[collection.manifest.id] = collection;
}
}
}
});
function parseManifestAsCollection(wFile) {
var wDir = path.dirname(wFile);
var manifest;
try {
manifest = jsonlint.parse(fs.readFileSync(wFile, 'utf8'));
} catch (e) {
exports.die('Error parsing "' + wFile + '"', e);
}
return {
dir: wDir,
manifest: manifest
};
}
function findWidgetAsNodeModule(id) {
var wFile;
try {
wFile = resolve.sync(path.join(CONST.NPM_WIDGET_PREFIX + id, 'widget'), { basedir: path.join(appDir,'..'), extensions: [ '.json' ], paths: paths() });
} catch (err) {
return;
}
var collection = parseManifestAsCollection(wFile);
if (collection.manifest.id !== id) {
return logger.warn('Expected "' + wFile + '" to have id "' + id + '" instead of "' + collection.manifest.id + '"');
}
var pFile = path.join(path.dirname(wFile), 'package.json');
var pkg;
try {
pkg = jsonlint.parse(fs.readFileSync(pFile, 'utf8'));
} catch (e) {
exports.die('Error parsing "' + pFile + '"', e);
}
var missingKeywords = _.difference(CONST.NPM_WIDGET_KEYWORDS, pkg.keywords || []);
if (missingKeywords.length > 0) {
return logger.warn('Expected "' + pFile + '" to have missing keywords "' + missingKeywords.join('", "') + '"');
}
return collection;
}
function walkWidgetDependencies(id) {
var collection = collections[id];
if (!collection) {
collection = findWidgetAsNodeModule(id);
if (!collection) {
notFound.push(id);
return;
}
}
dirs.push(collection);
for (var dependency in collection.manifest.dependencies) {
walkWidgetDependencies(dependency);
}
}
// walk the dependencies, tracking any missing widgets
var notFound = [];
for (var id in appWidgets) {
walkWidgetDependencies(id);
}
// if there are missing widgets, abort and tell the developer which ones
if (!!notFound.length) {
exports.die([
'config.json references non-existent widgets: ' + JSON.stringify(notFound),
'If you are not using these widgets, remove them from your config.json dependencies.',
'If you are using them, add them to your project\'s widget folder or as NPM package.'
]);
}
return dirs;
};
exports.properCase = function(n) {
return n.charAt(0).toUpperCase() + n.substring(1);
};
exports.ucfirst = function (text) {
if (!text)
return text;
return text[0].toUpperCase() + text.substr(1);
};
exports.lcfirst = function (text) {
if (!text)
return text;
return text[0].toLowerCase() + text.substr(1);
};
exports.trim = function(line) {
return String(line).replace(/^\s\s*/, '').replace(/\s\s*$/, '');
};
exports.rmdirContents = function(dir, exceptions) {
var files;
try {
files = fs.readdirSync(dir);
} catch (e) {
return;
}
for (var i = 0, l = files.length; i < l; i++) {
var currFile = path.join(dir,files[i]);
var stat = fs.lstatSync(currFile);
// process the exceptions
var result = _.find(exceptions, function(exception) {
if (exception instanceof RegExp) {
return exception.test(files[i]);
} else {
return files[i] === exception;
}
});
// skip any exceptions
if (result) {
continue;
// use wrench to delete directories
} else if (stat.isDirectory()) {
wrench.rmdirSyncRecursive(currFile, true);
// unlink any files or links
} else {
fs.unlinkSync(currFile);
}
}
};
exports.resolveAppHome = function() {
var indexView = path.join(CONST.DIR.VIEW,CONST.NAME_DEFAULT + '.' + CONST.FILE_EXT.VIEW);
var paths = [ path.join('.','app'), path.join('.') ];
// Do we have an Alloy project? Find views/index.xml.
for (var i = 0; i < paths.length; i++) {
paths[i] = path.resolve(paths[i]);
var testPath = path.join(paths[i],indexView);
if (fs.existsSync(testPath)) {
return paths[i];
}
}
// Report error, show the paths searched.
var errs = [ 'No valid Alloy project found at the following paths (no "views/index.xml"):' ];
errs.push(paths);
exports.die(errs);
};
exports.copyFileSync = function(srcFile, destFile) {
var BUF_LENGTH = 64 * 1024,
buff,
bytesRead,
fdr,
fdw,
pos;
buff = new Buffer(BUF_LENGTH);
fdr = fs.openSync(srcFile, 'r');
exports.ensureDir(path.dirname(destFile));
fdw = fs.openSync(destFile, 'w');
bytesRead = 1;
pos = 0;
while (bytesRead > 0) {
bytesRead = fs.readSync(fdr, buff, 0, BUF_LENGTH, pos);
fs.writeSync(fdw, buff, 0, bytesRead);
pos += bytesRead;
}
fs.closeSync(fdr);
return fs.closeSync(fdw);
};
exports.ensureDir = function(p) {
if (!fs.existsSync(p)) {
wrench.mkdirSyncRecursive(p, 0755);
}
};
exports.die = function(msg, e) {
if (e) {
logger.error(exports.createErrorOutput(msg, e));
} else {
logger.error(msg);
}
process.exit(1);
};
exports.dieWithNode = function(node, msg) {
msg = _.isArray(msg) ? msg : [msg];
msg.unshift('Error with <' + node.nodeName + '> at line ' + node.lineNumber);
exports.die(msg);
};
exports.changeTime = function(file) {
if (!fs.existsSync(file)) { return -1; }
var stat = fs.statSync(file);
return Math.max(stat.mtime.getTime(),stat.ctime.getTime());
};
exports.stripColors = function(str) {
return str.replace(/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]/g, '');
};
exports.installPlugin = function(alloyPath, projectPath) {
var id = 'ti.alloy';
var plugins = {
plugin: {
file: CONST.PLUGIN_FILE,
src: path.join(alloyPath,'Alloy','plugin'),
dest: path.join(projectPath,'plugins',id)
},
hook: {
file: CONST.HOOK_FILE,
src: path.join(alloyPath,'hooks'),
dest: path.join(projectPath,'plugins',id,'hooks')
},
cleanhook: {
file: CONST.HOOK_FILE_CLEAN,
src: path.join(alloyPath,'hooks'),
dest: path.join(projectPath,'plugins',id,'hooks')
}
};
_.each(plugins, function(o, type) {
var srcFile = path.join(o.src,o.file);
var destFile = path.join(o.dest,o.file);
// skip if the src and dest are the same file
if (fs.existsSync(destFile) &&
fs.readFileSync(srcFile,'utf8') === fs.readFileSync(destFile,'utf8')) {
return;
}
exports.ensureDir(o.dest);
exports.copyFileSync(srcFile, destFile);
logger.info('Deployed ti.alloy ' + type + ' to ' + destFile);
});
// add the plugin to tiapp.xml, if necessary
tiapp.init(path.join(projectPath, 'tiapp.xml'));
tiapp.installPlugin({
id: 'ti.alloy',
version: '1.0'
});
};
exports.normalizeReturns = function(s) {
return s.replace(/\r\n/g, '\n');
};
exports.createHash = function(files) {
if (_.isString(files)) {
files = [files];
} else if (!_.isArray(files)) {
throw new TypeError('bad argument');
}
var source = '';
_.each(files, function(f) {
source += util.format('%s\n%s\n', f, fs.existsSync(f) ? fs.readFileSync(f, 'utf8') : '');
});
return crypto.createHash('md5').update(source).digest('hex');
};
exports.createHashFromString = function(string) {
if (!_.isString(string)) {
throw new TypeError('bad argument');
}
return crypto.createHash('md5').update(string).digest('hex');
};
exports.proxyPropertyNameFromFullname = function(fullname) {
var nameParts = fullname.split('.');
return exports.lcfirst(nameParts[nameParts.length-1]);
};
/*
Two date-related functions for ALOY-263
- used by compile/parsers/Ti.UI.Picker.js and compile/styler.js
*/
exports.isValidDate = function(d, dateField) {
// not using _.isDate() because it accepts some invalid date strings
if(!require('moment')(d).isValid()) {
exports.die("Invalid date string. " + dateField + " must be a string that can be parsed by MomentJS's `moment()` constructor.");
} else {
return true;
}
};
exports.createDate = function(val) {
return require('moment')(val).toDate();
};
exports.isLocaleAlias = function(string) {
return /^\s*L\((['\"])(.+)\1\)\s*$/.test(string);
};
exports.getDeploymentTargets = function(projDir) {
var tiappPath = path.join(projDir,'tiapp.xml'),
tiappDoc,
targets;
if (fs.existsSync(tiappPath)) {
tiapp.init(tiappPath);
targets = tiapp.getDeploymentTargets().join(',');
} else {
targets = CONST.PLATFORMS.join(',');
}
return targets;
};
| mobilehero/adamantium | Alloy/utils.js | JavaScript | apache-2.0 | 18,249 |
var a00980 =
[
[ "kDoNotReverse", "a00980.html#a0db2198747060995d61a01dcfac97eb7", null ],
[ "kForceReverse", "a00980.html#a597d22620e40ecc0ec38dfa4f65a9d85", null ],
[ "kReverseIfHasRTL", "a00980.html#a402a13eb2d1593daed0190a118f23d88", null ],
[ "RTLReversePolicyNames", "a00980.html#af5c5a40d574f6ab56726b8b2f963f65c", null ]
]; | stweil/tesseract-ocr.github.io | 4.0.0-beta.1/a00980.js | JavaScript | apache-2.0 | 347 |
// ----------------------------------------------- imports
var Declare = require('tui/base/Declare');
var IValidator = require('tui/validation/IValidator');
// ----------------------------------------------- class
var Require = Declare({
extends : IValidator,
validate : function(value, options){
if(_.isNull(value)) return false;
return _.isString(value) ? string.trim(value) !== "" : false;
}
})
module.exports = Require; | mm250/TiFramework | app/lib/morcode/validation/Required.js | JavaScript | apache-2.0 | 463 |