code stringlengths 2 1.05M |
|---|
define([
"./core",
"./var/pnum",
"./core/access",
"./css/var/rmargin",
"./css/var/rnumnonpx",
"./css/var/cssExpand",
"./css/var/isHidden",
"./css/var/getStyles",
"./css/curCSS",
"./css/defaultDisplay",
"./css/addGetHookIf",
"./css/support",
"./data/var/dataPriv",
"./core/init",
"./css/swap",
"./core/ready",
"./selector" // contains
], function( jQuery, pnum, access, rmargin, rnumnonpx, cssExpand, isHidden,
getStyles, curCSS, defaultDisplay, addGetHookIf, support, dataPriv ) {
var
// Swappable if display is none or starts with table
// except "table", "table-cell", or "table-caption"
// See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ),
rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ),
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: "0",
fontWeight: "400"
},
cssPrefixes = [ "Webkit", "Moz", "ms" ];
// Return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {
// Shortcut for names that are not vendor prefixed
if ( name in style ) {
return name;
}
// Check for vendor prefixed names
var capName = name[0].toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in style ) {
return name;
}
}
return origName;
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// Both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
}
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
}
// At this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
} else {
// At this point, extra isn't content, so add padding
val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
// At this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var valueIsBorderBox = true,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
styles = getStyles( elem ),
isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
// Some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name, styles );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// Check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox &&
( support.boxSizingReliable() || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
}
// Use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox,
styles
)
) + "px";
}
function showHide( elements, show ) {
var display, elem, hidden,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = dataPriv.get( elem, "olddisplay" );
display = elem.style.display;
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = dataPriv.access(
elem,
"olddisplay",
defaultDisplay(elem.nodeName)
);
}
} else {
hidden = isHidden( elem );
if ( display !== "none" || !hidden ) {
dataPriv.set(
elem,
"olddisplay",
hidden ? display : jQuery.css( elem, "display" )
);
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Don't automatically add "px" to these possibly-unitless properties
cssNumber: {
"columnCount": true,
"fillOpacity": true,
"flexGrow": true,
"flexShrink": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"order": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
"float": "cssFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] ||
( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
// Gets hook for the prefixed version, then unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// Convert "+=" or "-=" to relative numbers (#7345)
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that null and NaN values aren't set (#7116)
if ( value == null || value !== value ) {
return;
}
// If a number was passed in, add 'px' (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// Support: IE9-11+
// background-* props affect original clone's values
if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) {
style[ name ] = "inherit";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) ||
(value = hooks.set( elem, value, extra )) !== undefined ) {
style[ name ] = value;
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks &&
(ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra, styles ) {
var val, num, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] ||
( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// Try prefixed name followed by the unprefixed name
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name, styles );
}
// Convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Make numeric if forced or a qualifier was provided and val looks numeric
if ( extra === "" || extra ) {
num = parseFloat( val );
return extra === true || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
}
});
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// Certain elements can have dimension info if we invisibly show them
// but it must have a current display style that would benefit
return rdisplayswap.test( jQuery.css( elem, "display" ) ) &&
elem.offsetWidth === 0 ?
jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
}) :
getWidthOrHeight( elem, name, extra );
}
},
set: function( elem, value, extra ) {
var styles = extra && getStyles( elem );
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
styles
) : 0
);
}
};
});
// Support: Android 2.3
jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight,
function( elem, computed ) {
if ( computed ) {
return jQuery.swap( elem, { "display": "inline-block" },
curCSS, [ elem, "marginRight" ] );
}
}
);
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i = 0,
expanded = {},
// Assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ];
for ( ; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
});
jQuery.fn.extend({
css: function( name, value ) {
return access( this, function( elem, name, value ) {
var styles, len,
map = {},
i = 0;
if ( jQuery.isArray( name ) ) {
styles = getStyles( elem );
len = name.length;
for ( ; i < len; i++ ) {
map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
}
return map;
}
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state ) {
if ( typeof state === "boolean" ) {
return state ? this.show() : this.hide();
}
return this.each(function() {
if ( isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
});
return jQuery;
});
|
describe('Server Integration 2', function () {
// This test must not be in the first executed describe block.
// For this reason the test exists two times to ensure this condition.
it('runs in the Meteor fiber', function () {
var callMeteorMethod = function () {
expect(Meteor.call('test', 1)).toBe(true)
}
expect(callMeteorMethod).not.toThrow()
});
});
|
define(
({
addDistance: "길이 단위 추가",
addArea: "면적 단위 추가",
label: "레이블",
abbr: "약어",
conversion: "변환",
actions: "작업",
areaUnits: "면적 단위",
distanceUnits: "길이 단위",
kilometers: "킬로미터",
miles: "마일",
meters: "미터",
feet: "피트",
yards: "야드",
squareKilometers: "제곱킬로미터",
squareMiles: "제곱마일",
acres: "에이커",
hectares: "헥타르",
squareMeters: "제곱미터",
squareFeet: "제곱피트",
squareYards: "제곱야드",
distance: "거리",
area: "면적",
kilometersAbbreviation: "km",
milesAbbreviation: "mi",
metersAbbreviation: "m",
feetAbbreviation: "ft",
yardsAbbreviation: "yd",
squareKilometersAbbreviation: "sq km",
squareMilesAbbreviation: "sq mi",
acresAbbreviation: "ac",
hectaresAbbreviation: "ha",
squareMetersAbbreviation: "sq m",
squareFeetAbbreviation: "sq ft",
squareYardsAbbreviation: "sq yd",
defineUnits: "측정 단위을 정의합니다.",
operationalLayer: "그리기를 맵의 운영 레이어로 추가합니다."
})
); |
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
/**
* Class representing a ProductResult.
*/
class ProductResult extends Array {
/**
* Create a ProductResult.
* @member {array} [values]
* @member {string} [nextLink]
*/
constructor() {
super();
}
/**
* Defines the metadata of ProductResult
*
* @returns {object} metadata of ProductResult
*
*/
mapper() {
return {
required: false,
serializedName: 'ProductResult',
type: {
name: 'Composite',
className: 'ProductResult',
modelProperties: {
values: {
required: false,
serializedName: '',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'ProductElementType',
type: {
name: 'Composite',
className: 'Product'
}
}
}
},
nextLink: {
required: false,
serializedName: 'nextLink',
type: {
name: 'String'
}
}
}
}
};
}
}
module.exports = ProductResult;
|
emq.globalize();
setResolver(Ember.DefaultResolver.extend({
testSubjects: {
'component:ic-modal': ic.modal.ModalComponent,
'component:ic-modal-trigger': ic.modal.ModalTriggerComponent,
'component:ic-modal-title': ic.modal.ModalTitleComponent
},
resolve: function(fullName) {
return this.testSubjects[fullName] || this._super.apply(this, arguments);
}
}).create());
Function.prototype.compile = function() {
var template = this.toString().split('\n').slice(1,-1).join('\n') + '\n';
return Ember.Handlebars.compile(template);
};
function lookupComponent(id) {
return Ember.View.views[id];
}
|
/*!
* filename: ej.localetexts.zh-CN.js
* Copyright Syncfusion Inc. 2001 - 2016. All rights reserved.
* Use of this code is subject to the terms of our license.
* A copy of the current license can be obtained at any time by e-mailing
* licensing@syncfusion.com. Any infringement will be prosecuted under
* applicable laws.
*/
ej.Autocomplete.Locale["zh-CN"] = {
addNewText: "添新",
emptyResultText: "没有建议",
actionFailure: "指定字段中不定的数据源存在",
};
ej.ColorPicker.Locale["zh-CN"] = {
buttonText: {
apply: "应用",
cancel: "取消",
swatches: "色板"
},
tooltipText: {
switcher: "切换器",
addbutton: "添加颜色",
basic: "基本",
monochrome: "单色铬",
flatcolors: "平的颜色",
seawolf: "海狼",
webcolors: "网颜色",
sandy: "沙",
pinkshades: "桃红色树荫",
misty: "蒙蒙",
citrus: "柑橘",
vintage: "葡萄酒",
moonlight: "月光",
candycrush: "糖果粉碎",
currentcolor: "当前颜色",
selectedcolor: "所选颜色"
},
};
ej.CurrencyTextbox.Locale["zh-CN"] = {
watermarkText: "输入值",
};
ej.DatePicker.Locale["zh-CN"] = {
watermarkText: "选择日期",
buttonText: "今天",
};
ej.DateRangePicker.Locale["zh-CN"] = {
ButtonText: {
apply: "应用",
cancel: "取消",
reset: "重启"
},
watermarkText: "选择范围",
customPicker: "自定义选择器",
};
ej.DateTimePicker.Locale["zh-CN"] = {
watermarkText: "选择日期时间",
buttonText: {
today: "今天",
timeNow: "现在时间",
done: "做",
timeTitle: "时间"
},
};
ej.datavisualization.Diagram.Locale["zh-CN"] = {
cut: "切",
copy: "复制",
paste: "糊",
undo: "解开",
redo: "重做",
selectAll: "全选",
grouping: "分组",
group: "组",
ungroup: "取消组合",
order: "订购",
bringToFront: "BringToFront",
moveForward: "向前移动",
sendBackward: "后移",
sendToBack: "SendToBack",
};
ej.Dialog.Locale["zh-CN"] = {
tooltip: {
close: "关闭",
collapse: "崩溃",
restore: "恢复",
maximize: "最大化",
minimize: "最小化最小化",
expand: "扩大",
unPin: "拔掉闩",
pin: "销"
},
closeIconTooltip: "关闭",
};
ej.DropDownList.Locale["zh-CN"] = {
emptyResultText: "没有建议",
watermarkText: " ",
};
ej.ExcelFilter.Locale["zh-CN"] = {
SortNoSmaller: "排序从最小到最大",
SortNoLarger: "排序从大到小",
SortTextAscending: "排序从A到Z",
SortTextDescending: "排序Z到A",
SortDateOldest: "按最早日期排序",
SortDateNewest: "排序方式最新",
SortByColor: "按颜色",
SortByCellColor: "排序方式细胞色",
SortByFontColor: "排序方式字体颜色",
FilterByColor: "过滤按颜色",
CustomSort: "自定义排序",
FilterByCellColor: "通过细胞彩色滤光片",
FilterByFontColor: "通过字体颜色过滤",
ClearFilter: "清除过滤器",
NumberFilter: "号码过滤",
GuidFilter: "GUD过滤器",
TextFilter: "文本过滤器",
DateFilter: "日期过滤器",
DateTimeFilter: "日期时间过滤器",
SelectAll: "全选",
Blanks: "空白",
Search: "搜索",
Showrowswhere: "显示的行",
NumericTextboxWaterMark: "数字水印文本框",
StringMenuOptions: [{ text: "等于", value: "equal" }, { text: "不平等", value: "notequal" }, { text: "以。。开始", value: "startswith" }, { text: "结束与", value: "endswith" }, { text: "包含", value: "contains" }, { text: "自定义过滤器", value: "customfilter" }, ],
NumberMenuOptions: [{ text: "等于", value: "equal" }, { text: "不平等", value: "notequal" }, { text: "少于", value: "lessthan" }, { text: "小于或等于", value: "lessthanorequal" }, { text: "比...更棒", value: "greaterthan" }, { text: "大于或等于", value: "greaterthanorequal" }, { text: "之间", value: "between" }, { text: "自定义过滤器", value: "customfilter" }, ],
GuidMenuOptions: [{ text: "等于", value: "equal" }, { text: "不平等", value: "notequal" }, { text: "自定义过滤器", value: "customfilter" }, ],
DateMenuOptions: [{ text: "等于", value: "equal" }, { text: "不平等", value: "notequal" }, { text: "少于", value: "lessthan" }, { text: "小于或等于", value: "lessthanorequal" }, { text: "比...更棒", value: "greaterthan" }, { text: "大于或等于", value: "greaterthanorequal" }, { text: "之间", value: "between" }, { text: "自定义过滤器", value: "customfilter" }, ],
DatetimeMenuOptions: [{ text: "等于", value: "equal" }, { text: "不平等", value: "notequal" }, { text: "少于", value: "lessthan" }, { text: "小于或等于", value: "lessthanorequal" }, { text: "比...更棒", value: "greaterthan" }, { text: "大于或等于", value: "greaterthanorequal" }, { text: "之间", value: "between" }, { text: "自定义过滤器", value: "customfilter" }, ],
Top10MenuOptions: [{ text: "最佳", value: "top" }, { text: "底部", value: "bottom" }, ],
title: "自定义过滤器",
PredicateAnd: "和",
PredicateOr: "要么",
Ok: "好",
MatchCase: "相符",
Cancel: "取消",
NoResult: "未找到匹配",
CheckBoxStatusMsg: "并非所有的项目展示",
DatePickerWaterMark: "选择日期",
DateTimePickerWaterMark: "水印的DateTimePicker",
True: "真正",
False: "假",
};
ej.FileExplorer.Locale["zh-CN"] = {
Back: "落后",
Forward: "前锋",
Upward: "向上",
Refresh: "刷新",
Addressbar: "地址栏",
Upload: "上传",
Rename: "重命名",
Delete: "删除",
Download: "下载",
Error: "错误",
Cut: "切",
Copy: "复制",
Paste: "糊",
Details: "详细信息",
Searchbar: "搜索栏",
Open: "打开",
Search: "搜索",
NewFolder: "新建文件夹",
Size: "尺寸",
RenameAlert: "请输入新的名称",
NewFolderAlert: "请输入新的文件夹名称,",
ContextMenuOpen: "打开",
ContextMenuNewFolder: "新建文件夹",
ContextMenuDelete: "删除",
ContextMenuRename: "重命名",
ContextMenuUpload: "上传",
ContextMenuDownload: "下载",
ContextMenuCut: "切",
ContextMenuCopy: "复制",
ContextMenuPaste: "糊",
ContextMenuGetinfo: "获取信息",
ContextMenuRefresh: "刷新",
ContextMenuOpenFolderLocation: "打开文件夹的位置",
Item: "项目",
Items: "项目",
GeneralError: "请参阅浏览器的控制台窗口的更多信息",
DeleteFolder: "你确定你要删除",
CancelPasteAction: "目标文件夹是源文件夹的子文件夹。",
OkButton: "好",
CancelButton: "取消",
YesToAllButton: "全部同意",
NoToAllButton: "全否",
YesButton: "是",
NoButton: "没有",
SkipButton: "跳跃",
Grid: "网格视图",
Tile: "瓷砖观点",
LargeIcons: "大图标",
Name: "名称",
Location: "位置",
Type: "物品种类",
Layout: "布局",
Created: "创建",
Accessed: "访问",
Modified: "改性",
DialogCloseToolTip: "关闭",
UploadSettings: {
dropAreaText: "将文件拖放或点击上传",
filedetail: "所选文件大小过大。请选择有效的尺寸范围内的文件。",
denyError: "与#Extension扩展名的文件是不允许的。",
allowError: "只有#Extension扩展名的文件是允许的。",
cancelToolTip: "取消",
removeToolTip: "清除",
retryToolTip: "重试",
completedToolTip: "完成",
failedToolTip: "失败的",
closeToolTip: "关闭"
},
};
ej.Gantt.Locale["zh-CN"] = {
emptyRecord: "无记录可显示",
alertTexts: {
indentAlert: "有没有横道记录被选中进行缩进",
outdentAlert: "有没有横道记录被选择执行凸出",
predecessorEditingValidationAlert: "循环相关性发生,请检查的前身",
predecessorAddingValidationAlert: "填写前身表中的所有列",
idValidationAlert: "重复ID",
dateValidationAlert: "无效的结束日期",
dialogResourceAlert: "填写资源表中的所有列"
},
columnHeaderTexts: {
taskId: "ID",
taskName: "任务名称",
startDate: "开始日期",
endDate: "结束日期",
resourceInfo: "资源",
duration: "为期",
status: "进展",
predecessor: "前辈",
type: "类型",
offset: "抵消",
baselineStartDate: "基线开始日期",
baselineEndDate: "基线结束日期",
WBS: "WBS",
WBSpredecessor: "WBS前身",
dialogCustomFieldName: "列名",
dialogCustomFieldValue: "值",
notes: "笔记",
taskType: "任务类型",
work: "工作",
unit: "单元",
effortDriven: "努力驱动"
},
editDialogTexts: {
addFormTitle: "新任务",
editFormTitle: "编辑任务",
saveButton: "保存",
deleteButton: "删除",
cancelButton: "取消",
addPredecessor: "添新",
removePredecessor: "清除"
},
columnDialogTexts: {
field: "领域",
headerText: "标题文本",
editType: "编辑类型",
filterEditType: "过滤器编辑类型",
allowFiltering: "允许过滤",
allowFilteringBlankContent: "允许过滤空白内容",
allowSorting: "允许排序",
visible: "可见",
width: "宽度",
textAlign: "文本对齐",
headerTextAlign: "头文字对齐",
columnsDropdownData: "列下拉数据",
dropdownTableText: "文本",
dropdownTableValue: "值",
addData: "加",
deleteData: "去掉",
allowCellSelection: "允许小区选择"
},
toolboxTooltipTexts: {
addTool: "加",
editTool: "编辑",
saveTool: "更新",
deleteTool: "删除",
cancelTool: "取消",
searchTool: "搜索",
indentTool: "缩进",
outdentTool: "凸出",
expandAllTool: "展开全部",
collapseAllTool: "全部收缩",
nextTimeSpanTool: "接下来时间跨度",
prevTimeSpanTool: "上一个时间跨度",
criticalPathTool: "关键路径",
excelExportTool: "Excel导出"
},
durationUnitTexts: {
days: "天",
hours: "小时",
minutes: "分钟",
day: "天",
hour: "小时",
minute: "分钟"
},
durationUnitEditText: {
minute: ["米", "分", "分钟", "分钟"],
hour: ["H", "小时", "小时", "小时"],
day: ["ð", "DY", "天", "天"]
},
workUnitTexts: {
days: "天",
hours: "小时",
minutes: "分钟"
},
taskTypeTexts: {
fixedWork: "固定办公",
fixedUnit: "固定单位",
fixedDuration: "固定期限"
},
effortDrivenTexts: {
yes: "是",
no: "没有"
},
contextMenuTexts: {
taskDetailsText: "任务详细信息...",
addNewTaskText: "添加新任务",
indentText: "缩进",
outdentText: "凸出",
deleteText: "删除",
aboveText: "以上",
belowText: "下面"
},
newTaskTexts: {
newTaskName: "新任务"
},
columnMenuTexts: {
sortAscendingText: "升序",
sortDescendingText: "降序",
columnsText: "列",
insertColumnLeft: "在左侧插入列",
insertColumnRight: "在右侧插入列",
deleteColumn: "删除列",
renameColumn: "重列"
},
taskModeTexts: {
manual: "手册",
auto: "汽车"
},
columnDialogTitle: {
insertColumn: "插入列",
deleteColumn: "删除列",
renameColumn: "重列"
},
deleteColumnText: "你确定要删除此列?",
okButtonText: "好",
cancelButtonText: "取消",
confirmDeleteText: "确认删除",
predecessorEditingTexts: {
fromText: "从",
toText: "至"
},
dialogTabTitleTexts: {
generalTabText: "一般",
predecessorsTabText: "前辈",
resourcesTabText: "资源",
customFieldsTabText: "自定义字段",
notesTabText: "笔记"
}
};
ej.Grid.Locale["zh-CN"] = {
EmptyRecord: "无记录可显示",
GroupDropArea: "这里拖动列标题,组其列",
DeleteOperationAlert: "未选择要删除操作记录",
EditOperationAlert: "未选择要编辑操作记录",
SaveButton: "保存",
OkButton: "好",
CancelButton: "取消",
EditFormTitle: "详情",
AddFormTitle: "添加新记录",
Notactionkeyalert: "此组合键无法使用",
Keyconfigalerttext: "此组合键已被分配到",
GroupCaptionFormat: "{{:headerText}}: {{:key}} - {{:count}} {{if count == 1 }} 项目 {{else}} 项目 {{/if}} ",
BatchSaveConfirm: "你确定你要保存更改?",
BatchSaveLostChanges: "未保存的更改将丢失。你确定要继续吗?",
ConfirmDelete: "您确定要删除记录?",
CancelEdit: "你确定要取消的变化?",
PagerInfo: "{0}{1}页({2}项)",
FrozenColumnsViewAlert: "冻结列应在GridView中区",
FrozenColumnsScrollAlert: "启用允许滚动,而使用冻结列",
FrozenNotSupportedException: "冻结行和列不支持分组,行模板,详细信息模板,等级电网和批量编辑",
Add: "加",
Edit: "编辑",
Delete: "删除",
Update: "更新",
Cancel: "取消",
Done: "做",
Columns: "列",
SelectAll: "(全选)",
PrintGrid: "打印",
ExcelExport: "Excel导出",
WordExport: "字出口",
PdfExport: "PDF导出",
StringMenuOptions: [{ text: "以。。开始", value: "Starts With" }, { text: "的endsWith", value: "Ends With" }, { text: "包含", value: "Contains" }, { text: "等于", value: "Equal" }, { text: "不平等", value: "NotEqual" }, ],
NumberMenuOptions: [{ text: "少于", value: "LessThan" }, { text: "比...更棒", value: "GreaterThan" }, { text: "小于或等于", value: "LessThanOrEqual" }, { text: "大于或等于", value: "GreaterThanOrEqual" }, { text: "等于", value: "Equal" }, { text: "不平等", value: "NotEqual" }, ],
PredicateAnd: "和",
PredicateOr: "要么",
Filter: "过滤",
FilterMenuCaption: "筛选值",
FilterbarTitle: "s滤波巴细胞",
MatchCase: "相符",
Clear: "明确",
ResponsiveFilter: "过滤",
ResponsiveSorting: "分类",
Search: "搜索",
DatePickerWaterMark: "选择日期",
EmptyDataSource: "因为列从数据源中自动生成的列网格生成的数据源绝不能以初始加载空",
ForeignKeyAlert: "更新后的值应该是一个有效的外键值",
True: "真正",
False: "假",
UnGroup: "点击这里取消组合",
AddRecord: "添加记录",
EditRecord: "编辑记录",
DeleteRecord: "删除记录",
Save: "保存",
Grouping: "组",
Ungrouping: "取消组合",
SortInAscendingOrder: "按升序排序",
SortInDescendingOrder: "按降序排序",
NextPage: "下一页",
PreviousPage: "上一页",
FirstPage: "第一页",
LastPage: "最后一页",
EmptyRowValidationMessage: "至少一个字段必须更新",
NoResult: "未找到匹配"
};
;
if (ej.mobile !== undefined && ej.mobile.Grid !== undefined) {
ej.mobile.Grid.Locale["zh-CN"] = {
emptyResult: "无记录可显示",
filterValidation: "输入有效过滤数据",
filterTypeValidation: "输入有效的过滤器的数据。当前的过滤器列式",
captionText: "项目",
spinnerText: "载入中...",
HideColumnAlert: "至少一列必须显示在格",
columnSelectorText: "隐藏列",
columnSelectorDone: "好",
columnSelectorCancel: "取消",
columnSelectorWarning: "警告",
filterOk: "好",
filterWarning: "警告"
};
;
}
if (ej.mobile !== undefined && ej.mobile.DatePicker !== undefined) {
ej.mobile.DatePicker.Locale["zh-CN"] = {
confirmText: "做",
Windows: {
cancelText: "取消",
headerText: "选择日期",
toolbarConfirmText: "DONE",
toolbarCancelText: "关闭"
},
};
;
}
if (ej.mobile !== undefined && ej.mobile.TimePicker !== undefined) {
ej.mobile.TimePicker.Locale["zh-CN"] = {
confirmText: "做",
AM: "上午",
PM: "下午",
Android: {
headerText: "设置时间"
},
Windows: {
cancelText: "取消",
headerText: "合理安排时间",
toolbarCancelText: "关闭",
toolbarConfirmText: "DONE"
},
};
;
}
ej.NumericTextbox.Locale["zh-CN"] = {
watermarkText: "输入值",
};
ej.PivotChart.Locale["zh-CN"] = {
Measure: "测量",
Row: "行",
Column: "柱",
Expand: "扩大",
Collapse: "崩溃",
Exit: "出口",
Value: "值"
};
ej.PivotClient.Locale["zh-CN"] = {
DeferUpdate: "推迟更新",
MDXQuery: "MDX查询",
Column: "柱",
Row: "行",
Slicer: "切片机",
CubeSelector: "立方选择",
ReportName: "报告名称",
NewReport: "新报告",
CubeDimensionBrowser: "多维数据集维度浏览器",
AddReport: "添加报告",
RemoveReport: "删除报告",
CannotRemoveSingleReport: "无法删除单个报表",
AreYouSureToDeleteTheReport: "您确定要删除的报告",
RenameReport: "重命名报告",
SaveReport: "保存报告",
ChartTypes: "图表类型",
ToggleAxis: "切换轴",
LoadReport: "负荷报告",
ExportToExcel: "导出到Excel",
ExportToWord: "导出到Word",
ExportToPdf: "导出为PDF",
FullScreen: "全屏",
Grid: "格",
Chart: "图表",
OK: "好",
Cancel: "取消",
MeasureEditor: "编辑测量",
MemberEditor: "编辑成员",
Measures: "措施",
SortOrFilterColumn: "排序/过滤器(列)",
SortOrFilterRow: "排序/过滤器(行)",
SortingAndFiltering: "排序和过滤",
Sorting: "排序",
Measure: "测量",
Order: "订购",
Filtering: "过滤",
Condition: "条件",
PreserveHierarchy: "维护层次",
Ascending: "按升序排列",
Descending: "按降序排列",
Enable: "启用",
Disable: "禁用",
and: "和",
Line: "线",
Spline: "仿样",
Area: "区",
SplineArea: "花键区",
StepLine: "步线",
StepArea: "步区",
Pie: "馅饼",
Bar: "酒吧",
StackingArea: "堆叠区",
StackingColumn: "堆积柱",
StackingBar: "堆积柱状图",
Pyramid: "金字塔",
Funnel: "漏斗",
Doughnut: "甜甜圈",
Scatter: "分散",
Sort: "排序",
SelectField: "选择字段",
LabelFilterLabel: "显示项目的标签。",
ValueFilterLabel: "显示的项目。",
LabelFilters: "标注筛选器",
BeginsWith: "开始使用",
NotBeginsWith: "未开始",
EndsWith: "结束于",
NotEndsWith: "不是结束于",
Contains: "包含",
NotContains: "不包含",
ValueFilters: "过滤器的值。",
ClearFilter: "清除过滤器",
Equals: "等于",
NotEquals: "不等于",
GreaterThan: "大于",
GreaterThanOrEqualTo: "大于或等于",
LessThan: "低于",
LessThanOrEqualTo: "小于或等于",
Between: "之间",
NotBetween: "不能在",
Top10: "顶级计数",
Close: "关闭",
AddToColumn: "添加到列",
AddToRow: "添加的行",
AddToSlicer: "添加到切片机",
Value: "值",
EqualTo: "等于",
ReportList: "报告列表",
Bubble: "球型罩",
TreeMap: "树形图",
Alert: "警报",
MDXAlertMsg: "请添加测量、尺寸或层次结构中的适当的轴查看 MDX 查询。",
FilterSortRowAlertMsg: "尺寸没有找到行中的轴。 请添加维元素行内的轴上排序/过滤。",
FilterSortColumnAlertMsg: "尺寸中未找到列的轴。 请添加维元素列中的轴上排序/过滤。",
FilterSortcolMeasureAlertMsg: "请添加度量的列的轴",
FilterSortrowMeasureAlertMsg: "请添加的行中轴",
FilterSortElementAlertMsg: "找不到元素列中的轴。 请将元素添加在列中轴用于排序/过滤。",
LoadReportAlertMsg: "请选择有效的报告。",
FilterMeasureSelectionAlertMsg: "请选择有效的措施。",
FilterConditionAlertMsg: "请设置有效的条件。",
FilterStartValueAlertMsg: "请设置的开始值。",
FilterEndValueAlertMsg: "请设置的终止值。",
FilterInvalidAlertMsg: "无效的操作!"
};
ej.PivotGauge.Locale["zh-CN"] = {
RevenueGoal: "收入目标",
RevenueValue: "收入值",
};
ej.Pager.Locale["zh-CN"] = {
pagerInfo: "{0}{1}页({2}项)",
firstPageTooltip: "转到第一页",
lastPageTooltip: "转到最后一页",
nextPageTooltip: "转到下一页",
previousPageTooltip: "转到上一页",
nextPagerTooltip: "转到下一页",
previousPagerTooltip: "转到上一页",
};
ej.PdfViewer.Locale["zh-CN"] = {
toolbar: {
print: {
headerText: "打印",
contentText: "打印PDF文档。"
},
first: {
headerText: "第一",
contentText: "去到PDF文档的第一页。"
},
previous: {
headerText: "以前",
contentText: "去到PDF文档的前一页。"
},
next: {
headerText: "下一个",
contentText: "转至PDF文档的下一个页面。"
},
last: {
headerText: "持续",
contentText: "去到PDF文档的最后一页。"
},
zoomIn: {
headerText: "放大",
contentText: "放大到PDF文档。"
},
zoomOut: {
headerText: "缩小",
contentText: "缩小的PDF文档。"
},
pageIndex: {
headerText: "页码",
contentText: "当前页编号,以查看。"
},
zoom: {
headerText: "放大",
contentText: "放大或缩小的PDF文档。"
},
fitToWidth: {
headerText: '适合宽度',
contentText: '适合PDF页面到容器的宽度。',
},
fitToPage: {
headerText: '适合页面',
contentText: '适合PDF页面的容器。',
},
},
};
ej.PercentageTextbox.Locale["zh-CN"] = {
watermarkText: "输入值",
};
ej.PivotGrid.Locale["zh-CN"] = {
ToolTipRow: "行",
ToolTipColumn: "柱",
ToolTipValue: "值",
SeriesPage: "系列的页面",
CategoricalPage: "分类页",
DragFieldHere: "这里拖动领域",
ColumnArea: "这里掉落列",
RowArea: "这里将行",
ValueArea: "这里降值",
OK: "好",
Cancel: "取消",
Remove: "清除",
ConditionalFormatting: "条件格式",
Condition: "有条件的类型",
Value1: "值1",
Value2: "值2",
Editcondtion: "编辑条件",
Backcolor: "背景颜色",
Borderrange: "边界范围",
Borderstyle: "边框样式",
Fontsize: "字体大小",
Fontstyle: "字体样式",
Bordercolor: "边框颜色",
Sort: "排序",
SelectField: "选择字段",
LabelFilterLabel: "显示项目的标签。",
ValueFilterLabel: "显示的项目。",
LabelFilters: "标注筛选器",
BeginsWith: "开始使用",
NotBeginsWith: "未开始",
EndsWith: "结束于",
NotEndsWith: "不是结束于",
Contains: "包含",
NotContains: "不包含",
ValueFilters: "过滤器的值。",
ClearFilter: "清除过滤器",
Equals: "等于",
NotEquals: "不等于",
GreaterThan: "大于",
GreaterThanOrEqualTo: "大于或等于",
LessThan: "低于",
LessThanOrEqualTo: "小于或等于",
Between: "之间",
NotBetween: "不能在",
AddToFilter: "添加到筛选器",
AddToRow: "添加的行",
AddToColumn: "添加到列",
AddToValues: "添加值",
Warning: "警告",
Error: "错误",
GroupingBarAlertMsg: "在被移动不能被放在这一领域的报告。",
Measures: "措施",
Expand: "展开",
Collapse: "崩溃",
NoValue: "没有值。",
Close: "关闭",
Goal: "目标",
Status: "状态",
Trend: "趋势",
Value: "值",
ConditionalFormattingErrorMsg: "给定的值不匹配",
ConditionalFormattingConformMsg: "您确定要删除所选的格式吗?",
EnterOperand1: "输入操作数1",
EnterOperand2: "输入操作数2",
ConditionalFormatting: "条件格式化",
AddNew: "添加新的",
Format: "格式",
NoMeasure: "请添加任何措施。",
AliceBlue: "爱丽丝蓝",
Black: "黑色",
Blue: "蓝色",
Brown: "Brown",
Gold: "金牌服务",
Green: "绿色",
Lime: "浅绿色",
Maroon: "栗色",
Orange: "橙色",
Pink: "粉红色",
Red: "红色",
Violet: "紫",
White: "白色",
Yellow: "黄色",
Solid: "固体",
Dashed: "虚线",
Dotted: "带点",
Double: "双",
Groove: "凹槽",
Inset: "插入",
Outset: "一开始",
Ridge: "Ridge",
None: "无",
Algerian: "阿尔及利亚",
Arial: "Arial",
BodoniMT: "Bodoni MT",
BritannicBold: "英国粗体",
Cambria: "Cambria",
Calibri: "Calibri",
CourierNew: "Courier New",
DejaVuSans: "DejaVu Sans",
Forte: "Forte",
Gerogia: "Gerogia",
Impact: "影响。",
SegoeUI: "Segoe UI",
Tahoma: "Tahoma",
TimesNewRoman: "Times New Roman",
Verdana: "Verdana",
CubeDimensionBrowser: "多维数据集维度浏览器",
SelectHierarchy: "请选择层次结构",
CalculatedField: "经过计算的字段",
Name: "名称:",
Add: "添加",
Formula: "公式:",
Delete: "删除",
Fields: "字段:",
CalculatedFieldNameNotFound: "给定的计算字段名称未找到",
InsertField: "插入字段",
EmptyField: "请输入计算出的字段名或公式。",
NotValid: "给定的公式无效。",
NotPresent: "值字段中使用的任何的计算字段的公式在中不存在 PivotGrid",
Confirm: "经过计算的字段已存在具有相同名称的。 由于要更换吗?",
CalcValue: "计算字段可以插入到只有在价值区域字段"
};
ej.PivotPager.Locale["zh-CN"] = {
SeriesPage: "系列的页面",
CategoricalPage: "分类页",
Error: "错误",
OK: "“确定” 按钮",
Close: "关闭",
PageCountErrorMsg: "输入有效的页码。"
};
ej.PivotSchemaDesigner.Locale["zh-CN"] = {
PivotTableFieldList: "数据透视表字段列表",
ChooseFieldsToAddToReport: "选择字段添加到报告:",
DragFieldBetweenAreasBelow: "下面区域之间拖动字段:",
ReportFilter: "报告过滤器",
ColumnLabel: "列标签",
RowLabel: "行标签",
Values: "值",
DeferLayoutUpdate: "延迟布局更新",
Update: "更新",
Sort: "排序",
SelectField: "选择字段",
LabelFilterLabel: "显示项目的标签。",
ValueFilterLabel: "显示的项目。",
LabelFilters: "标注筛选器",
BeginsWith: "开始使用",
NotBeginsWith: "未开始",
EndsWith: "结束于",
NotEndsWith: "不是结束于",
Contains: "包含",
NotContains: "不包含",
ValueFilters: "过滤器的值。",
ClearFilter: "清除过滤器",
Equals: "等于",
NotEquals: "不等于",
GreaterThan: "大于",
GreaterThanOrEqualTo: "大于或等于",
LessThan: "低于",
LessThanOrEqualTo: "小于或等于",
Between: "之间",
NotBetween: "不能在",
Measures: "措施",
AlertMsg: "在被移动不能被放在这一领域的报告。",
Close: "关闭",
Goal: "目标",
Status: "状态",
Trend: "趋势",
Value: "值",
AddToFilter: "添加到筛选器",
AddToRow: "添加的行",
AddToColumn: "添加到列",
AddToValues: "添加值",
Warning: "警告",
OK: "“确定” 按钮",
Cancel: "取消"
};
ej.datavisualization.RangeNavigator.Locale["zh-CN"] = {
intervals: {
quarter: {
longQuarters: "25美分硬币,",
shortQuarters: "Q"
},
week: {
longWeeks: "周,",
shortWeeks: "W¯¯"
},
},
};
ej.datavisualization.Chart.Locale["zh-CN"] = {
zoomIn: "放大",
zoomOut: "缩小",
zoom: "放大",
pan: "泛",
reset: "重启"
};
ej.ReportViewer.Locale["zh-CN"] = {
toolbar: {
print: {
headerText: "打印",
contentText: "打印报告。"
},
exportformat: {
headerText: "出口",
contentText: "选择导出的文件格式。",
Pdf: "PDF",
Excel: "高强",
Word: "字",
Html: "HTML",
PPT: 'PPT'
},
first: {
headerText: "第一",
contentText: "转至报告的第一页。"
},
previous: {
headerText: "以前",
contentText: "转至报告的前一页。"
},
next: {
headerText: "下一个",
contentText: "进入报告的下一页。"
},
last: {
headerText: "持续",
contentText: "转至报告的最后一页。"
},
documentMap: {
headerText: "文档结构图",
contentText: "显示或隐藏文档结构图。"
},
parameter: {
headerText: "参数",
contentText: "显示或隐藏参数窗格。"
},
zoomIn: {
headerText: "放大",
contentText: "放大到报告中。"
},
zoomOut: {
headerText: "缩小",
contentText: "缩小的报告。"
},
refresh: {
headerText: "刷新",
contentText: "刷新报表。"
},
printLayout: {
headerText: "打印布局",
contentText: "打印布局模式和正常模式之间切换。"
},
pageIndex: {
headerText: "页码",
contentText: "当前页编号,以查看。"
},
zoom: {
headerText: "放大",
contentText: "放大或缩小在报告中。"
},
back: {
headerText: "背部",
contentText: "返回到父报告。"
},
fittopage: {
headerText: "适合页面",
contentText: "适合报表页到容器。",
pageWidth: "页面宽度",
pageHeight: "整页"
},
pagesetup: {
headerText: "页面设置",
contentText: "选择页面设置选项来改变纸张大小,方向和页边距。"
},
},
pagesetupDialog: {
paperSize: '纸张大小',
height: '高度',
width: '宽度',
margins: '边距',
top: '最佳',
bottom: '底部',
right: '对',
left: '剩下',
unit: '在',
orientation: '方向',
portrait: '肖像',
landscape: '景观',
doneButton: '做',
cancelButton: '取消'
},
viewButton: "查看报告",
};
ej.Ribbon.Locale["zh-CN"] = {
CustomizeQuickAccess: "自定义快速访问工具栏",
RemoveFromQuickAccessToolbar: "从快速访问工具栏删除",
AddToQuickAccessToolbar: "添加到快速访问工具栏",
ShowAboveTheRibbon: "上面显示功能区",
ShowBelowTheRibbon: "下面显示功能区",
MoreCommands: "更多命令...",
};
ej.RTE.Locale["zh-CN"] = {
bold: "胆大",
italic: "斜体",
underline: "强调",
strikethrough: "删除线",
superscript: "标",
subscript: "标",
justifyCenter: "对齐文本中心",
justifyLeft: "对齐文本左",
justifyRight: "文本对齐正确",
justifyFull: "辩解",
unorderedList: "插入无序列表",
orderedList: "插入有序列表",
indent: "增加缩进",
fileBrowser: "文件浏览器",
outdent: "减少缩进",
cut: "切",
copy: "复制",
paste: "糊",
paragraph: "段",
undo: "解开",
redo: "重做",
upperCase: "大写",
lowerCase: "小写",
clearAll: "全部清除",
clearFormat: "清除格式",
createLink: "插入/编辑超链接",
removeLink: "删除超级链接",
image: "插入图片",
video: "插入视频",
editTable: "编辑表属性",
embedVideo: "下面粘贴您的嵌入代码",
viewHtml: "查看HTML",
fontName: "选择字体系列",
fontSize: "选择字号",
fontColor: "选择颜色",
format: "格式",
backgroundColor: "背景颜色",
style: "样式",
deleteAlert: "你确定要清除所有内容?",
copyAlert: "你的浏览器不支持剪贴板的直接访问。请使用Ctrl+ C快捷键,而不是复制操作。",
pasteAlert: "你的浏览器不支持剪贴板的直接访问。请用CTRL+ V键盘快捷键,而不是粘贴操作。",
cutAlert: "你的浏览器不支持剪贴板的直接访问。请用CTRL+ X键盘快捷键,而不是剪切操作。",
videoError: "该文本区域不能为空",
imageWebUrl: "网址",
imageAltText: "替换文本",
dimensions: "外形尺寸",
constrainProportions: "约束比例",
linkWebUrl: "网址",
imageLink: "形象链接",
imageBorder: "图像边界",
imageStyle: "样式",
linkText: "文本",
linkToolTip: "提示",
html5Support: "此工具图标只能在支持HTML5的浏览器支持",
linkOpenInNewWindow: "在新窗口中打开链接",
tableColumns: "节数列",
tableRows: "节数行",
tableWidth: "宽度",
tableHeight: "高度",
tableCellSpacing: "CELLSPACING",
tableCellPadding: "CELLPADDING",
tableBorder: "边境",
tableCaption: "标题",
tableAlignment: "对准",
textAlign: "文本对齐",
dialogUpdate: "更新",
dialogInsert: "插入",
dialogCancel: "取消",
dialogApply: "应用",
dialogOk: "好",
createTable: "插入表格",
addColumnLeft: "左侧添加列",
addColumnRight: "右侧添加列",
addRowAbove: "添加行上方",
addRowBelow: "下面添加一行",
deleteRow: "删除行",
deleteColumn: "删除列",
deleteTable: "删除表",
customTable: "创建自定义表...",
characters: "人物",
words: "话",
general: "一般",
advanced: "高级",
table: "表",
row: "行",
column: "柱",
cell: "细胞",
solid: "固体",
dotted: "带点",
dashed: "虚线",
doubled: "翻倍",
maximize: "最大化",
resize: "最小化",
swatches: "色板",
quotation: "行情",
heading1: "标题1",
heading2: "标题2",
heading3: "标题3",
heading4: "标题4",
heading5: "标题5",
heading6: "标题6",
segoeui: "濑越UI",
arial: "宋体",
couriernew: "宋体",
georgia: "格鲁吉亚",
impact: "碰撞",
lucidaconsole: "龙力控制台",
tahoma: "宋体",
timesnewroman: "英语字体格式一种",
trebuchetms: "投石机MS",
verdana: "宋体",
disc: "圆盘",
circle: "圈",
square: "广场",
number: "数",
loweralpha: "阿尔法较低",
upperalpha: "阿尔法上限",
lowerroman: "罗马较低",
upperroman: "大写罗马",
none: "无",
charSpace: "字符(带空格)",
charNoSpace: "字符(无空格)",
wordCount: "字数",
left: "剩下",
right: "对",
center: "中央",
zoomIn: "放大",
zoomOut: "缩小",
print: "打印",
'import': "导入文档",
wordExport: "导出为Word文档",
pdfExport: "导出为Pdf文件",
FindAndReplace: "查找替换",
Find: "找",
MatchCase: "相符",
WholeWord: "全词",
ReplaceWith: "用。。。来代替",
Replace: "更换",
ReplaceAll: "全部替换",
FindErrorMsg: "找不到指定的字词"
};
ej.Schedule.Locale["zh-CN"] = {
ReminderWindowTitle: "提醒窗口",
CreateAppointmentTitle: "创建约会",
RecurrenceEditTitle: "编辑重复约会",
RecurrenceEditMessage: "你想怎么改该系列中的约会?",
RecurrenceEditOnly: "只有这一任命",
RecurrenceEditSeries: "整个系列",
PreviousAppointment: "上一页约会",
NextAppointment: "下一个约会",
AppointmentSubject: "学科",
StartTime: "开始时间",
EndTime: "时间结束",
AllDay: "整天",
StartTimeZone: "启动时区",
EndTimeZone: "结束时区",
Today: "今天",
Recurrence: "重复",
Done: "做",
Cancel: "取消",
Ok: "好",
RepeatBy: "通过重复",
RepeatEvery: "每天重复",
RepeatOn: "重复上",
StartsOn: "开始于",
Ends: "完",
Summary: "概要",
Daily: "每日",
Weekly: "每周",
Monthly: "每月一次",
Yearly: "每年",
Every: "一切",
EveryWeekDay: "每个工作日",
Never: "决不",
After: "后",
Occurence: "发生(S)",
On: "上",
Edit: "编辑",
RecurrenceDay: "日(S)",
RecurrenceWeek: "周(S)",
RecurrenceMonth: "本月(S)",
RecurrenceYear: "年份)",
The: "该",
OfEvery: "每",
First: "第一",
Second: "第二",
Third: "第三",
Fourth: "第四",
Last: "持续",
WeekDay: "平日",
WeekEndDay: "周末天",
Subject: "学科",
Categorize: "分类",
DueIn: "由于在",
DismissAll: "关闭所有",
Dismiss: "解雇",
OpenItem: "开放项目",
Snooze: "打盹",
Day: "日",
Week: "周",
WorkWeek: "工作周",
Month: "月",
AddEvent: "添加事件",
CustomView: "自定义视图",
Agenda: "议程",
Detailed: "编辑约会",
EventBeginsin: "开始预约中",
Editevent: "编辑约会",
Editseries: "编辑系列",
Times: "时",
Until: "直到",
Eventwas: "任命",
Hours: "小时",
Minutes: "分钟",
Overdue: "逾期预约",
Days: "天(多个)",
Event: "事件",
Select: "选择",
Previous: "上一页",
Next: "下一个",
Close: "关闭",
Delete: "删除",
Date: "日期",
Showin: "显示",
Gotodate: "转到日期",
Resources: "资源",
RecurrenceDeleteTitle: "删除重复约会",
Location: "位置",
Priority: "优先",
RecurrenceAlert: "警报",
NoTitle: "无题",
OverFlowAppCount: "更多的约会)",
WrongPattern: "复发模式是无效",
CreateError: "约会的持续时间必须比它发生的频率更短。缩短工期,或更改约会复发对话框定期模式。",
DragResizeError: "如果跳过了同一约会以后发生无法重新安排定期约会的发生。",
StartEndError: "结束时间应大于开始时间",
MouseOverDeleteTitle: "删除约会",
DeleteConfirmation: "你确定要删除这个预约吗?",
Time: "时间",
EmptyResultText: "没有建议",
};
ej.Spreadsheet.Locale["zh-CN"] = {
Cut: "Cắt tỉa",
Copy: "bản sao",
FormatPainter: "Format Painter",
Paste: "dán",
PasteValues: "Chỉ dán giá trị",
PasteSpecial: "dán",
Filter: "Lọc",
FilterContent: "Bật lọc cho các ô được chọn.",
FilterSelected: "Lọc theo giá trị được chọn Cell",
Sort: "loại",
Clear: "Trong sáng",
ClearContent: "Xóa tất cả mọi thứ trong tế bào, hoặc loại bỏ chỉ định dạng, nội dung, ý kiến hoặc các siêu liên kết.",
ClearFilter: "Clear Filter",
ClearFilterContent: "Bỏ lọc và sắp xếp nhà nước trong phạm vi hiện tại của dữ liệu.",
SortAtoZ: "Sắp xếp từ A đến Z",
SortAtoZContent: "Thấp nhất đến cao nhất.",
SortZtoA: "Sắp xếp từ Z đến A",
SortZtoAContent: "Cao nhất đến thấp nhất.",
SortSmallesttoLargest: "Sắp xếp nhỏ nhất đến lớn nhất",
SortLargesttoSmallest: "Sắp xếp lớn nhất đến nhỏ nhất",
SortOldesttoNewest: "Sắp xếp Cũ nhất đến mới nhất",
SortNewesttoOldest: "Sắp xếp Mới nhất Cũ nhất",
Insert: "Chèn",
InsertTitle: "Chèn ô",
InsertContent: "Thêm các tế bào mới, hàng, hoặc cột để bảng tính của bạn <br /> <br /> FYI:. Để chèn nhiều hàng hoặc cột tại một thời điểm, chọn nhiều hàng hay cột trong bảng, và nhấn Insert.",
InsertSBContent: "Thêm ô, hàng, cột, hoặc tờ để bảng tính của bạn.",
Delete: "Xóa bỏ",
DeleteTitle: "xóa ô",
DeleteContent: "Xóa ô, hàng, cột, hoặc tờ từ bảng tính của bạn <br /> <br /> FYI:. Để xóa nhiều dòng hoặc cột tại một thời điểm, chọn nhiều hàng hay cột trong bảng, và nhấn Delete.",
FindSelectTitle: "Tìm & Chọn",
FindSelectContent: "Nhấn vào đây để xem các tùy chọn cho việc tìm kiếm văn bản trong tài liệu của bạn.",
CalculationOptions: "Tùy chọn tính toán",
CalcOptTitle: "Tùy chọn tính toán",
CalcOptContent: "Chọn để tính toán công thức tự động hoặc bằng tay. <br/> <br/> Nếu bạn thực hiện một sự thay đổi có ảnh hưởng đến một giá trị, bảng tính sẽ tự động tính toán lại nó.",
CalculateSheet: "tính Bảng",
CalculateNow: "tính Bây giờ",
CalculateNowContent: "Tính toàn bộ bảng tính bây giờ. <br/> <br/> Bạn chỉ cần sử dụng này nếu tính toán tự động bị tắt.",
CalculateSheetContent: "Tính toán bảng tính hiện tại. <br/> <br/> Bạn chỉ cần sử dụng này nếu tính toán tự động bị tắt.",
Title: "bảng tính",
Ok: "được",
Cancel: "hủy bỏ",
Alert: "Chúng tôi không thể làm điều này cho các phạm vi lựa chọn của các tế bào. Chọn một ô duy nhất trong một loạt các dữ liệu và sau đó thử lại.",
HeaderAlert: "Các lệnh có thể không được hoàn thành như bạn đang cố gắng để lọc với tiêu đề bộ lọc. Chọn một ô trong phạm vi lọc và thử lệnh một lần nữa.",
FlashFillAlert: "Tất cả các dữ liệu tiếp theo lựa chọn của bạn đã được kiểm tra và không có mô hình cho điền vào các giá trị.",
Formatcells: "Format Cells",
FontFamily: "Font",
FFContent: "Chọn một phông chữ mới cho văn bản của bạn.",
FontSize: "Cỡ chữ",
FSContent: "Thay đổi kích thước của văn bản.",
IncreaseFontSize: "Tăng cỡ chữ",
IFSContent: "Làm cho văn bản của bạn lớn hơn một chút.",
DecreaseFontSize: "Giảm cỡ chữ",
DFSContent: "Làm cho văn bản của bạn một chút nhỏ hơn.",
Bold: "Dũng cảm",
Italic: "nghiêng",
Underline: "nhấn mạnh",
Linethrough: "dòng Qua",
FillColor: "Tô màu",
FontColor: "Màu chữ",
TopAlign: "Top Align",
TopAlignContent: "Căn lề văn bản để trên đầu.",
MiddleAlign: "Middle Align",
MiddleAlignContent: "Căn lề văn bản để nó là trung tâm giữa đỉnh và đáy của tế bào.",
BottomAlign: "đáy Align",
BottomAlignContent: "Căn lề văn bản để phía dưới.",
WrapText: "Bao text",
WrapTextContent: "Quấn văn bản dài thêm ra nhiều dòng để bạn có thể nhìn thấy tất cả của nó.",
AlignLeft: "Align Left",
AlignLeftContent: "Căn nội dung của bạn sang bên trái.",
AlignCenter: "Trung tâm",
AlignCenterContent: "Đặt nội dung của bạn.",
AlignRight: "Align Right",
AlignRightContent: "Căn nội dung của bạn ở bên phải.",
Undo: "Hủy bỏ",
Redo: "Làm lại",
NumberFormat: "Định dạng số",
NumberFormatContent: "Chọn định dạng cho các tế bào của bạn, chẳng hạn như tỷ lệ phần trăm, tiền tệ, ngày tháng hoặc thời gian.",
AccountingStyle: "kế toán Phong cách",
AccountingStyleContent: "Format là định dạng số kế toán đôla.",
PercentageStyle: "Phần trăm Phong cách",
PercentageStyleContent: "Định dạng như một phần trăm.",
CommaStyle: "Comma Phong cách",
CommaStyleContent: "Format mà không cần phân cách hàng ngàn.",
IncreaseDecimal: "tăng số thập phân",
IncreaseDecimalContent: "Hiển thị thêm chữ số thập phân cho một giá trị chính xác hơn.",
DecreaseDecimal: "giảm số thập phân",
DecreaseDecimalContent: "Hiện chữ số thập phân ít hơn.",
AutoSum: "AutoSum",
AutoSumTitle: "tổng số",
AutoSumContent: "Tự động thêm một tính toán nhanh chóng để bảng tính của bạn, chẳng hạn như tiền hoặc trung bình.",
Fill: "Lấp đầy",
ExportXL: "Excel",
ExportCsv: "CSV",
SaveXml: "Lưu XML",
BackgroundColor: "Tô màu",
BGContent: "Màu nền của các tế bào để làm cho chúng nổi bật.",
ColorContent: "Thay đổi màu sắc của văn bản.",
Border: "Biên giới",
BorderContent: "Áp dụng đường viền để các tế bào hiện đang được chọn.",
BottomBorder: "dưới biên giới",
TopBorder: "Lên trên biên giới",
LeftBorder: "Còn lại biên giới",
RightBorder: "Border đúng",
OutsideBorder: "Biên giới bên ngoài",
NoBorder: "không có biên giới",
AllBorder: "Tất cả Borders",
ThickBoxBorder: "Dày Hộp Border",
ThickBottomBorder: "Biên giới dưới dày",
TopandThickBottomBorder: "Top và Dày biên dưới",
DrawBorderGrid: "Vẽ đường viền lưới",
DrawBorder: "vẽ biên giới",
TopandBottomBorder: "Đầu và Cuối Biên",
BorderColor: "dòng màu",
BorderStyle: "Line Style",
Number: "Số lượng ảnh được sử dụng để hiển thị tổng số. Tiền tệ và cung cấp kế toán chuyên định dạng cho giá trị tiền tệ.",
General: "tế bào dạng chung không có định dạng số cụ thể.",
Currency: "định dạng tiền tệ được sử dụng cho các giá trị tiền tệ nói chung. Sử dụng định dạng toán để căn chỉnh các điểm thập phân trong một cột.",
Accounting: "định dạng toán đường lên các ký hiệu tiền tệ và điểm thập phân trong một cột.",
Text: "tế bào định dạng văn bản được coi là văn bản ngay cả khi một số là trong tế bào. Các tế bào được hiển thị chính xác như đã nhập.",
Percentage: "Định dạng phần trăm nhân giá trị tế bào bằng 100 và hiển thị kết quả bằng một biểu tượng phần trăm.",
CustomMessage: "Nhập mã định dạng số, sử dụng một trong những mã có sẵn như là một điểm khởi đầu.",
Fraction: " ",
Scientific: " ",
Type: "Kiểu:",
CustomFormatAlert: "Nhập một định dạng hợp lệ",
Date: "định dạng ngày tháng hiển thị ngày tháng và thời gian số serial như giá trị ngày.",
Time: "Thời gian định dạng hiển thị ngày và số thời gian là giá trị ngày.",
File: "TẬP TIN",
New: "Mới",
Open: "Mở",
SaveAs: "Lưu thành",
Print: "In",
PrintContent: "In bảng tính hiện tại.",
PrintSheet: "In Tờ",
PrintSelected: "In chọn",
PrintSelectedContent: "Chọn một khu vực trên các sheet mà bạn muốn in.",
HighlightVal: "Định dạng dữ liệu không hợp lệ",
ClearVal: "rõ ràng Validation",
Validation: "Validation",
DataValidation: "Xác nhận dữ liệu",
DVContent: "Chọn từ một danh sách các quy tắc để hạn chế các loại dữ liệu có thể được nhập vào trong tế bào.",
A4: "A4",
A3: "A3",
Letter: "Lá thư",
PageSize: "Kích thước trang",
PageSizeContent: "Chọn kích thước trang cho tài liệu của bạn.",
FormatCells: "Format Cells",
ConditionalFormat: "Conditional Formatting",
CFContent: "Dễ dàng nhận ra xu hướng và các mẫu trong dữ liệu của bạn bằng cách sử dụng màu sắc để làm nổi bật giá trị trực quan quan trọng.",
And: "và",
With: "với",
GTTitle: "Lớn hơn",
GTContent: "tế bào định dạng đó là LỚN HƠN:",
LTTitle: "Ít hơn",
LTContent: "tế bào định dạng đó là DƯỚI:",
BWTitle: "Giữa",
BWContent: "tế bào định dạng đó là GIỮA:",
EQTitle: "Tương đương với",
EQContent: "tế bào định dạng đó là EQUAL TO:",
DateTitle: "Một ngày Xảy ra",
DateContent: "tế bào dạng có chứa một NGÀY:",
ContainsTitle: "Văn bản đó Có",
ContainsContent: "tế bào Format chứa các văn bản:",
GreaterThan: "Lớn hơn",
LessThan: "Ít hơn",
Between: "Giữa",
EqualTo: "Tương đương với",
TextthatContains: "Văn bản Có",
DateOccurring: "Một ngày Xảy ra",
ClearRules: "rõ ràng quy",
ClearRulesfromSelected: "Rõ ràng quy từ các tế bào được chọn",
ClearRulesfromEntireSheets: "Rõ ràng quy từ toàn bộ tấm",
CellStyles: "cell Styles",
CellStylesContent: "Một phong cách đầy màu sắc là một cách tuyệt vời để làm cho dữ liệu quan trọng nổi bật trên tờ giấy.",
CellStyleHeaderText: "Tốt, Xấu và Neutral / Nhan đề và tiêu đề / Thợ Cell Styles",
Custom: "Nhập mã số định dạng, sử dụng một trong các mã hiện có như là điểm khởi đầu.",
CellStyleGBN: "Bình thường / Bad / Tốt / Neutral",
CellStyleTH: "Tiêu đề 4 / Tiêu đề",
CellsStyleTCS: "20% - Accent1 / 20% - Accent2 / 20% - Accent3 / 20% - Accent4 / 60% - Accent1 / 60% - Accent2 / 60% - Accent3 / 60% - Accent4 / Accent1 / Accent2 / Accent3 / Accent4",
Style: "Phong cách",
FormatAsTable: "Format Như Bảng",
FormatasTable: "Format as Table",
FATContent: "Nhanh chóng chuyển đổi một loạt các tế bào vào một bảng với phong cách riêng của mình.",
FATHeaderText: "Light / Medium / Dark",
FATNameDlgText: "Bảng Tên: / Bảng của tôi có tiêu đề",
InvalidReference: "Phạm vi bạn đã xác định là không hợp lệ",
ResizeAlert: "Phạm vi chỉ định là không hợp lệ. Các đầu bảng vẫn phải ở trong cùng một hàng, và bảng kết quả phải chồng lên bàn ban đầu. Chỉ định phạm vi hợp lệ.",
RangeNotCreated: "Tăng hàng xa hơn số lượng tờ hàng tối đa được giới hạn trong Format as Table.",
ResizeRestrictAlert: "Tăng hoặc giảm số lượng cột và giảm số lượng hàng được giới hạn trong Format as Table.",
FATResizeTableText: "Nhập phạm vi dữ liệu mới cho bảng của bạn:",
FATReizeTableNote: "Lưu ý: Các tiêu đề vẫn phải ở trong cùng một hàng và phạm vi bảng kết quả phải chồng lên nhiều bảng gốc.",
FormatAsTableAlert: "không thể tạo ra một bảng với một hàng duy nhất. Một bảng phải có ít nhất hai hàng, một cho phần đầu bảng, và một cho dữ liệu",
FormatAsTableTitle: "Light 1 / Light 2 / Light 3 / Light 4 / Ánh sáng 5 / Light 6 / Light 7 / Light 8 / Ánh 9 / Light 10 / Light 11 / Light 12 / Medium 1 / Vừa 2 / Medium 3 / Medium 4 / Vừa 5 / Medium 6 / vừa 7 / Medium 8 / Dark 1 / Dark 2 / Dark 3 / Dark 4",
NewTableStyle: "New Table Style",
ResizeTable: "Thay đổi kích thước Bảng",
ResizeTableContent: "Thay đổi kích thước bảng này bằng cách thêm hoặc loại bỏ các hàng và cột.",
ConvertToRange: "Chuyển đổi thành vùng",
ConvertToRangeContent: "Chuyển đổi bảng này vào một phạm vi bình thường của các tế bào.",
ConverToRangeAlert: "Bạn có muốn chuyển đổi bảng vào một phạm vi bình thường?",
TableID: "Bảng ID:",
Table: "Bàn",
TableContent: "Tạo một bảng để tổ chức và phân tích các dữ liệu liên quan.",
TableStyleOptions: "Đầu cột / Cột cuối / Total Row / Lọc Nút",
Format: "định dạng",
NameManager: "Name Manager",
NameManagerContent: "Tạo, chỉnh sửa, xóa và tìm thấy tất cả các tên được sử dụng trong bảng tính. <br /> <br /> Tên có thể được sử dụng trong công thức thay thế cho các tham chiếu ô.",
DefinedNames: "Tên Defined",
DefineName: "xác định danh",
DefineNameContent: "Xác định và áp dụng các tên.",
UseInFormula: "Sử dụng trong công thức",
UseInFormulaContent: "Chọn một tên sử dụng trong bảng tính này và chèn nó vào công thức hiện tại.",
RefersTo: "Đề cập đến",
Name: "Tên",
Scope: "Phạm vi",
NMNameAlert: "Tên mà bạn nhập vào không phải là valid./Reason cho điều này có thể bao gồm: / tên không bắt đầu bằng một ký tự hoặc một gạch dưới / Tên có chứa một không gian hoặc các ký tự không hợp lệ khác / Những cuộc xung đột tên với một bảng tính được xây dựng trong tên hoặc tên của một đối tượng trong bảng tính, // không được sử dụng hoàn toàn",
NMUniqueNameAlert: "Tên nhập đã tồn tại. Nhập tên duy nhất.",
NMRangeAlert: "Nhập một phạm vi hợp lệ",
FORMULAS: "CÔNG THỨC",
DataValue: "Giá trị:",
Value:"Giá trị",
Formula: "công thức",
MissingParenthesisAlert: "Công thức của bạn thiếu parenthesis--) hoặc (. Kiểm tra công thức, và sau đó thêm các dấu ngoặc đơn ở nơi thích hợp.",
UnsupportedFile: "tập tin không được hỗ trợ",
IncorrectPassword: "Không thể mở tập tin hoặc bảng tính với mật khẩu được",
InvalidUrl: "Hãy xác định URL thích hợp",
Up: "Lên",
Down: "Xuống",
Sheet: "tấm",
Workbook: "Sách bài tập",
Rows: "by Rows",
Columns: "by Columns",
FindReplace: "Tìm Thay thế",
FindnReplace: "Tìm và thay thế",
Find: "Tìm thấy",
Replace: "Thay thế",
FindLabel: "Tìm gì:",
ReplaceLabel: "Thay bằng:",
ReplaceAll: "Thay thế tất cả",
Close: "Gần",
FindNext: "Tìm tiếp theo",
FindPrev: "Tìm Prev",
Automatic: "Tự động",
Manual: "Hướng dẫn sử dụng",
Settings: "Cài đặt",
MatchCase: "trường hợp trận đấu",
MatchAll: "Phù hợp với toàn bộ nội dung di động",
Within: "trong vòng:",
Search: "Tìm kiếm:",
Lookin: "Nhìn vào:",
ShiftRight: "tế bào Shift bên phải",
ShiftBottom: "tế bào Shift",
EntireRow: "toàn bộ hàng",
EntireColumn: "toàn bộ cột",
ShiftUp: "Di chuyển ô lên",
ShiftLeft: "chuyển ô sang trái",
Direction: "Phương hướng:",
GoTo: "Đi đến",
GoToName: "Đi đến:",
Reference: "Tài liệu tham khảo:",
Special: "Đặc biệt",
Select: "Lựa chọn",
Comments: "Bình luận",
Formulas: "công thức",
Constants: "hằng",
RowDiff: "khác biệt Row",
ColDiff: "chênh lệch cột",
LastCell: "ô cuối cùng",
CFormat: "định dạng có điều kiện",
Blanks: "Blanks",
GotoError: "lỗi",
GotoLogicals: "Logicals",
GotoNumbers: "số",
GotoText: "Bản văn",
FindSelect: "Tìm & Chọn",
Comment: "Bình luận",
NewComment: "Mới",
InsertComment: "Insert Comment",
EditComment: "Chỉnh sửa",
DeleteComment: "xóa Nhận xét",
DeleteCommentContent: "Xóa nhận xét chọn.",
HideComment: "Ẩn bình luận",
Next: "Kế tiếp",
NextContent: "Chuyển đến bình luận tiếp theo.",
Previous: "Trước",
PreviousContent: "Chuyển đến những nhận xét trước.",
ShowHide: "Show / Hide Comment",
ShowHideContent: "Hiển thị hoặc ẩn các bình luận trên các tế bào hoạt động.",
ShowAll: "Hiển thị tất cả Comment",
ShowAllContent: "Hiển thị tất cả các ý kiến trong bảng.",
UserName: "Tên đăng nhập",
Hide: "Ẩn giấu",
Unhide: "Bỏ ẩn",
Add: "Thêm vào",
DropAlert: "Bạn có muốn thay thế các dữ liệu hiện có?",
PutCellColor: "Đặt chọn màu di To The Top",
PutFontColor: "Đặt chọn Màu chữ To The Top",
WebPage: "Trang web",
WorkSheet: "bảng tham khảo",
SheetReference: "bảng tham khảo",
InsertHyperLink: "Insert Hyperlink",
HyperLink: "hyperlink",
EditLink: "chỉnh sửa liên kết",
OpenLink: "Mở liên kết",
HyperlinkText: "Bản văn:",
RemoveLink: "Remove Link",
WebAddress: "Địa chỉ web:",
CellAddress: "Tham khảo di động:",
SheetIndex: "Chọn một vị trí trong tài liệu này",
ClearAll: "Làm sạch tất cả",
ClearFormats: "Xóa Định dạng",
ClearContents: "Nội dung rõ ràng",
ClearComments: "rõ ràng Comments",
ClearHyperLinks: "rõ ràng Hyperlinks",
SortFilter: "Sắp xếp & Lọc",
SortFilterContent: "Tổ chức dữ liệu của bạn để nó dễ dàng hơn để phân tích.",
NumberStart: "tối thiểu:",
NumberEnd: "tối đa:",
DecimalStart: "tối thiểu:",
DecimalEnd: "tối đa:",
DateStart: "Ngày bắt đầu:",
DateEnd: "Ngày cuối:",
ListStart: "nguồn:",
FreeText: "cảnh báo Hiển thị lỗi sau khi dữ liệu không hợp lệ được nhập",
ListEnd: "Tham khảo di động:",
TimeStart: "Thời gian bắt đầu:",
TimeEnd: "Thời gian kết thúc:",
TextLengthStart: "tối thiểu:",
TextLengthEnd: "tối đa:",
CommentFindEndAlert: "Bảng tính đến cuối của bảng tính. Bạn có muốn tiếp tục xem xét từ đầu của bảng tính?",
InsertSheet: "Chèn",
DeleteSheet: "Xóa bỏ",
RenameSheet: "Đổi tên",
MoveorCopy: "Di chuyển hoặc sao chép",
HideSheet: "Ẩn giấu",
UnhideSheet: "Bỏ ẩn",
SheetRenameAlert: "Tên đó đã được lấy. Hãy thử một trong những khác nhau.",
SheetRenameEmptyAlert: "Bạn gõ tên không hợp lệ cho một tờ. Hãy chắc chắn rằng: <ul> <li> Tên mà bạn gõ không vượt quá 31 ký tự </ li> <li> Tên không chứa bất kỳ các ký tự sau:. \ /? * [Hoặc] </ li> <li> Bạn đã không để trống tên. </ Li> </ ul>",
SheetDeleteAlert: "Bạn không thể hoàn tác xóa tờ, và bạn có thể loại bỏ một số dữ liệu. Nếu bạn không cần nó, bấm OK để xóa.",
SheetDeleteErrorAlert: "Một bảng tính phải chứa ít nhất một bảng tính có thể nhìn thấy. Để ẩn, xóa, hoặc di chuyển các sheet chọn, đầu tiên bạn phải chèn một trang mới hoặc bỏ ẩn một tờ đó đã được ẩn.",
CtrlKeyErrorAlert: "lệnh đó không thể được sử dụng trên nhiều lựa chọn.",
MoveToEnd: "Move To End",
Beforesheet: "Trước khi tờ:",
CreateaCopy: "Tạo một bản sao",
AutoFillOptions: "Sao chép tế bào / Fill Series / Fill Formatting Chỉ / Điền không có định dạng / Flash Fill",
NumberValidationMsg: "Chỉ nhập chữ số",
DateValidationMsg: "Chỉ nhập ngày",
Required: "Cần thiết",
TimeValidationMsg: "Thời gian bạn nhập cho các Thời gian là không hợp lệ.",
CellAddrsValidationMsg: "Tham chiếu không hợp lệ.",
PivotTable: "Pivot Table",
PivotTableContent: "Dễ dàng sắp xếp và tổng hợp dữ liệu phức tạp trong một Pivot Table.",
NumberTab: "Con số",
AlignmentTab: "alignment",
FontTab: "Font",
FillTab: "Lấp đầy",
TextAlignment: "liên kết văn bản",
Horizontal: "Chiều ngang:",
Vertical: "Theo chiều dọc:",
Indent: "lõm vào",
TextControl: "Kiểm soát văn bản",
FontGroup: "Font:",
FontStyle: "Kiểu font:",
Size: "Kích thước:",
PSize: "kích thước trang",
Effects: "tác dụng:",
StrikeThrough: "gạch ngang",
Overline: "overline",
NormalFont: "phông chữ bình thường",
Preview: "Xem trước",
PreviewText: "aabbcc ZyZz",
Line: "Hàng",
Presets: "Presets",
None: "không ai",
Outline: "Đề cương",
AllSide: "Tất cả các bên",
InsCells: "Chèn ô",
InsRows: "Chèn dòng tấm",
InsCols: "Chèn Bảng Cột",
InsSheet: "Chèn Trang",
DelCells: "xóa ô",
DelRows: "Xóa dòng tấm",
DelCols: "Xóa Bảng Cột",
DelSheet: "xóa Bảng",
HyperLinkAlert: "Địa chỉ của trang web này không phải là valid.Check địa chỉ và thử lại.",
ReplaceData: "Tất cả đã được làm xong. Chúng tôi đã làm / thay thế.",
NotFound: "Chúng tôi không thể tìm thấy những gì bạn đang tìm kiếm. tab Chọn Cài đặt thêm các cách thức để tìm kiếm",
Data: "dữ liệu:",
Allow: "cho phép:",
IgnoreBlank: "Bỏ qua trống",
NotFind: "Không thể tìm thấy phù hợp để thay thế",
FreezeRow: "Freeze Top Row",
FreezeColumn: "Freeze cột đầu tiên",
UnFreezePanes: "unfreeze Panes",
DestroyAlert: "Bạn có chắc chắn muốn phá hủy các bảng tính hiện tại mà không lưu và tạo ra một bảng tính mới?",
ImageValAlert: "Chỉ tải lên các tập tin hình ảnh",
Pictures: "Những bức ảnh",
PicturesTitle: "From file",
PicturesContent: "Chèn hình ảnh từ máy tính hoặc từ các máy tính khác mà bạn đang kết nối đến.",
ImportAlert: "Bạn có chắc chắn muốn phá hủy các bảng tính hiện tại mà không lưu và mở một bảng tính mới?",
UnmergeCells: "Các tế bào Hủy hợp nhất",
MergeCells: "Merge Cells",
MergeAcross: "Merge Across",
MergeAndCenter: "Merge & Center",
MergeAndCenterContent: "Kết hợp và tập trung các nội dung của các ô được chọn trong một tế bào lớn hơn mới.",
MergeCellsAlert: "Việc sáp nhập các tế bào giữ giá trị di chỉ trên trái và loại bỏ các giá trị khác.",
MergeInsertAlert: "Thao tác này sẽ gây ra một số tế bào sáp nhập để hủy hợp nhất. Bạn có muốn tiếp tục không?",
Axes: "Axes",
PHAxis: "tiểu học ngang",
PVAxis: "dọc chính",
AxisTitle: "Axis Tiêu đề",
CTNone: "không ai",
CTCenter: "Trung tâm",
CTFar: "Xa",
CTNear: "Ở gần",
DataLabels: "dữ liệu Nhãn",
DLNone: "không ai",
DLCenter: "Trung tâm",
DLIEnd: "bên trong End",
DLIBase: "bên trong cơ sở",
DLOEnd: "Cuối ngoài",
ErrorBar: "Bars lỗi",
Gridline: "Các dòng lưới",
PMajorH: "Tiểu học chính ngang",
PMajorV: "Tiểu học chính dọc",
PMinorH: "Tiểu Tiểu ngang",
PMinorV: "Tiểu học chính dọc",
Legend: "Legends",
LNone: "không ai",
LLeft: "Trái",
LRight: "Đúng",
LBottom: "đáy",
LTop: "Hàng đầu",
ChartTitleDlgText: "nhập Tiêu đề",
ChartTitle: "Tiêu đề",
InvalidTitle: "Bạn gõ tên không hợp lệ cho tiêu đề.",
CorrectFormat: "Chọn định dạng tập tin chính xác",
ResetPicture: "Thiết lập lại hình ảnh",
ResetPictureContent: "Vứt bỏ tất cả các định dạng thay đổi làm cho hình ảnh này.",
PictureBorder: "hình ảnh biên phòng",
PictureBorderContent: "Chọn màu sắc, chiều rộng, và phong cách dòng cho các phác thảo của hình dạng của bạn.",
ResetSize: "Đặt lại ảnh & Kích",
Height: "Chiều cao",
Width: "Chiều rộng",
ThemeColor: "Màu sắc chủ đề",
NoOutline: "không Outline",
Weight: "Cân nặng",
Dashes: "Dấu gạch ngang",
ColumnChart: "2-D Column / Cột 3D",
ColumnChartTitle: "Chèn cột Chart",
ColumnChartContent: "Sử dụng loại biểu đồ này để các giá trị so sánh trực quan qua một vài loại.",
BarChart: "2-D Bar / 3D Bar",
BarChartTitle: "Chèn Bar Chart",
BarChartContent: "Sử dụng loại biểu đồ này để các giá trị so sánh trực quan qua một vài loại khi biểu đồ cho thấy thời gian hoặc các văn bản loại là dài.",
StockChart: "radar",
StockChartTitle: "Chèn Radar Chart",
StockChartContent: "Sử dụng loại biểu đồ này để hiển thị các giá trị liên quan đến một điểm trung tâm.",
LineChart: "2-D Line",
LineChartTitle: "Chèn Biểu đồ Đường",
LineChartContent: "Sử dụng loại biểu đồ này thể hiện xu hướng theo thời gian (năm, tháng và ngày) hoặc loại.",
AreaChart: "2-D Khu vực / Area 3D",
AreaChartTitle: "Insert Chart Area",
AreaChartContent: "Sử dụng loại biểu đồ này thể hiện xu hướng theo thời gian (năm, tháng và ngày) hoặc loại. Sử dụng nó để làm nổi bật tầm quan trọng của sự thay đổi theo thời gian.",
ComboChart: "Combo",
PieChart: "bánh",
PieChartTitle: "Chèn Pie / Doughnut Chart",
PieChartContent: "Sử dụng loại biểu đồ này cho thấy tỷ lệ của một toàn thể. Sử dụng nó khi tổng các số của bạn là 100%.",
ScatterChart: "Tiêu tan",
ScatterChartTitle: "Chèn Scatter (X, Y) Chart",
ScatterChartContent: "Sử dụng loại biểu đồ này cho thấy mối quan hệ giữa các bộ giá trị.",
ClusteredColumn: "Cột; Clustered & nbsp",
StackedColumn: "Cột; chồng & nbsp",
Stacked100Column: "100% & nbsp; Stacked & nbsp; Cột",
Cluster3DColumn: "3D & nbsp; Clustered & nbsp; Cột",
Stacked3DColumn: "3D & nbsp; Stacked & nbsp; Cột",
Stacked100Column3D: "3D & nbsp; 100% & nbsp; Stacked & nbsp; Cột",
ClusteredBar: "Clustered & nbsp; Bar",
StackedBar: "Xếp chồng & nbsp; Bar",
Stacked100Bar: "100% & nbsp; Stacked & nbsp; Bar",
Cluster3DBar: "3D & nbsp; Clustered & nbsp; Bar",
Stacked3DBar: "3D & nbsp; Stacked & nbsp; Bar",
Stacked100Bar3D: "3D & nbsp; 100% & nbsp; Stacked & nbsp; Bar",
Radar: "radar",
RadarMarkers: "Radar & nbsp; chiều rộng & nbsp; Markers",
LineMarkers: "Line & nbsp; chiều rộng & nbsp; Markers",
Area: "Khu vực",
StackedArea: "Xếp chồng & nbsp; Diện tích",
Stacked100Area: "100% & nbsp; Stacked & nbsp; Diện tích",
Pie: "bánh",
Pie3D: "3-D & nbsp; Pie",
Doughnut: "Bánh rán",
Scatter: "Tiêu tan",
ChartRange: "Phạm vi biểu đồ",
XAxisRange: "Nhập phạm vi trục X:",
YAxisRange: "Nhập phạm vi trục Y:",
LegendRange: "Nhập phạm vi truyền thuyết:",
YAxisMissing: "Nhập phạm vi trục Y để tạo biểu đồ",
InvalidYAxis: "phạm vi trục Y phải nằm trong phạm vi lựa chọn",
InvalidXAxis: "phạm vi trục X phải nằm trong phạm vi lựa chọn",
InvalidLegend: "phạm vi truyền thuyết phải nằm trong phạm vi lựa chọn",
InvalidXAxisColumns: "loạt X-trục nên trong vòng một cột duy nhất",
FreezePanes: "Panes đóng băng",
FreezePanesContent: "Đóng băng một phần chính của bảng để giữ cho nó có thể nhìn thấy trong khi bạn di chuyển qua phần còn lại của tấm.",
PasteTitle: "Paste (Ctrl + V)",
PasteContent: "Thêm nội dung vào Clipboard để tài liệu của bạn.",
PasteSplitContent: "Chọn một tùy chọn dán, chẳng hạn như giữ định dạng hoặc dán chỉ nội dung.",
CutTitle: "Cut (Ctrl + X)",
CutContent: "Hủy bỏ các lựa chọn và đặt nó vào Clipboard để bạn có thể dán nó ở một nơi khác.",
CopyTitle: "Copy (Ctrl + C)",
CopyContent: "Đặt một bản sao của các lựa chọn vào Clipboard để bạn có thể dán nó ở một nơi khác.",
FPTitle: "Format Painter",
FPContent: "Giống như cái nhìn của một lựa chọn cụ thể không? Bạn có thể áp dụng được cái nhìn nội dung khác trong tài liệu.",
BoldTitle: "Đậm (Ctrl + B)",
BoldContent: "Làm cho văn bản của bạn đậm.",
ItalicTitle: "Nghiêng (Ctrl + I)",
ItalicContent: "In nghiêng văn bản của bạn.",
ULineTitle: "Gạch chân (Ctrl + U)",
ULineContent: "Gạch dưới văn bản của bạn.",
LineTrTitle: "Gạch ngang (Ctrl + 5)",
LineTrContent: "Băng qua một cái gì đó ra bằng cách vẽ một cuộc tấn công thông qua nó.",
UndoTitle: "Undo (Ctrl + Z)",
UndoContent: "Hoàn tác hành động cuối cùng của bạn.",
RedoTitle: "Làm lại (Ctrl + Y)",
RedoContent: "Làm lại hành động cuối cùng của bạn.",
TableTitle: "Bảng (Ctrl + T)",
HyperLinkTitle: "Thêm một Hyperlink (Ctrl + K)",
HyperLinkContent: "Tạo một liên kết trong tài liệu của bạn để truy cập nhanh các trang web và các tập tin. <br /> <br /> Các siêu liên kết cũng có thể đưa bạn đến những nơi trong tài liệu của bạn.",
NewCommentTitle: "Chèn một Nhận xét",
NewCommentContent: "Thêm một lưu ý về phần này của tài liệu.",
RefreshTitle: "Làm mới",
RefreshContent: "Lấy dữ liệu mới nhất từ các nguồn kết nối với các tế bào hoạt động",
FieldListTitle: "Danh sách các trường",
FieldListContent: "Hiện hoặc ẩn Field List. <br /> <br /> Các danh sách trường cho phép bạn thêm và loại bỏ các lĩnh vực từ báo cáo PivotTable của bạn",
AddChartElement: "Thêm Chart tử",
AddChartElementContent: "Thêm yếu tố để các biểu đồ được tạo ra.",
SwitchRowColumn: "Chuyển Row / Column",
SwitchRowColumnContent: "Trao đổi các dữ liệu qua các trục.",
MergeAlert: "Chúng tôi không thể làm điều đó với một tế bào bị sáp nhập.",
UnhideDlgText: "Tấm Unhide:",
ChartThemes: "Chart Themes",
ChartThemesContent: "Chọn một chủ đề mới cho biểu đồ của bạn.",
ChangePicture: "Đổi ảnh",
ChangePictureContent: "Thay đổi một hình ảnh khác nhau, bảo quản các định dạng và kích thước của hình ảnh hiện tại.",
ChangeChartType: "Thay đổi Chart Type",
SelectData: "Chọn dữ liệu",
SelectDataContent: "Thay đổi phạm vi dữ liệu trong biểu đồ.",
Sum: "tổng số",
Average: "Trung bình cộng",
CountNumber: "số đếm",
Max: "Max",
Min: "min",
ChartType: "Thay đổi Chart Type",
ChartTypeContent: "Thay đổi để một loại biểu đồ khác nhau.",
AllCharts: "Tất cả các bảng xếp hạng",
defaultfont: "Mặc định",
LGeneral: "Chung",
LCurrency: "Tiền tệ",
LAccounting: "Kế toán",
LDate: "Ngày",
LTime: "Thời gian",
LPercentage: "tỷ lệ phần trăm",
LFraction: "phần",
LScientific: "Khoa học",
LText: "Bản văn",
LCustom: "Tập quán",
FormatSample: "Mẫu vật",
Category: "Thể loại:",
Top: "Hàng đầu",
Center: "Trung tâm",
Bottom: "đáy",
Left: "Left (Indent)",
Right: "Đúng",
Justify: "biện hộ",
GeneralTxt: "tế bào dạng chung không có định dạng số cụ thể.",
NegativeNumbersTxt: "số âm",
ThousandSeparatorTxt: "Sử dụng 1000 Separator",
DecimalPlacesTxt: "Địa điểm thập phân:",
TextTxt: "tế bào định dạng văn bản được coi là văn bản ngay cả khi một số là trong tế bào. Các tế bào được hiển thị chính xác như đã nhập.",
BoldItalic: "Bold Italic",
Regular: "Đều đặn",
HyperLinkHide: "<< Lựa chọn trong tài liệu >>",
InvalidSheetIndex: "Chỉ định SheetIndex thích",
HugeDataAlert: "Tệp quá lớn để mở.",
ImportExportUrl: "Cho nhập URL / xuất khẩu và thử lại.",
TitleColumnChart: "Clustered Column / Stacked Column / 100% Stacked Column / 3D Clustered Column / 3D Stacked Column / Cột 3D 100% xếp chồng",
TitleBarChart: "Clustered Bar / Stacked Bar / 100% Stacked Bar / 3D Clustered Bar / 3D Stacked Bar / 3D 100% Stacked Bar",
TitleRadarChart: "Radar / Radar với Markers",
TitleLineChart: "Line / Line với Markers",
TitleAreaChart: "Khu vực / vùng xếp chồng / 100% vùng xếp chồng",
TitlePieChart: "Pie / 3D Pie / Doughnut",
TitleScatterChart: "Tiêu tan",
BetweenAlert: "The tối đa phải lớn hơn hoặc bằng với tối thiểu.",
BorderStyles: "Rắn / Dashed / Chấm",
FPaneAlert: "Freeze Pane không áp dụng cho di động đầu tiên",
ReplaceNotFound: "Bảng tính không thể tìm thấy một trận đấu.",
BlankWorkbook: "workbook trống",
SaveAsExcel: "Save As Excel",
SaveAsCsv: "Save As CSV",
Design: "THIẾT KẾ",
NewName: "Tên mới",
FormulaBar: "Thanh công thức",
NameBox: "tên Box",
NumberValMsg: "Giá trị thập phân không thể được sử dụng cho điều kiện số.",
NumberAlertMsg: "Chỉ nhập chữ số.",
ListAlert: "phạm vi di động là không chính xác, hãy nhập dãy ô đúng.",
ListValAlert: "Các nguồn danh sách phải là một danh sách phân cách, hoặc một tham chiếu đến hàng hoặc một cột.",
ListAlertMsg: "Các giá trị mà bạn nhập vào không hợp lệ",
AutoFillTitle: "Tự động điền Tùy chọn",
NewSheet: "Tờ New",
FullSheetCopyPasteAlert: "Chúng tôi không thể dán vì khu vực Sao chép và khu vực dán không cùng kích thước.",
Heading: "tiêu đề",
Gridlines: "Các dòng lưới",
Firstsheet: "Di chuyển đến sheet đầu tiên",
Lastsheet: "Di chuyển đến sheet cuối cùng",
Nextsheet: "Di chuyển sang tờ kế tiếp",
Prevsheet: "Di chuyển đến sheet trước",
ProtectWorkbook: "bảo vệ Workbook",
UnProtectWorkbook: "Unprotect Workbook",
ProtectWBContent: "Giữ người khác làm thay đổi cấu trúc để bảng tính của bạn",
Password: "Mật khẩu",
ConfirmPassword: "Re Nhập mật khẩu để tiến hành:",
PasswordAlert1: "mật khẩu xác nhận là không giống nhau.",
PasswordAlert2: "Vui lòng nhập mật khẩu.",
PasswordAlert3: "Mật khẩu bạn cung cấp không chính xác. Xác minh rằng các CAPS LOCK là tắt và chắc chắn để sử dụng đúng chữ viết.",
Protect: "được bảo vệ.",
Lock: "Khóa di động",
Unlock: "mở khóa di động",
Protectsheet: "Protect Sheet",
ProtectSheetToolTip: "Ngăn chặn những thay đổi không mong muốn từ người khác bằng cách hạn chế khả năng của mình để chỉnh sửa",
Unprotect: "tấm Unprotect",
LockAlert: "Ô mà bạn đang cố gắng để thay đổi là trên tấm bảo vệ. Để thay đổi, nhấp vào Bảng Unprotect trong tab Review.",
CreateRule: "New Rule",
NewRule: "Quy tắc định dạng mới",
NewRuleLabelContent: "giá trị định dạng mà công thức này là đúng:",
InsertDeleteAlert: "hoạt động này không được phép. Các hoạt động đang cố gắng để thay đổi các tế bào trong một bảng trên bảng tính của bạn.",
ReadOnly: "Phạm vi bạn đang cố gắng để thay đổi có chứa chỉ đọc các tế bào.",
CreatePivotTable: "Tạo Pivot Table",
Range: "Phạm vi:",
ChoosePivotTable: "Chọn nơi bạn muốn PivotTable để được đặt",
NewWorksheet: "Worksheet mới",
ExistingWorksheet: "hiện Worksheet",
Location: "Vị trí:",
Refresh: "Làm mới",
PivotRowsAlert: "Lệnh này yêu cầu ít nhất hai dòng dữ liệu nguồn. Bạn không thể sử dụng các lệnh trên một vùng chọn chỉ có một hàng.",
PivotLabelsAlert: "Tên trường PivotTable là không hợp lệ, Để tạo một báo cáo PivotTable, bạn phải sử dụng dữ liệu được tổ chức như một danh sách với các cột có nhãn. Nếu bạn thay đổi tên của một trường PivotTable, bạn phải gõ một tên mới cho lĩnh vực này.",
FieldList: "Danh sách các trường",
MergeSortAlert: "Để làm điều này, tất cả các tế bào sáp nhập cần phải có cùng kích thước.",
FormulaSortAlert: "Phạm vi phân loại với các công thức không thể được sắp xếp.",
MergePreventInsertDelete: "hoạt động này không được phép. Các hoạt động đang cố gắng thay đổi một tế bào hợp nhất trên bảng tính của bạn.",
FormulaRuleMsg: "Vui lòng nhập đúng định dạng.",
MovePivotTable: "Di chuyển Pivot Table",
MovePivotTableContent: "Di chuyển Bảng Pivot đến một vị trí trong bảng tính.",
ClearAllContent: "Di chuyển các lĩnh vực và các bộ lọc.",
ChangeDataSource: "sửa đổi",
ChangeDataSourceContent: "Thay đổi dữ liệu nguồn cho PivotTable này",
ChangePivotTableDataSource: "Thay đổi nguồn dữ liệu PivotTable",
TotalRowAlert: "hoạt động này không được phép. Các hoạt động đang cố gắng để thay đổi các tế bào trong một bảng trên bảng tính của bạn. Nhấn OK để tiến hành toàn bộ hàng.",
CellTypeAlert: "Thao tác này không được cho phép trong loại tế bào phạm vi áp dụng.",
PivotOverlapAlert: "Một báo cáo của Pivot Table không thể chồng lên nhau một báo cáo khác Pivot Table",
NoCellFound: "Không có tế bào được tìm thấy",
};
ej.TreeGrid.Locale["zh-CN"] = {
toolboxTooltipTexts: {
addTool: "加",
editTool: "编辑",
updateTool: "更新",
deleteTool: "删除",
cancelTool: "取消",
expandAllTool: "展开全部",
collapseAllTool: "全部收缩",
pdfExportTool: "PDF导出",
excelExportTool: "Excel导出"
},
contextMenuTexts: {
addRowText: "添加行",
editText: "编辑",
deleteText: "删除",
saveText: "保存",
cancelText: "取消",
aboveText: "以上",
belowText: "下面"
},
columnMenuTexts: {
sortAscendingText: "升序",
sortDescendingText: "降序",
columnsText: "列",
freezeText: "冻结",
unfreezeText: "解冻",
freezePrecedingColumnsText: "冻结在先的栏目",
insertColumnLeft: "在左侧插入列",
insertColumnRight: "在右侧插入列",
deleteColumn: "删除列",
renameColumn: "重列",
menuFilter: "过滤"
},
filterMenuTexts: {
stringMenuOptions: [
{ text: "以。。开始", value: "startswith" },
{ text: "结束", value: "endswith" },
{ text: "包含", value: "contains" },
{ text: "等于", value: "equal" },
{ text: "不等于", value: "notequal" }
],
numberMenuOptions: [
{ text: "少于", value: "lessthan" },
{ text: "比...更棒", value: "greaterthan" },
{ text: "小于或等于", value: "lessthanorequal" },
{ text: "大于或等于", value: "greaterthanorequal" },
{ text: "等于", value: "equal" },
{ text: "不等于", value: "notequal" }
],
filterValue: "过滤器值",
filterButton: "过滤",
clearButton: "明确",
enterValueText: "输入值"
},
columnDialogTexts: {
field: "领域",
headerText: "标题文本",
editType: "编辑类型",
filterEditType: "过滤器编辑类型",
allowFiltering: "允许过滤",
allowFilteringBlankContent: "允许过滤空白内容",
allowSorting: "允许排序",
visible: "可见",
width: "宽度",
textAlign: "文本对齐",
headerTextAlign: "头文字对齐",
isFrozen: "被冻结",
allowFreezing: "允许冷冻",
columnsDropdownData: "列下拉数据",
dropdownTableText: "文本",
dropdownTableValue: "值",
addData: "加",
deleteData: "去掉",
allowCellSelection: "允许小区选择"
},
columnDialogTitle: {
insertColumn: "插入列",
deleteColumn: "删除列",
renameColumn: "重列"
},
deleteColumnText: "你确定要删除此列?",
okButtonText: "好",
cancelButtonText: "取消",
confirmDeleteText: "确认删除",
dropDownListBlanksText: "(空白)",
dropDownListClearText: "(清除过滤器)",
trueText: "真正",
falseText: "假",
emptyRecord: "无记录可显示",
};
ej.Uploadbox.Locale["zh-CN"] = {
buttonText: {
upload: "上传",
browse: "浏览",
cancel: "取消",
close: "关闭"
},
dialogText: {
title: "上传框",
name: "名称",
size: "尺寸",
status: "状态"
},
dropAreaText: "将文件拖放或点击上传",
filedetail: "所选文件大小过大。请选择有效的尺寸范围内的文件。",
denyError: "与#Extension扩展名的文件是不允许的。",
allowError: "只有#Extension扩展名的文件是允许的。",
cancelToolTip: "取消",
removeToolTip: "清除",
retryToolTip: "重试",
completedToolTip: "完成",
failedToolTip: "失败的",
closeToolTip: "关闭",
};
;
|
import ohlcBase from './ohlcBase';
import { webglSeriesCandlestick } from '@d3fc/d3fc-webgl';
export default () => ohlcBase(webglSeriesCandlestick());
|
var $jscomp={scope:{}};$jscomp.defineProperty="function"==typeof Object.defineProperties?Object.defineProperty:function(e,g,a){if(a.get||a.set)throw new TypeError("ES3 does not support getters and setters.");e!=Array.prototype&&e!=Object.prototype&&(e[g]=a.value)};$jscomp.getGlobal=function(e){return"undefined"!=typeof window&&window===e?e:"undefined"!=typeof global&&null!=global?global:e};$jscomp.global=$jscomp.getGlobal(this);$jscomp.SYMBOL_PREFIX="jscomp_symbol_";
$jscomp.initSymbol=function(){$jscomp.initSymbol=function(){};$jscomp.global.Symbol||($jscomp.global.Symbol=$jscomp.Symbol)};$jscomp.symbolCounter_=0;$jscomp.Symbol=function(e){return $jscomp.SYMBOL_PREFIX+(e||"")+$jscomp.symbolCounter_++};
$jscomp.initSymbolIterator=function(){$jscomp.initSymbol();var e=$jscomp.global.Symbol.iterator;e||(e=$jscomp.global.Symbol.iterator=$jscomp.global.Symbol("iterator"));"function"!=typeof Array.prototype[e]&&$jscomp.defineProperty(Array.prototype,e,{configurable:!0,writable:!0,value:function(){return $jscomp.arrayIterator(this)}});$jscomp.initSymbolIterator=function(){}};$jscomp.arrayIterator=function(e){var g=0;return $jscomp.iteratorPrototype(function(){return g<e.length?{done:!1,value:e[g++]}:{done:!0}})};
$jscomp.iteratorPrototype=function(e){$jscomp.initSymbolIterator();e={next:e};e[$jscomp.global.Symbol.iterator]=function(){return this};return e};$jscomp.array=$jscomp.array||{};$jscomp.iteratorFromArray=function(e,g){$jscomp.initSymbolIterator();e instanceof String&&(e+="");var a=0,l={next:function(){if(a<e.length){var k=a++;return{value:g(k,e[k]),done:!1}}l.next=function(){return{done:!0,value:void 0}};return l.next()}};l[Symbol.iterator]=function(){return l};return l};
$jscomp.polyfill=function(e,g,a,l){if(g){a=$jscomp.global;e=e.split(".");for(l=0;l<e.length-1;l++){var k=e[l];k in a||(a[k]={});a=a[k]}e=e[e.length-1];l=a[e];g=g(l);g!=l&&null!=g&&$jscomp.defineProperty(a,e,{configurable:!0,writable:!0,value:g})}};$jscomp.polyfill("Array.prototype.keys",function(e){return e?e:function(){return $jscomp.iteratorFromArray(this,function(e){return e})}},"es6-impl","es3");$jscomp.owns=function(e,g){return Object.prototype.hasOwnProperty.call(e,g)};
$jscomp.polyfill("Object.assign",function(e){return e?e:function(e,a){for(var g=1;g<arguments.length;g++){var k=arguments[g];if(k)for(var h in k)$jscomp.owns(k,h)&&(e[h]=k[h])}return e}},"es6-impl","es3");$jscomp.checkStringArgs=function(e,g,a){if(null==e)throw new TypeError("The 'this' value for String.prototype."+a+" must not be null or undefined");if(g instanceof RegExp)throw new TypeError("First argument to String.prototype."+a+" must not be a regular expression");return e+""};
$jscomp.polyfill("String.prototype.includes",function(e){return e?e:function(e,a){return-1!==$jscomp.checkStringArgs(this,e,"includes").indexOf(e,a||0)}},"es6-impl","es3");$jscomp.findInternal=function(e,g,a){e instanceof String&&(e=String(e));for(var l=e.length,k=0;k<l;k++){var h=e[k];if(g.call(a,h,k,e))return{i:k,v:h}}return{i:-1,v:void 0}};$jscomp.polyfill("Array.prototype.find",function(e){return e?e:function(e,a){return $jscomp.findInternal(this,e,a).v}},"es6-impl","es3");
$jscomp.polyfill("Array.prototype.values",function(e){return e?e:function(){return $jscomp.iteratorFromArray(this,function(e,a){return a})}},"es6","es3");
(function(e,g){"object"===typeof exports&&"object"===typeof module?module.exports=g():"function"===typeof define&&define.amd?define([],g):"object"===typeof exports?exports.RxPlayer=g():e.RxPlayer=g()})(this,function(){return function(e){function g(l){if(a[l])return a[l].exports;var k=a[l]={i:l,l:!1,exports:{}};e[l].call(k.exports,k,k.exports,g);k.l=!0;return k.exports}var a={};g.m=e;g.c=a;g.i=function(a){return a};g.d=function(a,k,h){g.o(a,k)||Object.defineProperty(a,k,{configurable:!1,enumerable:!0,
get:h})};g.n=function(a){var k=a&&a.__esModule?function(){return a["default"]}:function(){return a};g.d(k,"a",k);return k};g.o=function(a,k){return Object.prototype.hasOwnProperty.call(a,k)};g.p="";return g(g.s=108)}([function(e,g,a){var l=a(7),k=a(176),h=a(40);e=function(){function a(a){this._isScalar=!1;a&&(this._subscribe=a)}a.prototype.lift=function(c){var d=new a;d.source=this;d.operator=c;return d};a.prototype.subscribe=function(a,d,b){var c=this.operator;a=k.toSubscriber(a,d,b);c?c.call(a,
this):a.add(this._subscribe(a));if(a.syncErrorThrowable&&(a.syncErrorThrowable=!1,a.syncErrorThrown))throw a.syncErrorValue;return a};a.prototype.forEach=function(a,d){var b=this;d||(l.root.Rx&&l.root.Rx.config&&l.root.Rx.config.Promise?d=l.root.Rx.config.Promise:l.root.Promise&&(d=l.root.Promise));if(!d)throw Error("no Promise impl found");return new d(function(c,d){var m=b.subscribe(function(b){if(m)try{a(b)}catch(q){d(q),m.unsubscribe()}else a(b)},d,c)})};a.prototype._subscribe=function(a){return this.source.subscribe(a)};
a.prototype[h.$$observable]=function(){return this};a.create=function(c){return new a(c)};return a}();g.Observable=e},function(e,g,a){function l(a){this.name="AssertionError";this.message=a;Error.captureStackTrace&&Error.captureStackTrace(this,l)}function k(a,c){if(!a)throw new l(c);}var h="function"===typeof Symbol&&"symbol"===typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"===typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a};l.prototype=
Error();k.equal=function(a,c,d){return k(a===c,d)};k.iface=function(a,c,d){k(a,c+" should be an object");for(var b in d)k.equal(h(a[b]),d[b],c+" should have property "+b+" as a "+d[b])};g.a=k},function(e,g,a){var l=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var d in b)b.hasOwnProperty(d)&&(a[d]=b[d]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)},k=a(42);e=a(5);var h=a(52),f=a(41);a=function(a){function b(m,d,f){a.call(this);this.syncErrorValue=
null;this.isStopped=this.syncErrorThrowable=this.syncErrorThrown=!1;switch(arguments.length){case 0:this.destination=h.empty;break;case 1:if(!m){this.destination=h.empty;break}if("object"===typeof m){m instanceof b?(this.destination=m,this.destination.add(this)):(this.syncErrorThrowable=!0,this.destination=new c(this,m));break}default:this.syncErrorThrowable=!0,this.destination=new c(this,m,d,f)}}l(b,a);b.prototype[f.$$rxSubscriber]=function(){return this};b.create=function(a,c,d){a=new b(a,c,d);
a.syncErrorThrowable=!1;return a};b.prototype.next=function(a){this.isStopped||this._next(a)};b.prototype.error=function(a){this.isStopped||(this.isStopped=!0,this._error(a))};b.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())};b.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,a.prototype.unsubscribe.call(this))};b.prototype._next=function(a){this.destination.next(a)};b.prototype._error=function(a){this.destination.error(a);this.unsubscribe()};b.prototype._complete=
function(){this.destination.complete();this.unsubscribe()};return b}(e.Subscription);g.Subscriber=a;var c=function(a){function b(b,c,d,f){a.call(this);this._parent=b;var m;b=this;k.isFunction(c)?m=c:c&&(b=c,m=c.next,d=c.error,f=c.complete,k.isFunction(b.unsubscribe)&&this.add(b.unsubscribe.bind(b)),b.unsubscribe=this.unsubscribe.bind(this));this._context=b;this._next=m;this._error=d;this._complete=f}l(b,a);b.prototype.next=function(a){if(!this.isStopped&&this._next){var b=this._parent;b.syncErrorThrowable?
this.__tryOrSetError(b,this._next,a)&&this.unsubscribe():this.__tryOrUnsub(this._next,a)}};b.prototype.error=function(a){if(!this.isStopped){var b=this._parent;if(this._error)b.syncErrorThrowable?this.__tryOrSetError(b,this._error,a):this.__tryOrUnsub(this._error,a),this.unsubscribe();else if(b.syncErrorThrowable)b.syncErrorValue=a,b.syncErrorThrown=!0,this.unsubscribe();else throw this.unsubscribe(),a;}};b.prototype.complete=function(){if(!this.isStopped){var a=this._parent;this._complete&&(a.syncErrorThrowable?
this.__tryOrSetError(a,this._complete):this.__tryOrUnsub(this._complete));this.unsubscribe()}};b.prototype.__tryOrUnsub=function(a,b){try{a.call(this._context,b)}catch(p){throw this.unsubscribe(),p;}};b.prototype.__tryOrSetError=function(a,b,c){try{b.call(this._context,c)}catch(r){return a.syncErrorValue=r,a.syncErrorThrown=!0}return!1};b.prototype._unsubscribe=function(){var a=this._parent;this._parent=this._context=null;a.unsubscribe()};return b}(a)},function(e,g,a){function l(){}var k={NONE:0,
ERROR:1,WARNING:2,INFO:3,DEBUG:4},h=function(){};l.error=h;l.warn=h;l.info=h;l.debug=h;l.setLevel=function(a){"string"==typeof a&&(a=k[a]);l.error=a>=k.ERROR?console.error.bind(console):h;l.warn=a>=k.WARNING?console.warn.bind(console):h;l.info=a>=k.INFO?console.info.bind(console):h;l.debug=a>=k.DEBUG?console.log.bind(console):h};g.a=l},function(e,g,a){function l(a){var b=a.reduce(function(a,b){a[b]=b;return a},{});b.keys=a;return b}function k(a,b,c){return a+"("+b+")"+(c?": "+c.message:"")}function h(a,
b,c){this.name="MediaError";this.type=p.MEDIA_ERROR;this.reason=b;this.code=q[a];this.fatal=c;this.message=k(this.name,this.code,this.reason)}function f(a,b,c){this.name="NetworkError";this.type=p.NETWORK_ERROR;this.xhr=b.xhr;this.url=b.url;this.status=b.status;this.reqType=b.type;this.reason=b;this.code=q[a];this.fatal=c;this.message=this.reason?k(this.name,this.code,this.reason):k(this.name,this.code,{message:""+this.reqType+(0<this.status?"("+this.status+")":"")+" on "+this.url})}function c(a,
b,c){this.name="EncryptedMediaError";this.type=p.ENCRYPTED_MEDIA_ERROR;this.reason=b;this.code=q[a];this.fatal=c;this.message=k(this.name,this.code,this.reason)}function d(a,b,c){this.name="IndexError";this.type=p.INDEX_ERROR;this.indexType=b;this.reason=null;this.code=q[a];this.fatal=c;this.message=k(this.name,this.code,null)}function b(a,b,c){this.name="OtherError";this.type=p.OTHER_ERROR;this.reason=b;this.code=q[a];this.fatal=c;this.message=k(this.name,this.code,this.reason)}function m(a,b,c){this.name=
"RequestError";this.url=b.url;this.xhr=a;this.status=a.status;this.message=this.type=c}function n(a){return!!a&&!!a.type&&0<=p.keys.indexOf(a.type)}a.d(g,"a",function(){return p});a.d(g,"b",function(){return q});a.d(g,"d",function(){return h});a.d(g,"j",function(){return f});a.d(g,"c",function(){return c});a.d(g,"g",function(){return d});a.d(g,"f",function(){return b});a.d(g,"h",function(){return m});a.d(g,"i",function(){return r});a.d(g,"e",function(){return n});var p=l(["NETWORK_ERROR","MEDIA_ERROR",
"ENCRYPTED_MEDIA_ERROR","INDEX_ERROR","OTHER_ERROR"]),r=l(["TIMEOUT","ERROR_EVENT","ERROR_HTTP_CODE","PARSE_ERROR"]),q=l("PIPELINE_RESOLVE_ERROR PIPELINE_LOAD_ERROR PIPELINE_PARSING_ERROR MANIFEST_PARSE_ERROR MANIFEST_INCOMPATIBLE_CODECS_ERROR MEDIA_IS_ENCRYPTED_ERROR KEY_ERROR KEY_STATUS_CHANGE_ERROR KEY_UPDATE_ERROR KEY_LOAD_ERROR KEY_LOAD_TIMEOUT KEY_GENERATE_REQUEST_ERROR INCOMPATIBLE_KEYSYSTEMS BUFFER_APPEND_ERROR BUFFER_FULL_ERROR BUFFER_TYPE_UNKNOWN MEDIA_ERR_ABORTED MEDIA_ERR_NETWORK MEDIA_ERR_DECODE MEDIA_ERR_SRC_NOT_SUPPORTED MEDIA_SOURCE_NOT_SUPPORTED MEDIA_KEYS_NOT_SUPPORTED OUT_OF_INDEX_ERROR UNKNOWN_INDEX".split(" "));
h.prototype=Error();f.prototype=Error();f.prototype.isHttpError=function(a){return this.reqType==r.ERROR_HTTP_CODE&&this.status==a};c.prototype=Error();d.prototype=Error();b.prototype=Error();m.prototype=Error()},function(e,g,a){var l=a(17),k=a(175),h=a(42),f=a(43),c=a(27),d=a(174);e=function(){function a(a){this.closed=!1;a&&(this._unsubscribe=a)}a.prototype.unsubscribe=function(){var a=!1,b;if(!this.closed){this.closed=!0;var e=this._unsubscribe,g=this._subscriptions;this._subscriptions=null;if(h.isFunction(e)){var q=
f.tryCatch(e).call(this);q===c.errorObject&&(a=!0,(b=b||[]).push(c.errorObject.e))}if(l.isArray(g))for(var e=-1,x=g.length;++e<x;)q=g[e],k.isObject(q)&&(q=f.tryCatch(q.unsubscribe).call(q),q===c.errorObject&&(a=!0,b=b||[],q=c.errorObject.e,q instanceof d.UnsubscriptionError?b=b.concat(q.errors):b.push(q)));if(a)throw new d.UnsubscriptionError(b);}};a.prototype.add=function(b){if(!b||b===a.EMPTY)return a.EMPTY;if(b===this)return this;var c=b;switch(typeof b){case "function":c=new a(b);case "object":c.closed||
"function"!==typeof c.unsubscribe||(this.closed?c.unsubscribe():(this._subscriptions||(this._subscriptions=[])).push(c));break;default:throw Error("unrecognized teardown "+b+" added to Subscription.");}return c};a.prototype.remove=function(b){if(null!=b&&b!==this&&b!==a.EMPTY){var c=this._subscriptions;c&&(b=c.indexOf(b),-1!==b&&c.splice(b,1))}};a.EMPTY=function(a){a.closed=!0;return a}(new a);return a}();g.Subscription=e},function(e,g,a){var l=this&&this.__extends||function(a,h){function f(){this.constructor=
a}for(var c in h)h.hasOwnProperty(c)&&(a[c]=h[c]);a.prototype=null===h?Object.create(h):(f.prototype=h.prototype,new f)};e=function(a){function h(f){a.call(this);this.scheduler=f}l(h,a);h.create=function(a){return new h(a)};h.dispatch=function(a){a.subscriber.complete()};h.prototype._subscribe=function(a){var c=this.scheduler;if(c)return c.schedule(h.dispatch,0,{subscriber:a});a.complete()};return h}(a(0).Observable);g.EmptyObservable=e},function(e,g,a){(function(a){g.root="object"==typeof window&&
window.window===window&&window||"object"==typeof self&&self.self===self&&self||"object"==typeof a&&a.global===a&&a;if(!g.root)throw Error("RxJS could not find any global context (window, self, global)");}).call(g,a(177))},function(e,g,a){var l=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var d in b)b.hasOwnProperty(d)&&(a[d]=b[d]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)},k=a(0);e=a(2);var h=a(5),f=a(61),c=a(134),d=a(41),b=function(a){function b(b){a.call(this,
b);this.destination=b}l(b,a);return b}(e.Subscriber);g.SubjectSubscriber=b;a=function(a){function n(){a.call(this);this.observers=[];this.hasError=this.isStopped=this.closed=!1;this.thrownError=null}l(n,a);n.prototype[d.$$rxSubscriber]=function(){return new b(this)};n.prototype.lift=function(a){var b=new m(this,this);b.operator=a;return b};n.prototype.next=function(a){if(this.closed)throw new f.ObjectUnsubscribedError;if(!this.isStopped)for(var b=this.observers,c=b.length,b=b.slice(),d=0;d<c;d++)b[d].next(a)};
n.prototype.error=function(a){if(this.closed)throw new f.ObjectUnsubscribedError;this.hasError=!0;this.thrownError=a;this.isStopped=!0;for(var b=this.observers,c=b.length,b=b.slice(),d=0;d<c;d++)b[d].error(a);this.observers.length=0};n.prototype.complete=function(){if(this.closed)throw new f.ObjectUnsubscribedError;this.isStopped=!0;for(var a=this.observers,b=a.length,a=a.slice(),c=0;c<b;c++)a[c].complete();this.observers.length=0};n.prototype.unsubscribe=function(){this.closed=this.isStopped=!0;
this.observers=null};n.prototype._subscribe=function(a){if(this.closed)throw new f.ObjectUnsubscribedError;if(this.hasError)return a.error(this.thrownError),h.Subscription.EMPTY;if(this.isStopped)return a.complete(),h.Subscription.EMPTY;this.observers.push(a);return new c.SubjectSubscription(this,a)};n.prototype.asObservable=function(){var a=new k.Observable;a.source=this;return a};n.create=function(a,b){return new m(a,b)};return n}(k.Observable);g.Subject=a;var m=function(a){function b(b,c){a.call(this);
this.destination=b;this.source=c}l(b,a);b.prototype.next=function(a){var b=this.destination;b&&b.next&&b.next(a)};b.prototype.error=function(a){var b=this.destination;b&&b.error&&this.destination.error(a)};b.prototype.complete=function(){var a=this.destination;a&&a.complete&&this.destination.complete()};b.prototype._subscribe=function(a){return this.source?this.source.subscribe(a):h.Subscription.EMPTY};return b}(a);g.AnonymousSubject=m},function(e,g,a){function l(a,b){return a.reduce(function(a,c){return a.concat((b||
R).map(function(a){return a+c}))},[])}function k(a,b){return b.filter(function(b){var c;c=document.createElement(a.tagName);b="on"+b;b in c?c=!0:(c.setAttribute(b,"return;"),c="function"==typeof c[b]);return c})[0]}function h(b,c){var d=void 0;b=l(b,c);return function(c){return c instanceof N?("undefined"==typeof d&&(d=k(c,b)||null),d?S(c,d):V()):a.i(E.a)(c,b)}}function f(a){return!!M&&M.isTypeSupported(a)}function c(){return O}function d(a){return"open"==a.readyState?C.Observable.of(null):ha(a).take(1)}
function b(a){return a.readyState>=U?C.Observable.of(null):ba(a).take(1)}function m(b){return b.readyState>=P?C.Observable.of(null):a.i(E.a)(b,"canplay").take(1)}function n(b,c){function d(){var a=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};a.errorCode&&(a={systemCode:a.systemCode,code:a.errorCode.code});this.name="KeySessionError";this.mediaKeyError=a;this.message="MediaKeyError code:"+a.code+" and systemCode:"+a.systemCode}d.prototype=Error();return function(f,m){var h="function"==
typeof c?c.call(this):this,k=Z(h),n=W(h).map(function(a){throw new d(h.error||a);});try{return b.call(this,f,m),a.i(H.merge)(k,n).take(1)}catch(ma){return C.Observable["throw"](ma)}}}function p(a,b){if(b instanceof da)return b._setVideo(a);if(a.setMediaKeys)return a.setMediaKeys(b);if(null!==b){if(a.WebkitSetMediaKeys)return a.WebkitSetMediaKeys(b);if(a.mozSetMediaKeys)return a.mozSetMediaKeys(b);if(a.msSetMediaKeys)return a.msSetMediaKeys(b)}}function r(a){x()||(a.requestFullscreen?a.requestFullscreen():
a.msRequestFullscreen?a.msRequestFullscreen():a.mozRequestFullScreen?a.mozRequestFullScreen():a.webkitRequestFullscreen&&a.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT))}function q(){x()&&(F.exitFullscreen?F.exitFullscreen():F.msExitFullscreen?F.msExitFullscreen():F.mozCancelFullScreen?F.mozCancelFullScreen():F.webkitExitFullscreen&&F.webkitExitFullscreen())}function x(){return!!(F.fullscreenElement||F.mozFullScreenElement||F.webkitFullscreenElement||F.msFullscreenElement)}function t(){var b=
void 0;null!=F.hidden?b="":null!=F.mozHidden?b="moz":null!=F.msHidden?b="ms":null!=F.webkitHidden&&(b="webkit");var c=b?b+"Hidden":"hidden",b=b+"visibilitychange";return a.i(E.a)(F,b).map(function(){return F[c]})}function w(){return a.i(E.a)(I,"resize")}function v(a,b){var c,d=void 0;O?(c=a.textTracks.length,c=0<c?a.textTracks[c-1]:a.addTextTrack("subtitles"),c.mode=b?c.HIDDEN:c.SHOWING):(d=document.createElement("track"),a.appendChild(d),c=d.track,d.kind="subtitles",c.mode=b?"hidden":"showing");
return{track:c,trackElement:d}}function y(){return!O}function u(a){return X&&"timeupdate"===a.name&&a.range&&10<a.range.end-a.ts}function B(a){a.src="";a.removeAttribute("src")}a.d(g,"a",function(){return K});a.d(g,"m",function(){return M});a.d(g,"k",function(){return f});a.d(g,"n",function(){return d});a.d(g,"o",function(){return b});a.d(g,"p",function(){return m});a.d(g,"h",function(){return ea});a.d(g,"i",function(){return Q});a.d(g,"j",function(){return ca});a.d(g,"f",function(){return na});a.d(g,
"g",function(){return c});a.d(g,"c",function(){return x});a.d(g,"b",function(){return oa});a.d(g,"e",function(){return r});a.d(g,"d",function(){return q});a.d(g,"v",function(){return w});a.d(g,"u",function(){return t});a.d(g,"r",function(){return v});a.d(g,"l",function(){return B});a.d(g,"s",function(){return y});a.d(g,"q",function(){return u});a.d(g,"t",function(){return O});a(3);var A=a(31),z=a(10),G=a(1),C=a(0);a.n(C);var H=a(14);a.n(H);e=a(54);a.n(e);g=a(141);a.n(g);var D=a(53);a.n(D);var E=a(11),
L=a(4),T=function(){function a(a,b){for(var c=0;c<b.length;c++){var d=b[c];d.enumerable=d.enumerable||!1;d.configurable=!0;"value"in d&&(d.writable=!0);Object.defineProperty(a,d.key,d)}}return function(b,c,d){c&&a(b.prototype,c);d&&a(b,d);return b}}(),S=e.FromEventObservable.create,V=g.NeverObservable.create,Y=D.DeferObservable.create,F=document,I=window,R=["","webkit","moz","ms"],N=I.HTMLElement,K=I.HTMLVideoElement,M=I.MediaSource||I.MozMediaSource||I.WebKitMediaSource||I.MSMediaSource,J=I.MediaKeys||
I.MozMediaKeys||I.WebKitMediaKeys||I.MSMediaKeys,O="Microsoft Internet Explorer"==navigator.appName||"Netscape"==navigator.appName&&/(Trident|Edge)\//.test(navigator.userAgent),X=-1!==navigator.userAgent.toLowerCase().indexOf("firefox"),U=1,P=4,da=function(){},Q=void 0;navigator.requestMediaKeySystemAccess&&(Q=function(b,c){return a.i(E.b)(navigator.requestMediaKeySystemAccess(b,c))});var ea=function(){function a(b,c,d){if(!(this instanceof a))throw new TypeError("Cannot call a class as a function");
this._keyType=b;this._mediaKeys=c;this._configuration=d}a.prototype.createMediaKeys=function(){return C.Observable.of(this._mediaKeys)};a.prototype.getConfiguration=function(){return this._configuration};T(a,[{key:"keySystem",get:function(){return this._keyType}}]);return a}(),ba=h(["loadedmetadata"]),ha=h(["sourceopen","webkitsourceopen"]);e=h(["encrypted","needkey"]);var fa=h(["keymessage","message"]),Z=h(["keyadded","ready"]),W=h(["keyerror","error"]);g=h(["keystatuseschange"]);var na={onEncrypted:e,
onKeyMessage:fa,onKeyStatusesChange:g,onKeyError:W};if(!Q&&K.prototype.webkitGenerateKeyRequest){var ia=function(b,c){var d=this;A.a.call(this);this.sessionId="";this._vid=b;this._key=c;this._con=a.i(H.merge)(fa(b),Z(b),W(b)).subscribe(function(a){return d.trigger(a.type,a)})};ia.prototype=Object.assign({generateRequest:function(a,b){this._vid.webkitGenerateKeyRequest(this._key,b)},update:n(function(b,c){if(0<=this._key.indexOf("clearkey")){var d=JSON.parse(a.i(z.a)(b)),f=a.i(z.b)(atob(d.keys[0].k)),
d=a.i(z.b)(atob(d.keys[0].kid));this._vid.webkitAddKey(this._key,f,d,c)}else this._vid.webkitAddKey(this._key,b,null,c);this.sessionId=c}),close:function(){this._con&&this._con.unsubscribe();this._vid=this._con=null}},A.a.prototype);da=function(a){this.ks_=a};da.prototype={_setVideo:function(a){this._vid=a},createSession:function(){return new ia(this._vid,this.ks_)}};var pa=function(a){var b=F.querySelector("video")||F.createElement("video");return b&&b.canPlayType?!!b.canPlayType("video/mp4",a):
!1},Q=function(a,b){if(!pa(a))return C.Observable["throw"]();for(var c=0;c<b.length;c++){var d=b[c],f=d.videoCapabilities,m=d.audioCapabilities,h=d.initDataTypes,k=d.sessionTypes,n=d.distinctiveIdentifier,d=d.persistentState,e=!0;if(e=(e=(e=(e=e&&(!h||!!h.filter(function(a){return"cenc"===a})[0]))&&(!k||k.filter(function(a){return"temporary"===a}).length===k.length))&&"required"!==n)&&"required"!==d)return c={videoCapabilities:f,audioCapabilities:m,initDataTypes:["cenc"],distinctiveIdentifier:"not-allowed",
persistentState:"not-allowed",sessionTypes:["temporary"]},C.Observable.of(new ea(a,new da(a),c))}return C.Observable["throw"]()}}else if(J&&!Q){var ja=function(a){A.a.call(this);this.sessionId="";this._mk=a};ja.prototype=Object.assign({generateRequest:function(b,c){var d=this;this._ss=this._mk.memCreateSession("video/mp4",c);this._con=a.i(H.merge)(fa(this._ss),Z(this._ss),W(this._ss)).subscribe(function(a){return d.trigger(a.type,a)})},update:n(function(b,c){a.i(G.a)(this._ss);this._ss.update(b,c);
this.sessionId=c},function(){return this._ss}),close:function(){this._ss&&(this._ss.close(),this._ss=null);this._con&&(this._con.unsubscribe(),this._con=null)}},A.a.prototype);J.prototype.alwaysRenew=!0;J.prototype.memCreateSession=J.prototype.createSession;J.prototype.createSession=function(){return new ja(this)};Q=function(a,b){if(!J.isTypeSupported(a))return C.Observable["throw"]();for(var c=0;c<b.length;c++){var d=b[c],f=d.videoCapabilities,m=d.audioCapabilities,h=d.initDataTypes,d=d.distinctiveIdentifier,
k=!0;if(k=(k=k&&(!h||!!h.filter(function(a){return"cenc"===a})[0]))&&"required"!==d)return c={videoCapabilities:f,audioCapabilities:m,initDataTypes:["cenc"],distinctiveIdentifier:"not-allowed",persistentState:"required",sessionTypes:["temporary","persistent-license"]},C.Observable.of(new ea(a,new J(a),c))}return C.Observable["throw"]()}}J||(e=function(){throw new L.d("MEDIA_KEYS_NOT_SUPPORTED",null,!0);},J={create:e,isTypeSupported:e});var ca=function(b,c){return Y(function(){return a.i(E.b)(p(b,
c))})};if(I.WebKitSourceBuffer&&!I.WebKitSourceBuffer.prototype.addEventListener){e=I.WebKitSourceBuffer.prototype;for(var aa in A.a.prototype)e[aa]=A.a.prototype[aa];e.__listeners=[];e.appendBuffer=function(a){if(this.updating)throw Error("updating");this.trigger("updatestart");this.updating=!0;try{this.append(a)}catch(ka){this.__emitUpdate("error",ka);return}this.__emitUpdate("update")};e.__emitUpdate=function(a,b){var c=this;setTimeout(function(){c.trigger(a,b);c.updating=!1;c.trigger("updateend")},
0)}}var oa=h(["fullscreenchange","FullscreenChange"],R.concat("MS"))},function(e,g,a){function l(a){for(var b=a.length,c=new Uint8Array(b),d=0;d<b;d++)c[d]=a.charCodeAt(d)&255;return c}function k(a){return String.fromCharCode.apply(null,a)}function h(a){for(var b="",c=a.length,d=0;d<c;d+=2)b+=String.fromCharCode(a[d]);return b}function f(a){for(var b=a.length,c=new Uint8Array(b/2),d=0,f=0;d<b;d+=2,f++)c[f]=parseInt(a.substr(d,2),16)&255;return c}function c(a,b){b||(b="");for(var c="",d=0;d<a.byteLength;d++)c+=
(a[d]>>>4).toString(16),c+=(a[d]&15).toString(16),b.length&&d<a.byteLength-1&&(c+=b);return c}function d(){for(var a=arguments.length,b=-1,c=0,d;++b<a;)d=arguments[b],c+="number"===typeof d?d:d.length;for(var c=new Uint8Array(c),f=0,b=-1;++b<a;)d=arguments[b],"number"===typeof d?f+=d:0<d.length&&(c.set(d,f),f+=d.length);return c}function b(a,b){return(a[0+b]<<8)+(a[1+b]<<0)}function m(a,b){return 16777216*a[0+b]+65536*a[1+b]+256*a[2+b]+a[3+b]}function n(a,b){return 4294967296*(16777216*a[0+b]+65536*
a[1+b]+256*a[2+b]+a[3+b])+16777216*a[4+b]+65536*a[5+b]+256*a[6+b]+a[7+b]}function p(a){return new Uint8Array([a>>>8&255,a&255])}function r(a){return new Uint8Array([a>>>24&255,a>>>16&255,a>>>8&255,a&255])}function q(a){var b=a%4294967296;a=(a-b)/4294967296;return new Uint8Array([a>>>24&255,a>>>16&255,a>>>8&255,a&255,b>>>24&255,b>>>16&255,b>>>8&255,b&255])}function x(a,b){return(a[0+b]<<0)+(a[1+b]<<8)}function t(a,b){return a[0+b]+256*a[1+b]+65536*a[2+b]+16777216*a[3+b]}function w(a){v.a.equal(a.length,
16,"UUID length should be 16");var b=l(a);a=b[0];var d=b[1],f=b[2],m=b[3],h=b[4],k=b[5],n=b[6],e=b[7],p=b.subarray(8,10),b=b.subarray(10,16),t=new Uint8Array(16);t[0]=m;t[1]=f;t[2]=d;t[3]=a;t[4]=k;t[5]=h;t[6]=e;t[7]=n;t.set(p,8);t.set(b,10);return c(t)}a.d(g,"b",function(){return l});a.d(g,"a",function(){return k});a.d(g,"k",function(){return h});a.d(g,"j",function(){return f});a.d(g,"o",function(){return c});a.d(g,"h",function(){return d});a.d(g,"g",function(){return b});a.d(g,"e",function(){return m});
a.d(g,"f",function(){return n});a.d(g,"d",function(){return x});a.d(g,"c",function(){return t});a.d(g,"m",function(){return p});a.d(g,"i",function(){return r});a.d(g,"n",function(){return q});a.d(g,"l",function(){return w});var v=a(1)},function(e,g,a){function l(a,b){if("function"!==typeof b&&null!==b)throw new TypeError("Super expression must either be null or a function, not "+typeof b);a.prototype=Object.create(b&&b.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}});b&&
(Object.setPrototypeOf?Object.setPrototypeOf(a,b):a.__proto__=b)}function k(a,c){return Array.isArray(c)?b.merge.apply(null,c.map(function(b){return m(a,b)})):m(a,c)}function h(a){return a instanceof d.Observable?a:a&&"function"==typeof a.subscribe?new d.Observable(function(b){var c=a.subscribe(function(a){return b.next(a)},function(a){return b.error(a)},function(){return b.complete()});return function(){c&&c.dispose?c.dispose():c&&c.unsubscribe&&c.unsubscribe()}}):a&&"function"==typeof a.then?n(a):
d.Observable.of(a)}function f(a){return new p(a)}function c(a,b){try{return a(b)}catch(t){return d.Observable["throw"](t)}}a.d(g,"a",function(){return k});a.d(g,"e",function(){return f});a.d(g,"c",function(){return c});a.d(g,"b",function(){return h});a.d(g,"d",function(){return r});var d=a(0);a.n(d);var b=a(14);a.n(b);e=a(54);a.n(e);g=a(55);a.n(g);var m=e.FromEventObservable.create,n=g.PromiseObservable.create,p=function(a){function b(c){if(!(this instanceof b))throw new TypeError("Cannot call a class as a function");
var d;d=a.call(this);if(!this)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");d=!d||"object"!==typeof d&&"function"!==typeof d?this:d;d.value=c;return d}l(b,a);b.prototype._subscribe=function(a){a.next(this.value)};return b}(d.Observable),r=function(a){var b=!1;return function(){if(b)return d.Observable.empty();b=!0;return h(a.apply(void 0,arguments))["do"](null,function(){return b=!1},function(){return b=!1})}}},function(e,g,a){var l=this&&this.__extends||function(a,
h){function f(){this.constructor=a}for(var c in h)h.hasOwnProperty(c)&&(a[c]=h[c]);a.prototype=null===h?Object.create(h):(f.prototype=h.prototype,new f)};e=function(a){function h(){a.apply(this,arguments)}l(h,a);h.prototype.notifyNext=function(a,c,d,b,m){this.destination.next(c)};h.prototype.notifyError=function(a,c){this.destination.error(a)};h.prototype.notifyComplete=function(a){this.destination.complete()};return h}(a(2).Subscriber);g.OuterSubscriber=e},function(e,g,a){var l=this&&this.__extends||
function(a,d){function b(){this.constructor=a}for(var c in d)d.hasOwnProperty(c)&&(a[c]=d[c]);a.prototype=null===d?Object.create(d):(b.prototype=d.prototype,new b)};e=a(0);var k=a(36),h=a(6),f=a(18);a=function(a){function c(b,c){a.call(this);this.array=b;this.scheduler=c;c||1!==b.length||(this._isScalar=!0,this.value=b[0])}l(c,a);c.create=function(a,d){return new c(a,d)};c.of=function(){for(var a=[],d=0;d<arguments.length;d++)a[d-0]=arguments[d];d=a[a.length-1];f.isScheduler(d)?a.pop():d=null;var n=
a.length;return 1<n?new c(a,d):1===n?new k.ScalarObservable(a[0],d):new h.EmptyObservable(d)};c.dispatch=function(a){var b=a.array,c=a.index,d=a.subscriber;c>=a.count?d.complete():(d.next(b[c]),d.closed||(a.index=c+1,this.schedule(a)))};c.prototype._subscribe=function(a){var b=this.array,d=b.length,f=this.scheduler;if(f)return f.schedule(c.dispatch,0,{array:b,index:0,count:d,subscriber:a});for(f=0;f<d&&!a.closed;f++)a.next(b[f]);a.complete()};return c}(e.Observable);g.ArrayObservable=a},function(e,
g,a){e=a(156);g.merge=e.mergeStatic},function(e,g,a){var l=a(7),k=a(17),h=a(64),f=a(0),c=a(39),d=a(131),b=a(40);g.subscribeToResult=function(a,n,e,g){var m=new d.InnerSubscriber(a,e,g);if(m.closed)return null;if(n instanceof f.Observable)return n._isScalar?(m.next(n.value),m.complete(),null):n.subscribe(m);if(k.isArray(n)){a=0;for(e=n.length;a<e&&!m.closed;a++)m.next(n[a]);m.closed||m.complete()}else{if(h.isPromise(n))return n.then(function(a){m.closed||(m.next(a),m.complete())},function(a){return m.error(a)}).then(null,
function(a){l.root.setTimeout(function(){throw a;})}),m;if("function"===typeof n[c.$$iterator]){n=n[c.$$iterator]();do{a=n.next();if(a.done){m.complete();break}m.next(a.value);if(m.closed)break}while(1)}else if("function"===typeof n[b.$$observable])if(n=n[b.$$observable](),"function"!==typeof n.subscribe)m.error(Error("invalid observable"));else return n.subscribe(new d.InnerSubscriber(a,e,g));else m.error(new TypeError("unknown type returned"))}return null}},function(e,g,a){g.a=function k(){var a=
0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};if(!(this instanceof k))throw new TypeError("Cannot call a class as a function");this.id=a.id;this.duration=a.duration;this.isInit=!!a.init;this.range=a.range;this.time=a.time;this.indexRange=a.indexRange;this.number=a.number;this.timescale=a.timescale;this.media=a.media}},function(e,g,a){g.isArray=Array.isArray||function(a){return a&&"number"===typeof a.length}},function(e,g,a){g.isScheduler=function(a){return a&&"function"===typeof a.schedule}},
function(e,g,a){function l(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function");}function k(a){for(var b=a.length,c=[],d=0;d<b;d++)c.push(new r(a.start(d),a.end(d),0));return c}function h(a){for(var b=a.length,c=[],d=0;d<b;d++)c.push(a[d].clone());return c}function f(a,b){return a.start<=b&&b<a.end}function c(a,b){for(var c=0;c<b.length;c++)if(d(a,b[c]))return b[c];return null}function d(a,b){return f(a,b.start)||f(a,b.end)||f(b,a.start)}function b(a,b){return f(a,b.start)&&
f(a,b.end)}function m(a){for(var b=1;b<a.length;b++){var c=a[b-1],d=a[b];c.bitrate===d.bitrate&&(Math.abs(d.start-c.end)<p||Math.abs(d.end-c.start)<p)&&(c=new r(Math.min(c.start,d.start),Math.max(c.end,d.end),d.bitrate),a.splice(--b,2,c))}return a}function n(a){a=h(a);for(var b=0;b<a.length;b++)a[b].bitrate=0;return m(a)}a.d(g,"b",function(){return k});a.d(g,"a",function(){return q});a(1);var p=1/60,r=function(){function a(b,c,d){l(this,a);this.start=b;this.end=c;this.bitrate=d}a.prototype.isNil=
function(){return this.start===this.end};a.prototype.clone=function(){return new a(this.start,this.end,this.bitrate)};return a}(),q=function(){function a(b){l(this,a);this.ranges=b=b?Array.isArray(b)?h(b):k(b):[];this.length=b.length}a.prototype.start=function(a){return this.ranges[a].start};a.prototype.end=function(a){return this.ranges[a].end};a.prototype.hasRange=function(a,b){for(var c=a+b,d=0;d<this.ranges.length;d++){var f=this.ranges[d],m=f.start,f=f.end;if(m-a<=p&&a-f<=p&&m-c<=p&&c-f<=p)return this.ranges[d]}return null};
a.prototype.getRange=function(a){for(var b=0;b<this.ranges.length;b++)if(f(this.ranges[b],a))return this.ranges[b];return null};a.prototype.getOuterRanges=function(a){for(var b=[],c=0;c<this.ranges.length;c++)f(this.ranges[c],a)||b.push(this.ranges[c]);return b};a.prototype.getGap=function(a){var b=this.getRange(a);return b?b.end-a:Infinity};a.prototype.getLoaded=function(a){var b=this.getRange(a);return b?a-b.start:0};a.prototype.getSize=function(a){return(a=this.getRange(a))?a.end-a.start:0};a.prototype.getNextRangeGap=
function(a){for(var b=this.ranges,c=-1,d=void 0;++c<b.length;){var f=b[c].start;if(f>a){d=f;break}}return null!=d?d-a:Infinity};a.prototype.insert=function(a,c,f){var h=this.ranges;a=new r(c,f,a);if(!a.isNil()){for(c=0;c<h.length;c++){f=h[c];var k=d(a,f),n=Math.abs(f.start-a.end)<p||Math.abs(f.end-a.start)<p;if(k||n)if(a.bitrate===f.bitrate)a=new r(Math.min(a.start,f.start),Math.max(a.end,f.end),f.bitrate),h.splice(c--,1);else if(k)if(b(f,a))h.splice(++c,0,a),k=f.end,f.end=a.start,a=new r(a.end,k,
f.bitrate);else if(b(a,f))h.splice(c--,1);else if(f.start<a.start)f.end=a.start;else{f.start=a.end;break}else break;else if(0===c){if(a.end<=h[0].start)break}else if(h[c-1].end<=a.start&&a.end<=f.start)break}h.splice(c,0,a);for(a=0;a<h.length;a++)h[a].isNil()&&h.splice(a++,1);m(h)}this.length=this.ranges.length;return this.ranges};a.prototype.remove=function(b,c){this.intersect(new a([new r(0,b,0),new r(c,Infinity,0)]))};a.prototype.equals=function(a){a:{var b=a.ranges;a=n(this.ranges);for(var b=
n(b),d=0;d<a.length;d++){var f=a[d],m=c(f,b);if(!(m&&Math.abs(m.start-f.start)<p&&Math.abs(m.end-f.end)<p)){a=!1;break a}}a=!0}return a};a.prototype.intersect=function(a){var b=this.ranges;a=a.ranges;for(var d=0;d<b.length;d++){var f=b[d],m=c(f,a);m?(m.start>f.start&&(f.start=m.start),m.end<f.end&&(f.end=m.end)):b.splice(d--,1)}this.length=this.ranges.length;return this.ranges};return a}()},function(e,g,a){a.d(g,"e",function(){return k});a.d(g,"d",function(){return h});a.d(g,"a",function(){return f});
a.d(g,"b",function(){return c});a.d(g,"c",function(){return d});a(1);var l=a(16),k=function(a,c,d){var b=a.presentationTimeOffset||0;a=a.timescale||1;return{up:c*a-b,to:(c+d)*a-b}},h=function(a){var b=a.ts,c=a.d;a=a.r;return-1===c?b:b+(a+1)*c},f=function(a,c){var b=c.initialization,b=void 0===b?{}:b;return new l.a({id:""+a+"_init",init:!0,range:b.range||null,indexRange:c.indexRage||null,media:b.media})},c=function(a,c){a.timescale!==c&&(a.timescale=c);return a},d=function(a,c){return c/a.timescale}},
function(e,g,a){function l(a){if(null!=a){var b;"string"===typeof a?(b=a,a=!1):(b=f(a.language),a=!!a.closedCaption);return{language:b,closedCaption:a}}}function k(a){if(null!=a){var b;"string"===typeof a?(b=a,a=!1):(b=f(a.language),a=!!a.audioDescription);return{language:b,audioDescription:a}}}function h(a,m){if(!m)return-1;m=f(m);for(var h=d;h<=b;h++)for(var k=0;k<a.length;k++){var n;n=f(a[k]);var e=m,g=h;if(n===e)n=!0;else{var p=n.split("-")[0],e=e.split("-")[0];n=g>=c.BASE_LANG_MATCH&&n===e?!0:
g>=c.OTHER_SUBLANG_MATCH&&p===e?!0:!1}if(n)return k}return-1}function f(a){if(null==a||""===a)return"";a=(""+a).toLowerCase().split("-");var b=a[0],c=void 0;2===b.length?c=m[b]:3===b.length&&(c=n[b]);(b=c||b)&&(a[0]=b);return a.join("-")}a.d(g,"c",function(){return f});a.d(g,"a",function(){return k});a.d(g,"b",function(){return l});a.d(g,"d",function(){return h});var c={PERFECT_MATCH:0,BASE_LANG_MATCH:1,OTHER_SUBLANG_MATCH:2},d=c.PERFECT_MATCH,b=c.OTHER_SUBLANG_MATCH,m={aa:"aar",ab:"abk",ae:"ave",
af:"afr",ak:"aka",am:"amh",an:"arg",ar:"ara",as:"asm",av:"ava",ay:"aym",az:"aze",ba:"bak",be:"bel",bg:"bul",bh:"bih",bi:"bis",bm:"bam",bn:"ben",bo:"bod",br:"bre",bs:"bos",ca:"cat",ce:"che",ch:"cha",co:"cos",cr:"cre",cs:"ces",cu:"chu",cv:"chv",cy:"cym",da:"dan",de:"deu",dv:"div",dz:"dzo",ee:"ewe",el:"ell",en:"eng",eo:"epo",es:"spa",et:"est",eu:"baq",fa:"fas",ff:"ful",fi:"fin",fj:"fij",fo:"fao",fr:"fre",fy:"fry",ga:"gle",gd:"gla",gl:"glg",gn:"grn",gu:"guj",gv:"glv",ha:"hau",he:"heb",hi:"hin",ho:"hmo",
hr:"hrv",ht:"hat",hu:"hun",hy:"arm",hz:"her",ia:"ina",id:"ind",ie:"ile",ig:"ibo",ii:"iii",ik:"ipk",io:"ido",is:"ice",it:"ita",iu:"iku",ja:"jpn",jv:"jav",ka:"geo",kg:"kon",ki:"kik",kj:"kua",kk:"kaz",kl:"kal",km:"khm",kn:"kan",ko:"kor",kr:"kau",ks:"kas",ku:"kur",kv:"kom",kw:"cor",ky:"kir",la:"lat",lb:"ltz",lg:"lug",li:"lim",ln:"lin",lo:"lao",lt:"lit",lu:"lub",lv:"lav",mg:"mlg",mh:"mah",mi:"mao",mk:"mac",ml:"mal",mn:"mon",mr:"mar",ms:"may",mt:"mlt",my:"bur",na:"nau",nb:"nob",nd:"nde",ne:"nep",ng:"ndo",
nl:"dut",nn:"nno",no:"nor",nr:"nbl",nv:"nav",ny:"nya",oc:"oci",oj:"oji",om:"orm",or:"ori",os:"oss",pa:"pan",pi:"pli",pl:"pol",ps:"pus",pt:"por",qu:"que",rm:"roh",rn:"run",ro:"ron",ru:"rus",rw:"kin",sa:"san",sc:"srd",sd:"snd",se:"sme",sg:"sag",si:"sin",sk:"slk",sl:"slv",sm:"smo",sn:"sna",so:"som",sq:"alb",sr:"srp",ss:"ssw",st:"sot",su:"sun",sv:"swe",sw:"swa",ta:"tam",te:"tel",tg:"tgk",th:"tha",ti:"tir",tk:"tuk",tl:"tgl",tn:"tsn",to:"ton",tr:"tur",ts:"tso",tt:"tat",tw:"twi",ty:"tah",ug:"uig",uk:"ukr",
ur:"urd",uz:"uzb",ve:"ven",vi:"vie",vo:"vol",wa:"wln",wo:"wol",xh:"xho",yi:"yid",yo:"yor",za:"zha",zh:"chi",zu:"zul"},n={tib:"bod",cze:"ces",wel:"cym",ger:"deu",gre:"ell",eus:"baq",per:"fas",fra:"fre",hye:"arm",isl:"ice",kat:"geo",mri:"mao",mkd:"mac",msa:"may",mya:"bur",nld:"dut",rum:"ron",slo:"slk",sqi:"alb",zho:"chi"}},function(e,g,a){var l=a(18),k=a(17),h=a(13),f=a(145);g.combineLatest=function(){for(var a=[],d=0;d<arguments.length;d++)a[d-0]=arguments[d];var b=d=null;l.isScheduler(a[a.length-
1])&&(b=a.pop());"function"===typeof a[a.length-1]&&(d=a.pop());1===a.length&&k.isArray(a[0])&&(a=a[0]);return(new h.ArrayObservable(a,b)).lift(new f.CombineLatestOperator(d))}},function(e,g,a){function l(a,c){if("function"!==typeof c&&null!==c)throw new TypeError("Super expression must either be null or a function, not "+typeof c);a.prototype=Object.create(c&&c.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}});c&&(Object.setPrototypeOf?Object.setPrototypeOf(a,c):a.__proto__=
c)}function k(a,c){if(!(a instanceof c))throw new TypeError("Cannot call a class as a function");}function h(a){return"number"==typeof a&&!isNaN(a)||!isNaN(+a)?!0:!1}a.d(g,"b",function(){return c});a.d(g,"a",function(){return d});var f=a(34),c=function(){function b(a,c,d,f,e,g,l,w,v,y){k(this,b);this.id=d;this.ada=a;this.rep=c;this.time=h(e)?+e:-1;this.duration=h(g)?+g:-1;this.number=h(l)?+l:-1;this.media=f?""+f:"";this.range=Array.isArray(w)?w:null;this.indexRange=Array.isArray(v)?v:null;this.init=
!!y}b.create=function(a,c,d,f,h,k,e,g,l,y){return new b(a,c,a.id+"_"+c.id+"_"+d,f,h,k,e,g,l,y)};b.prototype.getId=function(){return this.id};b.prototype.getAdaptation=function(){return this.ada};b.prototype.getRepresentation=function(){return this.rep};b.prototype.getTime=function(){return this.time};b.prototype.getDuration=function(){return this.duration};b.prototype.getNumber=function(){return this.number};b.prototype.getMedia=function(){return this.media};b.prototype.getRange=function(){return this.range};
b.prototype.getIndexRange=function(){return this.indexRange};b.prototype.isInitSegment=function(){return this.init};b.prototype.getResolvedURL=function(){return a.i(f.b)(this.ada.rootURL,this.ada.baseURL,this.rep.baseURL)};return b}(),d=function(a){function b(c,d,f,h,m){k(this,b);c=a.call(this,c,d,c.id+"_"+d.id+"_init",f,-1,-1,-1,h,m,!0);if(!this)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!c||"object"!==typeof c&&"function"!==typeof c?this:c}l(b,a);
return b}(c)},function(e,g,a){var l=a(25),k=a(32);e=function(){function h(){var f=this,c=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};if(!(this instanceof h))throw new TypeError("Cannot call a class as a function");var d=a.i(k.a)();this.id=null==c.id?d:""+c.id;this.type=c.type||"";this.representations=Array.isArray(c.representations)?c.representations.map(function(a){return new l.a(Object.assign({rootId:f.id},a))}).sort(function(a,c){return a.bitrate-c.bitrate}):[];null!=c.lang?this.language=
c.lang:null!=c.language&&(this.language=c.language);d=c.accessibility;Array.isArray(d)&&(d.includes("audioDescription")&&(this.isAudioDescription=!0),d.includes("closedCaption")&&(this.isClosedCaption=!0));this.manual=c.manual}h.prototype.getAvailableBitrates=function(){return this.representations.map(function(a){return a.bitrate})};h.prototype.getRepresentationsForBitrate=function(a){return this.representations.filter(function(c){return c.bitrate===a})||null};return h}();g.a=e},function(e,g,a){var l=
a(32),k=a(115);g.a=function f(){var c=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};if(!(this instanceof f))throw new TypeError("Cannot call a class as a function");var d=a.i(l.a)();this.id=null==c.id?d:c.id;this.bitrate=c.bitrate;this.codec=c.codecs;null!=c.height&&(this.height=c.height);null!=c.width&&(this.width=c.width);null!=c.mimeType&&(this.mimeType=c.mimeType);this.index=new k.a({index:c.index,rootId:(null==c.rootId?"":c.rootId+"_")+this.id})}},function(e,g,a){e=a(59);a=a(60);
g.async=new a.AsyncScheduler(e.AsyncAction)},function(e,g,a){g.errorObject={e:{}}},function(e,g,a){var l=a(23);e=function(){function a(h,f,c){if(!(this instanceof a))throw new TypeError("Cannot call a class as a function");this.adaptation=h;this.representation=f;this.index=c}a.getRangeEnd=function(a){var f=a.ts,c=a.d;a=a.r;return-1===c?f:f+(a+1)*c};a.getLiveEdge=function(h,f){var c=a.getRangeEnd(h.timeline[h.timeline.length-1])/h.timescale-f.suggestedPresentationDelay;return Math.max(h.timeline[0].ts/
h.timescale+1,c)};a.prototype.createSegment=function(a,f,c){return l.b.create(this.adaptation,this.representation,a,this.index.media,a,c,0,f,null,!1)};a.prototype.calculateRepeat=function(a,f){var c=a.r||0;0>c&&(c=Math.ceil(((f?f.t:Infinity)-a.ts)/a.d)-1);return c};a.prototype.checkDiscontinuity=function(h){var f=this.index.timeline;if(0>=h)return-1;var c=this.getSegmentIndex(h);if(0>c||c>=f.length-1)return-1;var d=f[c];if(-1===d.d)return-1;var b=d.ts,d=a.getRangeEnd(d),f=f[c+1],c=this.index.timescale||
1;return d!==f.ts&&h>=b&&h<=d&&d-h<c?f.ts:-1};a.prototype.checkRange=function(h,f,c){h=this.index.timeline;h=h[h.length-1];if(!h)return!0;0>h.d&&(h={ts:h.ts,d:0,r:h.r});return c<=a.getRangeEnd(h)};a.prototype.getSegmentIndex=function(a){for(var f=this.index.timeline,c=0,d=f.length;c<d;){var b=c+d>>>1;f[b].ts<a?c=b+1:d=b}return 0<c?c-1:c};a.prototype.getSegmentNumber=function(a,f,c){a=f-a;return 0<a?Math.floor(a/c):0};a.prototype.getSegments=function(a,f){var c=this.index.timeline,d=[],b=c.length,
m=this.getSegmentIndex(a)-1,h=c.length&&c[0].d||0;a:for(;!(++m>=b);){var k=c[m],e=k.d,g=k.ts,l=k.range,h=Math.max(h,e);if(0>e){g+h<f&&d.push(this.createSegment(g,l,void 0));break}for(var k=this.calculateRepeat(k,c[m+1]),t=this.getSegmentNumber(g,a,e),w;(w=g+t*e)<f;)if(t++<=k)d.push(this.createSegment(w,l,e));else continue a;break}return d};a.prototype.addSegment=function(h,f){var c=this.index.timeline,d=c.length,b=c[d-1];if(f&&h.ts===f.ts){var m=h.ts+h.d,k=m-(b.ts+b.d*b.r);if(0>=k)return!1;-1===b.d&&
((d=c[d-2])&&d.d===k?(d.r++,c.pop()):b.d=k);c.push({d:-1,ts:m,r:0});return!0}return h.ts>=a.getRangeEnd(b)?(b.d===h.d?b.r++:c.push({d:h.d,ts:h.ts,r:0}),!0):!1};return a}();g.a=e},function(e,g,a){function l(b){var c=a.i(y.a)(b.locations[0]);(b=b.periods[0])&&b.baseURL&&(c+=""+b.baseURL);return c}function k(a,b,f,k){if(!b.transportType)throw new B.d("MANIFEST_PARSE_ERROR",null,!0);b.id=b.id||C++;b.type=b.type||"static";var e=b.locations;e&&e.length||(b.locations=[a]);b.isLive="dynamic"==b.type;var n=
{rootURL:l(b),baseURL:b.baseURL,isLive:b.isLive};f&&(f=c(f));k&&(k=d(k));a=b.periods.map(function(a){return h(a,n,f,k)});b=m(b,a[0]);b.periods=null;b.duration||(b.duration=Infinity);b.isLive&&(b.suggestedPresentationDelay=b.suggestedPresentationDelay||D,b.availabilityStartTime=b.availabilityStartTime||0);return b}function h(a,b,c,d){a.id=a.id||C++;var m=a.adaptations,m=m.concat(c||[]),m=m.concat(d||[]),m=m.map(function(a){return f(a,b)}),m=m.filter(function(a){return 0>H.indexOf(a.type)?(v.a.info("not supported adaptation type",
a.type),!1):!0});if(0===m.length)throw new B.d("MANIFEST_PARSE_ERROR",null,!0);c={};for(d=0;d<m.length;d++){var h=m[d],k=h.type,e=h.representations;c[k]=c[k]||[];0<e.length&&c[k].push(h)}for(var n in c)if(0===c[n].length)throw new B.d("MANIFEST_INCOMPATIBLE_CODECS_ERROR",null,!0);a.adaptations=c;return a}function f(b,c){if("undefined"==typeof b.id)throw new B.d("MANIFEST_PARSE_ERROR",null,!0);var d=m(c,b),f={};G.forEach(function(a){a in d&&(f[a]=d[a])});var h=d.representations.map(function(a){if("undefined"==
typeof a.id)throw new B.d("MANIFEST_PARSE_ERROR",null,!0);a=m(f,a);a.index=a.index||{};a.index.timescale||(a.index.timescale=1);a.bitrate||(a.bitrate=1);"mp4a.40.02"==a.codecs&&(a.codecs="mp4a.40.2");return a}).sort(function(a,b){return a.bitrate-b.bitrate}),k=d.type,e=d.accessibility,e=void 0===e?[]:e;if(!k)throw new B.d("MANIFEST_PARSE_ERROR",null,!0);"video"==k||"audio"==k?(h=h.filter(function(b){return a.i(u.k)(r(b))}),"audio"===k&&(k=e.includes("visuallyImpaired"),d.audioDescription=k)):"text"===
k&&(k=e.includes("hardOfHearing"),d.closedCaption=k);d.representations=h;d.bitrates=h.map(function(a){return a.bitrate});return d}function c(a){Array.isArray(a)||(a=[a]);return a.reduce(function(a,b){var c=b.mimeType,d=b.url,f=b.language,m=b.languages,h=b.closedCaption;f&&(m=[f]);return a.concat(m.map(function(a){return{id:C++,type:"text",lang:a,closedCaption:!!h,baseURL:d,representations:[{id:C++,mimeType:c,index:{indexType:"template",duration:Number.MAX_VALUE,timescale:1,startNumber:0}}]}}))},[])}
function d(a){Array.isArray(a)||(a=[a]);return a.map(function(a){var b=a.mimeType;a=a.url;return{id:C++,type:"image",baseURL:a,representations:[{id:C++,mimeType:b,index:{indexType:"template",duration:Number.MAX_VALUE,timescale:1,startNumber:0}}]}})}function b(a,c){for(var d in a)if(c.hasOwnProperty(d)){var f=a[d],m=c[d];"string"==typeof f||"number"==typeof f||"object"==("undefined"===typeof f?"undefined":z(f))&&f instanceof Date?a[d]=m:Array.isArray(f)?(f.length=0,Array.prototype.push.apply(f,m)):
a[d]=b(f,m)}return a}function m(){for(var a={},b=arguments.length,c=Array(b),d=0;d<b;d++)c[d]=arguments[d];for(b=c.length-1;0<=b;b--){var d=c[b],f;for(f in d)if(!a.hasOwnProperty(f)){var h=d[f];h&&"object"===("undefined"===typeof h?"undefined":z(h))?h instanceof Date?a[f]=new Date(h.getTime()):Array.isArray(h)?a[f]=h.slice(0):a[f]=m(h):a[f]=h}}return a}function n(a,c){var d=a.adaptations,f=c.adaptations,m=function(a){var c=f[a];d[a].forEach(function(a,d){a.representations.forEach(function(a,f){b(a.index,
c[d].representations[f].index)})})},h;for(h in d)m(h);return a}function p(a){var b=1<arguments.length&&void 0!==arguments[1]?arguments[1]:1;a.isLive&&(a.presentationLiveGap+=b)}function r(a){return a.mimeType+';codecs="'+a.codecs+'"'}function q(a){a=a.adaptations;if(!a)return[];var b=[],c;for(c in a){var d=a[c];b.push({type:c,adaptations:d,codec:r(d[0].representations[0])})}return b}function x(a,b){var c=a.adaptations;return(c=c&&c[b])?c:[]}function t(b){return x(b,"audio").map(function(b){return{language:a.i(A.c)(b.lang),
audioDescription:b.audioDescription,id:b.id}})}function w(b){return x(b,"text").map(function(b){return{language:a.i(A.c)(b.lang),closedCaption:b.closedCaption,id:b.id}})}a.d(g,"d",function(){return k});a.d(g,"e",function(){return n});a.d(g,"f",function(){return p});a.d(g,"g",function(){return q});a.d(g,"c",function(){return x});a.d(g,"b",function(){return w});a.d(g,"a",function(){return t});var v=a(3),y=a(34),u=a(9),B=a(4),A=a(21),z="function"===typeof Symbol&&"symbol"===typeof Symbol.iterator?function(a){return typeof a}:
function(a){return a&&"function"===typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a},G="audioSamplingRate codecs codingDependency frameRate height index maxPlayoutRate maximumSAPPeriod mimeType profiles segmentProfiles width".split(" "),C=0,H=["audio","video","text","image"],D=15},function(e,g,a){var l=a(16),k=a(20),h=function(a,c){for(var d=a.timeline,b=0,f=d.length;b<f;){var h=b+f>>>1;d[h].ts<c?b=h+1:f=h}return 0<b?b-1:b};g.a={getInitSegment:k.a,setTimescale:k.b,scale:k.c,
getSegments:function(f,c,d,b){b=a.i(k.e)(c,d,b);d=b.up;b=b.to;var m=c.timeline,e=c.timescale,g=[],r=m.length;c=h(c,d)-1;var q=m.length&&m[0].d||0;a:for(;!(++c>=r);){var x=m[c],t=x.d,w=x.ts,v=x.range,q=Math.max(q,t);if(0>t){w+q<b&&g.push(new l.a({id:""+f+"_"+w,time:w,init:!1,range:v,duration:void 0,indexRange:null,timescale:e}));break}var y=m[c+1],u=x.r||0;0>u&&(u=Math.ceil(((y?y.t:Infinity)-x.ts)/x.d)-1);x=u;y=d-w;y=0<y?Math.floor(y/t):0;for(;(u=w+y*t)<b;)if(y++<=x)g.push(new l.a({id:""+f+"_"+u,time:u,
init:!1,range:v,duration:t,indexRange:null,timescale:e}));else continue a;break}return g},shouldRefresh:function(f,c,d,b){f=f.timeline;f=f[f.length-1];if(!f)return!0;0>f.d&&(f={ts:f.ts,d:0,r:f.r});return!(b<=a.i(k.d)(f))},getFirstPosition:function(a){if(a.timeline.length)return a.timeline[0].ts/a.timescale},getLastPosition:function(f){if(f.timeline.length){var c=f.timeline[f.timeline.length-1];return a.i(k.d)(c)/f.timescale}},checkDiscontinuity:function(f,c){var d=f.timeline,b=f.timescale,b=void 0===
b?1:b,m=c*b;if(0>=m)return-1;var e=h(m);if(0>e||e>=d.length-1)return-1;var g=d[e];if(-1===g.d)return-1;var l=g.ts,g=a.i(k.d)(g),d=d[e+1];return g!==d.ts&&m>=l&&m<=g&&g-m<b?d.ts/b:-1},_addSegmentInfos:function(f,c,d){var b=f.timeline,m=b.length,h=b[m-1];if(d&&c.time===d.time){if(c=c.time+c.duration,d=c-(h.ts+h.d*h.r),!(0>=d))return-1===h.d&&((m=b[m-2])&&m.d===d?(m.r++,b.pop()):h.d=d),f.timeline.push({d:-1,ts:c,r:0}),f}else if(c.time>=a.i(k.d)(h))return h.d===c.duration?h.r++:f.timeline.push({d:c.duration,
ts:c.time,r:0}),f}}},function(e,g,a){function l(){this.__listeners={}}var k=a(1);l.prototype.addEventListener=function(h,f){a.i(k.a)("function"==typeof f,"eventemitter: second argument should be a function");this.__listeners[h]||(this.__listeners[h]=[]);this.__listeners[h].push(f)};l.prototype.removeEventListener=function(a,f){if(0===arguments.length)this.__listeners={};else if(this.__listeners.hasOwnProperty(a))if(1===arguments.length)delete this.__listeners[a];else{var c=this.__listeners[a],d=c.indexOf(f);
~d&&c.splice(d,1);c.length||delete this.__listeners[a]}};l.prototype.trigger=function(a,f){this.__listeners.hasOwnProperty(a)&&this.__listeners[a].slice().forEach(function(a){try{a(f)}catch(d){console.error(d,d.stack)}})};l.prototype.on=l.prototype.addEventListener;l.prototype.off=l.prototype.removeEventListener;g.a=l},function(e,g,a){var l=0;g.a=function(){var a=0;l<Number.MAX_VALUE&&(a=l+1);l=a;return""+a}},function(e,g,a){function l(a,b){var c=0;return function(){c&&clearTimeout(c);c=setTimeout(a,
b)}}function k(d,b){var h=b.retryDelay,k=b.totalRetry,e=b.shouldRetry,g=b.resetDelay,q=b.errorSelector,x=b.onRetry,t=0,w=void 0;0<g&&(w=l(function(){return t=0},g));return d["catch"](function(b,d){if(e&&!e(b)||t++>=k){if(q)throw q(b,t);throw b;}x&&x(b,t);var m=a.i(f.a)(h,t);return c(m).mergeMap(function(){w&&w();return d})})}function h(d,b){var h=b.retryDelay,k=b.totalRetry,e=b.shouldRetry,g=b.resetDelay,q=b.errorSelector,x=b.onRetry,t=0,w=void 0;0<g&&(w=l(function(){return t=0},g));return function y(){for(var b=
arguments.length,m=Array(b),n=0;n<b;n++)m[n]=arguments[n];return d.apply(void 0,m)["catch"](function(b){if(e&&!e(b)||t++>=k){if(q)throw q(b,t);throw b;}x&&x(b,t);b=a.i(f.a)(h,t);return c(b).mergeMap(function(){w&&w();return y.apply(void 0,m)})})}}a.d(g,"a",function(){return k});a.d(g,"b",function(){return h});var f=a(128);e=a(56);a.n(e);var c=e.TimerObservable.create},function(e,g,a){function l(){for(var a=arguments.length,d=Array(a),b=0;b<a;b++)d[b]=arguments[b];a=d.length;if(0===a)return"";for(var b=
"",m=0;m<a;m++){var k=d[m];"string"===typeof k&&""!==k&&(h.test(k)?b=k:("/"===k[0]&&(k=k.substr(1)),"/"===b[b.length-1]&&(b=b.substr(0,b.length-1)),b=b+"/"+k))}a=b;if(f.test(a)){d=[];a=a.split("/");b=0;for(m=a.length;b<m;b++)".."==a[b]?d.pop():"."!=a[b]&&d.push(a[b]);d=d.join("/")}else d=a;return d}function k(a){var c=a.lastIndexOf("/");return 0<=c?a.substring(0,c+1):a}a.d(g,"b",function(){return l});a.d(g,"a",function(){return k});var h=/^(?:[a-z]+:)?\/\//i,f=/\/\.{1,2}\//},function(e,g,a){var l=
this&&this.__extends||function(a,f){function c(){this.constructor=a}for(var d in f)f.hasOwnProperty(d)&&(a[d]=f[d]);a.prototype=null===f?Object.create(f):(c.prototype=f.prototype,new c)};e=a(8);var k=a(61);a=function(a){function f(c){a.call(this);this._value=c}l(f,a);Object.defineProperty(f.prototype,"value",{get:function(){return this.getValue()},enumerable:!0,configurable:!0});f.prototype._subscribe=function(c){var d=a.prototype._subscribe.call(this,c);d&&!d.closed&&c.next(this._value);return d};
f.prototype.getValue=function(){if(this.hasError)throw this.thrownError;if(this.closed)throw new k.ObjectUnsubscribedError;return this._value};f.prototype.next=function(c){a.prototype.next.call(this,this._value=c)};return f}(e.Subject);g.BehaviorSubject=a},function(e,g,a){var l=this&&this.__extends||function(a,h){function f(){this.constructor=a}for(var c in h)h.hasOwnProperty(c)&&(a[c]=h[c]);a.prototype=null===h?Object.create(h):(f.prototype=h.prototype,new f)};e=function(a){function h(f,c){a.call(this);
this.value=f;this.scheduler=c;this._isScalar=!0;c&&(this._isScalar=!1)}l(h,a);h.create=function(a,c){return new h(a,c)};h.dispatch=function(a){var c=a.value,d=a.subscriber;a.done?d.complete():(d.next(c),d.closed||(a.done=!0,this.schedule(a)))};h.prototype._subscribe=function(a){var c=this.value,d=this.scheduler;if(d)return d.schedule(h.dispatch,0,{done:!1,value:c,subscriber:a});a.next(c);a.closed||a.complete()};return h}(a(0).Observable);g.ScalarObservable=e},function(e,g,a){var l=this&&this.__extends||
function(a,d){function b(){this.constructor=a}for(var c in d)d.hasOwnProperty(c)&&(a[c]=d[c]);a.prototype=null===d?Object.create(d):(b.prototype=d.prototype,new b)};e=a(12);var k=a(15);g.mergeAll=function(a){void 0===a&&(a=Number.POSITIVE_INFINITY);return this.lift(new h(a))};var h=function(){function a(a){this.concurrent=a}a.prototype.call=function(a,b){return b._subscribe(new f(a,this.concurrent))};return a}();g.MergeAllOperator=h;var f=function(a){function c(b,c){a.call(this,b);this.concurrent=
c;this.hasCompleted=!1;this.buffer=[];this.active=0}l(c,a);c.prototype._next=function(a){this.active<this.concurrent?(this.active++,this.add(k.subscribeToResult(this,a))):this.buffer.push(a)};c.prototype._complete=function(){this.hasCompleted=!0;0===this.active&&0===this.buffer.length&&this.destination.complete()};c.prototype.notifyComplete=function(a){var b=this.buffer;this.remove(a);this.active--;0<b.length?this._next(b.shift()):0===this.active&&this.hasCompleted&&this.destination.complete()};return c}(e.OuterSubscriber);
g.MergeAllSubscriber=f},function(e,g,a){var l=a(136);g.multicast=function(a,f){var c;c="function"===typeof a?a:function(){return a};if("function"===typeof f)return this.lift(new k(c,f));var d=Object.create(this,l.connectableObservableDescriptor);d.source=this;d.subjectFactory=c;return d};var k=function(){function a(a,c){this.subjectFactory=a;this.selector=c}a.prototype.call=function(a,c){var d=this.selector,b=new l.ConnectableObservable(c.source,this.subjectFactory),d=d(b).subscribe(a);d.add(b.connect());
return d};return a}();g.MulticastOperator=k},function(e,g,a){e=a(7);a=e.root.Symbol;if("function"===typeof a)a.iterator?g.$$iterator=a.iterator:"function"===typeof a["for"]&&(g.$$iterator=a["for"]("iterator"));else if(e.root.Set&&"function"===typeof(new e.root.Set)["@@iterator"])g.$$iterator="@@iterator";else if(e.root.Map){a=Object.getOwnPropertyNames(e.root.Map.prototype);for(var l=0;l<a.length;++l){var k=a[l];if("entries"!==k&&"size"!==k&&e.root.Map.prototype[k]===e.root.Map.prototype.entries){g.$$iterator=
k;break}}}else g.$$iterator="@@iterator"},function(e,g,a){function l(a){var h=a.Symbol;"function"===typeof h?h.observable?a=h.observable:(a=h("observable"),h.observable=a):a="@@observable";return a}e=a(7);g.getSymbolObservable=l;g.$$observable=l(e.root)},function(e,g,a){e=a(7).root.Symbol;g.$$rxSubscriber="function"===typeof e&&"function"===typeof e["for"]?e["for"]("rxSubscriber"):"@@rxSubscriber"},function(e,g,a){g.isFunction=function(a){return"function"===typeof a}},function(e,g,a){function l(){try{return h.apply(this,
arguments)}catch(f){return k.errorObject.e=f,k.errorObject}}var k=a(27),h;g.tryCatch=function(a){h=a;return l}},function(e,g,a){function l(a,b){if(!a)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!b||"object"!==typeof b&&"function"!==typeof b?a:b}function k(a,b){if("function"!==typeof b&&null!==b)throw new TypeError("Super expression must either be null or a function, not "+typeof b);a.prototype=Object.create(b&&b.prototype,{constructor:{value:a,enumerable:!1,
writable:!0,configurable:!0}});b&&(Object.setPrototypeOf?Object.setPrototypeOf(a,b):a.__proto__=b)}function h(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function");}function f(a){if("number"==typeof a)return a;for(var b=0,c,d=0;d<a.length;d++)c=a[d],b=(b<<5)-b+c,b&=b;return b}function c(a,b,c){return{type:"eme",value:Object.assign({name:a,session:b},c)}}function d(b){if(!X||!J||a.i(D.g)())return null;var c=O;return(b=b.filter(function(a){return a.type!==X.type||a.persistentLicense&&
"required"!=c.persistentState||a.distinctiveIdentifierRequired&&"required"!=c.distinctiveIdentifier?!1:!0})[0])?{keySystem:b,keySystemAccess:new D.h(X,J,O)}:null}function b(a){var b=["temporary"],c="optional",d="optional";a.persistentLicense&&(c="required",b.push("persistent-license"));a.persistentStateRequired&&(c="required");a.distinctiveIdentifierRequired&&(d="required");var f=[],m=[];R.forEach(function(a){f.push({contentType:'video/mp4;codecs="avc1.4d401e"',robustness:a});m.push({contentType:'audio/mp4;codecs="mp4a.40.2"',
robustness:a})});return{initDataTypes:["cenc"],videoCapabilities:f,audioCapabilities:m,distinctiveIdentifier:d,persistentState:c,sessionTypes:b}}function m(c){var f=d(c);if(f)return u.a.debug("eme: found compatible keySystem quickly",f),G.Observable.of(f);var m=c.reduce(function(a,b){return a.concat((I[b.type]||[]).map(function(a){return{keyType:a,keySystem:b}}))},[]);return G.Observable.create(function(c){function d(k){if(!f)if(k>=m.length)c.error(new E.c("INCOMPATIBLE_KEYSYSTEMS",null,!0));else{var e=
m[k],n=e.keyType,g=e.keySystem,p=[b(g)];u.a.debug("eme: request keysystem access "+n+","+(k+1+" of "+m.length),p);h=a.i(D.i)(n,p).subscribe(function(a){u.a.info("eme: found compatible keysystem",n,p);c.next({keySystem:g,keySystemAccess:a});c.complete()},function(){u.a.debug("eme: rejected access to keysystem",n,p);h=null;d(k+1)})}}var f=!1,h=null;d(0);return function(){f=!0;h&&h.unsubscribe()}})}function n(b,c,d){var f=U,m=J;return a.i(A.b)(d.createMediaKeys()).mergeMap(function(h){J=h;O=d.getConfiguration();
X=c;U=b;if(b.mediaKeys===h)return G.Observable.of(h);m&&m!==J&&M.dispose();var k;f&&f!==U?(u.a.debug("eme: unlink old video element and set mediakeys"),k=a.i(D.j)(f,null).concat(a.i(D.j)(U,h))):(u.a.debug("eme: set mediakeys"),k=a.i(D.j)(U,h));return k.mapTo(h)})}function p(a,b,c,d,f){u.a.debug("eme: create a new "+b+" session");var m=a.createSession(b);a=t(m,c,f)["finally"](function(){M.deleteAndClose(m);K["delete"](d)}).publish();return{session:m,sessionEvents:a}}function r(b,d,f,m,h,k){b=p(b,f,
d,h,k);var e=b.session;b=b.sessionEvents;M.add(h,e,b);u.a.debug("eme: generate request",m,h);m=a.i(A.b)(e.generateRequest(m,h))["catch"](function(a){throw new E.c("KEY_GENERATE_REQUEST_ERROR",a,!1);})["do"](function(){"persistent-license"==f&&K.add(h,e)}).mapTo(c("generated-request",e,{initData:h,initDataType:m}));return a.i(H.merge)(b,m)}function q(a,b,c,d,f,m){return r(a,b,c,d,f,m)["catch"](function(h){if(h.code!==E.b.KEY_GENERATE_REQUEST_ERROR)throw h;var k=M.getFirst();if(!k)throw h;u.a.warn("eme: could not create a new session, retry after closing a currently loaded session",
h);return M.deleteAndClose(k).mergeMap(function(){return r(a,b,c,d,f,m)})})}function x(b,d,f,m,h,k){u.a.debug("eme: load persisted session",f);var e=p(b,"persistent-license",d,h,k),n=e.session,g=e.sessionEvents;return a.i(A.b)(n.load(f))["catch"](function(){return G.Observable.of(!1)}).mergeMap(function(a){if(a)return M.add(h,n,g),K.add(h,n),g.startWith(c("loaded-session",n,{storedSessionId:f}));u.a.warn("eme: no data stored for the loaded session, do fallback",f);M.deleteById(f);K["delete"](h);n.sessionId&&
n.remove();return q(b,d,"persistent-license",m,h,k).startWith(c("loaded-session-failed",n,{storedSessionId:f}))})}function t(b,d,f){function h(a,b){return a.type===E.a.ENCRYPTED_MEDIA_ERROR?(a.fatal=b,a):new E.c("KEY_LOAD_ERROR",a,b)}u.a.debug("eme: handle message events",b);var m=void 0,k={totalRetry:2,retryDelay:200,errorSelector:function(a){return h(a,!0)},onRetry:function(a){return f.next(h(a,!1))}},e=S(b).map(function(a){throw new E.c("KEY_ERROR",a,!0);}),n=V(b).mergeMap(function(c){m=c.sessionId;
u.a.debug("eme: keystatuseschange event",m,b,c);b.keyStatuses.forEach(function(a,b){if(N[b]||N[a])throw new E.c("KEY_STATUS_CHANGE_ERROR",b,!0);});return d.onKeyStatusesChange?a.i(A.c)(function(){return a.i(A.b)(d.onKeyStatusesChange(c,b))})["catch"](function(a){throw new E.c("KEY_STATUS_CHANGE_ERROR",a,!0);}):(u.a.info("eme: keystatuseschange event not handled"),Y())}),g=T(b).mergeMap(function(c){m=c.sessionId;var f=new Uint8Array(c.message),h=c.messageType||"license-request";u.a.debug("eme: event message type "+
h,b,c);c=F(function(){return a.i(A.b)(d.getLicense(f,h)).timeout(1E4,new E.c("KEY_LOAD_TIMEOUT",null,!1))});return a.i(z.a)(c,k)}),n=a.i(H.merge)(g,n).concatMap(function(d){u.a.debug("eme: update session",m,d);return a.i(A.b)(b.update(d,m))["catch"](function(a){throw new E.c("KEY_UPDATE_ERROR",a,!0);}).mapTo(c("session-update",b,{updatedWith:d}))}),e=a.i(H.merge)(n,e);return b.closed?e.takeUntil(a.i(A.b)(b.closed)):e}function w(b,d,f){function h(a,d){var h=d.keySystem,m=d.keySystemAccess;h.persistentLicense&&
K.setStorage(h.licenseStorage);u.a.info("eme: encrypted event",a);return n(b,h,m).mergeMap(function(b){a:{var d=m.getConfiguration(),k=a.initDataType,e=new Uint8Array(a.initData),n=M.get(e);if(n&&n.sessionId)u.a.debug("eme: reuse loaded session",n.sessionId),b=G.Observable.of(c("reuse-session",n));else{d=(n=(d=d.sessionTypes)&&0<=d.indexOf("persistent-license"))&&h.persistentLicense?"persistent-license":"temporary";if(n&&h.persistentLicense&&(n=K.get(e))){b=x(b,h,n.sessionId,k,e,f);break a}b=q(b,
h,d,k,e,f)}}return b})}return a.i(C.combineLatest)(L(b),m(d)).take(1).mergeMap(function(a){return h(a[0],a[1])})}function v(){return X&&X.type}function y(){U&&a.i(D.j)(U,null).subscribe(function(){});U=X=J=null;M.dispose()}a.d(g,"c",function(){return w});a.d(g,"b",function(){return v});a.d(g,"d",function(){return L});a.d(g,"a",function(){return y});var u=a(3),B=a(1),A=a(11),z=a(33),G=a(0);a.n(G);e=a(6);a.n(e);g=a(53);a.n(g);var C=a(22);a.n(C);var H=a(14);a.n(H);var D=a(9),E=a(4),L=D.f.onEncrypted,
T=D.f.onKeyMessage,S=D.f.onKeyError,V=D.f.onKeyStatusesChange,Y=e.EmptyObservable.create,F=g.DeferObservable.create,I={clearkey:["webkit-org.w3.clearkey","org.w3.clearkey"],widevine:["com.widevine.alpha"],playready:["com.microsoft.playready","com.chromecast.playready","com.youtube.playready"]},R=["HW_SECURE_ALL","HW_SECURE_DECODE","HW_SECURE_CRYPTO","SW_SECURE_DECODE","SW_SECURE_CRYPTO"],N={expired:!0,"internal-error":!0};e=function(){function a(){h(this,a);this._entries=[]}a.prototype.find=function(a){for(var b=
0;b<this._entries.length;b++)if(!0===a(this._entries[b]))return this._entries[b];return null};return a}();g=function(b){function c(){h(this,c);return l(this,b.apply(this,arguments))}k(c,b);c.prototype.getFirst=function(){if(0<this._entries.length)return this._entries[0].session};c.prototype.find=function(a){for(var b=0;b<this._entries.length;b++)if(!0===a(this._entries[b]))return this._entries[b];return null};c.prototype.get=function(a){a=f(a);var b=this.find(function(b){return b.initData===a});return b?
b.session:null};c.prototype.add=function(a,b,c){a=f(a);var d=this.get(a);d&&this.deleteAndClose(d);c=c.connect();a={session:b,initData:a,eventSubscription:c};u.a.debug("eme-mem-store: add session",a);this._entries.push(a)};c.prototype.deleteById=function(a){var b=this.find(function(b){return b.session.sessionId===a});return b?this["delete"](b.session):null};c.prototype["delete"]=function(a){var b=this.find(function(b){return b.session===a});if(!b)return null;var c=b.session,d=b.eventSubscription;
u.a.debug("eme-mem-store: delete session",b);b=this._entries.indexOf(b);this._entries.splice(b,1);d.unsubscribe();return c};c.prototype.deleteAndClose=function(b){return(b=this["delete"](b))?(u.a.debug("eme-mem-store: close session",b),a.i(A.b)(b.close())["catch"](function(){return G.Observable.of(null)})):G.Observable.of(null)};c.prototype.dispose=function(){var a=this,b=this._entries.map(function(b){return a.deleteAndClose(b.session)});this._entries=[];return H.merge.apply(null,b)};return c}(e);
var K=new (function(b){function c(a){h(this,c);var d=l(this,b.call(this));d.setStorage(a);return d}k(c,b);c.prototype.setStorage=function(b){if(this._storage!==b){a.i(B.a)(b,"no licenseStorage given for keySystem with persistentLicense");B.a.iface(b,"licenseStorage",{save:"function",load:"function"});this._storage=b;try{this._entries=this._storage.load(),a.i(B.a)(Array.isArray(this._entries))}catch(ea){u.a.warn("eme-persitent-store: could not get entries from license storage",ea),this.dispose()}}};
c.prototype.get=function(a){a=f(a);return this.find(function(b){return b.initData===a})||null};c.prototype.add=function(a,b){var c=b&&b.sessionId;if(c){a=f(a);var d=this.get(a);d&&d.sessionId===c||(d&&this["delete"](a),u.a.info("eme-persitent-store: add new session",c,b),this._entries.push({sessionId:c,initData:a}),this._save())}};c.prototype["delete"]=function(a){a=f(a);var b=this.find(function(b){return b.initData===a});b&&(u.a.warn("eme-persitent-store: delete session from store",b),b=this._entries.indexOf(b),
this._entries.splice(b,1),this._save())};c.prototype.dispose=function(){this._entries=[];this._save()};c.prototype._save=function(){try{this._storage.save(this._entries)}catch(Q){u.a.warn("eme-persitent-store: could not save licenses in localStorage")}};return c}(e))({load:function(){return[]},save:function(){}}),M=new g,J=void 0,O=void 0,X=void 0,U=void 0},function(e,g,a){function l(a){a=a.indexType;switch(a){case "template":return c.a;case "timeline":return d.a;case "list":return b.a;case "base":return m.a;
case "smooth":return n.a;default:throw new p.g("UNKNOWN_INDEX",a,!0);}}function k(b){var c=a.i(h.c)(b,"video")[0].representations[0].index;return l(c).getLiveEdge(c,b)}a.d(g,"b",function(){return r});a.d(g,"a",function(){return k});a(1);var h=a(29),f=a(23),c=a(103),d=a(28),b=a(101),m=a(100),n=a(102),p=a(4),r=function(){function a(b,c){if(!(this instanceof a))throw new TypeError("Cannot call a class as a function");this.adaptation=b;this.representation=c;this.index=c.index;this.handler=new (l(this.index))(b,
c,this.index)}a.prototype.getInitSegment=function(){var a=this.index.initialization||{};return new f.a(this.adaptation,this.representation,a.media,a.range,this.index.indexRange)};a.prototype._normalizeRange=function(a,b,c){var d=this.index.presentationTimeOffset||0,f=this.index.timescale||1;b||(b=0);c||(c=0);b=Math.min(b,c);return{time:a*f-d,up:(a+b)*f-d,to:(a+c)*f-d}};a.prototype.checkDiscontinuity=function(a){if(!this.adaptation.isLive)return null;var b=this.index.timescale||1;a=this.handler.checkDiscontinuity(a*
b);return 0<a?{ts:a/b+1}:null};a.prototype.getSegments=function(a,b,c){a=this._normalizeRange(a,b,c);b=a.up;c=a.to;if(!this.handler.checkRange(a.time,b,c))throw new p.g("OUT_OF_INDEX_ERROR",this.index.indexType,!1);return this.handler.getSegments(b,c)};a.prototype.insertNewSegments=function(a,b){for(var c=[],d=0;d<a.length;d++)this.handler.addSegment(a[d],b)&&c.push(a[d]);return c};a.prototype.setTimescale=function(a){var b=this.index;return b.timescale!==a?(b.timescale=a,!0):!1};a.prototype.scale=
function(a){return a/this.index.timescale};return a}()},function(e,g,a){function l(a,b){if("function"!==typeof b&&null!==b)throw new TypeError("Super expression must either be null or a function, not "+typeof b);a.prototype=Object.create(b&&b.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}});b&&(Object.setPrototypeOf?Object.setPrototypeOf(a,b):a.__proto__=b)}a.d(g,"a",function(){return c});e=a(31);var k=a(19),h=a(1),f=a(11),c=function(c){function b(a){if(!(this instanceof
b))throw new TypeError("Cannot call a class as a function");var d;d=c.call(this);if(!this)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");d=!d||"object"!==typeof d&&"function"!==typeof d?this:d;d.codec=a;d.updating=!1;d.readyState="opened";d.buffered=new k.a;return d}l(b,c);b.prototype.appendBuffer=function(a){var b=this;this._lock(function(){return b._append(a)})};b.prototype.remove=function(a,b){var c=this;this._lock(function(){return c._remove(a,b)})};b.prototype.abort=
function(){this.remove(0,Infinity);this.updating=!1;this.readyState="closed";this._abort()};b.prototype._append=function(){};b.prototype._remove=function(){};b.prototype._abort=function(){};b.prototype._lock=function(b){var c=this;a.i(h.a)(!this.updating,"updating");this.updating=!0;this.trigger("updatestart");a.i(f.c)(function(){return a.i(f.b)(b())}).subscribe(function(){return setTimeout(function(){return c._unlock("update")},0)},function(a){return setTimeout(function(){return c._unlock("error",
a)},0)})};b.prototype._unlock=function(a,b){this.updating=!1;this.trigger(a,b);this.trigger("updateend")};return b}(e.a)},function(e,g,a){function l(){return new z(0,new x.a,0,Infinity,"timeupdate",1,null,0,null,null)}function k(a,b){var c=a.currentTime,d=a.paused,f=new x.a(a.buffered);return new z(c,f,a.duration,f.getGap(c),b,a.playbackRate,f.getRange(c),a.readyState,null,d)}function h(a,b){var c=b.requiresMediaSource;return r.Observable.create(function(b){function d(d){d=k(a,d&&d.type||"timeupdate");
var h=d.name,m=d.ts,e=d.gap,n=d.paused,g=d.readyState,p=d.playback,l=f.stalled,t=f.name,r=f.ts,q;q=(q=d.range)?d.duration-(e+q.end)<=y:!1;var A=1<=g&&"loadedmetadata"!=h&&!l&&!q;c?(n=A&&(e<=y||Infinity===e||1===g),m=l&&1<g&&Infinity>e&&(e>("seeking"==l.name?y:u)||q)):(n=A&&(!n&&"timeupdate"==h&&"timeupdate"==t&&m===r||"seeking"==h&&Infinity===e),m=l&&("seeking"!=h&&m!==r||"canplay"==h||Infinity>e&&(e>("seeking"==l.name?y:u)||q)));d.stalled=n?{name:h,playback:p}:m?null:l;f=d;b.next(f)}var f=k(a,"init"),
h=setInterval(d,c?t:w);A.forEach(function(b){return a.addEventListener(b,d)});b.next(f);return function(){clearInterval(h);A.forEach(function(b){return a.removeEventListener(b,d)})}}).multicast(function(){return new q.BehaviorSubject({name:"init",stalled:null})}).refCount()}function f(a){return a.filter(function(a){return"seeking"==a.name&&(Infinity===a.gap||a.gap<-B)}).skip(1).startWith(!0)}function c(a,b){return new Date(1E3*(a+b.availabilityStartTime))}function d(a,b){var c=a,d=b.suggestedPresentationDelay,
f=b.presentationLiveGap,h=b.timeShiftBufferDepth;"number"!=typeof c&&(c=c.getTime());var m=Date.now();return Math.max(Math.min(c,m-1E3*(f+d)),m-1E3*h)/1E3-b.availabilityStartTime}function b(a){return n(a)[0]}function m(a){if(!a.isLive)return a.duration;var b=a.availabilityStartTime;a=a.presentationLiveGap;return Date.now()/1E3-b-a}function n(a){if(!a.isLive)return[0,a.duration];var b=a.availabilityStartTime,c=a.presentationLiveGap;a=a.timeShiftBufferDepth;b=Date.now()/1E3-b-c;return[Math.min(b,b-
a+5),b]}function p(a,b){if(!b.isLive)return Infinity;var c=b.availabilityStartTime,d=b.presentationLiveGap;return Date.now()/1E3-a-(c+d+v)}a.d(g,"b",function(){return l});a.d(g,"a",function(){return h});a.d(g,"h",function(){return f});a.d(g,"d",function(){return p});a.d(g,"c",function(){return c});a.d(g,"e",function(){return d});a.d(g,"f",function(){return b});a.d(g,"g",function(){return m});a.d(g,"i",function(){return n});var r=a(0);a.n(r);var q=a(35);a.n(q);var x=a(19),t=1E3,w=500,v=10,y=.5,u=5,
B=2,A="canplay play progress seeking seeked loadedmetadata".split(" "),z=function(){function a(b,c,d,f,h,m,k,e,n,g){if(!(this instanceof a))throw new TypeError("Cannot call a class as a function");this.ts=b;this.buffered=c;this.duration=d;this.gap=f;this.name=h;this.playback=m;this.range=k;this.readyState=e;this.stalled=n;this.paused=g}a.prototype.clone=function(){return new a(this.ts,this.buffered,this.duration,this.gap,this.name,this.playback,this.range,this.readyState,this.stalled,this.paused)};
return a}()},function(e,g,a){function l(a){if("timeline"===a.indexType){var b=a.timeline[a.timeline.length-1];return(b.ts+(b.r+1)*b.d)/a.timescale}return Date.now()/1E3}function k(a){return a}function h(a){return"true"==a}function f(a){return"true"==a?!0:"false"==a?!1:parseInt(a)}function c(a){return new Date(Date.parse(a))}function d(b){if(!b)return 0;var c=w.exec(b);a.i(t.a)(c,b+" is not a valid ISO8601 duration");return 31536E3*parseFloat(c[2]||0)+2592E3*parseFloat(c[4]||0)+86400*parseFloat(c[6]||
0)+3600*parseFloat(c[8]||0)+60*parseFloat(c[10]||0)+parseFloat(c[12]||0)}function b(a){var b=y.exec(a);if(!b)return-1;a=parseInt(b[1])||0;b=parseInt(b[2])||0;return 0<b?a/b:a}function m(a){return a}function n(a){return(a=v.exec(a))?[+a[1],+a[2]]:null}function p(a,b,c){for(a=a.firstElementChild;a;)c=b(c,a.nodeName,a),a=a.nextElementSibling;return c}function r(a){return a?"urn:tva:metadata:cs:AudioPurposeCS:2007"===a.schemeIdUri&&1===a.value:!1}function q(a){var b=a.mimeType,b=void 0===b?"":b,c=b.split("/")[0];
if(u.includes(c))return c;if("application/bif"===b)return"image";if("application/ttml+xml"===b)return"text";if("application/mp4"===b)return(a=a.role)&&"urn:mpeg:dash:role:2011"===a.schemeIdUri&&"subtitle"===a.value?"text":"metadata";a=a.representations;a=void 0===a?[]:a;return a.length&&(a=a[0].mimeType.split("/")[0],u.includes(a))?a:"unknown"}function x(a){return a?"urn:tva:metadata:cs:AudioPurposeCS:2007"===a.schemeIdUri&&2===a.value:!1}a.d(g,"g",function(){return k});a.d(g,"h",function(){return b});
a.d(g,"f",function(){return n});a.d(g,"i",function(){return h});a.d(g,"m",function(){return c});a.d(g,"j",function(){return d});a.d(g,"l",function(){return f});a.d(g,"k",function(){return m});a.d(g,"a",function(){return p});a.d(g,"b",function(){return B});a.d(g,"d",function(){return x});a.d(g,"e",function(){return r});a.d(g,"c",function(){return q});var t=a(1),w=/^P(([\d.]*)Y)?(([\d.]*)M)?(([\d.]*)D)?T?(([\d.]*)H)?(([\d.]*)M)?(([\d.]*)S)?/,v=/([0-9]+)-([0-9]+)/,y=/([0-9]+)(\/([0-9]+))?/,u=["audio",
"video","text","image"],B=function(a){if(a){var b=a.representations||[],c=b.filter(function(a){return a&&a.index});if(!b.length)return l(a.index);var d=Math.min.apply(Math,c.map(function(a){return l(a.index)}));if(!isNaN(d)){if(b.length===c.length)return d;if(a.index)return a=l(a.index),Math.min(d,a)}}}},function(e,g,a){function l(h){var f=0,c=h.length,d=a.i(k.a)(h.subarray(f,f+8)),f=f+8,b=h[f],f=f+1,m=h[f],f=f+1,e=h[f],f=f+1,g=h[f],f=f+1,b=[b,m,e,g].join("."),m=h[f]+a.i(k.c)(h,f+1),f=f+4,e=a.i(k.c)(h,
f),f=f+4,g=a.i(k.a)(h.subarray(f,f+4)),f=f+4,l=a.i(k.d)(h,f),f=f+2,q=a.i(k.d)(h,f),f=f+2,x=[h[f],h[f+1]].join(":"),t=1===h[f+2],f=64,w=[],v=void 0,y=0;if(!m)throw Error("bif: no images to parse");for(;f<c;){var u=a.i(k.c)(h,f),f=f+4,B=a.i(k.c)(h,f),f=f+4;if(v){var A=v.index,z=e,G=y,v=h.subarray(v.offset,B);w.push({index:A,duration:z,ts:G,data:v});y+=e}if(4294967295===u)break;v={index:u,offset:B}}return{fileFormat:d,version:b,imageCount:m,timescale:e,format:g,width:l,height:q,aspectRatio:x,isVod:t,
thumbs:w}}a.d(g,"a",function(){return l});var k=a(10)},function(e,g,a){function l(a,b,c){a="string"==typeof a?(new DOMParser).parseFromString(a,"text/xml"):a;if(!(a instanceof window.Document||a instanceof window.HTMLElement))throw Error("ttml needs a Document to parse");a=a.querySelector("tt");if(!a)throw Error("ttml could not find <tt> tag");a=k(a.querySelector("body"),0);for(b=0;b<a.length;b++){var d=a[b];d.start+=c;d.end+=c}return a}function k(a,b){var d=0;a=a.firstChild;for(var m=[],e;a;){if(1===
a.nodeType)switch(a.tagName.toUpperCase()){case "P":e=a;var n=b,g=d,d=h(e.getAttribute("begin"),n),l=h(e.getAttribute("end"),n),p=h(e.getAttribute("dur"),0);if("number"==!("undefined"===typeof d||f(d))&&"number"==!("undefined"===typeof l||f(l))&&"number"==!("undefined"===typeof p||f(p)))throw Error("ttml unsupported timestamp format");0<p?(null==d&&(d=g||n),null==l&&(l=d+p)):null==l&&(l=h(e.getAttribute("duration"),0),l=0<=l?l+d:Number.MAX_VALUE);n=e.innerHTML;null==n&&(n=(new XMLSerializer).serializeToString(e),
n=(new DOMParser).parseFromString(n,"text/html").body.firstChild.innerHTML);n=window.escape(n.replace(c,"\r\n"));n=n.replace(/%C3%26nbsp%3B/gm,"%C3%A0");e={id:e.getAttribute("xml:id")||e.getAttribute("id"),text:decodeURIComponent(n),start:d,end:l};d=e.end;m.push(e);break;case "DIV":e=h(a.getAttribute("begin"),0),null==e&&(e=b),m.push.apply(m,k(a,e))}a=a.nextSibling}return m}function h(a,c){if(!a)return null;var f;if(f=a.match(d)){var h=f[3],e=f[4],k=f[6];return 3600*parseInt(f[2]||0,10)+60*parseInt(h,
10)+parseInt(e,10)+parseFloat("0."+k)}return(f=a.match(b))?(h=f[4],parseFloat(f[1])*m[h]+c):null}a.d(g,"a",function(){return l});var f="function"===typeof Symbol&&"symbol"===typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"===typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a},c=/<br.*?>/gm,d=/^(([0-9]+):)?([0-9]+):([0-9]+)(\.([0-9]+))?$/,b=/(([0-9]+)(\.[0-9]+)?)(ms|h|m|s)/,m={h:3600,m:60,s:1,ms:.001}},function(e,g,a){function l(a,b){if(!a)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
return!b||"object"!==typeof b&&"function"!==typeof b?a:b}function k(a,b){if("function"!==typeof b&&null!==b)throw new TypeError("Super expression must either be null or a function, not "+typeof b);a.prototype=Object.create(b&&b.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}});b&&(Object.setPrototypeOf?Object.setPrototypeOf(a,b):a.__proto__=b)}function h(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function");}function f(){return new XMLHttpRequest}
function c(a){return new n(a)}e=a(0);a.n(e);var d=a(2);a.n(d);var b=a(4),m=function q(a,b,c,d,f,m,e){h(this,q);this.status=a;this.url=b;this.responseType=c;this.sentTime=d;this.receivedTime=f;this.duration=this.receivedTime-this.sentTime;this.size=m;this.responseData=e},n=function(a){function b(c){h(this,b);var d=l(this,a.call(this)),m={url:"",createXHR:f,headers:null,method:"GET",responseType:"json",timeout:1E4,resultSelector:null,body:null},e;for(e in c)m[e]=c[e];d.request=m;return d}k(b,a);b.prototype._subscribe=
function(a){return new p(a,this.request)};return b}(e.Observable),p=function(a){function c(b,d){h(this,c);var f=l(this,a.call(this,b));f.request=d;f.sentTime=Date.now();f.receivedTime=0;f.xhr=null;f.done=!1;f.resultSelector=d.resultSelector;f.send();return f}k(c,a);c.prototype.next=function(){this.done=!0;var a=this.resultSelector,c=this.xhr,d=this.request,f=this.destination,h=c.status,e=this.responseType,k=this.totalSize,n=this.sentTime,g=this.receivedTime,l=c.responseURL||d.url,p=void 0;if("json"==
d.responseType)if("string"!=typeof c.response)p=c.response;else try{p=JSON.parse(c.responseText)}catch(D){p=null}else p=c.response;null==p?f.error(new b.h(this,d,b.i.PARSE_ERROR)):(c=new m(h,l,e,n,g,k,p),a?f.next(a(c)):f.next(c))};c.prototype.setHeaders=function(a,b){for(var c in b)a.setRequestHeader(c,b[c])};c.prototype.setupEvents=function(a,c){a.ontimeout=function y(){y.subscriber.error(new b.h(this,y.request,b.i.TIMEOUT))};a.ontimeout.request=c;a.ontimeout.subscriber=this;a.onerror=function u(){u.subscriber.error(new b.h(this,
u.request,b.i.ERROR_EVENT))};a.onerror.request=c;a.onerror.subscriber=this;a.onload=function B(a){if(4===this.readyState){var c=B.subscriber,d=B.request;c.receivedTime=Date.now();c.totalSize=a.total;var f=this.status;200<=f&&300>f?(c.next(a),c.complete()):c.error(new b.h(this,d,b.i.ERROR_HTTP_CODE))}};a.onload.subscriber=this;a.onload.request=c};c.prototype.send=function(){var a=this.request,b=this.request,c=b.method,d=b.url,h=b.headers,m=b.body,e=b.responseType,b=b.timeout,k=(a.createXHR||f)(a);
this.xhr=k;k.open(c,d,!0);k.timeout=b;k.responseType=e;"document"==e&&k.overrideMimeType("text/xml");h&&this.setHeaders(k,h);this.setupEvents(k,a);m?k.send(m):k.send()};c.prototype.unsubscribe=function(){var b=this.xhr;!this.done&&b&&4!==b.readyState&&b.abort();b.ontimeout=null;b.onerror=null;b.onload=null;a.prototype.unsubscribe.call(this)};return c}(d.Subscriber);c.RequestObservable=n;c.RequestError=b.h;c.RequestResponse=m;c.RequestErrorTypes=b.i;g.a=c},function(e,g,a){g.empty={closed:!0,next:function(a){},
error:function(a){throw a;},complete:function(){}}},function(e,g,a){var l=this&&this.__extends||function(a,c){function d(){this.constructor=a}for(var b in c)c.hasOwnProperty(b)&&(a[b]=c[b]);a.prototype=null===c?Object.create(c):(d.prototype=c.prototype,new d)};e=a(0);var k=a(15);a=a(12);e=function(a){function c(c){a.call(this);this.observableFactory=c}l(c,a);c.create=function(a){return new c(a)};c.prototype._subscribe=function(a){return new h(a,this.observableFactory)};return c}(e.Observable);g.DeferObservable=
e;var h=function(a){function c(c,b){a.call(this,c);this.factory=b;this.tryDefer()}l(c,a);c.prototype.tryDefer=function(){try{this._callFactory()}catch(d){this._error(d)}};c.prototype._callFactory=function(){var a=this.factory();a&&this.add(k.subscribeToResult(this,a))};return c}(a.OuterSubscriber)},function(e,g,a){var l=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var d in b)b.hasOwnProperty(d)&&(a[d]=b[d]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,
new c)};e=a(0);var k=a(43),h=a(42),f=a(27),c=a(5);a=function(a){function b(b,c,d,f){a.call(this);this.sourceObj=b;this.eventName=c;this.selector=d;this.options=f}l(b,a);b.create=function(a,c,d,f){h.isFunction(d)&&(f=d,d=void 0);return new b(a,c,f,d)};b.setupSubscription=function(a,d,f,h,e){var m;if(a&&"[object NodeList]"===a.toString()||a&&"[object HTMLCollection]"===a.toString())for(var k=0,g=a.length;k<g;k++)b.setupSubscription(a[k],d,f,h,e);else a&&"function"===typeof a.addEventListener&&"function"===
typeof a.removeEventListener?(a.addEventListener(d,f,e),m=function(){return a.removeEventListener(d,f)}):a&&"function"===typeof a.on&&"function"===typeof a.off?(a.on(d,f),m=function(){return a.off(d,f)}):a&&"function"===typeof a.addListener&&"function"===typeof a.removeListener&&(a.addListener(d,f),m=function(){return a.removeListener(d,f)});h.add(new c.Subscription(m))};b.prototype._subscribe=function(a){var c=this.selector;b.setupSubscription(this.sourceObj,this.eventName,c?function(){for(var b=
[],d=0;d<arguments.length;d++)b[d-0]=arguments[d];b=k.tryCatch(c).apply(void 0,b);b===f.errorObject?a.error(f.errorObject.e):a.next(b)}:function(b){return a.next(b)},a,this.options)};return b}(e.Observable);g.FromEventObservable=a},function(e,g,a){function l(a){var c=a.value;a=a.subscriber;a.closed||(a.next(c),a.complete())}function k(a){var c=a.err;a=a.subscriber;a.closed||a.error(c)}var h=this&&this.__extends||function(a,d){function b(){this.constructor=a}for(var c in d)d.hasOwnProperty(c)&&(a[c]=
d[c]);a.prototype=null===d?Object.create(d):(b.prototype=d.prototype,new b)},f=a(7);e=function(a){function c(b,c){a.call(this);this.promise=b;this.scheduler=c}h(c,a);c.create=function(a,d){return new c(a,d)};c.prototype._subscribe=function(a){var b=this,c=this.promise,d=this.scheduler;if(null==d)this._isScalar?a.closed||(a.next(this.value),a.complete()):c.then(function(c){b.value=c;b._isScalar=!0;a.closed||(a.next(c),a.complete())},function(b){a.closed||a.error(b)}).then(null,function(a){f.root.setTimeout(function(){throw a;
})});else if(this._isScalar){if(!a.closed)return d.schedule(l,0,{value:this.value,subscriber:a})}else c.then(function(c){b.value=c;b._isScalar=!0;a.closed||a.add(d.schedule(l,0,{value:c,subscriber:a}))},function(b){a.closed||a.add(d.schedule(k,0,{err:b,subscriber:a}))}).then(null,function(a){f.root.setTimeout(function(){throw a;})})};return c}(a(0).Observable);g.PromiseObservable=e},function(e,g,a){var l=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var d in b)b.hasOwnProperty(d)&&
(a[d]=b[d]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)},k=a(63);e=a(0);var h=a(26),f=a(18),c=a(62);a=function(a){function b(b,d,e){void 0===b&&(b=0);a.call(this);this.period=-1;this.dueTime=0;k.isNumeric(d)?this.period=1>Number(d)&&1||Number(d):f.isScheduler(d)&&(e=d);f.isScheduler(e)||(e=h.async);this.scheduler=e;this.dueTime=c.isDate(b)?+b-this.scheduler.now():b}l(b,a);b.create=function(a,c,d){void 0===a&&(a=0);return new b(a,c,d)};b.dispatch=function(a){var b=a.index,
c=a.period,d=a.subscriber;d.next(b);if(!d.closed){if(-1===c)return d.complete();a.index=b+1;this.schedule(a,c)}};b.prototype._subscribe=function(a){return this.scheduler.schedule(b.dispatch,this.dueTime,{index:0,period:this.period,subscriber:a})};return b}(e.Observable);g.TimerObservable=a},function(e,g,a){function l(){for(var a=[],d=0;d<arguments.length;d++)a[d-0]=arguments[d];d=null;k.isScheduler(a[a.length-1])&&(d=a.pop());return null===d&&1===a.length?a[0]:(new h.ArrayObservable(a,d)).lift(new f.MergeAllOperator(1))}
var k=a(18),h=a(13),f=a(37);g.concat=function(){for(var a=[],d=0;d<arguments.length;d++)a[d-0]=arguments[d];return this.lift.call(l.apply(void 0,[this].concat(a)))};g.concatStatic=l},function(e,g,a){var l=this&&this.__extends||function(a,d){function b(){this.constructor=a}for(var c in d)d.hasOwnProperty(c)&&(a[c]=d[c]);a.prototype=null===d?Object.create(d):(b.prototype=d.prototype,new b)},k=a(15);e=a(12);g.mergeMap=function(a,d,b){void 0===b&&(b=Number.POSITIVE_INFINITY);"number"===typeof d&&(b=d,
d=null);return this.lift(new h(a,d,b))};var h=function(){function a(a,b,c){void 0===c&&(c=Number.POSITIVE_INFINITY);this.project=a;this.resultSelector=b;this.concurrent=c}a.prototype.call=function(a,b){return b._subscribe(new f(a,this.project,this.resultSelector,this.concurrent))};return a}();g.MergeMapOperator=h;var f=function(a){function c(b,c,d,f){void 0===f&&(f=Number.POSITIVE_INFINITY);a.call(this,b);this.project=c;this.resultSelector=d;this.concurrent=f;this.hasCompleted=!1;this.buffer=[];this.index=
this.active=0}l(c,a);c.prototype._next=function(a){this.active<this.concurrent?this._tryNext(a):this.buffer.push(a)};c.prototype._tryNext=function(a){var b,c=this.index++;try{b=this.project(a,c)}catch(p){this.destination.error(p);return}this.active++;this._innerSub(b,a,c)};c.prototype._innerSub=function(a,c,d){this.add(k.subscribeToResult(this,a,c,d))};c.prototype._complete=function(){this.hasCompleted=!0;0===this.active&&0===this.buffer.length&&this.destination.complete()};c.prototype.notifyNext=
function(a,c,d,f,h){this.resultSelector?this._notifyResultSelector(a,c,d,f):this.destination.next(c)};c.prototype._notifyResultSelector=function(a,c,d,f){var b;try{b=this.resultSelector(a,c,d,f)}catch(q){this.destination.error(q);return}this.destination.next(b)};c.prototype.notifyComplete=function(a){var b=this.buffer;this.remove(a);this.active--;0<b.length?this._next(b.shift()):0===this.active&&this.hasCompleted&&this.destination.complete()};return c}(e.OuterSubscriber);g.MergeMapSubscriber=f},function(e,
g,a){var l=this&&this.__extends||function(a,f){function c(){this.constructor=a}for(var d in f)f.hasOwnProperty(d)&&(a[d]=f[d]);a.prototype=null===f?Object.create(f):(c.prototype=f.prototype,new c)},k=a(7);e=function(a){function f(c,d){a.call(this,c,d);this.scheduler=c;this.work=d;this.pending=!1}l(f,a);f.prototype.schedule=function(a,d){void 0===d&&(d=0);if(this.closed)return this;this.state=a;this.pending=!0;var b=this.id,c=this.scheduler;null!=b&&(this.id=this.recycleAsyncId(c,b,d));this.delay=
d;this.id=this.id||this.requestAsyncId(c,this.id,d);return this};f.prototype.requestAsyncId=function(a,d,b){void 0===b&&(b=0);return k.root.setInterval(a.flush.bind(a,this),b)};f.prototype.recycleAsyncId=function(a,d,b){void 0===b&&(b=0);return null!==b&&this.delay===b?d:(k.root.clearInterval(d),void 0)};f.prototype.execute=function(a,d){if(this.closed)return Error("executing a cancelled action");this.pending=!1;var b=this._execute(a,d);if(b)return b;!1===this.pending&&null!=this.id&&(this.id=this.recycleAsyncId(this.scheduler,
this.id,null))};f.prototype._execute=function(a,d){var b=!1,c=void 0;try{this.work(a)}catch(n){b=!0,c=!!n&&n||Error(n)}if(b)return this.unsubscribe(),c};f.prototype._unsubscribe=function(){var a=this.id,d=this.scheduler,b=d.actions,f=b.indexOf(this);this.state=this.delay=this.work=null;this.pending=!1;this.scheduler=null;-1!==f&&b.splice(f,1);null!=a&&(this.id=this.recycleAsyncId(d,a,null))};return f}(a(167).Action);g.AsyncAction=e},function(e,g,a){var l=this&&this.__extends||function(a,h){function f(){this.constructor=
a}for(var c in h)h.hasOwnProperty(c)&&(a[c]=h[c]);a.prototype=null===h?Object.create(h):(f.prototype=h.prototype,new f)};e=function(a){function h(){a.apply(this,arguments);this.actions=[];this.active=!1;this.scheduled=void 0}l(h,a);h.prototype.flush=function(a){var c=this.actions;if(this.active)c.push(a);else{var d;this.active=!0;do if(d=a.execute(a.state,a.delay))break;while(a=c.shift());this.active=!1;if(d){for(;a=c.shift();)a.unsubscribe();throw d;}}};return h}(a(133).Scheduler);g.AsyncScheduler=
e},function(e,g,a){var l=this&&this.__extends||function(a,h){function f(){this.constructor=a}for(var c in h)h.hasOwnProperty(c)&&(a[c]=h[c]);a.prototype=null===h?Object.create(h):(f.prototype=h.prototype,new f)};e=function(a){function h(){var f=a.call(this,"object unsubscribed");this.name=f.name="ObjectUnsubscribedError";this.stack=f.stack;this.message=f.message}l(h,a);return h}(Error);g.ObjectUnsubscribedError=e},function(e,g,a){g.isDate=function(a){return a instanceof Date&&!isNaN(+a)}},function(e,
g,a){var l=a(17);g.isNumeric=function(a){return!l.isArray(a)&&0<=a-parseFloat(a)+1}},function(e,g,a){g.isPromise=function(a){return a&&"function"!==typeof a.subscribe&&"function"===typeof a.then}},function(e,g,a){g.noop=function(){}},function(e,g,a){function l(a,b){if(!a)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!b||"object"!==typeof b&&"function"!==typeof b?a:b}function k(a,b){if("function"!==typeof b&&null!==b)throw new TypeError("Super expression must either be null or a function, not "+
typeof b);a.prototype=Object.create(b&&b.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}});b&&(Object.setPrototypeOf?Object.setPrototypeOf(a,b):a.__proto__=b)}function h(a,b){if(a===b)return!0;if("object"===("undefined"===typeof a?"undefined":R(a))&&"object"===("undefined"===typeof b?"undefined":R(b))){if(null===a||null===b)return!1;var c=Object.keys(a);if(c.length!==Object.keys(b).length)return!1;for(var d=Array.isArray(c),f=0,c=d?c:c[Symbol.iterator]();;){var e;if(d){if(f>=
c.length)break;e=c[f++]}else{f=c.next();if(f.done)break;e=f.value}if(!b.hasOwnProperty(e)||!h(a[e],b[e]))return!1}return!0}return!1}function f(a,b){return b?"seeking"==b.name?"SEEKING":"BUFFERING":a?"PLAYING":"PAUSED"}function c(){}function d(b){a.i(v.a)(b.man,"player: no manifest loaded")}function b(a,b){return a.filter(function(a){return a.type==b}).map(function(a){return a.value})}var m=a(3),n=a(5);a.n(n);var p=a(8);a.n(p);var r=a(35);a.n(r);var q=a(22);a.n(q);var x=a(11),t=a(21);e=a(31);var w=
a(130),v=a(1),y=a(114),u=a(24),B=a(25),A=a(9),z=a(47),G=a(4),C=a(97),H=a(19),D=a(107),E=a(98),L=a(29),T=a(123),S=a(104),V=a(94),Y=a(105),F=a(44),I=function(){function a(a,b){for(var c=0;c<b.length;c++){var d=b[c];d.enumerable=d.enumerable||!1;d.configurable=!0;"value"in d&&(d.writable=!0);Object.defineProperty(a,d.key,d)}}return function(b,c,d){c&&a(b.prototype,c);d&&a(b,d);return b}}(),R="function"===typeof Symbol&&"symbol"===typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&
"function"===typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a};e=function(e){function g(){var b=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};if(!(this instanceof g))throw new TypeError("Cannot call a class as a function");var c=b.videoElement,d=b.transport,f=b.transportOptions,h=b.defaultLanguage,k=b.defaultAudioTrack,n=b.defaultSubtitle,q=b.defaultTextTrack,w=b.initVideoBitrate,u=b.initialVideoBitrate,y=b.initAudioBitrate,B=b.initialAudioBitrate,C=b.maxVideoBitrate,
x=b.maxAudioBitrate,H=b.limitVideoWidth,H=void 0===H?!0:H,b=b.throttleWhenHidden,b=void 0===b?!0:b,z=l(this,e.call(this)),D=u,G=B,ca=k,aa=q;null!=w&&null==u&&(console.warn("initVideoBitrate is deprecated. Use initialVideoBitrate instead"),D=w);null!=y&&null==B&&(console.warn("initAudioBitrate is deprecated. Use initialAudioBitrate instead"),G=y);null!=h&&null==k&&(console.warn("defaultLanguage is deprecated. Use defaultAudioTrack instead"),ca=h);null!=n&&null==q&&(console.warn("defaultSubtitle is deprecated. Use defaultTextTrack instead"),
aa=n);z._playPauseNext$=z._playPauseNext.bind(z);z._textTrackChanges$=z._textTrackChanges.bind(z);z._setPlayerState$=z._setPlayerState.bind(z);z._triggerTimeChange$=z._triggerTimeChange.bind(z);z._streamNext$=z._streamNext.bind(z);z._streamError$=z._streamError.bind(z);z._streamFatalError$=z._streamFatalError.bind(z);z._streamComplete$=z._streamComplete.bind(z);z.defaultTransport=d;z.defaultTransportOptions=f||{};c||(c=document.createElement("video"));a.i(v.a)(c instanceof A.a,"requires an actual HTMLVideoElement");
c.preload="auto";z.version="2.1.0";z.video=c;z.fullscreen=a.i(A.b)(c).subscribe(function(){return z.trigger("fullscreenChange",z.isFullscreen())});z.playing=new r.BehaviorSubject;z.stream=new p.Subject;z.images=new p.Subject;z.errorStream=new p.Subject;f=a.i(S.a)();d=f.createPipelines;f=f.metrics;c=a.i(E.a)(c);z.createPipelines=d;z.metrics=f;z.adaptive=a.i(V.a)(f,c,{initialVideoBitrate:D,initialAudioBitrate:G,maxVideoBitrate:C,maxAudioBitrate:x,defaultAudioTrack:a.i(t.a)(ca),defaultTextTrack:a.i(t.b)(aa),
limitVideoWidth:H,throttleWhenHidden:b});z.muted=.1;z._setPlayerState("STOPPED");z._resetStates();z.log=m.a;return z}k(g,e);g.getErrorTypes=function(){console.warn("getErrorTypes is deprecated. Use the ErrorTypes property instead");return G.a};g.getErrorCodes=function(){console.warn("getErrorCodes is deprecated. Use the ErrorCodes property instead");return G.b};I(g,null,[{key:"ErrorTypes",get:function(){return G.a}},{key:"ErrorCodes",get:function(){return G.b}}]);g.prototype._resetStates=function(){this.man=
null;this.reps={video:null,audio:null,text:null,images:null};this.adas={video:null,audio:null,text:null,images:null};this.evts={};this.frag={start:null,end:null};this.error=null;this.images.next(null);this._currentImagePlaylist=null};g.prototype._unsubscribe=function(){if(this.subscriptions){var a=this.subscriptions;this.subscriptions=null;a.unsubscribe()}};g.prototype.stop=function(){"STOPPED"!==this.state&&(this._resetStates(),this._unsubscribe(),this._setPlayerState("STOPPED"))};g.prototype.dispose=
function(){this.stop();this.metrics.unsubscribe();this.adaptive.unsubscribe();this.fullscreen.unsubscribe();this.stream.unsubscribe();a.i(F.a)();this.video=this.createPipelines=this.stream=this.fullscreen=this.adaptive=this.metrics=null};g.prototype._recordState=function(a,b){h(this.evts[a],b)||(this.evts[a]=b,this.trigger(a+"Change",b))};g.prototype._parseOptions=function(b){var c=b=Object.assign({transport:this.defaultTransport,transportOptions:{},keySystems:[],timeFragment:{},textTracks:[],imageTracks:[],
autoPlay:!1,hideNativeSubtitle:!1,directFile:!1},b),d=c.transport,f=c.url,h=c.keySystems,e=c.timeFragment,k=c.supplementaryTextTracks,m=c.supplementaryImageTracks,g=b,n=g.subtitles,l=g.images,c=g.transportOptions,p=g.manifests,t=g.autoPlay,M=g.directFile,q=g.defaultLanguage,r=g.defaultAudioTrack,w=g.defaultSubtitle,u=g.defaultTextTrack,A=g.hideNativeSubtitle,g=g.startAt,y=r,B=u;null!=q&&null==r&&(console.warn("defaultLanguage is deprecated. Use defaultAudioTrack instead"),y=q);null!=w&&null==u&&(console.warn("defaultSubtitle is deprecated. Use defaultTextTrack instead"),
B=w);void 0!==n&&void 0===k&&(console.warn("the subtitles option is deprecated. Use supplementaryTextTracks instead"),k=n);void 0!==l&&void 0===m&&(console.warn("the images option is deprecated. Use supplementaryImageTracks instead"),m=l);e=a.i(D.a)(e);M&&(d="directfile");a.i(v.a)(!!p^!!f,"player: you have to pass either a url or a list of manifests");p&&(console.warn("the manifests options is deprecated, use url instead"),h=p[0],f=h.url,k=h.subtitles||[],m=h.images||[],h=p.map(function(a){return a.keySystem}).filter(Boolean));
"string"==typeof d&&(d=T.a[d]);"function"==typeof d&&(d=d(Object.assign({},this.defaultTransportOptions,c)));a.i(v.a)(d,"player: transport "+b.transport+" is not supported");return{url:f,keySystems:h,supplementaryTextTracks:k,hideNativeSubtitle:A,supplementaryImageTracks:m,timeFragment:e,autoPlay:t,defaultAudioTrack:y,defaultTextTrack:B,transport:d,startAt:g}};g.prototype.loadVideo=function(){var d=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},d=this._parseOptions(d);m.a.info("loadvideo",
d);var h=d,e=h.url,k=h.keySystems,g=h.supplementaryTextTracks,l=h.hideNativeSubtitle,p=h.supplementaryImageTracks,r=h.timeFragment,w=h.autoPlay,v=h.transport,d=h.defaultAudioTrack,u=h.defaultTextTrack,h=h.startAt;this.stop();this.frag=r;this.playing.next(w);null!=d&&this.adaptive.setAudioTrack(a.i(t.a)(d));null!=u&&this.adaptive.setTextTrack(a.i(t.b)(u));var u=this.video,A=this.adaptive,d=this.errorStream,y=this.createPipelines(v,{errorStream:d,audio:{cache:new C.a},video:{cache:new C.a},image:{maxRetry:0}}),
v=a.i(z.a)(u,{requiresMediaSource:y.requiresMediaSource()}),e=a.i(Y.a)({url:e,errorStream:d,keySystems:k,supplementaryTextTracks:g,hideNativeSubtitle:l,timings:v,supplementaryImageTracks:p,timeFragment:r,adaptive:A,pipelines:y,videoElement:u,autoPlay:w,startAt:h}).publish(),g=b(e,"stalled").startWith(null),k=b(e,"loaded").take(1).share(),g=k.mapTo("LOADED").concat(a.i(q.combineLatest)(this.playing,g,f)).distinctUntilChanged().startWith("LOADING"),l=a.i(x.a)(u,["play","pause"]),u=a.i(x.a)(u.textTracks,
["addtrack"]),p=this.subscriptions=new n.Subscription;p.add(l.subscribe(this._playPauseNext$,c));p.add(u.subscribe(this._textTrackChanges$,c));p.add(g.subscribe(this._setPlayerState$,c));p.add(v.subscribe(this._triggerTimeChange$,c));p.add(e.subscribe(this._streamNext$,this._streamFatalError$,this._streamComplete$));p.add(d.subscribe(this._streamError$));p.add(e.connect());this.subscriptions?this._triggerTimeChange():p.unsubscribe();return k};g.prototype._streamNext=function(a){var b=a.type,c=a.value;
"buffer"==b&&this._bufferNext(c);"manifest"==b&&this._manifestNext(c);"pipeline"==b&&(this.trigger("progress",c.segment),b=c.parsed,"image"===c.bufferType&&(this._currentImagePlaylist=c=b.segmentData,this.trigger("imageTrackUpdate",{data:this._currentImagePlaylist}),this.images.next(c)));this.stream.next(a)};g.prototype._streamError=function(a){this.trigger("warning",a);this.stream.next({type:"warning",value:a})};g.prototype._streamFatalError=function(a){this._resetStates();this.error=a;this._setPlayerState("STOPPED");
this._unsubscribe();this.trigger("error",a);this.stream.next({type:"error",value:a})};g.prototype._streamComplete=function(){this._resetStates();this._setPlayerState("ENDED");this._unsubscribe();this.stream.next({type:"ended",value:null})};g.prototype._manifestNext=function(a){this.man=a;this.trigger("manifestChange",a)};g.prototype._bufferNext=function(a){var b=a.bufferType,c=a.adaptation;a=a.representation;this.reps[b]=a;this.adas[b]=c;if("text"==b){var d=c&&c.lang?{language:c.lang,closedCaption:!!c.closedCaption,
id:c.id}:null;this._recordState("subtitle",d&&d.language);this._recordState("textTrack",d)}"video"==b&&this._recordState("videoBitrate",a&&a.bitrate||-1);"audio"==b&&(b={language:c&&c.lang||"",audioDescription:!(!c||!c.audioDescription),id:c.id},this._recordState("language",b.language),this._recordState("audioTrack",b),this._recordState("audioBitrate",a&&a.bitrate||-1))};g.prototype._playPauseNext=function(a){!0!==this.video.ended&&this.playing.next("play"==a.type)};g.prototype._textTrackChanges=
function(a){(a=a.target[0])&&this.trigger("nativeTextTrackChange",a)};g.prototype._setPlayerState=function(a){this.state!==a&&(this.state=a,m.a.info("playerStateChange",a),this.trigger("playerStateChange",a))};g.prototype._triggerTimeChange=function(b){if(this.man&&b){this.man.isLive&&0<b.ts&&(b.wallClockTime=a.i(z.c)(b.ts,this.man),b.liveGap=a.i(z.d)(b.ts,this.man));var c={position:b.ts,duration:b.duration,bufferGap:isFinite(b.gap)?b.gap:0,liveGap:b.liveGap,playbackRate:b.playback,wallClockTime:b.wallClockTime&&
b.wallClockTime.getTime()/1E3};this.trigger("positionUpdate",c);this.trigger("currentTimeChange",b)}else this.trigger("currentTimeChange",a.i(z.b)())};g.prototype.getError=function(){return this.error};g.prototype.getManifest=function(){return this.man?new y.a(this.man):null};g.prototype.getCurrentAdaptations=function(){if(!this.man)return null;var a=this.adas||[];return Object.keys(a).reduce(function(b,c){a[c]&&(b[c]=new u.a(a[c]));return b},{})};g.prototype.getCurrentRepresentations=function(){if(!this.man)return null;
var a=this.reps||[];return Object.keys(a).reduce(function(b,c){a[c]&&(b[c]=new B.a(a[c]));return b},{})};g.prototype.getVideoElement=function(){return this.video};g.prototype.getNativeTextTrack=function(){return 0<this.video.textTracks.length?this.video.textTracks[0]:null};g.prototype.getImageTrack=function(){return this.images.distinctUntilChanged()};g.prototype.getPlayerState=function(){return this.state};g.prototype.isLive=function(){d(this);return this.man.isLive};g.prototype.getUrl=function(){d(this);
return this.man.locations[0]};g.prototype.getVideoDuration=function(){return this.video.duration};g.prototype.getVideoLoadedTime=function(){return(new H.a(this.video.buffered)).getSize(this.video.currentTime)};g.prototype.getVideoPlayedTime=function(){return(new H.a(this.video.buffered)).getLoaded(this.video.currentTime)};g.prototype.getCurrentTime=function(){if(!this.man)return 0;var b=this.video.currentTime;return this.man.isLive?a.i(z.c)(b,this.man):b};g.prototype.getWallClockTime=function(){if(!this.man)return 0;
var b=this.video.currentTime;return this.isLive()?+a.i(z.c)(b,this.man)/1E3:b};g.prototype.getPosition=function(){return this.video.currentTime};g.prototype.getStartTime=function(){return this.frag.start};g.prototype.getEndTime=function(){return this.frag.end};g.prototype.getPlaybackRate=function(){return this.video.playbackRate};g.prototype.getVolume=function(){return this.video.volume};g.prototype.isFullscreen=function(){return a.i(A.c)()};g.prototype.getAvailableLanguages=function(){console.warn("getAvailableLanguages is deprecated and won't be available in the next major version. Use getAvailableAudioTracks instead.");
return this.man&&a.i(L.a)(this.man).map(function(a){return a.language})||[]};g.prototype.getAvailableSubtitles=function(){console.warn("getAvailableSubtitles is deprecated and won't be available in the next major version. Use getAvailableTextTracks instead.");return this.man&&a.i(L.b)(this.man).map(function(a){return a.language})||[]};g.prototype.getLanguage=function(){console.warn("getLanguage is deprecated and won't be available in the next major version. Use getAudioTrack instead.");return this.evts.language};
g.prototype.getSubtitle=function(){console.warn("getSubtitle is deprecated and won't be available in the next major version. Use getTextTrack instead.");return this.evts.subtitle};g.prototype.getAvailableVideoBitrates=function(){var b=a.i(L.c)(this.man,"video");return b[0]&&b[0].bitrates.slice()||[]};g.prototype.getAvailableAudioBitrates=function(){var a=this.adas.audio;return a&&a.bitrates.slice()||[]};g.prototype.getVideoBitrate=function(){return this.evts.videoBitrate};g.prototype.getAudioBitrate=
function(){return this.evts.audioBitrate};g.prototype.getVideoMaxBitrate=function(){console.warn("getVideoMaxBitrate is deprecated. Use getMaxVideoBitrate instead");return this.getMaxVideoBitrate()};g.prototype.getMaxVideoBitrate=function(){return this.adaptive.getVideoMaxBitrate()};g.prototype.getAudioMaxBitrate=function(){console.warn("getAudioMaxBitrate is deprecated. Use getMaxAudioBitrate instead");return this.getMaxAudioBitrate()};g.prototype.getMaxAudioBitrate=function(){return this.adaptive.getAudioMaxBitrate()};
g.prototype.getVideoBufferSize=function(){return this.adaptive.getVideoBufferSize()};g.prototype.getAudioBufferSize=function(){return this.adaptive.getAudioBufferSize()};g.prototype.getAverageBitrates=function(){return this.adaptive.getAverageBitrates()};g.prototype.getMetrics=function(){return this.metrics};g.prototype.play=function(){this.video.play()};g.prototype.pause=function(){this.video.pause()};g.prototype.setPlaybackRate=function(a){this.video.playbackRate=a};g.prototype.goToStart=function(){return this.seekTo(this.getStartTime())};
g.prototype.seekTo=function(b){a.i(v.a)(this.man);var c=this.video.currentTime;if(b){if(b.relative){this.video.currentTime=c+b.relative;return}if(b.position){this.video.currentTime=b.relative;return}if(b.wallClockTime){this.video.currentTime=a.i(z.e)(1E3*b.wallClockTime,this.man);return}}this.man.isLive&&(b=a.i(z.e)(b,this.man));return b!==c?(m.a.info("seek to",b),this.video.currentTime=b):c};g.prototype.exitFullscreen=function(){a.i(A.d)()};g.prototype.setFullscreen=function(){!1===(0<arguments.length&&
void 0!==arguments[0]?arguments[0]:!0)?(console.warn("setFullscreen(false) is deprecated. Use exitFullscreen instead"),a.i(A.d)()):a.i(A.e)(this.video)};g.prototype.setVolume=function(a){a!==this.video.volume&&(this.video.volume=a,this.trigger("volumeChange",a))};g.prototype.mute=function(){this.muted=this.getVolume()||.1;this.setVolume(0)};g.prototype.unMute=function(){0===this.getVolume()&&this.setVolume(this.muted)};g.prototype.normalizeLanguageCode=function(b){return a.i(t.c)(b)};g.prototype.isLanguageAvailable=
function(b){var c=a.i(t.a)(b);return c?!!this.getAvailableAudioTracks().find(function(a){return a.language===c.language}):!1};g.prototype.isSubtitleAvailable=function(b){var c=a.i(t.b)(b);return c?!!this.getAvailableTextTracks().find(function(a){return a.language===c.language}):!1};g.prototype.setLanguage=function(b){console.warn("setLanguage is deprecated and won't be available in the next major version. Use setAudioTrack instead.");b=a.i(t.a)(b);a.i(v.a)(this.isLanguageAvailable(b),"player: unknown language");
this.adaptive.setAudioTrack(b)};g.prototype.setSubtitle=function(b){console.warn("setSubtitle is deprecated and won't be available in the next major version. Use setTextTrack instead.");null==b?(this.adaptive.setTextTrack(null),this._recordState("subtitle",null)):(b=a.i(t.b)(b),a.i(v.a)(this.isSubtitleAvailable(b),"player: unknown subtitle"),this.adaptive.setTextTrack(b))};g.prototype.setVideoBitrate=function(b){a.i(v.a)(0===b||0<=this.getAvailableVideoBitrates().indexOf(b),"player: video bitrate unavailable");
this.adaptive.setVideoBitrate(b)};g.prototype.setAudioBitrate=function(b){a.i(v.a)(0===b||0<=this.getAvailableAudioBitrates().indexOf(b),"player: audio bitrate unavailable");this.adaptive.setAudioBitrate(b)};g.prototype.setVideoMaxBitrate=function(a){console.warn("setVideoMaxBitrate is deprecated. Use setMaxVideoBitrate instead");return this.setMaxVideoBitrate(a)};g.prototype.setMaxVideoBitrate=function(a){this.adaptive.setVideoMaxBitrate(a)};g.prototype.setAudioMaxBitrate=function(a){console.warn("setAudioMaxBitrate is deprecated. Use setMaxAudioBitrate instead");
return this.setMaxAudioBitrate(a)};g.prototype.setMaxAudioBitrate=function(a){this.adaptive.setAudioMaxBitrate(a)};g.prototype.setVideoBufferSize=function(a){this.adaptive.setVideoBufferSize(a)};g.prototype.setAudioBufferSize=function(a){this.adaptive.setAudioBufferSize(a)};g.prototype.asObservable=function(){return this.stream};g.prototype.getDebug=function(){return w.a.getDebug(this)};g.prototype.showDebug=function(){w.a.showDebug(this,this.video)};g.prototype.hideDebug=function(){w.a.hideDebug()};
g.prototype.toggleDebug=function(){w.a.toggleDebug(this,this.video)};g.prototype.getCurrentKeySystem=function(){return a.i(F.b)()};g.prototype.getAvailableAudioTracks=function(){var b=this.getAudioTrack();return this.man?a.i(L.a)(this.man).map(function(a){return Object.assign({},a,{active:b.id===a.id})}):null};g.prototype.getAvailableTextTracks=function(){var b=this.getTextTrack();return this.man?a.i(L.b)(this.man).map(function(a){return Object.assign({},a,{active:!!b&&b.id===a.id})}):null};g.prototype.getAudioTrack=
function(){return this.evts.audioTrack};g.prototype.getTextTrack=function(){return this.evts.textTrack};g.prototype.setAudioTrack=function(b){var c=this.getAvailableAudioTracks().find(function(a){return a.id===b});a.i(v.a)(c,"player: unknown audio track");this.adaptive.setAudioTrack(c)};g.prototype.setTextTrack=function(b){var c=this.getAvailableTextTracks().find(function(a){return a.id===b});a.i(v.a)(c,"player: unknown text track");this.adaptive.setTextTrack(c)};g.prototype.disableTextTrack=function(){this.adaptive.setTextTrack(null);
this._recordState("subtitle",null)};g.prototype.getImageTrackData=function(){return this.man?this._currentImagePlaylist:null};g.prototype.getMinimumPosition=function(){return this.man?a.i(z.f)(this.man):null};g.prototype.getMaximumPosition=function(){return this.man?a.i(z.g)(this.man):null};return g}(e.a);g.a=e},function(e,g,a){g.a=function(a){if(void 0===a||null===a)throw new TypeError("Cannot convert undefined or null to object");for(var e=Object(a),h=1;h<arguments.length;h++){var f=arguments[h];
if(void 0!==f&&null!==f)for(var c in f)f.hasOwnProperty(c)&&(e[c]=f[c])}return e}},function(e,g,a){e=a(0);a=a(142);e.Observable.of=a.of},function(e,g,a){e=a(0);a=a(143);e.Observable["throw"]=a._throw},function(e,g,a){e=a(0);a=a(144);e.Observable.prototype["catch"]=a._catch;e.Observable.prototype._catch=a._catch},function(e,g,a){e=a(0);a=a(57);e.Observable.prototype.concat=a.concat},function(e,g,a){e=a(0);a=a(146);e.Observable.prototype.concatAll=a.concatAll},function(e,g,a){e=a(0);a=a(147);e.Observable.prototype.concatMap=
a.concatMap},function(e,g,a){e=a(0);a=a(148);e.Observable.prototype.debounceTime=a.debounceTime},function(e,g,a){e=a(0);a=a(149);e.Observable.prototype.distinctUntilChanged=a.distinctUntilChanged},function(e,g,a){e=a(0);a=a(150);e.Observable.prototype["do"]=a._do;e.Observable.prototype._do=a._do},function(e,g,a){e=a(0);a=a(151);e.Observable.prototype.filter=a.filter},function(e,g,a){e=a(0);a=a(152);e.Observable.prototype["finally"]=a._finally;e.Observable.prototype._finally=a._finally},function(e,
g,a){e=a(0);a=a(153);e.Observable.prototype.ignoreElements=a.ignoreElements},function(e,g,a){e=a(0);a=a(154);e.Observable.prototype.map=a.map},function(e,g,a){e=a(0);a=a(155);e.Observable.prototype.mapTo=a.mapTo},function(e,g,a){e=a(0);a=a(58);e.Observable.prototype.mergeMap=a.mergeMap;e.Observable.prototype.flatMap=a.mergeMap},function(e,g,a){e=a(0);a=a(38);e.Observable.prototype.multicast=a.multicast},function(e,g,a){e=a(0);a=a(158);e.Observable.prototype.publish=a.publish},function(e,g,a){e=a(0);
a=a(159);e.Observable.prototype.scan=a.scan},function(e,g,a){e=a(0);a=a(160);e.Observable.prototype.share=a.share},function(e,g,a){e=a(0);a=a(161);e.Observable.prototype.skip=a.skip},function(e,g,a){e=a(0);a=a(162);e.Observable.prototype.startWith=a.startWith},function(e,g,a){e=a(0);a=a(163);e.Observable.prototype.switchMap=a.switchMap},function(e,g,a){e=a(0);a=a(164);e.Observable.prototype.take=a.take},function(e,g,a){e=a(0);a=a(165);e.Observable.prototype.takeUntil=a.takeUntil},function(e,g,a){e=
a(0);a=a(166);e.Observable.prototype.timeout=a.timeout},function(e,g,a){function l(a){return function(h,f){return null==h?f:a*f+(1-a)*h}}g.a=function(a,h){return a.map(function(a){return a.value.response}).filter(function(a){return!a||2E3<a.size}).map(function(a){return a?a.size/a.duration*8E3:0}).scan(l(h.alpha))}},function(e,g,a){function l(a,b){for(var c=0;c<a.length;c++)if(!0===b(a[c],c,a))return a[c];return null}function k(a,b){return"number"==typeof a&&0<a?a:b}function h(a,b){for(var c=2<arguments.length&&
void 0!==arguments[2]?arguments[2]:0,d=a.length-1;0<=d;d--)if(a[d]/b<=1-c)return a[d];return a[0]}function f(a,b){var c=a.sort(function(a,b){return a.width-b.width}).find(function(a){return a.width>=b});if(c){var d=a.filter(function(a){return a.width<=c});return d[d.length-1].bitrate}return Infinity}function c(b,c){var d=b.map(function(a){return a.lang}),d=a.i(x.d)(d,c);return 0<=d?b[d]:null}function d(a,b){var d=2<arguments.length&&void 0!==arguments[2]?arguments[2]:!1,f=a.filter(function(a){return a.audioDescription==
d});return c(f,b)}function b(a,b){var d=2<arguments.length&&void 0!==arguments[2]?arguments[2]:!1,f=a.filter(function(a){return a.closedCaption==d});return c(f,b)}function m(a,b){return a.filter(function(a){return a.type===b})}var n=a(5);a.n(n);var p=a(35);a.n(p);var r=a(22);a.n(r);var q=a(11),x=a(21),t=a(93),w={defaultAudioTrack:{language:"fra",audioDescription:!1},defaultTextTrack:null,defaultBufferSize:30,defaultBufferThreshold:.3,initialVideoBitrate:0,initialAudioBitrate:0,maxVideoBitrate:Infinity,
maxAudioBitrate:Infinity};g.a=function(c,e){function g(a){return I.distinctUntilChanged().map(function(b){return d(a,b.language,b.audioDescription)||a[0]})}function v(a){return R.distinctUntilChanged().map(function(c){return c?b(a,c.language,c.closedCaption):null})}var A=2<arguments.length&&void 0!==arguments[2]?arguments[2]:{};Object.keys(A).forEach(function(a){return void 0===A[a]&&delete A[a]});var y=Object.assign({},w,A),x=y.defaultTextTrack,C=y.defaultBufferSize,H=y.defaultBufferThreshold,D=
y.initialVideoBitrate,E=y.initialAudioBitrate,L=y.maxVideoBitrate,T=y.maxAudioBitrate,S=y.limitVideoWidth,V=y.throttleWhenHidden,Y=e.videoWidth,F=e.inBackground,I=new p.BehaviorSubject(y.defaultAudioTrack),R=new p.BehaviorSubject(x),N={audio:new p.BehaviorSubject(E),video:new p.BehaviorSubject(D)},y=[a.i(t.a)(m(c,"audio"),{alpha:.6}).multicast(N.audio),a.i(t.a)(m(c,"video"),{alpha:.6}).multicast(N.video)],K=new n.Subscription;y.forEach(function(a){return K.add(a.connect())});var M={audio:new p.BehaviorSubject(Infinity),
video:new p.BehaviorSubject(Infinity)},J={audio:new p.BehaviorSubject(T),video:new p.BehaviorSubject(L)},O={audio:new p.BehaviorSubject(C),video:new p.BehaviorSubject(C),text:new p.BehaviorSubject(C)};return{setAudioTrack:function(a){I.next(a)},setTextTrack:function(a){R.next(a)},getAudioTrack:function(){return I.getValue()},getTextTrack:function(){return R.getValue()},getAverageBitrates:function(){return N},getAudioMaxBitrate:function(){return J.audio.getValue()},getVideoMaxBitrate:function(){return J.video.getValue()},
getAudioBufferSize:function(){return O.audio.getValue()},getVideoBufferSize:function(){return O.video.getValue()},setAudioBitrate:function(a){M.audio.next(k(a,Infinity))},setVideoBitrate:function(a){M.video.next(k(a,Infinity))},setAudioMaxBitrate:function(a){J.audio.next(k(a,Infinity))},setVideoMaxBitrate:function(a){J.video.next(k(a,Infinity))},setAudioBufferSize:function(a){O.audio.next(k(a,C))},setVideoBufferSize:function(a){O.video.next(k(a,C))},getBufferAdapters:function(b){var c=b.type,d=b.bitrates,
e=b.representations;b=void 0;if(1<e.length){b=M[c];var m=J[c],k=N[c].map(function(a,b){return h(d,a,0===b?0:H)}).distinctUntilChanged().debounceTime(2E3).startWith(h(d,N[c].getValue(),0));"video"==c&&(m=a.i(r.combineLatest)([m,Y,F]).map(function(a){var b=a[0],c=a[1];a=a[2];if(V&&a)return d[0];c=S?f(e,c):d[d.length-1];return Math.min(c,b)}));b=a.i(r.combineLatest)(b,m,k,function(a,b,c){var f=void 0,f=Infinity>a?a:Infinity>b?Math.min(b,c):c;return l(e,function(a){return a.bitrate===h(d,f)})}).distinctUntilChanged(function(a,
b){return a.id===b.id})}else b=a.i(q.e)(e[0]);return{representations:b,bufferSizes:O[c]||new p.BehaviorSubject(C)}},getAdaptationsChoice:function(b,c){return"audio"==b?g(c):"text"==b?v(c):a.i(q.e)(c[0])},unsubscribe:function(){K&&(K.unsubscribe(),K=null)}}}},function(e,g,a){function l(e){function k(a,b){for(var c=a.ts,d=a.buffered,f=d.getRange(c),d=d.getOuterRanges(c),e=[],m=0;m<d.length;m++){var k=d[m];c-b<k.end?e.push(k):c+b>k.start&&e.push(k)}f&&(h.a.debug("buffer: gc removing part of inner range",
e),c-b>f.start&&e.push({start:f.start,end:c-b}),c+b<f.end&&e.push({start:c+b,end:f.end}));return e}function g(){h.a.warn("buffer: running garbage collector");return S.take(1).mergeMap(function(a){var b=k(a,u);0===b.length&&(b=k(a,B));h.a.debug("buffer: gc cleaning",b);return w(b.map(function(a){return K.removeBuffer(a)})).concatAll()})}function l(b){function f(a){if(k.test(a.getId()))return!1;if(a.isInitSegment()||0>a.getTime())return!0;var b=e.scale(a.getTime()),c=e.scale(a.getDuration());return(b=
N.hasRange(b,c))?(a=a.getRepresentation().bitrate,b.bitrate*y<a):!0}h.a.info("bitrate",p,b.bitrate);var e=new q.b(E,b),k=new r.a,w=a.i(m.combineLatest)(S,R).mergeMap(function(a,d){var m=a[0],g=a[1],n=new c.a(A.buffered);if(m.stalled){var l=e.checkDiscontinuity(m.ts);l&&V.next({type:"index-discontinuity",value:l})}l=void 0;try{var q=e,r=null;0===d&&(h.a.debug("add init segment",p),r=q.getInitSegment());if(0===m.readyState)l=r?[r]:[];else{var w=m.ts,v=Math.max(0,Math.min(g,m.liveGap,(m.duration||Infinity)-
w)),m=void 0,u=n.getGap(w),m=u>Y&&Infinity>u?Math.min(u,F):0,y=N.getRange(w);if(y&&y.bitrate===b.bitrate){var B=Math.floor(y.end-w);B>m&&(m=B)}var C=q.getSegments(w,m,v);r&&C.unshift(r);l=C}l=l.filter(f)}catch(aa){if(aa.type===x.a.INDEX_ERROR&&aa.code===x.b.OUT_OF_INDEX_ERROR)return V.next({type:"out-of-index",value:aa}),t();throw aa;}for(n=0;n<l.length;n++)k.add(l[n].getId());return l}).concatMap(function(a){return L({segment:a})}).concatMap(function(a){var c=a.segment,d=a.parsed,f=d.segmentData,
h=d.nextSegments,m=d.currentSegment;(d=d.timescale)&&e.setTimescale(d);var n=h?e.insertNewSegments(h,m):[];k.remove(c.getId());m&&N.insert(b.bitrate,e.scale(m.ts),e.scale(m.ts+m.d));return K.appendBuffer(f)["catch"](function(a){if("QuotaExceededError"!=a.name)throw new x.d("BUFFER_APPEND_ERROR",a,!1);return g().mergeMap(function(){return K.appendBuffer(f)})["catch"](function(a){throw new x.d("BUFFER_FULL_ERROR",a,!0);})}).map(function(){return{type:"pipeline",value:Object.assign({bufferType:p,addedSegments:n},
a)}})});return a.i(n.merge)(w,V)["catch"](function(a){if(!E.isLive||a.type!=x.a.NETWORK_ERROR||!a.isHttpError(412))throw a;return d.Observable.of({type:"precondition-failed",value:a}).concat(v(2E3)).concat(l(b))}).startWith({type:"buffer",value:{bufferType:p,adaptation:E,representation:b}})}var p=e.bufferType,A=e.sourceBuffer,E=e.adaptation,L=e.pipeline,T=e.adapters,S=e.timings;e=e.seekings;var V=new b.Subject,Y="video"==p?4:1,F="video"==p?6:1,I=T.representations,R=T.bufferSizes,N=new c.a,K=new f.a(A);
return a.i(m.combineLatest)(I,e,function(a){return a}).switchMap(l)["finally"](function(){return K.dispose()})}function k(a){return d.Observable.of({type:"buffer",value:{bufferType:a,adaptation:null,representation:null}})}a.d(g,"b",function(){return l});a.d(g,"a",function(){return k});var h=a(3),f=a(96),c=a(19),d=a(0);a.n(d);var b=a(8);a.n(b);var m=a(22);a.n(m);var n=a(14);a.n(n);e=a(6);a.n(e);g=a(138);a.n(g);var p=a(56);a.n(p);var r=a(129),q=a(45),x=a(4),t=e.EmptyObservable.create,w=g.FromObservable.create,
v=p.TimerObservable.create,y=1.5,u=240,B=30},function(e,g,a){a.d(g,"a",function(){return k});var l=a(8);a.n(l);var k=function(){function a(f){if(!(this instanceof a))throw new TypeError("Cannot call a class as a function");this.buffer=f;this.queue=[];this.flushing=null;this._onUpdate=this.onUpdate.bind(this);this._onError=this.onError.bind(this);this._flush=this.flush.bind(this);this.buffer.addEventListener("update",this._onUpdate);this.buffer.addEventListener("error",this._onError);this.buffer.addEventListener("updateend",
this._flush)}a.prototype.dispose=function(){this.buffer.removeEventListener("update",this._onUpdate);this.buffer.removeEventListener("error",this._onError);this.buffer.removeEventListener("updateend",this._flush);this.buffer=null;this.queue.length=0;this.flushing=null};a.prototype.onUpdate=function(a){this.flushing&&(this.flushing.next(a),this.flushing.complete(),this.flushing=null)};a.prototype.onError=function(a){this.flushing&&(this.flushing.error(a),this.flushing=null)};a.prototype.queueAction=
function(a,c){var d=new l.Subject;1===this.queue.unshift({type:a,args:c,subj:d})&&this.flush();return d};a.prototype.appendBuffer=function(a){return this.queueAction("append",a)};a.prototype.removeBuffer=function(a){return this.queueAction("remove",{start:a.start,end:a.end})};a.prototype.appendStream=function(a){return this.queueAction("stream",a)};a.prototype.flush=function(){if(!this.flushing&&0!==this.queue.length&&!this.buffer.updating){var a=this.queue.pop(),c=a.type,d=a.args;this.flushing=a.subj;
try{switch(c){case "append":this.buffer.appendBuffer(d);break;case "stream":this.buffer.appendStream(d);break;case "remove":this.buffer.remove(d.start,d.end)}}catch(b){this.onError(b)}}};return a}()},function(e,g,a){a.d(g,"a",function(){return l});var l=function(){function a(){if(!(this instanceof a))throw new TypeError("Cannot call a class as a function");this.cache={}}a.prototype.add=function(a,f){var c=a.segment;c.isInitSegment()&&(this.cache[c.getId()]=f)};a.prototype.get=function(a){a=a.segment;
return a.isInitSegment()&&(a=this.cache[a.getId()],null!=a)?a:null};return a}()},function(e,g,a){var l=a(14);a.n(l);e=a(139);a.n(e);var k=a(9),h=e.IntervalObservable.create,f=window.devicePixelRatio||1;g.a=function(c){var d=a.i(k.u)().filter(function(a){return!1===a}),b=a.i(k.u)().debounceTime(6E4).filter(function(a){return!0===a}),d=a.i(l.merge)(d,b).startWith(!1);return{videoWidth:a.i(l.merge)(h(2E4),a.i(k.v)().debounceTime(500)).startWith("init").map(function(){return c.clientWidth*f}).distinctUntilChanged(),
inBackground:d}}},function(e,g,a){function l(a,h){if("function"!==typeof h&&null!==h)throw new TypeError("Super expression must either be null or a function, not "+typeof h);a.prototype=Object.create(h&&h.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}});h&&(Object.setPrototypeOf?Object.setPrototypeOf(a,h):a.__proto__=h)}e=function(a){function h(){if(!(this instanceof h))throw new TypeError("Cannot call a class as a function");var f=a.apply(this,arguments);if(!this)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
return!f||"object"!==typeof f&&"function"!==typeof f?this:f}l(h,a);h.prototype._append=function(){this.buffered.insert(0,0,Infinity)};return h}(a(46).a);g.a=e},function(e,g,a){function l(a,h){if("function"!==typeof h&&null!==h)throw new TypeError("Super expression must either be null or a function, not "+typeof h);a.prototype=Object.create(h&&h.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}});h&&(Object.setPrototypeOf?Object.setPrototypeOf(a,h):a.__proto__=h)}e=function(a){function h(){if(!(this instanceof
h))throw new TypeError("Cannot call a class as a function");var f=a.apply(this,arguments);if(!this)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!f||"object"!==typeof f&&"function"!==typeof f?this:f}l(h,a);h.getLiveEdge=function(){throw Error("not implemented");};h.prototype.addSegment=function(a){this.index.timeline.push(a);return!0};return h}(a(28).a);g.a=e},function(e,g,a){var l=a(23);e=function(){function a(h,f,c){if(!(this instanceof a))throw new TypeError("Cannot call a class as a function");
this.adaptation=h;this.representation=f;this.index=c}a.getLiveEdge=function(){throw Error("not implemented");};a.prototype.checkDiscontinuity=function(){return-1};a.prototype.checkRange=function(a,f,c){f=this.index;a=f.list;c=Math.floor(c/f.duration);return 0<=c&&c<a.length};a.prototype.createSegment=function(a,f){var c=this.index,d=c.list[a];return l.b.create(this.adaptation,this.representation,a,d.media,f,c.duration,0,d.range,null,!1)};a.prototype.getSegments=function(a,f){for(var c=this.index,
d=c.duration,c=Math.min(c.list.length-1,Math.floor(f/d)),b=[],h=Math.floor(a/d);h<=c;)b.push(this.createSegment(h,h*d)),h++;return b};a.prototype.addSegment=function(){return!1};return a}();g.a=e},function(e,g,a){function l(a,f){if("function"!==typeof f&&null!==f)throw new TypeError("Super expression must either be null or a function, not "+typeof f);a.prototype=Object.create(f&&f.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}});f&&(Object.setPrototypeOf?Object.setPrototypeOf(a,
f):a.__proto__=f)}var k=a(28);e=function(a){function f(){if(!(this instanceof f))throw new TypeError("Cannot call a class as a function");var c=a.apply(this,arguments);if(!this)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!c||"object"!==typeof c&&"function"!==typeof c?this:c}l(f,a);f.prototype.checkRange=function(a){var c=this.index.timeline,c=c[c.length-1];if(!c)return!0;0>c.d&&(c={ts:c.ts,d:0,r:c.r});return a<=k.a.getRangeEnd(c)};return f}(k.a);g.a=
e},function(e,g,a){var l=a(23);e=function(){function a(h,f,c){if(!(this instanceof a))throw new TypeError("Cannot call a class as a function");this.adaptation=h;this.representation=f;this.index=c}a.getLiveEdge=function(a,f){return Date.now()/1E3-f.availabilityStartTime-f.suggestedPresentationDelay};a.prototype.checkDiscontinuity=function(){return-1};a.prototype.checkRange=function(){return!0};a.prototype.createSegment=function(a){var f=this.index,c=f.startNumber,f=f.duration;a=Math.floor(a/f)+(null==
c?1:c);return l.b.create(this.adaptation,this.representation,a,this.index.media,a*f,this.index.duration,a,null,null,!1)};a.prototype.getSegments=function(a,f){for(var c=this.index.duration,d=[],b=a;b<=f;b+=c)d.push(this.createSegment(b));return d};a.prototype.addSegment=function(){return!1};return a}();g.a=e},function(e,g,a){function l(b,c,d){var f=3<arguments.length&&void 0!==arguments[3]?arguments[3]:!0;a.i(m.e)(d)||(d=new (d instanceof m.h?m.j:m.f)(b,d,f));d.pipelineType=c;return d}function k(a){return a instanceof
m.h?a.type===m.i.ERROR_HTTP_CODE?500<=a.status||404==a.status:a.type===m.i.TIMEOUT||a.type===m.i.ERROR_EVENT:!1}function h(f,h,e,m){function g(a){throw l("PIPELINE_RESOLVE_ERROR",f,a);}function p(a){throw l("PIPELINE_PARSING_ERROR",f,a);}function q(a){e.next(a)}function r(c){return a.i(d.a)(a.i(b.c)(C,c),T)}function u(c){var d=L?L.get(c):null;return null===d?r(c):a.i(b.b)(d)["catch"](function(){return r(c)})}function B(c){return a.i(b.c)(H,c)["catch"](p)}function A(a,b){var c=Object.assign({response:b},
a);L&&L.add(a,b);n.schedule(q,0,{type:f,value:c});return c}function x(a,b){return Object.assign({parsed:b},a)}var G=h.resolver,C=h.loader,H=h.parser,D=4<arguments.length&&void 0!==arguments[4]?arguments[4]:{};G||(G=c.Observable.of);C||(C=c.Observable.of);H||(H=c.Observable.of);var E=D.maxRetry,L=D.cache,D="number"===typeof E?E:4,T={retryDelay:200,errorSelector:function(a){throw l("PIPELINE_LOAD_ERROR",f,a);},totalRetry:D,shouldRetry:D&&k,onRetry:function(a){n.schedule(q,0,{type:f,value:a.xhr});m.next(l("PIPELINE_LOAD_ERROR",
f,a,!1))}};return function(c){return a.i(b.c)(G,c)["catch"](g).mergeMap(u,A).mergeMap(B,x)}}var f=a(8);a.n(f);e=a(170);a.n(e);var c=a(0);a.n(c);var d=a(33),b=a(11),m=a(4),n=e.asap;g.a=function(){var a=new f.Subject;return{createPipelines:function(b){var c=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},d={requiresMediaSource:function(){return!0!==b.directFile}},f;for(f in b)d[f]=h(f,b[f],a,c.errorStream,c[f]);return d},metrics:a}}},function(e,g,a){function l(a){return"audio"==a||"video"==
a}var k=a(3),h=a(1),f=a(47),c=a(33),d=a(0);a.n(d);var b=a(11);e=a(6);a.n(e);var m=a(14);a.n(m);var n=a(22);a.n(n);var p=a(9),r=a(106),q=a(99),x=a(45),t=a(95),w=a(44),v=a(4),y=a(29),u=Math.min,B=e.EmptyObservable.create;g.a=function(e){function g(a,b,c){Z[b]||(k.a.info("add sourcebuffer",c),Z[b]=a.addSourceBuffer(c));return Z[b]}function A(a,b,c){var d=c.type;c=c.codec;if(l(d))a=g(b,d,c);else{if(b=W[d])try{b.abort()}catch(ca){k.a.warn(ca)}finally{delete W[d]}if("text"==d)k.a.info("add text sourcebuffer",
c),a=new r.a(a,c,K);else if("image"==d)k.a.info("add image sourcebuffer",c),a=new q.a(c);else throw k.a.error("unknown buffer type "+d),new v.d("BUFFER_TYPE_UNKNOWN",null,!0);W[d]=a}return a}function C(a,b,c){a=c.type;var d=l(a);d?(c=Z[a],delete Z[a]):(c=W[a],delete W[a]);if(c)try{c.abort(),d&&b.removeSourceBuffer(c)}catch(ca){k.a.warn(ca)}}function H(b){var c=J.map(function(c){var d;ha?(d=c.clone(),d.ts=u(c.ts,ba),d.duration=u(c.duration,ba)):d=c;d.liveGap=a.i(f.d)(c.ts,b);return d}),d=a.i(f.h)(c);
return{timings:c,seekings:d}}function D(b,c,d,f){var e=c.type;return X.getAdaptationsChoice(e,c.adaptations).switchMap(function(h){if(!h)return C(P,b,c),a.i(t.a)(e);var m=X.getBufferAdapters(h);h=a.i(t.b)({bufferType:e,sourceBuffer:A(P,b,c),pipeline:U[e],adaptation:h,timings:d,seekings:f,adapters:m});return l(e)?h:h["catch"](function(a){k.a.error("buffer",e,"has crashed",a);I.next(a);return B()})})}function E(b){var c=a.i(p.o)(P)["do"](function(){var c=b.duration,d=ea,e=ba,m=/^\d*(\.\d+)? ?%$/;if(Q)e=
a.i(f.i)(b),c=e[0],e=e[1],null!=Q.position?d=Math.max(Math.min(Q.position,e),c):null!=Q.wallClockTime?d=Math.max(Math.min(b.isLive?Q.wallClockTime-b.availabilityStartTime:Q.wallClockTime,e),c):null!=Q.fromFirstPosition?(d=Q.fromFirstPosition,d=0>=d?c:Math.min(c+d,e)):null!=Q.fromLastPosition&&(d=Q.fromLastPosition,d=0<=d?e:Math.max(c,e+d));else{"string"==typeof d&&m.test(d)&&(d=parseFloat(d)/100*c);"string"==typeof e&&m.test(e)&&(ba=parseFloat(e)/100*c);if(Infinity===e||"100%"===e)e=c;b.isLive?d=
d?a.i(f.e)(d,b):a.i(x.a)(b):a.i(h.a)(d<c&&e<=c,"stream: bad startTime and endTime")}k.a.info("set initial time",d);P.playbackRate=1;P.currentTime=d}),d=a.i(p.p)(P)["do"](function(){k.a.info("canplay event");da&&P.play();da=!0});return a.i(n.combineLatest)(c,d).take(1).mapTo({type:"loaded",value:!0})}function L(){return R&&R.length?a.i(w.c)(P,R,I):a.i(w.d)(P).map(function(){k.a.error("eme: ciphered media and no keySystem passed");throw new v.c("MEDIA_IS_ENCRYPTED_ERROR",null,!0);})}function T(b,c){var d=
c.changePlaybackRate,f=void 0===d?!0:d;return b.distinctUntilChanged(function(b,c){var d=c.stalled,e=b.stalled,h;h=e||d?e&&d?e.name==d.name:!1:!0;!h&&f&&(e?(k.a.info("resume playback",c.ts,c.name),P.playbackRate=e.playback):(k.a.info("stop playback",c.ts,c.name),P.playbackRate=0));d&&(d=c.buffered.getNextRangeGap(c.ts),a.i(p.q)(c)?(P.currentTime=c.ts,k.a.warn("after freeze seek",c.ts,c.range)):1>d&&(e=c.ts+d+1/60,P.currentTime=e,k.a.warn("discontinuity seek",c.ts,d,e)));return h}).map(function(a){return{type:"stalled",
value:a.stalled}})}function S(b){return fa({url:b.locations[0]}).map(function(c){c=c.parsed;return{type:"manifest",value:a.i(y.e)(b,a.i(y.d)(c.url,c.manifest,N,M))}})}function V(b,c,f,e){var h=a.i(y.g)(c);h.forEach(function(a){var c=a.type;a=a.codec;l(c)&&g(b,c,a)});h=h.map(function(a){return D(b,a,f,e)});h=m.merge.apply(void 0,h);return c.isLive?h.concatMap(function(b){a:{switch(b.type){case "index-discontinuity":k.a.warn("explicit discontinuity seek",b.value.ts);P.currentTime=b.value.ts;break;case "precondition-failed":a.i(y.f)(c,
1);k.a.warn("precondition failed",c.presentationLiveGap);break;case "out-of-index":k.a.info("out of index");b=S(c);break a}b=d.Observable.of(b)}return b}):h}function Y(){return a.i(b.a)(P,"error").mergeMap(function(){var a=void 0;switch(P.error.code){case 1:a="MEDIA_ERR_ABORTED";break;case 2:a="MEDIA_ERR_NETWORK";break;case 3:a="MEDIA_ERR_DECODE";break;case 4:a="MEDIA_ERR_SRC_NOT_SUPPORTED"}k.a.error("stream: video element MEDIA_ERR("+a+")");throw new v.d(a,null,!0);})}var F=e.url,I=e.errorStream,
R=e.keySystems,N=e.supplementaryTextTracks,K=e.hideNativeSubtitle,M=e.supplementaryImageTracks,J=e.timings,O=e.timeFragment,X=e.adaptive,U=e.pipelines,P=e.videoElement,da=e.autoPlay,Q=e.startAt,ea=O.start,ba=O.end,ha=Infinity>ba,fa=a.i(b.d)(U.manifest),Z={},W={};e=J.filter(function(a){var b=a.ts;a=a.duration;return 0<a&&.5>u(a,ba)-b});O=a.i(c.b)(function(b){var c=b.url,f=b.mediaSource;b=f?a.i(p.n)(f):d.Observable.of(null);return a.i(n.combineLatest)(fa({url:c}),b).mergeMap(function(b){b=b[0].parsed;
b=a.i(y.d)(b.url,b.manifest,N,M);if(f){var c=b.duration,c=Infinity===c?Number.MAX_VALUE:c;f.duration!==c&&(f.duration=c,k.a.info("set duration",f.duration))}var c=H(b),e=c.timings,h=c.seekings,c=d.Observable.of({type:"manifest",value:b}),g=L(),n=T(e,{changePlaybackRate:U.requiresMediaSource()}),l=E(b);b=V(f,b,e,h);e=Y();return a.i(m.merge)(c,l,n,g,b,e)})},{totalRetry:3,retryDelay:250,resetDelay:6E4,shouldRetry:function(a){return!0!==a.fatal},errorSelector:function(b){a.i(v.e)(b)||(b=new v.f("NONE",
b,!0));b.fatal=!0;return b},onRetry:function(a,b){k.a.warn("stream retry",a,b);I.next(a)}});return function(b,c){return d.Observable.create(function(d){function f(){if(e&&"closed"!=e.readyState)for(var b=e,d=b.readyState,b=b.sourceBuffers,f=0;f<b.length;f++){var m=b[f];try{"open"==d&&m.abort(),e.removeSourceBuffer(m)}catch(ga){k.a.warn("error while disposing souceBuffer",ga)}}Object.keys(W).forEach(function(a){a=W[a];try{a.abort()}catch(la){k.a.warn("error while disposing souceBuffer",la)}});a.i(p.l)(c);
if(h)try{URL.revokeObjectURL(h)}catch(ga){k.a.warn("error while revoking ObjectURL",ga)}Z={};W={};h=e=null}var e=void 0,h=void 0;f();if(U.requiresMediaSource()){if(!p.m)throw new v.d("MEDIA_SOURCE_NOT_SUPPORTED",null,!0);e=new p.m;h=URL.createObjectURL(e)}else e=null,h=b;c.src=h;d.next({url:b,mediaSource:e});k.a.info("create mediasource object",h);return f})}(F,P).mergeMap(O).takeUntil(e)}},function(e,g,a){function l(a,d){if("function"!==typeof d&&null!==d)throw new TypeError("Super expression must either be null or a function, not "+
typeof d);a.prototype=Object.create(d&&d.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}});d&&(Object.setPrototypeOf?Object.setPrototypeOf(a,d):a.__proto__=d)}e=a(46);var k=a(9),h=a(3),f=window.VTTCue||window.TextTrackCue;e=function(c){function d(b,f,e){if(!(this instanceof d))throw new TypeError("Cannot call a class as a function");var h;h=c.call(this,f);if(!this)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");h=!h||"object"!==typeof h&&
"function"!==typeof h?this:h;h.video=b;h.codec=f;h.isVTT=/^text\/vtt/.test(f);b=a.i(k.r)(b,e);f=b.trackElement;h.track=b.track;h.trackElement=f;return h}l(d,c);d.prototype.createCuesFromArray=function(a){for(var b=[],c=0;c<a.length;c++){var d=a[c],e=d.start,h=d.end;(d=d.text)&&b.push(new f(e,h,d))}return b};d.prototype._append=function(b){var c=this;if(this.isVTT)a.i(k.s)()&&this.trackElement?(b=new Blob([b],{type:"text/vtt"}),b=URL.createObjectURL(b),this.trackElement.src=b,this.buffered.insert(0,
Infinity)):h.a.warn("vtt subtitles not supported");else if(b=this.createCuesFromArray(b),0<b.length){var d=b[0],f=b[b.length-1],e=this.track.cues;0<e.length&&d.startTime<e[e.length-1].startTime&&this._remove(d.startTime,Infinity);b.forEach(function(a){return c.track.addCue(a)});this.buffered.insert(0,d.startTime,f.endTime)}};d.prototype._remove=function(a,c){for(var b=this.track,d=b.cues,f=d.length-1;0<=f;f--){var e=d[f],h=e.startTime,m=e.endTime;h>=a&&h<=c&&m<=c&&b.removeCue(e)}this.buffered.remove(a,
c)};d.prototype._abort=function(){var a=this.trackElement,c=this.video;a&&c&&c.hasChildNodes(a)&&c.removeChild(a);this.track.mode="disabled";this.size=0;this.video=this.track=this.trackElement=null};return d}(e.a);g.a=e},function(e,g,a){function l(e){if("string"==typeof e){var g=e,m=g.split(",");a.i(d.a)(2>=m.length,b);e=m[0]?m[0]:"";m=m[1]?m[1]:"";a.i(d.a)((e||m)&&(!e||m||-1===g.indexOf(",")),b);e=e.replace(/^smpte(-25|-30|-30-drop)?:/,"").replace(/^npt[:=]/,"").replace("clock:","");var g=/(((\d+:)?(\d\d):(\d\d))|(\d+))(\.\d*)?$/,
l=/^\d+:\d\d:\d\d(:\d\d(\.\d\d)?)?$/,q=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|([-+]\d{2}:\d{2}))?$/,x=/^\d*(\.\d+)? ?%$/;if(g.test(e)&&g.test(m))g=k;else if(l.test(e)&&l.test(m))g=h;else if(q.test(e)&&q.test(m))g=f;else if(x.test(e)&&x.test(m))g=c;else throw Error(b);e=g(e);m=g(m);a.i(d.a)(!1!==e||!1!==m,b);e={start:!1===e?"":e,end:!1===m?"":m}}else e||(e={});"string"==typeof e.start&&"string"==typeof e.end?(e.start||(e.start="0%"),e.end||(e.end="100%")):(e.start||(e.start=0),e.end||(e.end=
Infinity));"string"==typeof e.start&&"string"==typeof e.end?(a.i(d.a)(0<=parseFloat(e.start)&&100>=parseFloat(e.start),"player: startTime should be between 0% and 100%"),a.i(d.a)(0<=parseFloat(e.end)&&100>=parseFloat(e.end),"player: endTime should be between 0% and 100%")):(a.i(d.a)(("number"==typeof e.start||e.start instanceof Date)&&("number"==typeof e.end||e.end instanceof Date),"player: timeFragment should have interface { start, end } where start and end are numbers or dates"),a.i(d.a)(e.start<
e.end,"player: startTime should be lower than endTime"),a.i(d.a)(0<=e.start,"player: startTime should be greater than 0"));return e}function k(c){if(!c)return!1;c=c.replace(/\.$/,"");var f,e;c=c.split(":");var h=c.length;switch(h){case 3:f=parseInt(c[0],10);e=parseInt(c[1],10);c=parseFloat(c[2]);break;case 2:f=0;e=parseInt(c[0],10);c=parseFloat(c[1]);break;case 1:e=f=0;c=parseFloat(c[0]);break;default:return!1}a.i(d.a)(23>=f,b);a.i(d.a)(59>=e,b);a.i(d.a)(1>=h||60>c,b);return 3600*f+60*e+c}function h(c){if(!c)return!1;
var f,e,h,g;c=c.split(":");switch(c.length){case 3:f=parseInt(c[0],10);e=parseInt(c[1],10);h=parseInt(c[2],10);g=c=0;break;case 4:f=parseInt(c[0],10);e=parseInt(c[1],10);h=parseInt(c[2],10);-1===c[3].indexOf(".")?(c=parseInt(c[3],10),g=0):(g=c[3].split("."),c=parseInt(g[0],10),g=parseInt(g[1],10));break;default:return!1}a.i(d.a)(23>=f,b);a.i(d.a)(59>=e,b);a.i(d.a)(59>=h,b);return 3600*f+60*e+h+.001*c+1E-6*g}function f(a){return new Date(Date.parse(a))}function c(a){return a?a:!1}a.d(g,"a",function(){return l});
var d=a(1),b="invalid MediaFragment"},function(e,g,a){Object.defineProperty(g,"__esModule",{value:!0});e=a(68);a.n(e);e=a(69);a.n(e);e=a(70);a.n(e);e=a(71);a.n(e);e=a(72);a.n(e);e=a(73);a.n(e);e=a(74);a.n(e);e=a(75);a.n(e);e=a(76);a.n(e);e=a(77);a.n(e);e=a(78);a.n(e);e=a(79);a.n(e);e=a(80);a.n(e);e=a(81);a.n(e);e=a(82);a.n(e);e=a(83);a.n(e);e=a(84);a.n(e);e=a(85);a.n(e);e=a(86);a.n(e);e=a(87);a.n(e);e=a(88);a.n(e);e=a(89);a.n(e);e=a(90);a.n(e);e=a(91);a.n(e);e=a(92);a.n(e);e=a(67);a(3);a=a(66);"function"!=
typeof Object.assign&&(Object.assign=e.a);g["default"]=a.a},function(e,g,a){e=a(30);a=a(20);g.a=Object.assign({},e.a,{getInitSegment:a.a,setTimescale:a.b,scale:a.c,_addSegmentInfos:function(a,e){a.timeline.push({ts:e.time,d:e.duration});return a}})},function(e,g,a){a.d(g,"a",function(){return d});var l=a(30),k=a(111),h=a(113),f=a(112),c=a(109),d=function(a){switch(a.indexType){case "timeline":return l.a;case "list":return k.a;case "template":return h.a;case "smooth":return f.a;case "base":return c.a;
default:return l.a}}},function(e,g,a){var l=a(16),k=a(20);g.a={getInitSegment:k.a,setTimescale:k.b,scale:k.c,getSegments:function(e,f,c,d){var b=a.i(k.e)(f,c,d);c=f.duration;d=f.list;f=f.timescale;for(var h=Math.min(d.length-1,Math.floor(b.to/c)),g=[],b=Math.floor(b.up/c);b<=h;)g.push(new l.a({id:""+e+"_"+b,time:b*c,init:!1,range:d[b].range,duration:c,indexRange:null,timescale:f})),b++;return g},getFirstPosition:function(){return 0},getLastPosition:function(a){return a.list.length*a.duration/a.timescale},
shouldRefresh:function(a,f,c,d){f=a.list;a=Math.floor(d/a.duration);return!(0<=a&&a<f.length)},_addSegmentInfos:function(){},checkDiscontinuity:function(){return-1}}},function(e,g,a){e=a(30);var l=a(20);g.a={getSegments:e.a.getSegments,getInitSegment:l.a,checkDiscontinuity:e.a.checkDiscontinuity,_addSegmentInfos:e.a._addSegmentInfos,setTimescale:l.b,scale:l.c,shouldRefresh:function(e,h){var f=e.timeline,f=f[f.length-1];if(!f)return!1;0>f.d&&(f={ts:f.ts,d:0,r:f.r});return h>=a.i(l.d)(f)},getFirstPosition:function(a){if(a.timeline.length)return a.timeline[0].ts/
a.timescale},getLastPosition:function(e){if(e.timeline.length){var h=e.timeline[e.timeline.length-1];return a.i(l.d)(h)/e.timescale}}}},function(e,g,a){var l=a(16),k=a(20);g.a={getInitSegment:k.a,setTimescale:k.b,scale:k.c,getSegments:function(e,f,c,d){var b=a.i(k.e)(f,c,d);c=b.to;d=f.duration;var h=f.startNumber;f=f.timescale;for(var g=[],b=b.up;b<=c;b+=d){var p=Math.floor(b/d)+(null==h?1:h),b=p*d;g.push(new l.a({id:""+e+"_"+p,number:p,time:b,init:!1,duration:d,range:null,indexRange:null,timescale:f}))}return g},
getFirstPosition:function(){},getLastPosition:function(){},shouldRefresh:function(){return!1},checkDiscontinuity:function(){return-1},_addSegmentInfos:function(){}}},function(e,g,a){var l=a(24),k=a(32);e=function(){function e(){var f=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};if(!(this instanceof e))throw new TypeError("Cannot call a class as a function");var c=a.i(k.a)();this.id=null==f.id?c:""+f.id;this.transport=f.transportType||"";this.adaptations=f.adaptations?Object.keys(f.adaptations).reduce(function(a,
b){a[b]=f.adaptations[b].map(function(a){return new l.a(a)});return a},{}):[];this.periods=[{adaptations:this.adaptations}];this.isLive="dynamic"===f.type;this.uris=f.locations;this._duration=f.duration}e.prototype.getDuration=function(){return this._duration};return e}();g.a=e},function(e,g,a){var l=a(110);e=function(){function e(h){if(!(this instanceof e))throw new TypeError("Cannot call a class as a function");this._index=h.index;this._rootId=h.rootId;this._indexHelpers=a.i(l.a)(this._index)}e.prototype.getInitSegment=
function(){return this._indexHelpers.getInitSegment(this._rootId,this._index)};e.prototype.getSegments=function(a,f){return this._indexHelpers.getSegments(this._rootId,this._index,a,f)};e.prototype.shouldRefresh=function(a,f,c){return this._indexHelpers.shouldRefresh(this._index,a,f,c)};e.prototype.getFirstPosition=function(){return this._indexHelpers.getFirstPosition(this._index)};e.prototype.getLastPosition=function(){return this._indexHelpers.getLastPosition(this._index)};e.prototype.checkDiscontinuity=
function(a){return this._indexHelpers.checkDiscontinuity(this._index,a)};e.prototype.scale=function(a){return this._indexHelpers.scale(this._index,a)};e.prototype.setTimescale=function(a){return this._indexHelpers.setTimescale(this._index,a)};e.prototype._addSegments=function(a,f){for(var c=[],d=0;d<a.length;d++)this._indexHelpers._addSegmentInfos(a[d],f)&&c.push(a[d]);return c};return e}();g.a=e},function(e,g,a){function l(a){var b=a[0];return(a=a[1])&&Infinity!==a?"bytes="+ +b+"-"+ +a:"bytes="+
+b+"-"}function k(a){return function(b,c,d){b=d?parseInt(d,10):1;c=""+a;c=c.toString();b=c.length>=b?c:(Array(b+1).join("0")+c).slice(-b);return b}}function h(a,b){if(-1===a.indexOf("$"))return a;var c=b.getRepresentation();return a.replace(/\$\$/g,"$").replace(/\$RepresentationID\$/g,c.id).replace(/\$Bandwidth(|\%0(\d+)d)\$/g,k(c.bitrate)).replace(/\$Number(|\%0(\d+)d)\$/g,k(b.getNumber())).replace(/\$Time(|\%0(\d+)d)\$/g,k(b.getTime()))}var f=a(0);a.n(f);e=a(6);a.n(e);var c=a(14);a.n(c);a(1);var d=
a(34),b=a(121),m=a(10),n=a(24),p=a(25),r=a(16),q=a(51),x=a(119),t=a(50),w=a(49),v=e.EmptyObservable.create;g.a=function(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},g=e.contentProtectionParser;g||(g=function(){});var k=e.createXHR,A=function(b){var d=b.url;b=b.segment;var f=b.range;b=b.indexRange;if(f&&b&&f[1]===b[0]-1)return a.i(q.a)({url:d,responseType:"arraybuffer",headers:{Range:l([f[0],b[1]])},createXHR:k});f=f?{Range:l(f)}:null;f=a.i(q.a)({url:d,responseType:"arraybuffer",
headers:f,createXHR:k});return b?(d=a.i(q.a)({url:d,responseType:"arraybuffer",headers:{Range:l(b)},createXHR:k}),a.i(c.merge)(f,d)):f},z=function(b){b=b.segment;var c=b.getMedia(),g=b.getRange(),k=b.getIndexRange();if(b.isInitSegment()&&!(c||g||k))return v();var m=e.segmentLoader,c=c?h(c,b):"",c=a.i(d.b)(b.getResolvedURL(),c),l={adaptation:new n.a(b.getAdaptation()),representation:new p.a(b.getRepresentation()),segment:new r.a(b),transport:"dash",url:c};return m?f.Observable.create(function(a){var b=
!1,c=!1,d=m(l,{reject:function(){var d=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};c||(b=!0,a.error(d))},resolve:function(){var d=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};c||(b=!0,a.next({responseData:d.data,size:d.size||0,duration:d.duration||0}),a.complete())},fallback:function(){c=!0;A(l).subscribe(a)}});return function(){b||c||"function"!==typeof d||d()}}):A(l)},G={loader:function(a){return z({segment:a.segment})},parser:function(c){var d=c.segment;c=new Uint8Array(c.response.responseData);
var e=void 0,h=void 0,g=void 0,k=d.getIndexRange();if(k=a.i(b.a)(c,k?k[0]:0))e=k.segments,h=k.timescale;d.isInitSegment()||(0<=d.getTime()&&0<=d.getDuration()?g={ts:d.getTime(),d:d.getDuration()}:k&&1===k.segments.length&&(g={ts:k.segments[0].ts,d:k.segments[0].d}));k=c;d.isInitSegment()&&(d=d.getAdaptation(),d.contentProtection&&(k=a.i(b.b)(c,d.contentProtection)));return f.Observable.of({segmentData:k,currentSegment:g,nextSegments:e,timescale:h})}};return{directFile:!1,manifest:{loader:function(b){b=
b.url;return a.i(q.a)({url:b,responseType:"document",createXHR:k})},parser:function(b){b=b.response;var c=b.responseData;return f.Observable.of({manifest:a.i(x.a)(c,g),url:b.url})}},audio:G,video:G,text:{loader:function(b){var f=b.segment,e=f.getMedia(),g=f.getRange();b=f.getIndexRange();var m=0<=("application/mp4"===f.getRepresentation().mimeType)?"arraybuffer":"text";if(f.isInitSegment()&&!(e||g||b))return v();e=e?h(e,f):"";f=a.i(d.b)(f.getResolvedURL(),e);if(g&&b&&g[1]===b[0]-1)return a.i(q.a)({url:f,
responseType:m,headers:{Range:l([g[0],b[1]])},createXHR:k});g=a.i(q.a)({url:f,responseType:m,headers:g?{Range:l(g)}:null,createXHR:k});return b?(b=a.i(q.a)({url:f,responseType:m,headers:{Range:l(b)},createXHR:k}),a.i(c.merge)(g,b)):g},parser:function(c){var d=c.segment,e=c.response;c=d.getAdaptation().lang;var h;"application/mp4"===d.getRepresentation().mimeType?(h=new Uint8Array(e.responseData),e=a.i(m.a)(a.i(b.c)(h))):e=h=e.responseData;var g=void 0,k=void 0,n=void 0,l=d.getIndexRange();if(l=a.i(b.a)(h,
l?l[0]:0))g=l.segments,k=l.timescale;h=[];if(!d.isInitSegment())switch(0<=d.getTime()&&0<=d.getDuration()?n={ts:d.getTime(),d:d.getDuration()}:l&&1===l.segments.length&&(n={ts:l.segments[0].ts,d:l.segments[0].d}),d=d.getRepresentation().codecs,(void 0===d?"":d).toLowerCase()){case "stpp":h=a.i(t.a)(e,c,0);break;default:console.warn("The codec used for the subtitle is not managed yet.")}return f.Observable.of({segmentData:h,currentSegment:n,nextSegments:g,timescale:k})}},image:{loader:function(b){b=
b.segment;if(b.init)return v();var c=b.getMedia(),c=c?h(c,b):"";b=a.i(d.b)(b.getResolvedURL(),c);return a.i(q.a)({url:b,responseType:"arraybuffer",createXHR:k})},parser:function(b){var c=new Uint8Array(b.response.responseData),d=b=void 0;c&&(c=a.i(w.a)(c),b=c.thumbs,d=c.timescale);return f.Observable.of({segmentData:b,currentSegment:{ts:0,d:Infinity},timescale:d})}}}}},function(e,g,a){var l=a(1);e=a(21);var k=a(48),h=[{k:"profiles",fn:k.g},{k:"width",fn:parseInt},{k:"height",fn:parseInt},{k:"frameRate",
fn:k.h},{k:"audioSamplingRate",fn:k.g},{k:"mimeType",fn:k.g},{k:"segmentProfiles",fn:k.g},{k:"codecs",fn:k.g},{k:"maximumSAPPeriod",fn:parseFloat},{k:"maxPlayoutRate",fn:parseFloat},{k:"codingDependency",fn:k.i}],f=[{k:"timescale",fn:parseInt,def:1},{k:"timeShiftBufferDepth",fn:k.j},{k:"presentationTimeOffset",fn:parseFloat,def:0},{k:"indexRange",fn:k.f},{k:"indexRangeExact",fn:k.i,def:!1},{k:"availabilityTimeOffset",fn:parseFloat},{k:"availabilityTimeComplete",fn:k.i,def:!0}],c=f.concat([{k:"duration",
fn:parseInt},{k:"startNumber",fn:parseInt}]),d={ContentProtection:[{k:"schemeIdUri",fn:k.g},{k:"value",fn:k.g}],SegmentURL:[{k:"media",fn:k.g},{k:"mediaRange",fn:k.f},{k:"index",fn:k.g},{k:"indexRange",fn:k.f}],S:[{k:"t",fn:parseInt,n:"ts"},{k:"d",fn:parseInt},{k:"r",fn:parseInt}],SegmentTimeline:[],SegmentBase:f,SegmentTemplate:c.concat([{k:"initialization",fn:function(a){return{media:a,range:void 0}}},{k:"index",fn:k.g},{k:"media",fn:k.g},{k:"bitstreamSwitching",fn:k.g}]),SegmentList:c,ContentComponent:[{k:"id",
fn:k.g},{k:"lang",fn:e.c},{k:"contentType",fn:k.g},{k:"par",fn:k.k}],Representation:h.concat([{k:"id",fn:k.g},{k:"bandwidth",fn:parseInt,n:"bitrate"},{k:"qualityRanking",fn:parseInt}]),AdaptationSet:h.concat([{k:"id",fn:k.g},{k:"group",fn:parseInt},{k:"lang",fn:e.c},{k:"contentType",fn:k.g},{k:"par",fn:k.k},{k:"minBandwidth",fn:parseInt,n:"minBitrate"},{k:"maxBandwidth",fn:parseInt,n:"maxBitrate"},{k:"minWidth",fn:parseInt},{k:"maxWidth",fn:parseInt},{k:"minHeight",fn:parseInt},{k:"maxHeight",fn:parseInt},
{k:"minFrameRate",fn:k.h},{k:"maxFrameRate",fn:k.h},{k:"segmentAlignment",fn:k.l},{k:"subsegmentAlignment",fn:k.l},{k:"bitstreamSwitching",fn:k.i}]),Period:[{k:"id",fn:k.g},{k:"start",fn:k.j},{k:"duration",fn:k.j},{k:"bitstreamSwitching",fn:k.i}],MPD:[{k:"id",fn:k.g},{k:"profiles",fn:k.g},{k:"type",fn:k.g,def:"static"},{k:"availabilityStartTime",fn:k.m},{k:"availabilityEndTime",fn:k.m},{k:"publishTime",fn:k.m},{k:"mediaPresentationDuration",fn:k.j,n:"duration"},{k:"minimumUpdatePeriod",fn:k.j},{k:"minBufferTime",
fn:k.j},{k:"timeShiftBufferDepth",fn:k.j},{k:"suggestedPresentationDelay",fn:k.j},{k:"maxSegmentDuration",fn:k.j},{k:"maxSubsegmentDuration",fn:k.j}],Role:[{k:"schemeIdUri",fn:k.g},{k:"value",fn:k.g}],Accessibility:[{k:"schemeIdUri",fn:k.g},{k:"value",fn:parseInt}]};g.a=function(b,c){var f=d[b.nodeName];a.i(l.a)(f,"no attributes for "+b.nodeName);for(var e=c||{},h=0;h<f.length;h++){var g=f[h],k=g.k,m=g.fn,w=g.n,g=g.def;b.hasAttribute(k)?e[w||k]=m(b.getAttribute(k)):null!=g&&(e[w||k]=g)}return e}},
function(e,g,a){a.d(g,"a",function(){return l});a.d(g,"b",function(){return k});a.d(g,"c",function(){return h});a.d(g,"d",function(){return f});e=function(a){return function(c){return a.reduce(function(a,d){c.hasOwnProperty(d)&&(a[d]=c[d]);return a},{})}};var l=e("availabilityStartTime baseURL duration id locations periods presentationLiveGap suggestedPresentationDelay timeShiftBufferDepth transportType type".split(" ")),k=e(["adaptations","baseURL","duration","id","start"]),h=e("accessibility baseURL contentProtection id lang representations type".split(" ")),
f=e("bitrate baseURL codecs height id index mimeType width".split(" "))},function(e,g,a){function l(a,c){return"string"==typeof a?l.parseFromString(a,c):l.parseFromDocument(a,c)}var k=a(1),h=a(120);l.parseFromString=function(a,c){return l.parseFromDocument((new DOMParser).parseFromString(a,"application/xml"),c)};l.parseFromDocument=function(f,c){var d=f.documentElement;k.a.equal(d.nodeName,"MPD","document root should be MPD");return a.i(h.a)(d,c)};g.a=l},function(e,g,a){function l(b,c){var d=a.i(p.a)(b,
function(a,b,d){switch(b){case "BaseURL":a.baseURL=d.textContent;break;case "Location":a.locations.push(d.textContent);break;case "Period":a.periods.push(k(d,c))}return a},{transportType:"dash",periods:[],locations:[]}),d=a.i(q.a)(b,d);if(/dynamic/.test(d.type)){var f=d.periods[0].adaptations.filter(function(a){return"video"==a.type})[0],f=a.i(p.b)(f);f||(console.warn("Live edge not deduced from manifest, setting a default one"),f=Date.now()/1E3-60);d.availabilityStartTime=d.availabilityStartTime.getTime()/
1E3;d.presentationLiveGap=Date.now()/1E3-(f+d.availabilityStartTime)}return a.i(r.a)(d)}function k(b,c){var d=a.i(q.a)(b,a.i(p.a)(b,function(a,b,d){switch(b){case "BaseURL":a.baseURL=d.textContent;break;case "AdaptationSet":b=h(d,c),null==b.id&&(b.id=a.adaptations.length),a.adaptations.push(b)}return a},{adaptations:[]}));return a.i(r.b)(d)}function h(e,h){var g=void 0,k=a.i(p.a)(e,function(e,k,m){switch(k){case "Accessibility":g=a.i(q.a)(m);break;case "BaseURL":e.baseURL=m.textContent;break;case "ContentComponent":k=
a.i(q.a)(m);e.contentComponent=k;break;case "ContentProtection":k=h(a.i(q.a)(m),m);e.contentProtection=k;break;case "Representation":k=f(m);null==k.id&&(k.id=e.representations.length);e.representations.push(k);break;case "Role":k=a.i(q.a)(m);e.role=k;break;case "SegmentBase":e.index=b(m);break;case "SegmentList":e.index=d(m);break;case "SegmentTemplate":e.index=c(m)}return e},{representations:[]}),m=a.i(q.a)(e,k);m.type=a.i(p.c)(m);m.accessibility=[];a.i(p.d)(g)&&m.accessibility.push("hardOfHearing");
a.i(p.e)(g)&&m.accessibility.push("visuallyImpaired");m.representations=m.representations.map(function(a){x.forEach(function(b){!a.hasOwnProperty(b)&&m.hasOwnProperty(b)&&(a[b]=m[b])});return a});return a.i(r.c)(m)}function f(f){var e=a.i(p.a)(f,function(a,f,e){switch(f){case "BaseURL":a.baseURL=e.textContent;break;case "SegmentBase":a.index=b(e);break;case "SegmentList":a.index=d(e);break;case "SegmentTemplate":a.index=c(e)}return a},{});f=a.i(q.a)(f,e);return a.i(r.d)(f)}function c(a){a=m(a);a.indexType||
(a.indexType="template");return a}function d(b){var c=m(b);c.list=[];c.indexType="list";return a.i(p.a)(b,function(b,c,d){"SegmentURL"==c&&b.list.push(a.i(q.a)(d));return b},c)}function b(b){var c=a.i(p.a)(b,function(b,c,d){if("Initialization"==c){var f=c=void 0;d.hasAttribute("range")&&(c=a.i(p.f)(d.getAttribute("range")));d.hasAttribute("sourceURL")&&(f=d.getAttribute("sourceURL"));b.initialization={range:c,media:f}}return b},a.i(q.a)(b));"SegmentBase"==b.nodeName&&(c.indexType="base",c.timeline=
[]);return c}function m(c){return a.i(p.a)(c,function(a,b,c){"SegmentTimeline"==b&&(a.indexType="timeline",a.timeline=n(c));return a},b(c))}function n(b){return a.i(p.a)(b,function(b,c,d){c=b.length;d=a.i(q.a)(d);null==d.ts&&(c=0<c&&b[c-1],d.ts=c?c.ts+c.d*(c.r+1):0);null==d.r&&(d.r=0);b.push(d);return b},[])}a.d(g,"a",function(){return l});a(1);var p=a(48),r=a(118),q=a(117),x=["codecs","height","index","mimeType","width"]},function(e,g,a){function l(c,f){for(var e=c.length,h=0,g,k=void 0;h+8<e&&(k=
a.i(b.e)(c,h),g=a.i(b.e)(c,h+4),a.i(d.a)(0<k,"dash: out of range size"),g!==f);)h+=k;if(h>=e)return-1;a.i(d.a)(h+k<=e,"dash: atom out of range");return h}function k(c){for(var f=c.length,e=0,h,g=void 0;e+8<f&&(g=a.i(b.e)(c,e),h=a.i(b.e)(c,e+4),a.i(d.a)(0<g,"dash: out of range size"),1835295092!==h);)e+=g;c=e<f?c.subarray(e+8,e+g):null;return c}function h(c,d){var f=l(c,1936286840);if(-1==f)return null;var e=a.i(b.e)(c,f),f=f+4+4,h=c[f],f=f+8,g=a.i(b.e)(c,f),f=f+4;if(0===h)h=a.i(b.e)(c,f),f+=4,d+=
a.i(b.e)(c,f)+e,f+=4;else if(1===h)h=a.i(b.f)(c,f),f+=8,d+=a.i(b.f)(c,f)+e,f+=8;else return null;for(var e=[],f=f+2,k=a.i(b.g)(c,f),f=f+2;0<=--k;){var m=a.i(b.e)(c,f),f=f+4,n=m&2147483647;if(1==(m&2147483648)>>>31)throw Error("not implemented");m=a.i(b.e)(c,f);f+=4;f+=4;e.push({ts:h,d:m,r:0,range:[d,d+n-1]});h+=m;d+=n}return{segments:e,timescale:g}}function f(c){var f=c.systemId;c=c.privateData;f=f.replace(/-/g,"");a.i(d.a)(32===f.length);f=a.i(b.h)(4,a.i(b.j)(f),a.i(b.i)(c.length),c);c=f.length+
8;return a.i(b.h)(a.i(b.i)(c),a.i(b.b)("pssh"),f)}function c(c,d){if(!d||!d.length)return c;var e=l(c,1836019574);if(-1==e)return c;for(var h=a.i(b.e)(c,e),g=[c.subarray(e,e+h)],k=0;k<d.length;k++)g.push(f(d[k]));g=b.h.apply(null,g);g.set(a.i(b.i)(g.length),0);return a.i(b.h)(c.subarray(0,e),g,c.subarray(e+h))}a.d(g,"a",function(){return h});a.d(g,"b",function(){return c});a.d(g,"c",function(){return k});var d=a(1),b=a(10)},function(e,g,a){var l=a(0);a.n(l);g.a={directFile:!0,manifest:{parser:function(a){a=
a.url;return l.Observable.of({manifest:{transportType:"directfile",locations:[a],periods:[],isLive:!1,duration:Infinity,adaptations:null},url:a})}}}},function(e,g,a){e=a(125);var l=a(116);a=a(122);g.a={smooth:e.a,dash:l.a,directfile:a.a}},function(e,g,a){function l(a){return a.replace(c,"\n").replace(f,function(a,b){return String.fromCharCode(b)})}function k(c,f){var e=/<sync[ >]/ig,g=/<sync[ >]|<\/body>/ig,k=[],n=c.match(d)[1],p,v;g.exec(c);p=/\.(\S+)\s*{([^}]*)}/gi;v={};for(var y;y=p.exec(n);){var u=
y[1];y=y[2].match(/\s*lang:\s*(\S+);/i)[1];u&&y&&(v[y]=u)}n=v[f];for(a.i(h.a)(n,"sami: could not find lang "+f+" in CSS");;){p=e.exec(c);v=g.exec(c);if(!p&&!v)break;if(!p||!v||p.index>=v.index)throw Error("parse error");v=c.slice(p.index,v.index);p=v.match(m);if(!p)throw Error("parse error (sync time attribute)");u=+p[1];if(isNaN(u))throw Error("parse error (sync time attribute NaN)");p=k;v=v.split("\n");u/=1E3;y=v.length;for(var B;0<=--y;)if(B=v[y].match(b)){var A=B[2];n===B[1]&&(" "===A?p[p.length-
1].end=u:p.push({text:l(A),start:u}))}}return k}a.d(g,"a",function(){return k});var h=a(1),f=/&#([0-9]+);/g,c=/<br>/gi,d=/<style[^>]*>([\s\S]*?)<\/style[^>]*>/i,b=/\s*<p class=([^>]+)>(.*)/i,m=/<sync[^>]+?start="?([0-9]*)"?[^0-9]/i},function(e,g,a){function l(a){return a.responseData.getElementsByTagName("media")[0].getAttribute("src")}function k(a){return(a=a.match(S))&&a[1]||""}function h(a,b){return b?a.replace(S,"?token="+b):a.replace(S,"")}function f(a){return a.getResolvedURL().replace(/\{bitrate\}/g,
a.getRepresentation().bitrate).replace(/\{start time\}/g,a.getTime())}var c=a(0);a.n(c);e=a(6);a.n(e);var d=a(10),b=a(3),m=a(24),n=a(25),p=a(16),r=a(51),q=a(127),x=a(126),t=a(49),w=a(124),v=a(50),y=x.a.patchSegment,u=x.a.createVideoInitSegment,B=x.a.createAudioInitSegment,A=x.a.getMdat,z=x.a.getTraf,G=x.a.parseTfrf,C=x.a.parseTfxd,H={"application/x-sami":w.a,"application/smil":w.a,"application/ttml+xml":v.a,"application/ttml+xml+mp4":v.a,"text/vtt":function(a){return a}},D=r.a.RequestResponse,E=e.EmptyObservable.create,
L=/\.(isml?)(\?token=\S+)?$/,T=/\.wsx?(\?token=\S+)?/,S=/\?token=(\S+)/;g.a=function(){function e(a,c){var d=void 0,f=void 0;if(c.getAdaptation().isLive){var e=z(a);e?(d=G(e),f=C(e)):b.a.warn("smooth: could not find traf atom")}else d=null;f||(f={d:c.getDuration(),ts:c.getTime()});return{nextSegments:d,currentSegment:f}}var g=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},w=a.i(q.a)(g),v=g.createXHR,x=function(a){var b=a.segment;if(b.isInitSegment()){a=b.getAdaptation();var b=b.getRepresentation(),
d={},e=a.smoothProtection||{};switch(a.type){case "video":d=u(b.index.timescale,b.width,b.height,72,72,4,b.codecPrivateData,e.keyId,e.keySystems);break;case "audio":d=B(b.index.timescale,b.channels,b.bitsPerSample,b.packetSize,b.samplingRate,b.codecPrivateData,e.keyId,e.keySystems)}return c.Observable.of(new D(200,"","arraybuffer",Date.now()-100,Date.now(),d.length,d))}var h=g.segmentLoader;a=f(b);var k={adaptation:new m.a(b.getAdaptation()),representation:new n.a(b.getRepresentation()),segment:new p.a(b),
transport:"smooth",url:a};return h?c.Observable.create(function(a){var b=!1,c=!1,d=h(k,{reject:function(){var d=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};c||(b=!0,a.error(d))},resolve:function(){var d=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};c||(b=!0,a.next({responseData:d.data,size:d.size||0,duration:d.duration||0}),a.complete())},fallback:function(){c=!0;N(k).subscribe(a)}});return function(){b||c||"function"!==typeof d||d()}}):N(k)},N=function(b){var c=b.url,d=
void 0;if(b=b.segment.range)d=b[0],d=(b=b[1])&&Infinity!==b?"bytes="+ +d+"-"+ +b:"bytes="+ +d+"-",d={Range:d};return a.i(r.a)({url:c,responseType:"arraybuffer",headers:d,createXHR:v})},K={loader:function(a){return x({segment:a.segment})},parser:function(a){var b=a.segment;a=a.response.responseData;if(b.isInitSegment())return c.Observable.of({segmentData:a,timings:null});a=new Uint8Array(a);var d=e(a,b),b=d.nextSegments,d=d.currentSegment;a=y(a,d.ts);return c.Observable.of({segmentData:a,nextSegments:b,
currentSegment:d})}};return{directFile:!1,manifest:{resolver:function(b){b=b.url;var d=void 0,f=k(b),d=T.test(b)?a.i(r.a)({url:h(b,""),responseType:"document",resultSelector:l,createXHR:v}):c.Observable.of(b);return d.map(function(a){var b=a.match(L);a=b?a.replace(b[1],b[1]+"/manifest"):a;return{url:h(a,f)}})},loader:function(b){b=b.url;return a.i(r.a)({url:b,responseType:"document",createXHR:v})},parser:function(a){a=a.response;return c.Observable.of({manifest:w(a.responseData),url:a.url})}},audio:K,
video:K,text:{loader:function(b){var c=b.segment;if(c.isInitSegment())return E();b=c.getRepresentation().mimeType;c=f(c);return 0<=b.indexOf("mp4")?a.i(r.a)({url:c,responseType:"arraybuffer",createXHR:v}):a.i(r.a)({url:c,responseType:"text",createXHR:v})},parser:function(b){var f=b.response;b=b.segment;var h=b.getAdaptation().lang,g=b.getRepresentation(),k=g.mimeType,g=g.index,m=H[k];if(!m)throw Error("could not find a text-track parser for the type "+k);var l=f.responseData;0<=k.indexOf("mp4")?(l=
new Uint8Array(l),f=a.i(d.a)(A(l))):f=l;l=e(l,b);k=l.nextSegments;l=l.currentSegment;b=m(f,h,b.getTime()/g.timescale);return c.Observable.of({segmentData:b,currentSegment:l,nextSegments:k})}},image:{loader:function(b){b=b.segment;if(b.init)return E();b=f(b);return a.i(r.a)({url:b,responseType:"arraybuffer",createXHR:v})},parser:function(b){var d=new Uint8Array(b.response.responseData),f=b=void 0;d&&(d=a.i(t.a)(d),b=d.thumbs,f=d.timescale);return c.Observable.of({segmentData:b,currentSegment:{ts:0,
d:Infinity},timescale:f})}}}}},function(e,g,a){function l(b,c){var d=c.length+8,f=a.i(n.h),d=a.i(n.i)(d),e;r[b]?e=r[b]:(e=a.i(n.b)(b),r[b]=e);return f(d,e,c)}function k(b,c,d,f,e){for(var h=b.length,g=0,k;g<h;){k=a.i(n.e)(b,g);if(1970628964===a.i(n.e)(b,g+4)&&a.i(n.e)(b,g+8)===c&&a.i(n.e)(b,g+12)===d&&a.i(n.e)(b,g+16)===f&&a.i(n.e)(b,g+20)===e)return b.subarray(g+24,g+k);g+=k}}function h(c,d){for(var f=c.length,e=0,h,g=void 0;e+8<f&&(g=a.i(n.e)(c,e),h=a.i(n.e)(c,e+4),a.i(b.a)(0<g,"smooth: out of range size"),
h!==d);)e+=g;return e<f?c.subarray(e+8,e+g):null}function f(a,b,c,d){var f=[a,b,c];d.forEach(function(a){a=q.pssh(a.systemId,a.privateData,a.keyIds);f.push(a)});return f}function c(b,c,d,f){var e=b.length,h=c.length;d=d.length;b=b.subarray(d,e);e=new Uint8Array(h+(e-d));e.set(c,0);e.set(b,h);c=c.length+8;e.set(a.i(n.i)(c),f+16);return e}function d(b,c,d,e,h,g,k){d=q.mult("stbl",[d,l("stts",new Uint8Array(8)),l("stsc",new Uint8Array(8)),l("stsz",new Uint8Array(12)),l("stco",new Uint8Array(8))]);var m=
l("url ",new Uint8Array([0,0,0,1])),m=q.dref(m),m=q.mult("dinf",[m]);e=q.mult("minf",[e,m,d]);c=q.hdlr(c);d=q.mdhd(b);c=q.mult("mdia",[d,c,e]);h=q.tkhd(h,g,1);h=q.mult("trak",[h,c]);g=q.trex(1);g=q.mult("mvex",[g]);b=q.mvhd(b,1);k=q.mult("moov",f(b,g,h,k));b=q.ftyp("isom",["isom","iso2","iso6","avc1","dash"]);return a.i(n.h)(b,k)}var b=a(1),m=a(9),n=a(10),p=[96E3,88200,64E3,48E3,44100,32E3,24E3,22050,16E3,12E3,11025,8E3,7350],r={},q={mult:function(a,b){return l(a,n.h.apply(null,b))},avc1encv:function(b,
c,d,f,e,h,g,k,m,p){return l(b,a.i(n.h)(6,a.i(n.m)(c),16,a.i(n.m)(d),a.i(n.m)(f),a.i(n.m)(e),2,a.i(n.m)(h),6,[0,1,g.length],a.i(n.b)(g),31-g.length,a.i(n.m)(k),[255,255],m,"encv"===b?p:[]))},avcc:function(b,c,d){d=2===d?1:4===d?3:0;var f=b[1],e=b[2],h=b[3];return l("avcC",a.i(n.h)([1,f,e,h,252|d,225],a.i(n.m)(b.length),b,[1],a.i(n.m)(c.length),c))},dref:function(b){return l("dref",a.i(n.h)(7,[1],b))},esds:function(b,c){return l("esds",a.i(n.h)(4,[3,25],a.i(n.m)(b),[0,4,17,64,21],11,[5,2],a.i(n.j)(c),
[6,1,2]))},frma:function(b){return l("frma",a.i(n.b)(b))},free:function(a){return l("free",new Uint8Array(a-8))},ftyp:function(b,c){return l("ftyp",n.h.apply(null,[a.i(n.b)(b),[0,0,0,1]].concat(c.map(n.b))))},hdlr:function(b){var c;switch(b){case "video":b="vide";c="VideoHandler";break;case "audio":b="soun";c="SoundHandler";break;default:b="hint",c=""}return l("hdlr",a.i(n.h)(8,a.i(n.b)(b),12,a.i(n.b)(c),1))},mdhd:function(b){return l("mdhd",a.i(n.h)(12,a.i(n.i)(b),8))},moof:function(a,b){return q.mult("moof",
[a,b])},mp4aenca:function(b,c,d,f,e,h,g,k){return l(b,a.i(n.h)(6,a.i(n.m)(c),8,a.i(n.m)(d),a.i(n.m)(f),2,a.i(n.m)(e),a.i(n.m)(h),2,g,"enca"===b?k:[]))},mvhd:function(b,c){return l("mvhd",a.i(n.h)(12,a.i(n.i)(b),4,[0,1],2,[1,0],10,[0,1],14,[0,1],14,[64,0,0,0],26,a.i(n.m)(c+1)))},pssh:function(c){var d=1<arguments.length&&void 0!==arguments[1]?arguments[1]:[],f=2<arguments.length&&void 0!==arguments[2]?arguments[2]:[];c=c.replace(/-/g,"");a.i(b.a)(32===c.length,"wrong system id length");var e,h=f.length;
0<h?(e=1,f=n.h.apply(null,[a.i(n.i)(h)].concat(f))):(e=0,f=[]);return l("pssh",a.i(n.h)([e,0,0,0],a.i(n.j)(c),f,a.i(n.i)(d.length),d))},saio:function(b,c,d,f){return l("saio",a.i(n.h)(4,[0,0,0,1],a.i(n.i)(b.length+c.length+d.length+f.length+8+8+8+8)))},saiz:function(b){if(0===b.length)return l("saiz",new Uint8Array);var c=a.i(n.e)(b,0),d=a.i(n.e)(b,4),f=new Uint8Array(9+d);f.set(a.i(n.i)(d),5);for(var d=9,e=8,h,g;e<b.length;)e+=8,2===(c&2)?(g=2,h=a.i(n.g)(b,e),e+=2+6*h):g=h=0,f[d]=6*h+8+g,d++;return l("saiz",
f)},schm:function(b,c){return l("schm",a.i(n.h)(4,a.i(n.b)(b),a.i(n.i)(c)))},senc:function(a){return l("senc",a)},smhd:function(){return l("smhd",new Uint8Array(8))},stsd:function(a){return l("stsd",n.h.apply(null,[7,[a.length]].concat(a)))},tkhd:function(b,c,d){return l("tkhd",a.i(n.h)(a.i(n.i)(7),8,a.i(n.i)(d),20,[1,0,0,0],[0,1,0,0],12,[0,1,0,0],12,[64,0,0,0],a.i(n.m)(b),2,a.i(n.m)(c),2))},trex:function(b){return l("trex",a.i(n.h)(4,a.i(n.i)(b),[0,0,0,1],12))},tfdt:function(b){return l("tfdt",a.i(n.h)([1,
0,0,0],a.i(n.n)(b)))},tenc:function(b,c,d){return l("tenc",a.i(n.h)(6,[b,c],a.i(n.j)(d)))},traf:function(a,b,c,d,f){var e=[a,b,c];d&&e.push(q.senc(d),q.saiz(d),q.saio(f,a,b,c));return q.mult("traf",e)},trun:function(b){if(b[11]&1)return b;var c=new Uint8Array(b.length+4);c.set(a.i(n.i)(b.length+4),0);c.set(b.subarray(4,16),4);c[11]|=1;c.set([0,0,0,0],16);c.set(b.subarray(16,b.length),20);return c},vmhd:function(){var a=new Uint8Array(12);a[3]=1;return l("vmhd",a)}},x={traf:function(a){return(a=h(a,
1836019558))?h(a,1953653094):null},senc:function(a){return k(a,2721664850,1520127764,2722393154,2086964724)},tfxd:function(a){return k(a,1830656773,1121273062,2162299933,2952222642)},tfrf:function(a){return k(a,3565190898,3392751253,2387879627,2655430559)},mdat:function(a){return h(a,1835295092)}};g.a={getMdat:x.mdat,getTraf:x.traf,parseTfrf:function(b){b=x.tfrf(b);if(!b)return[];for(var c=[],d=b[0],f=b[4],e=0;e<f;e++){var h,g;1==d?(g=a.i(n.f)(b,16*e+5),h=a.i(n.f)(b,16*e+13)):(g=a.i(n.e)(b,8*e+5),
h=a.i(n.e)(b,8*e+9));c.push({ts:g,d:h})}return c},parseTfxd:function(b){if(b=x.tfxd(b))return{d:a.i(n.f)(b,12),ts:a.i(n.f)(b,4)}},createVideoInitSegment:function(b,c,f,e,h,g,k,m,l){l||(l=[]);var p=k.split("00000001");k=p[1];p=p[2];k=a.i(n.j)(k);p=a.i(n.j)(p);g=q.avcc(k,p,g);l.length?(m=q.tenc(1,8,m),m=q.mult("schi",[m]),k=q.schm("cenc",65536),p=q.frma("avc1"),m=q.mult("sinf",[p,k,m]),e=q.avc1encv("encv",1,c,f,e,h,"AVC Coding",24,g,m)):e=q.avc1encv("avc1",1,c,f,e,h,"AVC Coding",24,g);e=q.stsd([e]);
return d(b,"video",e,q.vmhd(),c,f,l)},createAudioInitSegment:function(b,c,f,e,h,g,k,m){m||(m=[]);g||(g=(32|p.indexOf(h)&31)<<4,g=(g|c&31)<<3,g=a.i(n.o)(a.i(n.m)(g)));g=q.esds(1,g);if(m.length){k=q.tenc(1,8,k);k=q.mult("schi",[k]);var l=q.schm("cenc",65536),r=q.frma("mp4a");k=q.mult("sinf",[r,l,k]);c=q.mp4aenca("enca",1,c,f,e,h,g,k)}else c=q.mp4aenca("mp4a",1,c,f,e,h,g);c=q.stsd([c]);return d(b,"audio",c,q.smhd(),0,0,m)},patchSegment:function(b,d){var f=b.subarray(0,a.i(n.e)(b,0)),e=q.tfdt(d),h=e.length,
g=a.i(n.e)(f,8),k=a.i(n.e)(f,8+g),l=a.i(n.e)(f,8+g+8),p=a.i(n.e)(f,8+g+8+l),r=f.subarray(8,8+g),t=f.subarray(8+g+8,8+g+8+k-8),k=t.subarray(0,l),p=t.subarray(l,l+p);k.set([0,0,0,1],12);t=x.senc(t);p=q.trun(p);e=q.traf(k,e,p,t,r);r=q.moof(r,e);h=8+g+8+l+h;return m.t?c(b,r,f,h):8<=f.length-r.length?(f=f.length-r.length,b.set(r,0),b.set(q.free(f),r.length),f=r.length+8+f,b.set(a.i(n.i)(f),h+16),b):c(b,r,f,h)}}},function(e,g,a){function l(a){return"boolean"==typeof a?a:"string"==typeof a?"TRUE"===a.toUpperCase():
!1}function k(a){if(!a)return Infinity;a=a.index;var b=a.timeline[a.timeline.length-1];return(b.ts+(b.r+1)*b.d)/a.timescale}function h(b){return[{systemId:"edef8ba9-79d6-4ace-a3c8-27dcd51d21ed",privateData:a.i(f.h)([8,1,18,16],b)}]}var f=a(10),c=a(1),d=a(21),b={audio:"audio/mp4",video:"video/mp4",text:"application/ttml+xml"},m={audio:"mp4a.40.2",video:"avc1.4D401E"};e={AACL:"audio/mp4",AVC1:"video/mp4",H264:"video/mp4",TTML:"application/ttml+xml+mp4"};var n={audio:[["Bitrate","bitrate",parseInt],
["AudioTag","audiotag",parseInt],["FourCC","mimeType",e],["Channels","channels",parseInt],["SamplingRate","samplingRate",parseInt],["BitsPerSample","bitsPerSample",parseInt],["PacketSize","packetSize",parseInt],["CodecPrivateData","codecPrivateData",String]],video:[["Bitrate","bitrate",parseInt],["FourCC","mimeType",e],["CodecPrivateData","codecs",function(a){return(a=(/00000001\d7([0-9a-fA-F]{6})/.exec(a)||[])[1])?"avc1."+a:""}],["MaxWidth","width",parseInt],["MaxHeight","height",parseInt],["CodecPrivateData",
"codecPrivateData",String]],text:[["Bitrate","bitrate",parseInt],["FourCC","mimeType",e]]};g.a=function(){function e(a,b,c){for(a=a.firstElementChild;a;)c=b(c,a.nodeName,a),a=a.nextElementSibling;return c}function g(f,h){f.hasAttribute("Timescale")&&(h=+f.getAttribute("Timescale"));var g=f.getAttribute("Type"),k=f.getAttribute("Subtype"),l=f.getAttribute("Name"),p=a.i(d.c)(f.getAttribute("Language")),r=f.getAttribute("Url"),q=n[g],t=[];a.i(c.a)(q,"unrecognized QualityLevel type "+g);var x=0,w=e(f,
function(a,b,c){switch(b){case "QualityLevel":b={};for(var d=0;d<q.length;d++){var f=q[d],e=f[0],h=f[2];b[f[1]]="function"==typeof h?h(c.getAttribute(e)):h[c.getAttribute(e)]}"audio"==g&&(c=c.getAttribute("FourCC")||"",d=b.codecPrivateData,c="AACH"==c?5:d?(parseInt(d.substr(0,2),16)&248)>>3:2,b.codecs=c?"mp4a.40."+c:"");if("video"!=g||b.bitrate>u)b.id=x++,a.representations.push(b);break;case "c":b=a.index;var d=a.index.timeline,f=d.length,e=0<f?d[f-1]:{d:0,ts:0,r:0},h=+c.getAttribute("d"),k=c.getAttribute("t");
(c=+c.getAttribute("r"))&&c--;0<f&&!e.d&&(e.d=k-e.ts,d[f-1]=e);0<f&&h==e.d&&null==k?e.r+=(c||0)+1:d.push({d:h,ts:null==k?e.ts+e.d*(e.r+1):+k,r:c});b.timeline=d}return a},{representations:[],index:{timeline:[],indexType:"smooth",timescale:h,initialization:{}}}),v=w.representations,w=w.index;a.i(c.a)(v.length,"adaptation should have at least one representation");v.forEach(function(a){return a.codecs=a.codecs||m[g]});v.forEach(function(a){return a.mimeType=a.mimeType||b[g]});if("ADVT"==k)return null;
"text"===g&&"DESC"===k&&t.push("hardOfHearing");return{type:g,accessibility:t,index:w,representations:v,name:l,lang:p,baseURL:r}}function q(a){return x((new DOMParser).parseFromString(a,"application/xml"))}function x(b){b=b.documentElement;c.a.equal(b.nodeName,"SmoothStreamingMedia","document root should be SmoothStreamingMedia");a.i(c.a)(/^[2]-[0-2]$/.test(b.getAttribute("MajorVersion")+"-"+b.getAttribute("MinorVersion")),"Version should be 2.0, 2.1 or 2.2");var d=+b.getAttribute("Timescale")||1E7,
h=0,m=e(b,function(b,e,k){switch(e){case "Protection":k=k.firstElementChild;c.a.equal(k.nodeName,"ProtectionHeader","Protection should have ProtectionHeader child");e=a.i(f.b)(atob(k.textContent));var m;m=a.i(f.d)(e,8);m=a.i(f.k)(e.subarray(10,10+m));m=(new DOMParser).parseFromString(m,"application/xml").querySelector("KID").textContent;m=a.i(f.l)(atob(m)).toLowerCase();var l=a.i(f.j)(m);k=k.getAttribute("SystemID").toLowerCase().replace(/\{|\}/g,"");e={keyId:m,keySystems:[{systemId:k,privateData:e}].concat(B(l))};
b.protection=e;break;case "StreamIndex":if(e=g(k,d))e.id=h++,b.adaptations.push(e)}return b},{protection:null,adaptations:[]}),n=m.protection,m=m.adaptations;m.forEach(function(a){return a.smoothProtection=n});var p=void 0,r=void 0,q=void 0,t=void 0,w=l(b.getAttribute("IsLive"));if(w)var p=v,q=+b.getAttribute("DVRWindowLength")/d,t=y,r=m.filter(function(a){return"video"==a.type})[0],x=m.filter(function(a){return"audio"==a.type})[0],r=Math.min(k(r),k(x)),r=Date.now()/1E3-(r+t);return{transportType:"smooth",
profiles:"",type:w?"dynamic":"static",suggestedPresentationDelay:p,timeShiftBufferDepth:q,presentationLiveGap:r,availabilityStartTime:t,periods:[{duration:(+b.getAttribute("Duration")||Infinity)/d,adaptations:m,laFragCount:+b.getAttribute("LookAheadFragmentCount")}]}}function t(a){return"string"==typeof a?q(a):x(a)}var w=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},v=w.suggestedPresentationDelay||20,y=w.referenceDateTime||Date.UTC(1970,0,1,0,0,0,0)/1E3,u=w.minRepresentationBitrate||19E4,
B=w.keySystems||h;t.parseFromString=q;t.parseFromDocument=x;return t}},function(e,g,a){function l(a){return a*Math.pow(2,(1<arguments.length&&void 0!==arguments[1]?arguments[1]:1)-1)*(1+(2*Math.random()-1)*k)}a.d(g,"a",function(){return l});var k=.3},function(e,g,a){a.d(g,"a",function(){return l});var l=function(){function a(){if(!(this instanceof a))throw new TypeError("Cannot call a class as a function");this.hash={}}a.prototype.add=function(a){this.hash[a]=!0};a.prototype.remove=function(a){delete this.hash[a]};
a.prototype.test=function(a){return!0===this.hash[a]};return a}()},function(e,g,a){function l(a){return null==a?"":String(a).replace(n,function(a){return p[a]})}function k(b){var c=b.getAverageBitrates(),f=void 0,e=void 0;c.video.take(1).subscribe(function(a){return e=a|0});c.audio.take(1).subscribe(function(a){return f=a|0});return{manifest:b.man,version:b.version,timeFragment:b.frag,currentTime:b.getCurrentTime(),state:b.getPlayerState(),buffer:a.i(d.b)(b.video.buffered),volume:b.getVolume(),video:{adaptation:b.adas.video,
representation:b.reps.video,maxBitrate:b.getVideoMaxBitrate(),bufferSize:b.getVideoBufferSize(),avrBitrate:e},audio:{adaptation:b.adas.audio,representation:b.reps.audio,maxBitrate:b.getAudioMaxBitrate(),bufferSize:b.getAudioBufferSize(),avrBitrate:f}}}function h(a,b){var c=b.parentNode.querySelector("#cp--debug-infos-content");if(c){var d=void 0;try{d=k(a)}catch(u){return}var f=d,e=f.video,h=f.audio,f=f.manifest,d="<b>Player v"+d.version+"</b> ("+d.state+")<br>";f&&e&&h&&(d+=["Container: "+l(f.transportType),
"Live: "+l(""+f.isLive),"Downloading bitrate (Kbit/s):\n "+(e.representation.bitrate/1E3).toFixed(3)+"/"+(h.representation.bitrate/1E3).toFixed(3),"Estimated bandwidth (Kbit/s):\n "+(e.avrBitrate/1E3).toFixed(3)+"/"+(h.avrBitrate/1E3).toFixed(3),"Location: "+f.locations[0]].join("<br>"));c.innerHTML=d}}function f(a,d){var f="<style>\n#cp--debug-infos {\n position: absolute;\n top: "+l(d.offsetTop+10)+"px;\n left: "+l(d.offsetLeft+10)+'px;\n width: 500px;\n height: 300px;\n background-color: rgba(10, 10, 10, 0.83);\n overflow: hidden;\n color: white;\n text-align: left;\n padding: 2em;\n box-sizing: border-box;\n}\n#cp--debug-hide-infos {\n float: right;\n cursor: pointer;\n}\n</style>\n<div id="cp--debug-infos">\n <a id="cp--debug-hide-infos">[x]</a>\n <p id="cp--debug-infos-content"></p>\n</div>',
e=d.parentNode,g=e.querySelector("#cp--debug-infos-container");g||(g=document.createElement("div"),g.setAttribute("id","cp--debug-infos-container"),e.appendChild(g));g.innerHTML=f;m||(m=e.querySelector("#cp--debug-hide-infos"),m.addEventListener("click",function(){return c(d)}));b&&clearInterval(b);b=setInterval(function(){return h(a,d)},1E3);h(a,d)}function c(a){(a=a.parentNode.querySelector("#cp--debug-infos-container"))&&a.parentNode.removeChild(a);b&&(clearInterval(b),b=null);m&&(m.removeEventListener("click",
c),m=null)}var d=a(19),b=void 0,m=void 0,n=/[&<>"']/g,p={"&":"&","<":"<",">":">",'"':""","'":"'"};g.a={getDebug:k,showDebug:f,hideDebug:c,toggleDebug:function(a,b){b.parentNode.querySelector("#cp--debug-infos-container")?c(b):f(a,b)}}},function(e,g,a){var l=this&&this.__extends||function(a,e){function f(){this.constructor=a}for(var c in e)e.hasOwnProperty(c)&&(a[c]=e[c]);a.prototype=null===e?Object.create(e):(f.prototype=e.prototype,new f)};e=function(a){function e(f,c,d){a.call(this);
this.parent=f;this.outerValue=c;this.outerIndex=d;this.index=0}l(e,a);e.prototype._next=function(a){this.parent.notifyNext(this.outerValue,a,this.outerIndex,this.index++,this)};e.prototype._error=function(a){this.parent.notifyError(a,this);this.unsubscribe()};e.prototype._complete=function(){this.parent.notifyComplete(this);this.unsubscribe()};return e}(a(2).Subscriber);g.InnerSubscriber=e},function(e,g,a){var l=a(0);e=function(){function a(a,f,c){this.kind=a;this.value=f;this.exception=c;this.hasValue=
"N"===a}a.prototype.observe=function(a){switch(this.kind){case "N":return a.next&&a.next(this.value);case "E":return a.error&&a.error(this.exception);case "C":return a.complete&&a.complete()}};a.prototype["do"]=function(a,f,c){switch(this.kind){case "N":return a&&a(this.value);case "E":return f&&f(this.exception);case "C":return c&&c()}};a.prototype.accept=function(a,f,c){return a&&"function"===typeof a.next?this.observe(a):this["do"](a,f,c)};a.prototype.toObservable=function(){switch(this.kind){case "N":return l.Observable.of(this.value);
case "E":return l.Observable["throw"](this.exception);case "C":return l.Observable.empty()}throw Error("unexpected notification kind value");};a.createNext=function(e){return"undefined"!==typeof e?new a("N",e):this.undefinedValueNotification};a.createError=function(e){return new a("E",void 0,e)};a.createComplete=function(){return this.completeNotification};a.completeNotification=new a("C");a.undefinedValueNotification=new a("N",void 0);return a}();g.Notification=e},function(e,g,a){e=function(){function a(e,
h){void 0===h&&(h=a.now);this.SchedulerAction=e;this.now=h}a.prototype.schedule=function(a,e,f){void 0===e&&(e=0);return(new this.SchedulerAction(this,a)).schedule(f,e)};a.now=Date.now?Date.now:function(){return+new Date};return a}();g.Scheduler=e},function(e,g,a){var l=this&&this.__extends||function(a,e){function f(){this.constructor=a}for(var c in e)e.hasOwnProperty(c)&&(a[c]=e[c]);a.prototype=null===e?Object.create(e):(f.prototype=e.prototype,new f)};e=function(a){function e(f,c){a.call(this);
this.subject=f;this.subscriber=c;this.closed=!1}l(e,a);e.prototype.unsubscribe=function(){if(!this.closed){this.closed=!0;var a=this.subject,c=a.observers;this.subject=null;!c||0===c.length||a.isStopped||a.closed||(a=c.indexOf(this.subscriber),-1!==a&&c.splice(a,1))}};return e}(a(5).Subscription);g.SubjectSubscription=e},function(e,g,a){var l=this&&this.__extends||function(a,c){function d(){this.constructor=a}for(var b in c)c.hasOwnProperty(b)&&(a[b]=c[b]);a.prototype=null===c?Object.create(c):(d.prototype=
c.prototype,new d)};e=a(0);var k=a(36),h=a(6);a=function(a){function c(c,b){a.call(this);this.arrayLike=c;this.scheduler=b;b||1!==c.length||(this._isScalar=!0,this.value=c[0])}l(c,a);c.create=function(a,b){var d=a.length;return 0===d?new h.EmptyObservable:1===d?new k.ScalarObservable(a[0],b):new c(a,b)};c.dispatch=function(a){var b=a.arrayLike,c=a.index,d=a.subscriber;d.closed||(c>=a.length?d.complete():(d.next(b[c]),a.index=c+1,this.schedule(a)))};c.prototype._subscribe=function(a){var b=this.arrayLike,
d=this.scheduler,f=b.length;if(d)return d.schedule(c.dispatch,0,{arrayLike:b,index:0,length:f,subscriber:a});for(d=0;d<f&&!a.closed;d++)a.next(b[d]);a.complete()};return c}(e.Observable);g.ArrayLikeObservable=a},function(e,g,a){var l=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var d in b)b.hasOwnProperty(d)&&(a[d]=b[d]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)};e=a(8);var k=a(0),h=a(2),f=a(5);a=function(a){function b(b,c){a.call(this);this.source=
b;this.subjectFactory=c;this._refCount=0}l(b,a);b.prototype._subscribe=function(a){return this.getSubject().subscribe(a)};b.prototype.getSubject=function(){var a=this._subject;if(!a||a.isStopped)this._subject=this.subjectFactory();return this._subject};b.prototype.connect=function(){var a=this._connection;a||(a=this._connection=new f.Subscription,a.add(this.source.subscribe(new c(this.getSubject(),this))),a.closed?(this._connection=null,a=f.Subscription.EMPTY):this._connection=a);return a};b.prototype.refCount=
function(){return this.lift(new d(this))};return b}(k.Observable);g.ConnectableObservable=a;g.connectableObservableDescriptor={operator:{value:null},_refCount:{value:0,writable:!0},_subscribe:{value:a.prototype._subscribe},getSubject:{value:a.prototype.getSubject},connect:{value:a.prototype.connect},refCount:{value:a.prototype.refCount}};var c=function(a){function b(b,c){a.call(this,b);this.connectable=c}l(b,a);b.prototype._error=function(b){this._unsubscribe();a.prototype._error.call(this,b)};b.prototype._complete=
function(){this._unsubscribe();a.prototype._complete.call(this)};b.prototype._unsubscribe=function(){var a=this.connectable;if(a){this.connectable=null;var b=a._connection;a._refCount=0;a._subject=null;a._connection=null;b&&b.unsubscribe()}};return b}(e.SubjectSubscriber),d=function(){function a(a){this.connectable=a}a.prototype.call=function(a,c){var d=this.connectable;d._refCount++;var f=new b(a,d),e=c._subscribe(f);f.closed||(f.connection=d.connect());return e};return a}(),b=function(a){function b(b,
c){a.call(this,b);this.connectable=c}l(b,a);b.prototype._unsubscribe=function(){var a=this.connectable;if(a){this.connectable=null;var b=a._refCount;0>=b?this.connection=null:(a._refCount=b-1,1<b?this.connection=null:(b=this.connection,a=a._connection,this.connection=null,!a||b&&a!==b||a.unsubscribe()))}else this.connection=null};return b}(h.Subscriber)},function(e,g,a){var l=this&&this.__extends||function(a,e){function f(){this.constructor=a}for(var c in e)e.hasOwnProperty(c)&&(a[c]=e[c]);a.prototype=
null===e?Object.create(e):(f.prototype=e.prototype,new f)};e=function(a){function e(e,c){a.call(this);this.error=e;this.scheduler=c}l(e,a);e.create=function(a,c){return new e(a,c)};e.dispatch=function(a){a.subscriber.error(a.error)};e.prototype._subscribe=function(a){var c=this.error,d=this.scheduler;if(d)return d.schedule(e.dispatch,0,{error:c,subscriber:a});a.error(c)};return e}(a(0).Observable);g.ErrorObservable=e},function(e,g,a){var l=this&&this.__extends||function(a,b){function c(){this.constructor=
a}for(var d in b)b.hasOwnProperty(d)&&(a[d]=b[d]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)},k=a(17),h=a(64),f=a(55),c=a(140),d=a(13),b=a(135),m=a(39),n=a(0),p=a(157),r=a(40);e=function(a){function e(b,c){a.call(this,null);this.ish=b;this.scheduler=c}l(e,a);e.create=function(a,g){if(null!=a){if("function"===typeof a[r.$$observable])return a instanceof n.Observable&&!g?a:new e(a,g);if(k.isArray(a))return new d.ArrayObservable(a,g);if(h.isPromise(a))return new f.PromiseObservable(a,
g);if("function"===typeof a[m.$$iterator]||"string"===typeof a)return new c.IteratorObservable(a,g);if(a&&"number"===typeof a.length)return new b.ArrayLikeObservable(a,g)}throw new TypeError((null!==a&&typeof a||a)+" is not observable");};e.prototype._subscribe=function(a){var b=this.ish,c=this.scheduler;return null==c?b[r.$$observable]().subscribe(a):b[r.$$observable]().subscribe(new p.ObserveOnSubscriber(a,c,0))};return e}(n.Observable);g.FromObservable=e},function(e,g,a){var l=this&&this.__extends||
function(a,c){function d(){this.constructor=a}for(var b in c)c.hasOwnProperty(b)&&(a[b]=c[b]);a.prototype=null===c?Object.create(c):(d.prototype=c.prototype,new d)},k=a(63);e=a(0);var h=a(26);a=function(a){function c(c,b){void 0===c&&(c=0);void 0===b&&(b=h.async);a.call(this);this.period=c;this.scheduler=b;if(!k.isNumeric(c)||0>c)this.period=0;b&&"function"===typeof b.schedule||(this.scheduler=h.async)}l(c,a);c.create=function(a,b){void 0===a&&(a=0);void 0===b&&(b=h.async);return new c(a,b)};c.dispatch=
function(a){var b=a.subscriber,c=a.period;b.next(a.index);b.closed||(a.index+=1,this.schedule(a,c))};c.prototype._subscribe=function(a){var b=this.period;a.add(this.scheduler.schedule(c.dispatch,b,{index:0,subscriber:a,period:b}))};return c}(e.Observable);g.IntervalObservable=a},function(e,g,a){var l=this&&this.__extends||function(a,c){function b(){this.constructor=a}for(var d in c)c.hasOwnProperty(d)&&(a[d]=c[d]);a.prototype=null===c?Object.create(c):(b.prototype=c.prototype,new b)},k=a(7);e=a(0);
var h=a(39);a=function(a){function b(b,d){a.call(this);this.scheduler=d;if(null==b)throw Error("iterator cannot be null.");var e;if((e=b[h.$$iterator])||"string"!==typeof b)if(e||void 0===b.length){if(!e)throw new TypeError("object is not iterable");e=b[h.$$iterator]()}else e=new c(b);else e=new f(b);this.iterator=e}l(b,a);b.create=function(a,c){return new b(a,c)};b.dispatch=function(a){var b=a.index,c=a.iterator,d=a.subscriber;a.hasError?d.error(a.error):(c=c.next(),c.done?d.complete():(d.next(c.value),
a.index=b+1,d.closed||this.schedule(a)))};b.prototype._subscribe=function(a){var c=this.iterator,d=this.scheduler;if(d)return d.schedule(b.dispatch,0,{index:0,iterator:c,subscriber:a});do{d=c.next();if(d.done){a.complete();break}else a.next(d.value);if(a.closed)break}while(1)};return b}(e.Observable);g.IteratorObservable=a;var f=function(){function a(a,b,c){void 0===b&&(b=0);void 0===c&&(c=a.length);this.str=a;this.idx=b;this.len=c}a.prototype[h.$$iterator]=function(){return this};a.prototype.next=
function(){return this.idx<this.len?{done:!1,value:this.str.charAt(this.idx++)}:{done:!0,value:void 0}};return a}(),c=function(){function a(a,b,c){void 0===b&&(b=0);if(void 0===c)if(c=+a.length,isNaN(c))c=0;else if(0!==c&&"number"===typeof c&&k.root.isFinite(c)){var e;e=+c;e=0===e?e:isNaN(e)?e:0>e?-1:1;c=e*Math.floor(Math.abs(c));c=0>=c?0:c>d?d:c}this.arr=a;this.idx=b;this.len=c}a.prototype[h.$$iterator]=function(){return this};a.prototype.next=function(){return this.idx<this.len?{done:!1,value:this.arr[this.idx++]}:
{done:!0,value:void 0}};return a}(),d=Math.pow(2,53)-1},function(e,g,a){var l=this&&this.__extends||function(a,e){function c(){this.constructor=a}for(var d in e)e.hasOwnProperty(d)&&(a[d]=e[d]);a.prototype=null===e?Object.create(e):(c.prototype=e.prototype,new c)};e=a(0);var k=a(65);a=function(a){function e(){a.call(this)}l(e,a);e.create=function(){return new e};e.prototype._subscribe=function(a){k.noop()};return e}(e.Observable);g.NeverObservable=a},function(e,g,a){e=a(13);g.of=e.ArrayObservable.of},
function(e,g,a){e=a(137);g._throw=e.ErrorObservable.create},function(e,g,a){var l=this&&this.__extends||function(a,d){function b(){this.constructor=a}for(var c in d)d.hasOwnProperty(c)&&(a[c]=d[c]);a.prototype=null===d?Object.create(d):(b.prototype=d.prototype,new b)};e=a(12);var k=a(15);g._catch=function(a){a=new h(a);var c=this.lift(a);return a.caught=c};var h=function(){function a(a){this.selector=a}a.prototype.call=function(a,b){return b._subscribe(new f(a,this.selector,this.caught))};return a}(),
f=function(a){function c(b,c,d){a.call(this,b);this.selector=c;this.caught=d}l(c,a);c.prototype.error=function(a){if(!this.isStopped){var b=void 0;try{b=this.selector(a,this.caught)}catch(n){this.destination.error(n);return}this.unsubscribe();this.destination.remove(this);k.subscribeToResult(this,b)}};return c}(e.OuterSubscriber)},function(e,g,a){var l=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var d in b)b.hasOwnProperty(d)&&(a[d]=b[d]);a.prototype=null===b?Object.create(b):
(c.prototype=b.prototype,new c)},k=a(13),h=a(17);e=a(12);var f=a(15),c={};g.combineLatest=function(){for(var a=[],b=0;b<arguments.length;b++)a[b-0]=arguments[b];b=null;"function"===typeof a[a.length-1]&&(b=a.pop());1===a.length&&h.isArray(a[0])&&(a=a[0]);a.unshift(this);return this.lift.call(new k.ArrayObservable(a),new d(b))};var d=function(){function a(a){this.project=a}a.prototype.call=function(a,c){return c._subscribe(new b(a,this.project))};return a}();g.CombineLatestOperator=d;var b=function(a){function b(b,
c){a.call(this,b);this.project=c;this.active=0;this.values=[];this.observables=[]}l(b,a);b.prototype._next=function(a){this.values.push(c);this.observables.push(a)};b.prototype._complete=function(){var a=this.observables,b=a.length;if(0===b)this.destination.complete();else{this.toRespond=this.active=b;for(var c=0;c<b;c++){var d=a[c];this.add(f.subscribeToResult(this,d,d,c))}}};b.prototype.notifyComplete=function(a){0===--this.active&&this.destination.complete()};b.prototype.notifyNext=function(a,
b,d,e,f){a=this.values;e=a[d];e=this.toRespond?e===c?--this.toRespond:this.toRespond:0;a[d]=b;0===e&&(this.project?this._tryProject(a):this.destination.next(a.slice()))};b.prototype._tryProject=function(a){var b;try{b=this.project.apply(this,a)}catch(q){this.destination.error(q);return}this.destination.next(b)};return b}(e.OuterSubscriber);g.CombineLatestSubscriber=b},function(e,g,a){var l=a(37);g.concatAll=function(){return this.lift(new l.MergeAllOperator(1))}},function(e,g,a){var l=a(58);g.concatMap=
function(a,e){return this.lift(new l.MergeMapOperator(a,e,1))}},function(e,g,a){function l(a){a.debouncedNext()}var k=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var d in b)b.hasOwnProperty(d)&&(a[d]=b[d]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)};e=a(2);var h=a(26);g.debounceTime=function(a,b){void 0===b&&(b=h.async);return this.lift(new f(a,b))};var f=function(){function a(a,c){this.dueTime=a;this.scheduler=c}a.prototype.call=function(a,d){return d._subscribe(new c(a,
this.dueTime,this.scheduler))};return a}(),c=function(a){function b(b,c,d){a.call(this,b);this.dueTime=c;this.scheduler=d;this.lastValue=this.debouncedSubscription=null;this.hasValue=!1}k(b,a);b.prototype._next=function(a){this.clearDebounce();this.lastValue=a;this.hasValue=!0;this.add(this.debouncedSubscription=this.scheduler.schedule(l,this.dueTime,this))};b.prototype._complete=function(){this.debouncedNext();this.destination.complete()};b.prototype.debouncedNext=function(){this.clearDebounce();
this.hasValue&&(this.destination.next(this.lastValue),this.lastValue=null,this.hasValue=!1)};b.prototype.clearDebounce=function(){var a=this.debouncedSubscription;null!==a&&(this.remove(a),a.unsubscribe(),this.debouncedSubscription=null)};return b}(e.Subscriber)},function(e,g,a){var l=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var d in b)b.hasOwnProperty(d)&&(a[d]=b[d]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)};e=a(2);var k=a(43),h=a(27);g.distinctUntilChanged=
function(a,b){return this.lift(new f(a,b))};var f=function(){function a(a,c){this.compare=a;this.keySelector=c}a.prototype.call=function(a,d){return d._subscribe(new c(a,this.compare,this.keySelector))};return a}(),c=function(a){function b(b,c,d){a.call(this,b);this.keySelector=d;this.hasKey=!1;"function"===typeof c&&(this.compare=c)}l(b,a);b.prototype.compare=function(a,b){return a===b};b.prototype._next=function(a){var b=a;if(this.keySelector&&(b=k.tryCatch(this.keySelector)(a),b===h.errorObject))return this.destination.error(h.errorObject.e);
var c=!1;if(this.hasKey){if(c=k.tryCatch(this.compare)(this.key,b),c===h.errorObject)return this.destination.error(h.errorObject.e)}else this.hasKey=!0;!1===!!c&&(this.key=b,this.destination.next(a))};return b}(e.Subscriber)},function(e,g,a){var l=this&&this.__extends||function(a,d){function b(){this.constructor=a}for(var c in d)d.hasOwnProperty(c)&&(a[c]=d[c]);a.prototype=null===d?Object.create(d):(b.prototype=d.prototype,new b)},k=a(2);g._do=function(a,d,b){return this.lift(new h(a,d,b))};var h=
function(){function a(a,b,c){this.nextOrObserver=a;this.error=b;this.complete=c}a.prototype.call=function(a,b){return b._subscribe(new f(a,this.nextOrObserver,this.error,this.complete))};return a}(),f=function(a){function c(b,c,d,e){a.call(this,b);b=new k.Subscriber(c,d,e);b.syncErrorThrowable=!0;this.add(b);this.safeSubscriber=b}l(c,a);c.prototype._next=function(a){var b=this.safeSubscriber;b.next(a);b.syncErrorThrown?this.destination.error(b.syncErrorValue):this.destination.next(a)};c.prototype._error=
function(a){var b=this.safeSubscriber;b.error(a);b.syncErrorThrown?this.destination.error(b.syncErrorValue):this.destination.error(a)};c.prototype._complete=function(){var a=this.safeSubscriber;a.complete();a.syncErrorThrown?this.destination.error(a.syncErrorValue):this.destination.complete()};return c}(k.Subscriber)},function(e,g,a){var l=this&&this.__extends||function(a,c){function d(){this.constructor=a}for(var b in c)c.hasOwnProperty(b)&&(a[b]=c[b]);a.prototype=null===c?Object.create(c):(d.prototype=
c.prototype,new d)};e=a(2);g.filter=function(a,c){return this.lift(new k(a,c))};var k=function(){function a(a,d){this.predicate=a;this.thisArg=d}a.prototype.call=function(a,d){return d._subscribe(new h(a,this.predicate,this.thisArg))};return a}(),h=function(a){function c(c,b,e){a.call(this,c);this.predicate=b;this.thisArg=e;this.count=0;this.predicate=b}l(c,a);c.prototype._next=function(a){var b;try{b=this.predicate.call(this.thisArg,a,this.count++)}catch(m){this.destination.error(m);return}b&&this.destination.next(a)};
return c}(e.Subscriber)},function(e,g,a){var l=this&&this.__extends||function(a,d){function b(){this.constructor=a}for(var c in d)d.hasOwnProperty(c)&&(a[c]=d[c]);a.prototype=null===d?Object.create(d):(b.prototype=d.prototype,new b)};e=a(2);var k=a(5);g._finally=function(a){return this.lift(new h(a))};var h=function(){function a(a){this.callback=a}a.prototype.call=function(a,b){return b._subscribe(new f(a,this.callback))};return a}(),f=function(a){function c(b,c){a.call(this,b);this.add(new k.Subscription(c))}
l(c,a);return c}(e.Subscriber)},function(e,g,a){var l=this&&this.__extends||function(a,d){function b(){this.constructor=a}for(var c in d)d.hasOwnProperty(c)&&(a[c]=d[c]);a.prototype=null===d?Object.create(d):(b.prototype=d.prototype,new b)};e=a(2);var k=a(65);g.ignoreElements=function(){return this.lift(new h)};var h=function(){function a(){}a.prototype.call=function(a,b){return b._subscribe(new f(a))};return a}(),f=function(a){function c(){a.apply(this,arguments)}l(c,a);c.prototype._next=function(a){k.noop()};
return c}(e.Subscriber)},function(e,g,a){var l=this&&this.__extends||function(a,c){function d(){this.constructor=a}for(var b in c)c.hasOwnProperty(b)&&(a[b]=c[b]);a.prototype=null===c?Object.create(c):(d.prototype=c.prototype,new d)};e=a(2);g.map=function(a,c){if("function"!==typeof a)throw new TypeError("argument is not a function. Are you looking for `mapTo()`?");return this.lift(new k(a,c))};var k=function(){function a(a,d){this.project=a;this.thisArg=d}a.prototype.call=function(a,d){return d._subscribe(new h(a,
this.project,this.thisArg))};return a}();g.MapOperator=k;var h=function(a){function c(c,b,e){a.call(this,c);this.project=b;this.count=0;this.thisArg=e||this}l(c,a);c.prototype._next=function(a){var b;try{b=this.project.call(this.thisArg,a,this.count++)}catch(m){this.destination.error(m);return}this.destination.next(b)};return c}(e.Subscriber)},function(e,g,a){var l=this&&this.__extends||function(a,c){function d(){this.constructor=a}for(var b in c)c.hasOwnProperty(b)&&(a[b]=c[b]);a.prototype=null===
c?Object.create(c):(d.prototype=c.prototype,new d)};e=a(2);g.mapTo=function(a){return this.lift(new k(a))};var k=function(){function a(a){this.value=a}a.prototype.call=function(a,d){return d._subscribe(new h(a,this.value))};return a}(),h=function(a){function c(c,b){a.call(this,c);this.value=b}l(c,a);c.prototype._next=function(a){this.destination.next(this.value)};return c}(e.Subscriber)},function(e,g,a){function l(){for(var a=[],d=0;d<arguments.length;d++)a[d-0]=arguments[d];var d=Number.POSITIVE_INFINITY,
b=null,e=a[a.length-1];f.isScheduler(e)?(b=a.pop(),1<a.length&&"number"===typeof a[a.length-1]&&(d=a.pop())):"number"===typeof e&&(d=a.pop());return null===b&&1===a.length?a[0]:(new k.ArrayObservable(a,b)).lift(new h.MergeAllOperator(d))}var k=a(13),h=a(37),f=a(18);g.merge=function(){for(var a=[],d=0;d<arguments.length;d++)a[d-0]=arguments[d];return this.lift.call(l.apply(void 0,[this].concat(a)))};g.mergeStatic=l},function(e,g,a){var l=this&&this.__extends||function(a,b){function c(){this.constructor=
a}for(var d in b)b.hasOwnProperty(d)&&(a[d]=b[d]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,new c)};e=a(2);var k=a(132);g.observeOn=function(a,b){void 0===b&&(b=0);return this.lift(new h(a,b))};var h=function(){function a(a,c){void 0===c&&(c=0);this.scheduler=a;this.delay=c}a.prototype.call=function(a,c){return c._subscribe(new f(a,this.scheduler,this.delay))};return a}();g.ObserveOnOperator=h;var f=function(a){function b(b,c,d){void 0===d&&(d=0);a.call(this,b);this.scheduler=
c;this.delay=d}l(b,a);b.dispatch=function(a){a.notification.observe(a.destination)};b.prototype.scheduleMessage=function(a){this.add(this.scheduler.schedule(b.dispatch,this.delay,new c(a,this.destination)))};b.prototype._next=function(a){this.scheduleMessage(k.Notification.createNext(a))};b.prototype._error=function(a){this.scheduleMessage(k.Notification.createError(a))};b.prototype._complete=function(){this.scheduleMessage(k.Notification.createComplete())};return b}(e.Subscriber);g.ObserveOnSubscriber=
f;var c=function(){return function(a,b){this.notification=a;this.destination=b}}();g.ObserveOnMessage=c},function(e,g,a){var l=a(8),k=a(38);g.publish=function(a){return a?k.multicast.call(this,function(){return new l.Subject},a):k.multicast.call(this,new l.Subject)}},function(e,g,a){var l=this&&this.__extends||function(a,c){function d(){this.constructor=a}for(var b in c)c.hasOwnProperty(b)&&(a[b]=c[b]);a.prototype=null===c?Object.create(c):(d.prototype=c.prototype,new d)};e=a(2);g.scan=function(a,
c){return this.lift(new k(a,c))};var k=function(){function a(a,d){this.accumulator=a;this.seed=d}a.prototype.call=function(a,d){return d._subscribe(new h(a,this.accumulator,this.seed))};return a}(),h=function(a){function c(c,b,e){a.call(this,c);this.accumulator=b;this.index=0;this.accumulatorSet=!1;this.seed=e;this.accumulatorSet="undefined"!==typeof e}l(c,a);Object.defineProperty(c.prototype,"seed",{get:function(){return this._seed},set:function(a){this.accumulatorSet=!0;this._seed=a},enumerable:!0,
configurable:!0});c.prototype._next=function(a){if(this.accumulatorSet)return this._tryNext(a);this.seed=a;this.destination.next(a)};c.prototype._tryNext=function(a){var b=this.index++,c;try{c=this.accumulator(this.seed,a,b)}catch(n){this.destination.error(n)}this.seed=c;this.destination.next(c)};return c}(e.Subscriber)},function(e,g,a){function l(){return new h.Subject}var k=a(38),h=a(8);g.share=function(){return k.multicast.call(this,l).refCount()}},function(e,g,a){var l=this&&this.__extends||function(a,
c){function d(){this.constructor=a}for(var b in c)c.hasOwnProperty(b)&&(a[b]=c[b]);a.prototype=null===c?Object.create(c):(d.prototype=c.prototype,new d)};e=a(2);g.skip=function(a){return this.lift(new k(a))};var k=function(){function a(a){this.total=a}a.prototype.call=function(a,d){return d._subscribe(new h(a,this.total))};return a}(),h=function(a){function c(c,b){a.call(this,c);this.total=b;this.count=0}l(c,a);c.prototype._next=function(a){++this.count>this.total&&this.destination.next(a)};return c}(e.Subscriber)},
function(e,g,a){var l=a(13),k=a(36),h=a(6),f=a(57),c=a(18);g.startWith=function(){for(var a=[],b=0;b<arguments.length;b++)a[b-0]=arguments[b];b=a[a.length-1];c.isScheduler(b)?a.pop():b=null;var e=a.length;return 1===e?f.concatStatic(new k.ScalarObservable(a[0],b),this):1<e?f.concatStatic(new l.ArrayObservable(a,b),this):f.concatStatic(new h.EmptyObservable(b),this)}},function(e,g,a){var l=this&&this.__extends||function(a,d){function b(){this.constructor=a}for(var c in d)d.hasOwnProperty(c)&&(a[c]=
d[c]);a.prototype=null===d?Object.create(d):(b.prototype=d.prototype,new b)};e=a(12);var k=a(15);g.switchMap=function(a,d){return this.lift(new h(a,d))};var h=function(){function a(a,b){this.project=a;this.resultSelector=b}a.prototype.call=function(a,b){return b._subscribe(new f(a,this.project,this.resultSelector))};return a}(),f=function(a){function c(b,c,d){a.call(this,b);this.project=c;this.resultSelector=d;this.index=0}l(c,a);c.prototype._next=function(a){var b,c=this.index++;try{b=this.project(a,
c)}catch(p){this.destination.error(p);return}this._innerSub(b,a,c)};c.prototype._innerSub=function(a,c,d){var b=this.innerSubscription;b&&b.unsubscribe();this.add(this.innerSubscription=k.subscribeToResult(this,a,c,d))};c.prototype._complete=function(){var b=this.innerSubscription;b&&!b.closed||a.prototype._complete.call(this)};c.prototype._unsubscribe=function(){this.innerSubscription=null};c.prototype.notifyComplete=function(b){this.remove(b);this.innerSubscription=null;this.isStopped&&a.prototype._complete.call(this)};
c.prototype.notifyNext=function(a,c,d,e,f){this.resultSelector?this._tryNotifyNext(a,c,d,e):this.destination.next(c)};c.prototype._tryNotifyNext=function(a,c,d,e){var b;try{b=this.resultSelector(a,c,d,e)}catch(q){this.destination.error(q);return}this.destination.next(b)};return c}(e.OuterSubscriber)},function(e,g,a){var l=this&&this.__extends||function(a,b){function c(){this.constructor=a}for(var d in b)b.hasOwnProperty(d)&&(a[d]=b[d]);a.prototype=null===b?Object.create(b):(c.prototype=b.prototype,
new c)};e=a(2);var k=a(171),h=a(6);g.take=function(a){return 0===a?new h.EmptyObservable:this.lift(new f(a))};var f=function(){function a(a){this.total=a;if(0>this.total)throw new k.ArgumentOutOfRangeError;}a.prototype.call=function(a,d){return d._subscribe(new c(a,this.total))};return a}(),c=function(a){function b(b,c){a.call(this,b);this.total=c;this.count=0}l(b,a);b.prototype._next=function(a){var b=this.total,c=++this.count;c<=b&&(this.destination.next(a),c===b&&(this.destination.complete(),this.unsubscribe()))};
return b}(e.Subscriber)},function(e,g,a){var l=this&&this.__extends||function(a,d){function b(){this.constructor=a}for(var c in d)d.hasOwnProperty(c)&&(a[c]=d[c]);a.prototype=null===d?Object.create(d):(b.prototype=d.prototype,new b)};e=a(12);var k=a(15);g.takeUntil=function(a){return this.lift(new h(a))};var h=function(){function a(a){this.notifier=a}a.prototype.call=function(a,b){return b._subscribe(new f(a,this.notifier))};return a}(),f=function(a){function c(b,c){a.call(this,b);this.notifier=c;
this.add(k.subscribeToResult(this,c))}l(c,a);c.prototype.notifyNext=function(a,c,d,e,f){this.complete()};c.prototype.notifyComplete=function(){};return c}(e.OuterSubscriber)},function(e,g,a){var l=this&&this.__extends||function(a,c){function b(){this.constructor=a}for(var d in c)c.hasOwnProperty(d)&&(a[d]=c[d]);a.prototype=null===c?Object.create(c):(b.prototype=c.prototype,new b)},k=a(26),h=a(62);e=a(2);var f=a(173);g.timeout=function(a,d,e){void 0===d&&(d=null);void 0===e&&(e=k.async);var b=h.isDate(a);
a=b?+a-e.now():Math.abs(a);return this.lift(new c(a,b,d,e))};var c=function(){function a(a,b,c,d){this.waitFor=a;this.absoluteTimeout=b;this.errorToSend=c;this.scheduler=d}a.prototype.call=function(a,b){return b._subscribe(new d(a,this.absoluteTimeout,this.waitFor,this.errorToSend,this.scheduler))};return a}(),d=function(a){function b(b,c,d,e,f){a.call(this,b);this.absoluteTimeout=c;this.waitFor=d;this.errorToSend=e;this.scheduler=f;this._previousIndex=this.index=0;this._hasCompleted=!1;this.scheduleTimeout()}
l(b,a);Object.defineProperty(b.prototype,"previousIndex",{get:function(){return this._previousIndex},enumerable:!0,configurable:!0});Object.defineProperty(b.prototype,"hasCompleted",{get:function(){return this._hasCompleted},enumerable:!0,configurable:!0});b.dispatchTimeout=function(a){var b=a.subscriber;a=a.index;b.hasCompleted||b.previousIndex!==a||b.notifyTimeout()};b.prototype.scheduleTimeout=function(){var a=this.index;this.scheduler.schedule(b.dispatchTimeout,this.waitFor,{subscriber:this,index:a});
this.index++;this._previousIndex=a};b.prototype._next=function(a){this.destination.next(a);this.absoluteTimeout||this.scheduleTimeout()};b.prototype._error=function(a){this.destination.error(a);this._hasCompleted=!0};b.prototype._complete=function(){this.destination.complete();this._hasCompleted=!0};b.prototype.notifyTimeout=function(){this.error(this.errorToSend||new f.TimeoutError)};return b}(e.Subscriber)},function(e,g,a){var l=this&&this.__extends||function(a,e){function f(){this.constructor=
a}for(var c in e)e.hasOwnProperty(c)&&(a[c]=e[c]);a.prototype=null===e?Object.create(e):(f.prototype=e.prototype,new f)};e=function(a){function e(e,c){a.call(this)}l(e,a);e.prototype.schedule=function(a,c){return this};return e}(a(5).Subscription);g.Action=e},function(e,g,a){var l=this&&this.__extends||function(a,e){function c(){this.constructor=a}for(var d in e)e.hasOwnProperty(d)&&(a[d]=e[d]);a.prototype=null===e?Object.create(e):(c.prototype=e.prototype,new c)},k=a(172);e=function(a){function e(c,
d){a.call(this,c,d);this.scheduler=c;this.work=d}l(e,a);e.prototype.requestAsyncId=function(c,d,b){void 0===b&&(b=0);if(null!==b&&0<b)return a.prototype.requestAsyncId.call(this,c,d,b);c.actions.push(this);return c.scheduled||(c.scheduled=k.Immediate.setImmediate(c.flush.bind(c,null)))};e.prototype.recycleAsyncId=function(c,d,b){void 0===b&&(b=0);if(null!==b&&0<b||null===b&&0<this.delay)return a.prototype.recycleAsyncId.call(this,c,d,b);0===c.actions.length&&(k.Immediate.clearImmediate(d),c.scheduled=
void 0)};return e}(a(59).AsyncAction);g.AsapAction=e},function(e,g,a){var l=this&&this.__extends||function(a,e){function f(){this.constructor=a}for(var c in e)e.hasOwnProperty(c)&&(a[c]=e[c]);a.prototype=null===e?Object.create(e):(f.prototype=e.prototype,new f)};e=function(a){function e(){a.apply(this,arguments)}l(e,a);e.prototype.flush=function(a){this.active=!0;this.scheduled=void 0;var c=this.actions,d,b=-1,e=c.length;a=a||c.shift();do if(d=a.execute(a.state,a.delay))break;while(++b<e&&(a=c.shift()));
this.active=!1;if(d){for(;++b<e&&(a=c.shift());)a.unsubscribe();throw d;}};return e}(a(60).AsyncScheduler);g.AsapScheduler=e},function(e,g,a){e=a(168);a=a(169);g.asap=new a.AsapScheduler(e.AsapAction)},function(e,g,a){var l=this&&this.__extends||function(a,e){function f(){this.constructor=a}for(var c in e)e.hasOwnProperty(c)&&(a[c]=e[c]);a.prototype=null===e?Object.create(e):(f.prototype=e.prototype,new f)};e=function(a){function e(){var e=a.call(this,"argument out of range");this.name=e.name="ArgumentOutOfRangeError";
this.stack=e.stack;this.message=e.message}l(e,a);return e}(Error);g.ArgumentOutOfRangeError=e},function(e,g,a){e=a(7);a=function(){function a(a){this.root=a;a.setImmediate&&"function"===typeof a.setImmediate?(this.setImmediate=a.setImmediate.bind(a),this.clearImmediate=a.clearImmediate.bind(a)):(this.nextHandle=1,this.tasksByHandle={},this.currentlyRunningATask=!1,this.canUseProcessNextTick()?this.setImmediate=this.createProcessNextTickSetImmediate():this.canUsePostMessage()?this.setImmediate=this.createPostMessageSetImmediate():
this.canUseMessageChannel()?this.setImmediate=this.createMessageChannelSetImmediate():this.canUseReadyStateChange()?this.setImmediate=this.createReadyStateChangeSetImmediate():this.setImmediate=this.createSetTimeoutSetImmediate(),a=function f(a){delete f.instance.tasksByHandle[a]},a.instance=this,this.clearImmediate=a)}a.prototype.identify=function(a){return this.root.Object.prototype.toString.call(a)};a.prototype.canUseProcessNextTick=function(){return"[object process]"===this.identify(this.root.process)};
a.prototype.canUseMessageChannel=function(){return!!this.root.MessageChannel};a.prototype.canUseReadyStateChange=function(){var a=this.root.document;return!!(a&&"onreadystatechange"in a.createElement("script"))};a.prototype.canUsePostMessage=function(){var a=this.root;if(a.postMessage&&!a.importScripts){var e=!0,f=a.onmessage;a.onmessage=function(){e=!1};a.postMessage("","*");a.onmessage=f;return e}return!1};a.prototype.partiallyApplied=function(a){for(var e=[],f=1;f<arguments.length;f++)e[f-1]=arguments[f];
f=function d(){var a=d.handler,e=d.args;"function"===typeof a?a.apply(void 0,e):(new Function(""+a))()};f.handler=a;f.args=e;return f};a.prototype.addFromSetImmediateArguments=function(a){this.tasksByHandle[this.nextHandle]=this.partiallyApplied.apply(void 0,a);return this.nextHandle++};a.prototype.createProcessNextTickSetImmediate=function(){var a=function f(){var a=f.instance,d=a.addFromSetImmediateArguments(arguments);a.root.process.nextTick(a.partiallyApplied(a.runIfPresent,d));return d};a.instance=
this;return a};a.prototype.createPostMessageSetImmediate=function(){var a=this.root,e="setImmediate$"+a.Math.random()+"$",f=function d(b){var f=d.instance;b.source===a&&"string"===typeof b.data&&0===b.data.indexOf(e)&&f.runIfPresent(+b.data.slice(e.length))};f.instance=this;a.addEventListener("message",f,!1);f=function b(){var a=b,e=a.messagePrefix,a=a.instance,f=a.addFromSetImmediateArguments(arguments);a.root.postMessage(e+f,"*");return f};f.instance=this;f.messagePrefix=e;return f};a.prototype.runIfPresent=
function(a){if(this.currentlyRunningATask)this.root.setTimeout(this.partiallyApplied(this.runIfPresent,a),0);else{var e=this.tasksByHandle[a];if(e){this.currentlyRunningATask=!0;try{e()}finally{this.clearImmediate(a),this.currentlyRunningATask=!1}}}};a.prototype.createMessageChannelSetImmediate=function(){var a=this,e=new this.root.MessageChannel;e.port1.onmessage=function(c){a.runIfPresent(c.data)};var f=function d(){var a=d,e=a.channel,a=a.instance.addFromSetImmediateArguments(arguments);e.port2.postMessage(a);
return a};f.channel=e;f.instance=this;return f};a.prototype.createReadyStateChangeSetImmediate=function(){var a=function f(){var a=f.instance,d=a.root.document,b=d.documentElement,e=a.addFromSetImmediateArguments(arguments),g=d.createElement("script");g.onreadystatechange=function(){a.runIfPresent(e);g.onreadystatechange=null;b.removeChild(g);g=null};b.appendChild(g);return e};a.instance=this;return a};a.prototype.createSetTimeoutSetImmediate=function(){var a=function f(){var a=f.instance,d=a.addFromSetImmediateArguments(arguments);
a.root.setTimeout(a.partiallyApplied(a.runIfPresent,d),0);return d};a.instance=this;return a};return a}();g.ImmediateDefinition=a;g.Immediate=new a(e.root)},function(e,g,a){var l=this&&this.__extends||function(a,e){function f(){this.constructor=a}for(var c in e)e.hasOwnProperty(c)&&(a[c]=e[c]);a.prototype=null===e?Object.create(e):(f.prototype=e.prototype,new f)};e=function(a){function e(){var e=a.call(this,"Timeout has occurred");this.name=e.name="TimeoutError";this.stack=e.stack;this.message=e.message}
l(e,a);return e}(Error);g.TimeoutError=e},function(e,g,a){var l=this&&this.__extends||function(a,e){function f(){this.constructor=a}for(var c in e)e.hasOwnProperty(c)&&(a[c]=e[c]);a.prototype=null===e?Object.create(e):(f.prototype=e.prototype,new f)};e=function(a){function e(e){a.call(this);this.errors=e;e=Error.call(this,e?e.length+" errors occurred during unsubscription:\n "+e.map(function(a,d){return d+1+") "+a.toString()}).join("\n "):"");this.name=e.name="UnsubscriptionError";this.stack=e.stack;
this.message=e.message}l(e,a);return e}(Error);g.UnsubscriptionError=e},function(e,g,a){g.isObject=function(a){return null!=a&&"object"===typeof a}},function(e,g,a){var l=a(2),k=a(41),h=a(52);g.toSubscriber=function(a,c,d){if(a){if(a instanceof l.Subscriber)return a;if(a[k.$$rxSubscriber])return a[k.$$rxSubscriber]()}return a||c||d?new l.Subscriber(a,c,d):new l.Subscriber(h.empty)}},function(e,g){var a;a=function(){return this}();try{a=a||Function("return this")()||(0,eval)("this")}catch(l){"object"===
typeof window&&(a=window)}e.exports=a}])});
|
import {
beforeBlockString,
blurComments,
hasBlock,
report,
ruleMessages,
validateOptions,
} from "../../utils"
import {
findIndex,
findLastIndex,
range,
} from "lodash"
import { lengthUnits } from "../../reference/keywordSets"
import styleSearch from "style-search"
import valueParser from "postcss-value-parser"
export const ruleName = "length-zero-no-unit"
export const messages = ruleMessages(ruleName, {
rejected: "Unexpected unit",
})
export default function (actual) {
return (root, result) => {
const validOptions = validateOptions(result, ruleName, { actual })
if (!validOptions) { return }
root.walkDecls(decl => {
check(blurComments(decl.toString()), decl)
})
root.walkAtRules(atRule => {
const source = (hasBlock(atRule))
? beforeBlockString(atRule, { noRawBefore: true })
: atRule.toString()
check(source, atRule)
})
function check(value, node) {
const ignorableIndexes = new Set()
styleSearch({ source: value, target: "0" }, match => {
const index = match.startIndex
// Given a 0 somewhere in the full property value (not in a string, thanks
// to styleSearch) we need to isolate the value that contains the zero.
// To do so, we'll find the last index before the 0 of a character that would
// divide one value in a list from another, and the next index of such a
// character; then we build a substring from those indexes, which we can
// assess.
// If a single value includes multiple 0's (e.g. 100.01px), we don't want
// each 0 to be treated as a separate value, possibly resulting in multiple
// warnings for the same value (e.g. 0.00px).
//
// This check prevents that from happening: we build and check against a
// Set containing all the indexes that are part of a value already validated.
if (ignorableIndexes.has(index)) { return }
const prevValueBreakIndex = findLastIndex(value.substr(0, index), char => {
return [ " ", ",", ")", "(", "#" ].indexOf(char) !== -1
})
// Ignore hex colors
if (value[prevValueBreakIndex] === "#") { return }
// If no prev break was found, this value starts at 0
const valueWithZeroStart = (prevValueBreakIndex === -1)
? 0
: prevValueBreakIndex + 1
const nextValueBreakIndex = findIndex(value.substr(valueWithZeroStart), char => {
return [ " ", ",", ")" ].indexOf(char) !== -1
})
// If no next break was found, this value ends at the end of the string
const valueWithZeroEnd = (nextValueBreakIndex === -1)
? value.length
: nextValueBreakIndex + valueWithZeroStart
const valueWithZero = value.slice(valueWithZeroStart, valueWithZeroEnd)
const parsedValue = valueParser.unit(valueWithZero)
if (!parsedValue || (parsedValue && !parsedValue.unit)) { return }
// Add the indexes to ignorableIndexes so the same value will not
// be checked multiple times.
range(valueWithZeroStart, valueWithZeroEnd).forEach(i => ignorableIndexes.add(i))
// Only pay attention if the value parses to 0
// and units with lengths
if (parseFloat(valueWithZero, 10) !== 0
|| !lengthUnits.has(parsedValue.unit.toLowerCase())
) { return }
report({
message: messages.rejected,
node,
index: valueWithZeroEnd - parsedValue.unit.length,
result,
ruleName,
})
})
}
}
}
|
/**
* Copyright (c) BoonEx Pty Limited - http://www.boonex.com/
* CC-BY License - http://creativecommons.org/licenses/by/3.0/
*
* @defgroup TridentStudio Trident Studio
* @{
*/
function BxDolStudioDesign(oOptions) {
this.sActionsUrl = oOptions.sActionUrl;
this.sObjName = oOptions.sObjName == undefined ? 'oBxDolStudioDesign' : oOptions.sObjName;
this.sAnimationEffect = oOptions.sAnimationEffect == undefined ? 'fade' : oOptions.sAnimationEffect;
this.iAnimationSpeed = oOptions.iAnimationSpeed == undefined ? 'slow' : oOptions.iAnimationSpeed;
this.sCodeMirror = oOptions.sCodeMirror == undefined ? '' : oOptions.sCodeMirror;
var $this = this;
$(document).ready (function () {
if($this.sCodeMirror != '')
$this.initCodeMirror($this.sCodeMirror);
});
var oCollapsable = $('#adm-settings-form .bx-form-collapsable');
oCollapsable.on('bx_show', function() {
$this.refreshCodeMirror();
});
}
BxDolStudioDesign.prototype.initCodeMirror = function(sSelector) {
var oSelector = $(sSelector);
for(var i = 0; i < oSelector.length; i++) {
var e = CodeMirror.fromTextArea(oSelector.get(i), {
lineNumbers: true,
mode: "htmlmixed",
htmlMode: true,
matchBrackets: true
});
}
};
BxDolStudioDesign.prototype.refreshCodeMirror = function() {
$('.CodeMirror').each(function() {
this.CodeMirror.refresh();
});
};
BxDolStudioDesign.prototype.activate = function(sTemplateName, oChecbox) {
var $this = this;
var oDate = new Date();
$.get(
this.sActionsUrl,
{
templ_action: 'activate',
templ_value: sTemplateName,
_t:oDate.getTime()
},
function(oData) {
if(oData.code != 0) {
alert(oData.message);
$(oChecbox).attr('checked', 'checked').trigger('enable');
return;
}
var oBg = $('.bx-std-page-bg');
var oContent = $('#bx-std-page-columns');
if(oData.content.length > 0) {
oBg.removeClass('bx-std-page-bg-empty');
oContent.html(oData.content).bx_anim('show', $this.sAnimationEffect, $this.iAnimationSpeed);
}
else
oContent.bx_anim('hide', $this.sAnimationEffect, $this.iAnimationSpeed, function() {
$(this).html(oData.content)
oBg.addClass('bx-std-page-bg-empty');
});
},
'json'
);
return true;
};
/** @} */
|
/*
MAPSTRACTION v2.0.18 http://www.mapstraction.com
Copyright (c) 2012 Tom Carden, Steve Coast, Mikel Maron, Andrew Turner, Henri Bergius, Rob Moran, Derek Fowler, Gary Gale
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Mapstraction nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
mxn.register('openmq', {
Mapstraction: {
init: function(element, api) {
var me = this;
var map = new MQA.TileMap(element);
this.maps[api] = map;
this.loaded[api] = true;
MQA.withModule('shapes', function() {
// Loading all modules that can't be loaded on-demand
// [This space left intentionally blank]
});
MQA.EventManager.addListener(map, 'click', function(e) {
me.click.fire();
});
MQA.EventManager.addListener(map, 'zoomend', function(e) {
me.changeZoom.fire();
});
MQA.EventManager.addListener(map, 'moveend', function(e) {
me.endPan.fire();
});
},
applyOptions: function(){
if (this.options.enableScrollWheelZoom) {
MQA.withModule('mousewheel', function() {
var map = this.maps[this.api];
map.enableMouseWheelZoom();
});
}
},
resizeTo: function(width, height){
this.currentElement.style.width = width;
this.currentElement.style.height = height;
},
addControls: function( args ) {
var map = this.maps[this.api];
if (args.zoom) {
if (args.zoom == 'large') {
this.addLargeControls();
} else {
this.addSmallControls();
}
}
},
addSmallControls: function() {
var map = this.maps[this.api];
MQA.withModule('smallzoom', function() {
map.addControl(
new MQA.SmallZoom(),
new MQA.MapCornerPlacement(MQA.MapCorner.TOP_LEFT, new MQA.Size(5,5))
);
});
},
addLargeControls: function() {
var map = this.maps[this.api];
MQA.withModule('largezoom', function() {
map.addControl(
new MQA.LargeZoom(),
new MQA.MapCornerPlacement(MQA.MapCorner.TOP_LEFT, new MQA.Size(5,5))
);
});
},
addMapTypeControls: function() {
var map = this.maps[this.api];
// Open MapQuest only supports a single map type, so there is no map type control
},
setCenterAndZoom: function(point, zoom) {
this.setCenter(point);
this.setZoom(zoom);
},
addMarker: function(marker, old) {
var map = this.maps[this.api];
var pin = marker.toProprietary(this.api);
map.addShape(pin);
return pin;
},
removeMarker: function(marker) {
var map = this.maps[this.api];
map.removeShape(marker.proprietary_marker);
},
declutterMarkers: function(opts) {
var map = this.maps[this.api];
// TODO: Add provider code
},
addPolyline: function(polyline, old) {
var thisapi = this.api;
var map = this.maps[thisapi];
MQA.withModule('shapes', function() {
var pl = polyline.toProprietary(thisapi);
map.addShape(pl);
});
},
removePolyline: function(polyline) {
var map = this.maps[this.api];
// TODO: Add provider code
},
getCenter: function() {
var map = this.maps[this.api];
var point = map.getCenter();
return new mxn.LatLonPoint(point.lat, point.lng);
},
setCenter: function(point, options) {
var map = this.maps[this.api];
var pt = point.toProprietary(this.api);
map.setCenter(pt);
},
setZoom: function(zoom) {
var map = this.maps[this.api];
map.setZoomLevel(zoom);
},
getZoom: function() {
var map = this.maps[this.api];
var zoom = map.getZoomLevel();
return zoom;
},
getZoomLevelForBoundingBox: function( bbox ) {
var map = this.maps[this.api];
// NE and SW points from the bounding box.
var ne = bbox.getNorthEast();
var sw = bbox.getSouthWest();
var zoom;
// TODO: Add provider code
return zoom;
},
setMapType: function(type) {
var map = this.maps[this.api];
// MapQuest has a function to set map type, but open MapQuest only supports road
/*
switch (type) {
case mxn.Mapstraction.SATELLITE:
map.setMapType('sat');
break;
case mxn.Mapstraction.HYBRID:
map.setMapType('hyb');
break;
//case mxn.Mapstraction.ROAD:
// break;
default:
map.setMapType('map');
break;
}
*/
map.setMapType('map');
},
getMapType: function() {
var map = this.maps[this.api];
/*
var type = map.getMapType();
switch(type) {
case 'sat':
return mxn.Mapstraction.SATELLITE;
case 'hyb':
return mxn.Mapstraction.HYBRID;
case 'map':
default:
return mxn.Mapstraction.ROAD
}
*/
return mxn.Mapstraction.ROAD;
},
getBounds: function () {
var map = this.maps[this.api];
var rect = map.getBounds();
var se = rect.lr;
var nw = rect.ul;
// MapQuest uses SE and NW points to declare bounds
return new mxn.BoundingBox(se.lat, nw.lng, nw.lat, se.lng);
},
setBounds: function(bounds){
var map = this.maps[this.api];
var sw = bounds.getSouthWest();
var ne = bounds.getNorthEast();
// MapQuest uses SE and NW points to declare bounds
var rect = new MQA.RectLL(new MQA.LatLng(sw.lat, ne.lon), new MQA.LatLng(ne.lat, sw.lon));
map.zoomToRect(rect);
},
addImageOverlay: function(id, src, opacity, west, south, east, north, oContext) {
var map = this.maps[this.api];
// TODO: Add provider code
},
setImagePosition: function(id, oContext) {
var map = this.maps[this.api];
var topLeftPoint; var bottomRightPoint;
// TODO: Add provider code
//oContext.pixels.top = ...;
//oContext.pixels.left = ...;
//oContext.pixels.bottom = ...;
//oContext.pixels.right = ...;
},
addOverlay: function(url, autoCenterAndZoom) {
var map = this.maps[this.api];
// TODO: Add provider code
},
addTileLayer: function(tile_url, opacity, copyright_text, min_zoom, max_zoom, map_type) {
var map = this.maps[this.api];
// TODO: Add provider code
},
toggleTileLayer: function(tile_url) {
var map = this.maps[this.api];
// TODO: Add provider code
},
getPixelRatio: function() {
var map = this.maps[this.api];
// TODO: Add provider code
},
mousePosition: function(element) {
var map = this.maps[this.api];
// TODO: Add provider code
}
},
LatLonPoint: {
toProprietary: function() {
return new MQA.LatLng(this.lat, this.lon);
},
fromProprietary: function(mqPoint) {
this.lat = mqPoint.lat;
this.lon = mqPoint.lng;
}
},
Marker: {
toProprietary: function() {
var pt = this.location.toProprietary(this.api);
var mk = new MQA.Poi(pt);
if (this.iconUrl) {
var icon = new MQA.Icon(this.iconUrl, this.iconSize[0], this.iconSize[1]);
mk.setIcon(icon);
}
if (this.infoBubble) {
mk.setInfoContentHTML(this.infoBubble);
}
MQA.EventManager.addListener(mk, 'click', function() {
mk.mapstraction_marker.click.fire();
});
return mk;
},
openBubble: function() {
// TODO: Add provider code
},
hide: function() {
// TODO: Add provider code
},
show: function() {
// TODO: Add provider code
},
update: function() {
// TODO: Add provider code
}
},
Polyline: {
toProprietary: function() {
var points = [];
var oldpoints = this.points;
for(var i =0, length = this.points.length; i < length; i++) {
var thispt = this.points[i];
points.push(thispt.lat);
points.push(thispt.lon);
}
var line = new MQA.LineOverlay();
line.setShapePoints(points);
// Line options
line.color = this.color || '#000000';
line.colorAlpha = this.opacity || 1.0;
line.borderWidth = this.width || 3;
return line;
},
show: function() {
// TODO: Add provider code
},
hide: function() {
// TODO: Add provider code
}
}
}); |
/*!
* Glide.js v3.2.4
* (c) 2013-2018 Jędrzej Chałubek <jedrzej.chalubek@gmail.com> (http://jedrzejchalubek.com/)
* Released under the MIT License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.Glide = factory());
}(this, (function () { 'use strict';
var defaults = {
/**
* Type of the movement.
*
* Available types:
* `slider` - Rewinds slider to the start/end when it reaches the first or last slide.
* `carousel` - Changes slides without starting over when it reaches the first or last slide.
*
* @type {String}
*/
type: 'slider',
/**
* Start at specific slide number defined with zero-based index.
*
* @type {Number}
*/
startAt: 0,
/**
* A number of slides visible on the single viewport.
*
* @type {Number}
*/
perView: 1,
/**
* Focus currently active slide at a specified position in the track.
*
* Available inputs:
* `center` - Current slide will be always focused at the center of a track.
* `0,1,2,3...` - Current slide will be focused on the specified zero-based index.
*
* @type {String|Number}
*/
focusAt: 0,
/**
* A size of the gap added between slides.
*
* @type {Number}
*/
gap: 10,
/**
* Change slides after a specified interval. Use `false` for turning off autoplay.
*
* @type {Number|Boolean}
*/
autoplay: false,
/**
* Stop autoplay on mouseover event.
*
* @type {Boolean}
*/
hoverpause: true,
/**
* Allow for changing slides with left and right keyboard arrows.
*
* @type {Boolean}
*/
keyboard: true,
/**
* Stop running `perView` number of slides from the end. Use this
* option if you don't want to have an empty space after
* a slider. Works only with `slider` type and a
* non-centered `focusAt` setting.
*
* @type {Boolean}
*/
bound: false,
/**
* Minimal swipe distance needed to change the slide. Use `false` for turning off a swiping.
*
* @type {Number|Boolean}
*/
swipeThreshold: 80,
/**
* Minimal mouse drag distance needed to change the slide. Use `false` for turning off a dragging.
*
* @type {Number|Boolean}
*/
dragThreshold: 120,
/**
* A maximum number of slides to which movement will be made on swiping or dragging. Use `false` for unlimited.
*
* @type {Number|Boolean}
*/
perTouch: false,
/**
* Moving distance ratio of the slides on a swiping and dragging.
*
* @type {Number}
*/
touchRatio: 0.5,
/**
* Angle required to activate slides moving on swiping or dragging.
*
* @type {Number}
*/
touchAngle: 45,
/**
* Duration of the animation in milliseconds.
*
* @type {Number}
*/
animationDuration: 400,
/**
* Allows looping the `slider` type. Slider will rewind to the first/last slide when it's at the start/end.
*
* @type {Boolean}
*/
rewind: true,
/**
* Duration of the rewinding animation of the `slider` type in milliseconds.
*
* @type {Number}
*/
rewindDuration: 800,
/**
* Easing function for the animation.
*
* @type {String}
*/
animationTimingFunc: 'cubic-bezier(.165, .840, .440, 1)',
/**
* Throttle costly events at most once per every wait milliseconds.
*
* @type {Number}
*/
throttle: 10,
/**
* Moving direction mode.
*
* Available inputs:
* - 'ltr' - left to right movement,
* - 'rtl' - right to left movement.
*
* @type {String}
*/
direction: 'ltr',
/**
* The distance value of the next and previous viewports which
* have to peek in the current view. Accepts number and
* pixels as a string. Left and right peeking can be
* set up separately with a directions object.
*
* For example:
* `100` - Peek 100px on the both sides.
* { before: 100, after: 50 }` - Peek 100px on the left side and 50px on the right side.
*
* @type {Number|String|Object}
*/
peek: 0,
/**
* Collection of options applied at specified media breakpoints.
* For example: display two slides per view under 800px.
* `{
* '800px': {
* perView: 2
* }
* }`
*/
breakpoints: {},
/**
* Collection of internally used HTML classes.
*
* @todo Refactor `slider` and `carousel` properties to single `type: { slider: '', carousel: '' }` object
* @type {Object}
*/
classes: {
direction: {
ltr: 'glide--ltr',
rtl: 'glide--rtl'
},
slider: 'glide--slider',
carousel: 'glide--carousel',
swipeable: 'glide--swipeable',
dragging: 'glide--dragging',
cloneSlide: 'glide__slide--clone',
activeNav: 'glide__bullet--active',
activeSlide: 'glide__slide--active',
disabledArrow: 'glide__arrow--disabled'
}
};
/**
* Outputs warning message to the bowser console.
*
* @param {String} msg
* @return {Void}
*/
function warn(msg) {
console.error("[Glide warn]: " + msg);
}
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var _extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
var get = function get(object, property, receiver) {
if (object === null) object = Function.prototype;
var desc = Object.getOwnPropertyDescriptor(object, property);
if (desc === undefined) {
var parent = Object.getPrototypeOf(object);
if (parent === null) {
return undefined;
} else {
return get(parent, property, receiver);
}
} else if ("value" in desc) {
return desc.value;
} else {
var getter = desc.get;
if (getter === undefined) {
return undefined;
}
return getter.call(receiver);
}
};
var inherits = function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
};
var possibleConstructorReturn = function (self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
};
/**
* Converts value entered as number
* or string to integer value.
*
* @param {String} value
* @returns {Number}
*/
function toInt(value) {
return parseInt(value);
}
/**
* Converts value entered as number
* or string to flat value.
*
* @param {String} value
* @returns {Number}
*/
function toFloat(value) {
return parseFloat(value);
}
/**
* Indicates whether the specified value is a string.
*
* @param {*} value
* @return {Boolean}
*/
function isString(value) {
return typeof value === 'string';
}
/**
* Indicates whether the specified value is an object.
*
* @param {*} value
* @return {Boolean}
*
* @see https://github.com/jashkenas/underscore
*/
function isObject(value) {
var type = typeof value === 'undefined' ? 'undefined' : _typeof(value);
return type === 'function' || type === 'object' && !!value; // eslint-disable-line no-mixed-operators
}
/**
* Indicates whether the specified value is a number.
*
* @param {*} value
* @return {Boolean}
*/
function isNumber(value) {
return typeof value === 'number';
}
/**
* Indicates whether the specified value is a function.
*
* @param {*} value
* @return {Boolean}
*/
function isFunction(value) {
return typeof value === 'function';
}
/**
* Indicates whether the specified value is undefined.
*
* @param {*} value
* @return {Boolean}
*/
function isUndefined(value) {
return typeof value === 'undefined';
}
/**
* Indicates whether the specified value is an array.
*
* @param {*} value
* @return {Boolean}
*/
function isArray(value) {
return value.constructor === Array;
}
/**
* Creates and initializes specified collection of extensions.
* Each extension receives access to instance of glide and rest of components.
*
* @param {Object} glide
* @param {Object} extensions
*
* @returns {Object}
*/
function mount(glide, extensions, events) {
var components = {};
for (var name in extensions) {
if (isFunction(extensions[name])) {
components[name] = extensions[name](glide, components, events);
} else {
warn('Extension must be a function');
}
}
for (var _name in components) {
if (isFunction(components[_name].mount)) {
components[_name].mount();
}
}
return components;
}
/**
* Defines getter and setter property on the specified object.
*
* @param {Object} obj Object where property has to be defined.
* @param {String} prop Name of the defined property.
* @param {Object} definition Get and set definitions for the property.
* @return {Void}
*/
function define(obj, prop, definition) {
Object.defineProperty(obj, prop, definition);
}
/**
* Sorts aphabetically object keys.
*
* @param {Object} obj
* @return {Object}
*/
function sortKeys(obj) {
return Object.keys(obj).sort().reduce(function (r, k) {
r[k] = obj[k];
return r[k], r;
}, {});
}
/**
* Merges passed settings object with default options.
*
* @param {Object} defaults
* @param {Object} settings
* @return {Object}
*/
function mergeOptions(defaults, settings) {
var options = _extends({}, defaults, settings);
// `Object.assign` do not deeply merge objects, so we
// have to do it manually for every nested object
// in options. Although it does not look smart,
// it's smaller and faster than some fancy
// merging deep-merge algorithm script.
if (settings.hasOwnProperty('classes')) {
options.classes = _extends({}, defaults.classes, settings.classes);
if (settings.classes.hasOwnProperty('direction')) {
options.classes.direction = _extends({}, defaults.classes.direction, settings.classes.direction);
}
}
if (settings.hasOwnProperty('breakpoints')) {
options.breakpoints = _extends({}, defaults.breakpoints, settings.breakpoints);
}
return options;
}
var EventsBus = function () {
/**
* Construct a EventBus instance.
*
* @param {Object} events
*/
function EventsBus() {
var events = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
classCallCheck(this, EventsBus);
this.events = events;
this.hop = events.hasOwnProperty;
}
/**
* Adds listener to the specifed event.
*
* @param {String|Array} event
* @param {Function} handler
*/
createClass(EventsBus, [{
key: 'on',
value: function on(event, handler) {
if (isArray(event)) {
for (var i = 0; i < event.length; i++) {
this.on(event[i], handler);
}
}
// Create the event's object if not yet created
if (!this.hop.call(this.events, event)) {
this.events[event] = [];
}
// Add the handler to queue
var index = this.events[event].push(handler) - 1;
// Provide handle back for removal of event
return {
remove: function remove() {
delete this.events[event][index];
}
};
}
/**
* Runs registered handlers for specified event.
*
* @param {String|Array} event
* @param {Object=} context
*/
}, {
key: 'emit',
value: function emit(event, context) {
if (isArray(event)) {
for (var i = 0; i < event.length; i++) {
this.emit(event[i], context);
}
}
// If the event doesn't exist, or there's no handlers in queue, just leave
if (!this.hop.call(this.events, event)) {
return;
}
// Cycle through events queue, fire!
this.events[event].forEach(function (item) {
item(context || {});
});
}
}]);
return EventsBus;
}();
var Glide = function () {
/**
* Construct glide.
*
* @param {String} selector
* @param {Object} options
*/
function Glide(selector) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
classCallCheck(this, Glide);
this._c = {};
this._t = [];
this._e = new EventsBus();
this.disabled = false;
this.selector = selector;
this.settings = mergeOptions(defaults, options);
this.index = this.settings.startAt;
}
/**
* Initializes glide.
*
* @param {Object} extensions Collection of extensions to initialize.
* @return {Glide}
*/
createClass(Glide, [{
key: 'mount',
value: function mount$$1() {
var extensions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
this._e.emit('mount.before');
if (isObject(extensions)) {
this._c = mount(this, extensions, this._e);
} else {
warn('You need to provide a object on `mount()`');
}
this._e.emit('mount.after');
return this;
}
/**
* Collects an instance `translate` transformers.
*
* @param {Array} transformers Collection of transformers.
* @return {Void}
*/
}, {
key: 'mutate',
value: function mutate() {
var transformers = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
if (isArray(transformers)) {
this._t = transformers;
} else {
warn('You need to provide a array on `mutate()`');
}
return this;
}
/**
* Updates glide with specified settings.
*
* @param {Object} settings
* @return {Glide}
*/
}, {
key: 'update',
value: function update() {
var settings = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
this.settings = mergeOptions(this.settings, settings);
if (settings.hasOwnProperty('startAt')) {
this.index = settings.startAt;
}
this._e.emit('update');
return this;
}
/**
* Change slide with specified pattern. A pattern must be in the special format:
* `>` - Move one forward
* `<` - Move one backward
* `={i}` - Go to {i} zero-based slide (eq. '=1', will go to second slide)
* `>>` - Rewinds to end (last slide)
* `<<` - Rewinds to start (first slide)
*
* @param {String} pattern
* @return {Glide}
*/
}, {
key: 'go',
value: function go(pattern) {
this._c.Run.make(pattern);
return this;
}
/**
* Move track by specified distance.
*
* @param {String} distance
* @return {Glide}
*/
}, {
key: 'move',
value: function move(distance) {
this._c.Transition.disable();
this._c.Move.make(distance);
return this;
}
/**
* Destroy instance and revert all changes done by this._c.
*
* @return {Glide}
*/
}, {
key: 'destroy',
value: function destroy() {
this._e.emit('destroy');
return this;
}
/**
* Start instance autoplaying.
*
* @param {Boolean|Number} interval Run autoplaying with passed interval regardless of `autoplay` settings
* @return {Glide}
*/
}, {
key: 'play',
value: function play() {
var interval = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
if (interval) {
this.settings.autoplay = interval;
}
this._e.emit('play');
return this;
}
/**
* Stop instance autoplaying.
*
* @return {Glide}
*/
}, {
key: 'pause',
value: function pause() {
this._e.emit('pause');
return this;
}
/**
* Sets glide into a idle status.
*
* @return {Glide}
*/
}, {
key: 'disable',
value: function disable() {
this.disabled = true;
return this;
}
/**
* Sets glide into a active status.
*
* @return {Glide}
*/
}, {
key: 'enable',
value: function enable() {
this.disabled = false;
return this;
}
/**
* Adds cuutom event listener with handler.
*
* @param {String|Array} event
* @param {Function} handler
* @return {Glide}
*/
}, {
key: 'on',
value: function on(event, handler) {
this._e.on(event, handler);
return this;
}
/**
* Checks if glide is a precised type.
*
* @param {String} name
* @return {Boolean}
*/
}, {
key: 'isType',
value: function isType(name) {
return this.settings.type === name;
}
/**
* Gets value of the core options.
*
* @return {Object}
*/
}, {
key: 'settings',
get: function get$$1() {
return this._o;
}
/**
* Sets value of the core options.
*
* @param {Object} o
* @return {Void}
*/
,
set: function set$$1(o) {
if (isObject(o)) {
this._o = o;
} else {
warn('Options must be an `object` instance.');
}
}
/**
* Gets current index of the slider.
*
* @return {Object}
*/
}, {
key: 'index',
get: function get$$1() {
return this._i;
}
/**
* Sets current index a slider.
*
* @return {Object}
*/
,
set: function set$$1(i) {
this._i = toInt(i);
}
/**
* Gets type name of the slider.
*
* @return {String}
*/
}, {
key: 'type',
get: function get$$1() {
return this.settings.type;
}
/**
* Gets value of the idle status.
*
* @return {Boolean}
*/
}, {
key: 'disabled',
get: function get$$1() {
return this._d;
}
/**
* Sets value of the idle status.
*
* @return {Boolean}
*/
,
set: function set$$1(status) {
this._d = !!status;
}
}]);
return Glide;
}();
function Run (Glide, Components, Events) {
var Run = {
/**
* Initializes autorunning of the glide.
*
* @return {Void}
*/
mount: function mount() {
this._o = false;
},
/**
* Makes glides running based on the passed moving schema.
*
* @param {String} move
*/
make: function make(move) {
var _this = this;
if (!Glide.disabled) {
Glide.disable();
this.move = move;
Events.emit('run.before', this.move);
this.calculate();
Events.emit('run', this.move);
Components.Transition.after(function () {
if (_this.isOffset('<') || _this.isOffset('>')) {
_this._o = false;
Events.emit('run.offset', _this.move);
}
Events.emit('run.after', _this.move);
Glide.enable();
});
}
},
/**
* Calculates current index based on defined move.
*
* @return {Void}
*/
calculate: function calculate() {
var move = this.move,
length = this.length;
var steps = move.steps,
direction = move.direction;
var countableSteps = isNumber(toInt(steps)) && toInt(steps) !== 0;
switch (direction) {
case '>':
if (steps === '>') {
Glide.index = length;
} else if (this.isEnd()) {
if (!(Glide.isType('slider') && !Glide.settings.rewind)) {
this._o = true;
Glide.index = 0;
}
Events.emit('run.end', move);
} else if (countableSteps) {
Glide.index += Math.min(length - Glide.index, -toInt(steps));
} else {
Glide.index++;
}
break;
case '<':
if (steps === '<') {
Glide.index = 0;
} else if (this.isStart()) {
if (!(Glide.isType('slider') && !Glide.settings.rewind)) {
this._o = true;
Glide.index = length;
}
Events.emit('run.start', move);
} else if (countableSteps) {
Glide.index -= Math.min(Glide.index, toInt(steps));
} else {
Glide.index--;
}
break;
case '=':
Glide.index = steps;
break;
}
},
/**
* Checks if we are on the first slide.
*
* @return {Boolean}
*/
isStart: function isStart() {
return Glide.index === 0;
},
/**
* Checks if we are on the last slide.
*
* @return {Boolean}
*/
isEnd: function isEnd() {
return Glide.index === this.length;
},
/**
* Checks if we are making a offset run.
*
* @param {String} direction
* @return {Boolean}
*/
isOffset: function isOffset(direction) {
return this._o && this.move.direction === direction;
}
};
define(Run, 'move', {
/**
* Gets value of the move schema.
*
* @returns {Object}
*/
get: function get() {
return this._m;
},
/**
* Sets value of the move schema.
*
* @returns {Object}
*/
set: function set(value) {
this._m = {
direction: value.substr(0, 1),
steps: value.substr(1) ? value.substr(1) : 0
};
}
});
define(Run, 'length', {
/**
* Gets value of the running distance based
* on zero-indexing number of slides.
*
* @return {Number}
*/
get: function get() {
var settings = Glide.settings;
var length = Components.Html.slides.length;
// If the `bound` option is acitve, a maximum running distance should be
// reduced by `perView` and `focusAt` settings. Running distance
// should end before creating an empty space after instance.
if (Glide.isType('slider') && settings.focusAt !== 'center' && settings.bound) {
return length - 1 - (toInt(settings.perView) - 1) + toInt(settings.focusAt);
}
return length - 1;
}
});
define(Run, 'offset', {
/**
* Gets status of the offsetting flag.
*
* @return {Boolean}
*/
get: function get() {
return this._o;
}
});
return Run;
}
/**
* Returns a current time.
*
* @return {Number}
*/
function now() {
return new Date().getTime();
}
/**
* Returns a function, that, when invoked, will only be triggered
* at most once during a given window of time.
*
* @param {Function} func
* @param {Number} wait
* @param {Object=} options
* @return {Function}
*
* @see https://github.com/jashkenas/underscore
*/
function throttle(func, wait, options) {
var timeout = void 0,
context = void 0,
args = void 0,
result = void 0;
var previous = 0;
if (!options) options = {};
var later = function later() {
previous = options.leading === false ? 0 : now();
timeout = null;
result = func.apply(context, args);
if (!timeout) context = args = null;
};
var throttled = function throttled() {
var at = now();
if (!previous && options.leading === false) previous = at;
var remaining = wait - (at - previous);
context = this;
args = arguments;
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
previous = at;
result = func.apply(context, args);
if (!timeout) context = args = null;
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
throttled.cancel = function () {
clearTimeout(timeout);
previous = 0;
timeout = context = args = null;
};
return throttled;
}
var MARGIN_TYPE = {
ltr: ['marginLeft', 'marginRight'],
rtl: ['marginRight', 'marginLeft']
};
function Gaps (Glide, Components, Events) {
var Gaps = {
/**
* Applies gaps between slides. First and last
* slides do not receive it's edge margins.
*
* @param {HTMLCollection} slides
* @return {Void}
*/
apply: function apply(slides) {
for (var i = 0, len = slides.length; i < len; i++) {
var style = slides[i].style;
var direction = Components.Direction.value;
if (i !== 0) {
style[MARGIN_TYPE[direction][0]] = this.value / 2 + 'px';
} else {
style[MARGIN_TYPE[direction][0]] = '';
}
if (i !== slides.length - 1) {
style[MARGIN_TYPE[direction][1]] = this.value / 2 + 'px';
} else {
style[MARGIN_TYPE[direction][1]] = '';
}
}
},
/**
* Removes gaps from the slides.
*
* @param {HTMLCollection} slides
* @returns {Void}
*/
remove: function remove(slides) {
for (var i = 0, len = slides.length; i < len; i++) {
var style = slides[i].style;
style.marginLeft = '';
style.marginRight = '';
}
}
};
define(Gaps, 'value', {
/**
* Gets value of the gap.
*
* @returns {Number}
*/
get: function get() {
return toInt(Glide.settings.gap);
}
});
define(Gaps, 'grow', {
/**
* Gets additional dimentions value caused by gaps.
* Used to increase width of the slides wrapper.
*
* @returns {Number}
*/
get: function get() {
return Gaps.value * (Components.Sizes.length - 1);
}
});
define(Gaps, 'reductor', {
/**
* Gets reduction value caused by gaps.
* Used to subtract width of the slides.
*
* @returns {Number}
*/
get: function get() {
var perView = Glide.settings.perView;
return Gaps.value * (perView - 1) / perView;
}
});
/**
* Apply calculated gaps:
* - after building, so slides (including clones) will receive proper margins
* - on updating via API, to recalculate gaps with new options
*/
Events.on(['build.after', 'update'], throttle(function () {
Gaps.apply(Components.Html.wrapper.children);
}, 30));
/**
* Remove gaps:
* - on destroying to bring markup to its inital state
*/
Events.on('destroy', function () {
Gaps.remove(Components.Html.wrapper.children);
});
return Gaps;
}
/**
* Finds siblings nodes of the passed node.
*
* @param {Element} node
* @return {Array}
*/
function siblings(node) {
if (node && node.parentNode) {
var n = node.parentNode.firstChild;
var matched = [];
for (; n; n = n.nextSibling) {
if (n.nodeType === 1 && n !== node) {
matched.push(n);
}
}
return matched;
}
return [];
}
/**
* Checks if passed node exist and is a valid element.
*
* @param {Element} node
* @return {Boolean}
*/
function exist(node) {
if (node && node instanceof window.HTMLElement) {
return true;
}
return false;
}
var TRACK_SELECTOR = '[data-glide-el="track"]';
function Html (Glide, Components) {
var Html = {
/**
* Setup slider HTML nodes.
*
* @param {Glide} glide
*/
mount: function mount() {
this.root = Glide.selector;
this.track = this.root.querySelector(TRACK_SELECTOR);
this.slides = Array.prototype.slice.call(this.wrapper.children).filter(function (slide) {
return !slide.classList.contains(Glide.settings.classes.cloneSlide);
});
}
};
define(Html, 'root', {
/**
* Gets node of the glide main element.
*
* @return {Object}
*/
get: function get() {
return Html._r;
},
/**
* Sets node of the glide main element.
*
* @return {Object}
*/
set: function set(r) {
if (isString(r)) {
r = document.querySelector(r);
}
if (exist(r)) {
Html._r = r;
} else {
warn('Root element must be a existing Html node');
}
}
});
define(Html, 'track', {
/**
* Gets node of the glide track with slides.
*
* @return {Object}
*/
get: function get() {
return Html._t;
},
/**
* Sets node of the glide track with slides.
*
* @return {Object}
*/
set: function set(t) {
if (exist(t)) {
Html._t = t;
} else {
warn('Could not find track element. Please use ' + TRACK_SELECTOR + ' attribute.');
}
}
});
define(Html, 'wrapper', {
/**
* Gets node of the slides wrapper.
*
* @return {Object}
*/
get: function get() {
return Html.track.children[0];
}
});
return Html;
}
function Peek (Glide, Components, Events) {
var Peek = {
/**
* Setups how much to peek based on settings.
*
* @return {Void}
*/
mount: function mount() {
this.value = Glide.settings.peek;
}
};
define(Peek, 'value', {
/**
* Gets value of the peek.
*
* @returns {Number|Object}
*/
get: function get() {
return Peek._v;
},
/**
* Sets value of the peek.
*
* @param {Number|Object} value
* @return {Void}
*/
set: function set(value) {
if (isObject(value)) {
value.before = toInt(value.before);
value.after = toInt(value.after);
} else {
value = toInt(value);
}
Peek._v = value;
}
});
define(Peek, 'reductor', {
/**
* Gets reduction value caused by peek.
*
* @returns {Number}
*/
get: function get() {
var value = Peek.value;
var perView = Glide.settings.perView;
if (isObject(value)) {
return value.before / perView + value.after / perView;
}
return value * 2 / perView;
}
});
/**
* Recalculate peeking sizes on:
* - when resizing window to update to proper percents
*/
Events.on(['resize', 'update'], function () {
Peek.mount();
});
return Peek;
}
function Move (Glide, Components, Events) {
var Move = {
/**
* Constructs move component.
*
* @returns {Void}
*/
mount: function mount() {
this._o = 0;
},
/**
* Calculates a movement value based on passed offset and currently active index.
*
* @param {Number} offset
* @return {Void}
*/
make: function make() {
var _this = this;
var offset = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
this.offset = offset;
Events.emit('move', {
movement: this.value
});
Components.Transition.after(function () {
Events.emit('move.after', {
movement: _this.value
});
});
}
};
define(Move, 'offset', {
/**
* Gets an offset value used to modify current translate.
*
* @return {Object}
*/
get: function get() {
return Move._o;
},
/**
* Sets an offset value used to modify current translate.
*
* @return {Object}
*/
set: function set(value) {
Move._o = !isUndefined(value) ? toInt(value) : 0;
}
});
define(Move, 'translate', {
/**
* Gets a raw movement value.
*
* @return {Number}
*/
get: function get() {
return Components.Sizes.slideWidth * Glide.index;
}
});
define(Move, 'value', {
/**
* Gets an actual movement value corrected by offset.
*
* @return {Number}
*/
get: function get() {
var offset = this.offset;
var translate = this.translate;
if (Components.Direction.is('rtl')) {
return translate + offset;
}
return translate - offset;
}
});
/**
* Make movement to proper slide on:
* - before build, so glide will start at `startAt` index
* - on each standard run to move to newly calculated index
*/
Events.on(['build.before', 'run'], function () {
Move.make();
});
return Move;
}
function Sizes (Glide, Components, Events) {
var Sizes = {
/**
* Setups dimentions of slides.
*
* @return {Void}
*/
setupSlides: function setupSlides() {
var slides = Components.Html.slides;
for (var i = 0; i < slides.length; i++) {
slides[i].style.width = this.slideWidth + 'px';
}
},
/**
* Setups dimentions of slides wrapper.
*
* @return {Void}
*/
setupWrapper: function setupWrapper(dimention) {
Components.Html.wrapper.style.width = this.wrapperSize + 'px';
},
/**
* Removes applied styles from HTML elements.
*
* @returns {Void}
*/
remove: function remove() {
var slides = Components.Html.slides;
for (var i = 0; i < slides.length; i++) {
slides[i].style.width = '';
}
Components.Html.wrapper.style.width = '';
}
};
define(Sizes, 'length', {
/**
* Gets count number of the slides.
*
* @return {Number}
*/
get: function get() {
return Components.Html.slides.length;
}
});
define(Sizes, 'width', {
/**
* Gets width value of the glide.
*
* @return {Number}
*/
get: function get() {
return Components.Html.root.offsetWidth;
}
});
define(Sizes, 'wrapperSize', {
/**
* Gets size of the slides wrapper.
*
* @return {Number}
*/
get: function get() {
return Sizes.slideWidth * Sizes.length + Components.Gaps.grow + Components.Clones.grow;
}
});
define(Sizes, 'slideWidth', {
/**
* Gets width value of the single slide.
*
* @return {Number}
*/
get: function get() {
return Sizes.width / Glide.settings.perView - Components.Peek.reductor - Components.Gaps.reductor;
}
});
/**
* Apply calculated glide's dimensions:
* - before building, so other dimentions (e.g. translate) will be calculated propertly
* - when resizing window to recalculate sildes dimensions
* - on updating via API, to calculate dimensions based on new options
*/
Events.on(['build.before', 'resize', 'update'], function () {
Sizes.setupSlides();
Sizes.setupWrapper();
});
/**
* Remove calculated glide's dimensions:
* - on destoting to bring markup to its inital state
*/
Events.on('destroy', function () {
Sizes.remove();
});
return Sizes;
}
function Build (Glide, Components, Events) {
var Build = {
/**
* Init glide building. Adds classes, sets
* dimensions and setups initial state.
*
* @return {Void}
*/
mount: function mount() {
Events.emit('build.before');
this.typeClass();
this.activeClass();
Events.emit('build.after');
},
/**
* Adds `type` class to the glide element.
*
* @return {Void}
*/
typeClass: function typeClass() {
Components.Html.root.classList.add(Glide.settings.classes[Glide.settings.type]);
},
/**
* Sets active class to current slide.
*
* @return {Void}
*/
activeClass: function activeClass() {
var classes = Glide.settings.classes;
var slide = Components.Html.slides[Glide.index];
if (slide) {
slide.classList.add(classes.activeSlide);
siblings(slide).forEach(function (sibling) {
sibling.classList.remove(classes.activeSlide);
});
}
},
/**
* Removes HTML classes applied at building.
*
* @return {Void}
*/
removeClasses: function removeClasses() {
var classes = Glide.settings.classes;
Components.Html.root.classList.remove(classes[Glide.settings.type]);
Components.Html.slides.forEach(function (sibling) {
sibling.classList.remove(classes.activeSlide);
});
}
};
/**
* Clear building classes:
* - on destroying to bring HTML to its initial state
* - on updating to remove classes before remounting component
*/
Events.on(['destroy', 'update'], function () {
Build.removeClasses();
});
/**
* Remount component:
* - on resizing of the window to calculate new dimentions
* - on updating settings via API
*/
Events.on(['resize', 'update'], function () {
Build.mount();
});
/**
* Swap active class of current slide:
* - after each move to the new index
*/
Events.on('move.after', function () {
Build.activeClass();
});
return Build;
}
function Clones (Glide, Components, Events) {
var Clones = {
/**
* Create pattern map and collect slides to be cloned.
*/
mount: function mount() {
this.items = [];
if (Glide.isType('carousel')) {
this.items = this.collect();
}
},
/**
* Collect clones with pattern.
*
* @return {Void}
*/
collect: function collect() {
var items = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
var slides = Components.Html.slides;
var _Glide$settings = Glide.settings,
perView = _Glide$settings.perView,
classes = _Glide$settings.classes;
var peekIncrementer = +!!Glide.settings.peek;
var part = perView + peekIncrementer;
var start = slides.slice(0, part);
var end = slides.slice(-part);
for (var r = 0; r < Math.max(1, Math.floor(perView / slides.length)); r++) {
for (var i = 0; i < start.length; i++) {
var clone = start[i].cloneNode(true);
clone.classList.add(classes.cloneSlide);
items.push(clone);
}
for (var _i = 0; _i < end.length; _i++) {
var _clone = end[_i].cloneNode(true);
_clone.classList.add(classes.cloneSlide);
items.unshift(_clone);
}
}
return items;
},
/**
* Append cloned slides with generated pattern.
*
* @return {Void}
*/
append: function append() {
var items = this.items;
var _Components$Html = Components.Html,
wrapper = _Components$Html.wrapper,
slides = _Components$Html.slides;
var half = Math.floor(items.length / 2);
var prepend = items.slice(0, half).reverse();
var append = items.slice(half, items.length);
for (var i = 0; i < append.length; i++) {
wrapper.appendChild(append[i]);
}
for (var _i2 = 0; _i2 < prepend.length; _i2++) {
wrapper.insertBefore(prepend[_i2], slides[0]);
}
for (var _i3 = 0; _i3 < items.length; _i3++) {
items[_i3].style.width = Components.Sizes.slideWidth + 'px';
}
},
/**
* Remove all cloned slides.
*
* @return {Void}
*/
remove: function remove() {
var items = this.items;
for (var i = 0; i < items.length; i++) {
Components.Html.wrapper.removeChild(items[i]);
}
}
};
define(Clones, 'grow', {
/**
* Gets additional dimentions value caused by clones.
*
* @return {Number}
*/
get: function get() {
return (Components.Sizes.slideWidth + Components.Gaps.value) * Clones.items.length;
}
});
/**
* Append additional slide's clones:
* - while glide's type is `carousel`
*/
Events.on('update', function () {
Clones.remove();
Clones.mount();
Clones.append();
});
/**
* Append additional slide's clones:
* - while glide's type is `carousel`
*/
Events.on('build.before', function () {
if (Glide.isType('carousel')) {
Clones.append();
}
});
/**
* Remove clones HTMLElements:
* - on destroying, to bring HTML to its initial state
*/
Events.on('destroy', function () {
Clones.remove();
});
return Clones;
}
var EventsBinder = function () {
/**
* Construct a EventsBinder instance.
*/
function EventsBinder() {
var listeners = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
classCallCheck(this, EventsBinder);
this.listeners = listeners;
}
/**
* Adds events listeners to arrows HTML elements.
*
* @param {String|Array} events
* @param {Element|Window|Document} el
* @param {Function} closure
* @param {Boolean|Object} capture
* @return {Void}
*/
createClass(EventsBinder, [{
key: 'on',
value: function on(events, el, closure) {
var capture = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
if (isString(events)) {
events = [events];
}
for (var i = 0; i < events.length; i++) {
this.listeners[events[i]] = closure;
el.addEventListener(events[i], this.listeners[events[i]], capture);
}
}
/**
* Removes event listeners from arrows HTML elements.
*
* @param {String|Array} events
* @param {Element|Window|Document} el
* @return {Void}
*/
}, {
key: 'off',
value: function off(events, el) {
if (isString(events)) {
events = [events];
}
for (var i = 0; i < events.length; i++) {
el.removeEventListener(events[i], this.listeners[events[i]], false);
}
}
/**
* Destroy collected listeners.
*
* @returns {Void}
*/
}, {
key: 'destroy',
value: function destroy() {
delete this.listeners;
}
}]);
return EventsBinder;
}();
function Resize (Glide, Components, Events) {
/**
* Instance of the binder for DOM Events.
*
* @type {EventsBinder}
*/
var Binder = new EventsBinder();
var Resize = {
/**
* Initializes window bindings.
*/
mount: function mount() {
this.bind();
},
/**
* Binds `rezsize` listener to the window.
* It's a costly event, so we are debouncing it.
*
* @return {Void}
*/
bind: function bind() {
Binder.on('resize', window, throttle(function () {
Events.emit('resize');
}, Glide.settings.throttle));
},
/**
* Unbinds listeners from the window.
*
* @return {Void}
*/
unbind: function unbind() {
Binder.off('resize', window);
}
};
/**
* Remove bindings from window:
* - on destroying, to remove added EventListener
*/
Events.on('destroy', function () {
Resize.unbind();
Binder.destroy();
});
return Resize;
}
var VALID_DIRECTIONS = ['ltr', 'rtl'];
var FLIPED_MOVEMENTS = {
'>': '<',
'<': '>',
'=': '='
};
function Direction (Glide, Components, Events) {
var Direction = {
/**
* Setups gap value based on settings.
*
* @return {Void}
*/
mount: function mount() {
this.value = Glide.settings.direction;
},
/**
* Resolves pattern based on direction value
*
* @param {String} pattern
* @returns {String}
*/
resolve: function resolve(pattern) {
var token = pattern.slice(0, 1);
if (this.is('rtl')) {
return pattern.split(token).join(FLIPED_MOVEMENTS[token]);
}
return pattern;
},
/**
* Checks value of direction mode.
*
* @param {String} direction
* @returns {Boolean}
*/
is: function is(direction) {
return this.value === direction;
},
/**
* Applies direction class to the root HTML element.
*
* @return {Void}
*/
addClass: function addClass() {
Components.Html.root.classList.add(Glide.settings.classes.direction[this.value]);
},
/**
* Removes direction class from the root HTML element.
*
* @return {Void}
*/
removeClass: function removeClass() {
Components.Html.root.classList.remove(Glide.settings.classes.direction[this.value]);
}
};
define(Direction, 'value', {
/**
* Gets value of the direction.
*
* @returns {Number}
*/
get: function get() {
return Direction._v;
},
/**
* Sets value of the direction.
*
* @param {String} value
* @return {Void}
*/
set: function set(value) {
if (VALID_DIRECTIONS.indexOf(value) > -1) {
Direction._v = value;
} else {
warn('Direction value must be `ltr` or `rtl`');
}
}
});
/**
* Clear direction class:
* - on destroy to bring HTML to its initial state
* - on update to remove class before reappling bellow
*/
Events.on(['destroy', 'update'], function () {
Direction.removeClass();
});
/**
* Remount component:
* - on update to reflect changes in direction value
*/
Events.on('update', function () {
Direction.mount();
});
/**
* Apply direction class:
* - before building to apply class for the first time
* - on updating to reapply direction class that may changed
*/
Events.on(['build.before', 'update'], function () {
Direction.addClass();
});
return Direction;
}
/**
* Reflects value of glide movement.
*
* @param {Object} Glide
* @param {Object} Components
* @return {Object}
*/
function Rtl (Glide, Components) {
return {
/**
* Negates the passed translate if glide is in RTL option.
*
* @param {Number} translate
* @return {Number}
*/
modify: function modify(translate) {
if (Components.Direction.is('rtl')) {
return -translate;
}
return translate;
}
};
}
/**
* Updates glide movement with a `gap` settings.
*
* @param {Object} Glide
* @param {Object} Components
* @return {Object}
*/
function Gap (Glide, Components) {
return {
/**
* Modifies passed translate value with number in the `gap` settings.
*
* @param {Number} translate
* @return {Number}
*/
modify: function modify(translate) {
return translate + Components.Gaps.value * Glide.index;
}
};
}
/**
* Updates glide movement with width of additional clones width.
*
* @param {Object} Glide
* @param {Object} Components
* @return {Object}
*/
function Grow (Glide, Components) {
return {
/**
* Adds to the passed translate width of the half of clones.
*
* @param {Number} translate
* @return {Number}
*/
modify: function modify(translate) {
return translate + Components.Clones.grow / 2;
}
};
}
/**
* Updates glide movement with a `peek` settings.
*
* @param {Object} Glide
* @param {Object} Components
* @return {Object}
*/
function Peeking (Glide, Components) {
return {
/**
* Modifies passed translate value with a `peek` setting.
*
* @param {Number} translate
* @return {Number}
*/
modify: function modify(translate) {
if (Glide.settings.focusAt >= 0) {
var peek = Components.Peek.value;
if (isObject(peek)) {
return translate - peek.before;
}
return translate - peek;
}
return translate;
}
};
}
/**
* Updates glide movement with a `focusAt` settings.
*
* @param {Object} Glide
* @param {Object} Components
* @return {Object}
*/
function Focusing (Glide, Components) {
return {
/**
* Modifies passed translate value with index in the `focusAt` setting.
*
* @param {Number} translate
* @return {Number}
*/
modify: function modify(translate) {
var gap = Components.Gaps.value;
var width = Components.Sizes.width;
var focusAt = Glide.settings.focusAt;
var slideWidth = Components.Sizes.slideWidth;
if (focusAt === 'center') {
return translate - (width / 2 - slideWidth / 2);
}
return translate - slideWidth * focusAt - gap * focusAt;
}
};
}
/**
* Applies diffrent transformers on translate value.
*
* @param {Object} Glide
* @param {Object} Components
* @return {Object}
*/
function mutator (Glide, Components, Events) {
/**
* Merge instance transformers with collection of default transformers.
* It's important that the Rtl component be last on the list,
* so it reflects all previous transformations.
*
* @type {Array}
*/
var TRANSFORMERS = [Gap, Grow, Peeking, Focusing].concat(Glide._t, [Rtl]);
return {
/**
* Piplines translate value with registered transformers.
*
* @param {Number} translate
* @return {Number}
*/
mutate: function mutate(translate) {
for (var i = 0; i < TRANSFORMERS.length; i++) {
var transformer = TRANSFORMERS[i];
if (isFunction(transformer) && isFunction(transformer().modify)) {
translate = transformer(Glide, Components, Events).modify(translate);
} else {
warn('Transformer should be a function that returns an object with `modify()` method');
}
}
return translate;
}
};
}
function Translate (Glide, Components, Events) {
var Translate = {
/**
* Sets value of translate on HTML element.
*
* @param {Number} value
* @return {Void}
*/
set: function set(value) {
var transform = mutator(Glide, Components).mutate(value);
Components.Html.wrapper.style.transform = 'translate3d(' + -1 * transform + 'px, 0px, 0px)';
},
/**
* Removes value of translate from HTML element.
*
* @return {Void}
*/
remove: function remove() {
Components.Html.wrapper.style.transform = '';
}
};
/**
* Set new translate value:
* - on move to reflect index change
* - on updating via API to reflect possible changes in options
*/
Events.on('move', function (context) {
var gap = Components.Gaps.value;
var length = Components.Sizes.length;
var width = Components.Sizes.slideWidth;
if (Glide.isType('carousel') && Components.Run.isOffset('<')) {
Components.Transition.after(function () {
Events.emit('translate.jump');
Translate.set(width * (length - 1));
});
return Translate.set(-width - gap * length);
}
if (Glide.isType('carousel') && Components.Run.isOffset('>')) {
Components.Transition.after(function () {
Events.emit('translate.jump');
Translate.set(0);
});
return Translate.set(width * length + gap * length);
}
return Translate.set(context.movement);
});
/**
* Remove translate:
* - on destroying to bring markup to its inital state
*/
Events.on('destroy', function () {
Translate.remove();
});
return Translate;
}
function Transition (Glide, Components, Events) {
/**
* Holds inactivity status of transition.
* When true transition is not applied.
*
* @type {Boolean}
*/
var disabled = false;
var Transition = {
/**
* Composes string of the CSS transition.
*
* @param {String} property
* @return {String}
*/
compose: function compose(property) {
var settings = Glide.settings;
if (!disabled) {
return property + ' ' + this.duration + 'ms ' + settings.animationTimingFunc;
}
return property + ' 0ms ' + settings.animationTimingFunc;
},
/**
* Sets value of transition on HTML element.
*
* @param {String=} property
* @return {Void}
*/
set: function set() {
var property = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'transform';
Components.Html.wrapper.style.transition = this.compose(property);
},
/**
* Removes value of transition from HTML element.
*
* @return {Void}
*/
remove: function remove() {
Components.Html.wrapper.style.transition = '';
},
/**
* Runs callback after animation.
*
* @param {Function} callback
* @return {Void}
*/
after: function after(callback) {
setTimeout(function () {
callback();
}, this.duration);
},
/**
* Enable transition.
*
* @return {Void}
*/
enable: function enable() {
disabled = false;
this.set();
},
/**
* Disable transition.
*
* @return {Void}
*/
disable: function disable() {
disabled = true;
this.set();
}
};
define(Transition, 'duration', {
/**
* Gets duration of the transition based
* on currently running animation type.
*
* @return {Number}
*/
get: function get() {
var settings = Glide.settings;
if (Glide.isType('slider') && Components.Run.offset) {
return settings.rewindDuration;
}
return settings.animationDuration;
}
});
/**
* Set transition `style` value:
* - on each moving, because it may be cleared by offset move
*/
Events.on('move', function () {
Transition.set();
});
/**
* Disable transition:
* - before initial build to avoid transitioning from `0` to `startAt` index
* - while resizing window and recalculating dimentions
* - on jumping from offset transition at start and end edges in `carousel` type
*/
Events.on(['build.before', 'resize', 'translate.jump'], function () {
Transition.disable();
});
/**
* Enable transition:
* - on each running, because it may be disabled by offset move
*/
Events.on('run', function () {
Transition.enable();
});
/**
* Remove transition:
* - on destroying to bring markup to its inital state
*/
Events.on('destroy', function () {
Transition.remove();
});
return Transition;
}
/**
* Test via a getter in the options object to see
* if the passive property is accessed.
*
* @see https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md#feature-detection
*/
var supportsPassive = false;
try {
var opts = Object.defineProperty({}, 'passive', {
get: function get() {
supportsPassive = true;
}
});
window.addEventListener('testPassive', null, opts);
window.removeEventListener('testPassive', null, opts);
} catch (e) {}
var supportsPassive$1 = supportsPassive;
var START_EVENTS = ['touchstart', 'mousedown'];
var MOVE_EVENTS = ['touchmove', 'mousemove'];
var END_EVENTS = ['touchend', 'touchcancel', 'mouseup', 'mouseleave'];
var MOUSE_EVENTS = ['mousedown', 'mousemove', 'mouseup', 'mouseleave'];
function Swipe (Glide, Components, Events) {
/**
* Instance of the binder for DOM Events.
*
* @type {EventsBinder}
*/
var Binder = new EventsBinder();
var swipeSin = 0;
var swipeStartX = 0;
var swipeStartY = 0;
var disabled = false;
var moveable = true;
var capture = supportsPassive$1 ? { passive: true } : false;
var Swipe = {
/**
* Initializes swipe bindings.
*
* @return {Void}
*/
mount: function mount() {
this.bindSwipeStart();
},
/**
* Handler for `swipestart` event. Calculates entry points of the user's tap.
*
* @param {Object} event
* @return {Void}
*/
start: function start(event) {
if (!disabled && !Glide.disabled) {
this.disable();
var swipe = this.touches(event);
moveable = true;
swipeSin = null;
swipeStartX = toInt(swipe.pageX);
swipeStartY = toInt(swipe.pageY);
this.bindSwipeMove();
this.bindSwipeEnd();
Events.emit('swipe.start');
}
},
/**
* Handler for `swipemove` event. Calculates user's tap angle and distance.
*
* @param {Object} event
*/
move: function move(event) {
if (!Glide.disabled) {
var _Glide$settings = Glide.settings,
touchAngle = _Glide$settings.touchAngle,
touchRatio = _Glide$settings.touchRatio,
classes = _Glide$settings.classes;
var swipe = this.touches(event);
var subExSx = toInt(swipe.pageX) - swipeStartX;
var subEySy = toInt(swipe.pageY) - swipeStartY;
var powEX = Math.abs(subExSx << 2);
var powEY = Math.abs(subEySy << 2);
var swipeHypotenuse = Math.sqrt(powEX + powEY);
var swipeCathetus = Math.sqrt(powEY);
swipeSin = Math.asin(swipeCathetus / swipeHypotenuse);
if (moveable && swipeSin * 180 / Math.PI < touchAngle) {
event.stopPropagation();
Components.Move.make(subExSx * toFloat(touchRatio));
Components.Html.root.classList.add(classes.dragging);
Events.emit('swipe.move');
} else {
moveable = false;
return false;
}
}
},
/**
* Handler for `swipeend` event. Finitializes user's tap and decides about glide move.
*
* @param {Object} event
* @return {Void}
*/
end: function end(event) {
if (!Glide.disabled) {
var settings = Glide.settings;
var swipe = this.touches(event);
var threshold = this.threshold(event);
var swipeDistance = swipe.pageX - swipeStartX;
var swipeDeg = swipeSin * 180 / Math.PI;
var steps = Math.round(swipeDistance / Components.Sizes.slideWidth);
this.enable();
if (moveable) {
if (swipeDistance > threshold && swipeDeg < settings.touchAngle) {
// While swipe is positive and greater than threshold move backward.
if (settings.perTouch) {
steps = Math.min(steps, toInt(settings.perTouch));
}
if (Components.Direction.is('rtl')) {
steps = -steps;
}
Components.Run.make(Components.Direction.resolve('<' + steps));
} else if (swipeDistance < -threshold && swipeDeg < settings.touchAngle) {
// While swipe is negative and lower than negative threshold move forward.
if (settings.perTouch) {
steps = Math.max(steps, -toInt(settings.perTouch));
}
if (Components.Direction.is('rtl')) {
steps = -steps;
}
Components.Run.make(Components.Direction.resolve('>' + steps));
} else {
// While swipe don't reach distance apply previous transform.
Components.Move.make();
}
}
Components.Html.root.classList.remove(settings.classes.dragging);
this.unbindSwipeMove();
this.unbindSwipeEnd();
Events.emit('swipe.end');
}
},
/**
* Binds swipe's starting event.
*
* @return {Void}
*/
bindSwipeStart: function bindSwipeStart() {
var _this = this;
var settings = Glide.settings;
if (settings.swipeThreshold) {
Binder.on(START_EVENTS[0], Components.Html.wrapper, function (event) {
_this.start(event);
}, capture);
}
if (settings.dragThreshold) {
Binder.on(START_EVENTS[1], Components.Html.wrapper, function (event) {
_this.start(event);
}, capture);
}
},
/**
* Unbinds swipe's starting event.
*
* @return {Void}
*/
unbindSwipeStart: function unbindSwipeStart() {
Binder.off(START_EVENTS[0], Components.Html.wrapper);
Binder.off(START_EVENTS[1], Components.Html.wrapper);
},
/**
* Binds swipe's moving event.
*
* @return {Void}
*/
bindSwipeMove: function bindSwipeMove() {
var _this2 = this;
Binder.on(MOVE_EVENTS, Components.Html.wrapper, throttle(function (event) {
_this2.move(event);
}, Glide.settings.throttle), capture);
},
/**
* Unbinds swipe's moving event.
*
* @return {Void}
*/
unbindSwipeMove: function unbindSwipeMove() {
Binder.off(MOVE_EVENTS, Components.Html.wrapper);
},
/**
* Binds swipe's ending event.
*
* @return {Void}
*/
bindSwipeEnd: function bindSwipeEnd() {
var _this3 = this;
Binder.on(END_EVENTS, Components.Html.wrapper, function (event) {
_this3.end(event);
});
},
/**
* Unbinds swipe's ending event.
*
* @return {Void}
*/
unbindSwipeEnd: function unbindSwipeEnd() {
Binder.off(END_EVENTS, Components.Html.wrapper);
},
/**
* Normalizes event touches points accorting to different types.
*
* @param {Object} event
*/
touches: function touches(event) {
if (MOUSE_EVENTS.indexOf(event.type) > -1) {
return event;
}
return event.touches[0] || event.changedTouches[0];
},
/**
* Gets value of minimum swipe distance settings based on event type.
*
* @return {Number}
*/
threshold: function threshold(event) {
var settings = Glide.settings;
if (MOUSE_EVENTS.indexOf(event.type) > -1) {
return settings.dragThreshold;
}
return settings.swipeThreshold;
},
/**
* Enables swipe event.
*
* @return {self}
*/
enable: function enable() {
disabled = false;
Components.Transition.enable();
return this;
},
/**
* Disables swipe event.
*
* @return {self}
*/
disable: function disable() {
disabled = true;
Components.Transition.disable();
return this;
}
};
/**
* Add component class:
* - after initial building
*/
Events.on('build.after', function () {
Components.Html.root.classList.add(Glide.settings.classes.swipeable);
});
/**
* Remove swiping bindings:
* - on destroying, to remove added EventListeners
*/
Events.on('destroy', function () {
Swipe.unbindSwipeStart();
Swipe.unbindSwipeMove();
Swipe.unbindSwipeEnd();
Binder.destroy();
});
return Swipe;
}
function Images (Glide, Components, Events) {
/**
* Instance of the binder for DOM Events.
*
* @type {EventsBinder}
*/
var Binder = new EventsBinder();
var Images = {
/**
* Binds listener to glide wrapper.
*
* @return {Void}
*/
mount: function mount() {
this.bind();
},
/**
* Binds `dragstart` event on wrapper to prevent dragging images.
*
* @return {Void}
*/
bind: function bind() {
Binder.on('dragstart', Components.Html.wrapper, this.dragstart);
},
/**
* Unbinds `dragstart` event on wrapper.
*
* @return {Void}
*/
unbind: function unbind() {
Binder.off('dragstart', Components.Html.wrapper);
},
/**
* Event handler. Prevents dragging.
*
* @return {Void}
*/
dragstart: function dragstart(event) {
event.preventDefault();
}
};
/**
* Remove bindings from images:
* - on destroying, to remove added EventListeners
*/
Events.on('destroy', function () {
Images.unbind();
Binder.destroy();
});
return Images;
}
function Anchors (Glide, Components, Events) {
/**
* Instance of the binder for DOM Events.
*
* @type {EventsBinder}
*/
var Binder = new EventsBinder();
/**
* Holds detaching status of anchors.
* Prevents detaching of already detached anchors.
*
* @private
* @type {Boolean}
*/
var detached = false;
/**
* Holds preventing status of anchors.
* If `true` redirection after click will be disabled.
*
* @private
* @type {Boolean}
*/
var prevented = false;
var Anchors = {
/**
* Setups a initial state of anchors component.
*
* @returns {Void}
*/
mount: function mount() {
/**
* Holds collection of anchors elements.
*
* @private
* @type {HTMLCollection}
*/
this._a = Components.Html.wrapper.querySelectorAll('a');
this.bind();
},
/**
* Binds events to anchors inside a track.
*
* @return {Void}
*/
bind: function bind() {
Binder.on('click', Components.Html.wrapper, this.click);
},
/**
* Unbinds events attached to anchors inside a track.
*
* @return {Void}
*/
unbind: function unbind() {
Binder.off('click', Components.Html.wrapper);
},
/**
* Handler for click event. Prevents clicks when glide is in `prevent` status.
*
* @param {Object} event
* @return {Void}
*/
click: function click(event) {
event.stopPropagation();
if (prevented) {
event.preventDefault();
}
},
/**
* Detaches anchors click event inside glide.
*
* @return {self}
*/
detach: function detach() {
prevented = true;
if (!detached) {
for (var i = 0; i < this.items.length; i++) {
this.items[i].draggable = false;
this.items[i].setAttribute('data-href', this.items[i].getAttribute('href'));
this.items[i].removeAttribute('href');
}
detached = true;
}
return this;
},
/**
* Attaches anchors click events inside glide.
*
* @return {self}
*/
attach: function attach() {
prevented = false;
if (detached) {
for (var i = 0; i < this.items.length; i++) {
this.items[i].draggable = true;
this.items[i].setAttribute('href', this.items[i].getAttribute('data-href'));
}
detached = false;
}
return this;
}
};
define(Anchors, 'items', {
/**
* Gets collection of the arrows HTML elements.
*
* @return {HTMLElement[]}
*/
get: function get() {
return Anchors._a;
}
});
/**
* Detach anchors inside slides:
* - on swiping, so they won't redirect to its `href` attributes
*/
Events.on('swipe.move', function () {
Anchors.detach();
});
/**
* Attach anchors inside slides:
* - after swiping and transitions ends, so they can redirect after click again
*/
Events.on('swipe.end', function () {
Components.Transition.after(function () {
Anchors.attach();
});
});
/**
* Unbind anchors inside slides:
* - on destroying, to bring anchors to its initial state
*/
Events.on('destroy', function () {
Anchors.attach();
Anchors.unbind();
Binder.destroy();
});
return Anchors;
}
var NAV_SELECTOR = '[data-glide-el="controls[nav]"]';
var CONTROLS_SELECTOR = '[data-glide-el^="controls"]';
function Controls (Glide, Components, Events) {
/**
* Instance of the binder for DOM Events.
*
* @type {EventsBinder}
*/
var Binder = new EventsBinder();
var Controls = {
/**
* Inits arrows. Binds events listeners
* to the arrows HTML elements.
*
* @return {Void}
*/
mount: function mount() {
/**
* Collection of navigation HTML elements.
*
* @private
* @type {HTMLCollection}
*/
this._n = Components.Html.root.querySelectorAll(NAV_SELECTOR);
/**
* Collection of controls HTML elements.
*
* @private
* @type {HTMLCollection}
*/
this._c = Components.Html.root.querySelectorAll(CONTROLS_SELECTOR);
this.addBindings();
},
/**
* Sets active class to current slide.
*
* @return {Void}
*/
setActive: function setActive() {
for (var i = 0; i < this._n.length; i++) {
this.addClass(this._n[i].children);
}
},
/**
* Removes active class to current slide.
*
* @return {Void}
*/
removeActive: function removeActive() {
for (var i = 0; i < this._n.length; i++) {
this.removeClass(this._n[i].children);
}
},
/**
* Toggles active class on items inside navigation.
*
* @param {HTMLElement} controls
* @return {Void}
*/
addClass: function addClass(controls) {
var settings = Glide.settings;
var item = controls[Glide.index];
item.classList.add(settings.classes.activeNav);
siblings(item).forEach(function (sibling) {
sibling.classList.remove(settings.classes.activeNav);
});
},
/**
* Removes active class from active control.
*
* @param {HTMLElement} controls
* @return {Void}
*/
removeClass: function removeClass(controls) {
controls[Glide.index].classList.remove(Glide.settings.classes.activeNav);
},
/**
* Adds handles to the each group of controls.
*
* @return {Void}
*/
addBindings: function addBindings() {
for (var i = 0; i < this._c.length; i++) {
this.bind(this._c[i].children);
}
},
/**
* Removes handles from the each group of controls.
*
* @return {Void}
*/
removeBindings: function removeBindings() {
for (var i = 0; i < this._c.length; i++) {
this.unbind(this._c[i].children);
}
},
/**
* Binds events to arrows HTML elements.
*
* @param {HTMLCollection} elements
* @return {Void}
*/
bind: function bind(elements) {
for (var i = 0; i < elements.length; i++) {
Binder.on(['click', 'touchstart'], elements[i], this.click);
}
},
/**
* Unbinds events binded to the arrows HTML elements.
*
* @param {HTMLCollection} elements
* @return {Void}
*/
unbind: function unbind(elements) {
for (var i = 0; i < elements.length; i++) {
Binder.off(['click', 'touchstart'], elements[i]);
}
},
/**
* Handles `click` event on the arrows HTML elements.
* Moves slider in driection precised in
* `data-glide-dir` attribute.
*
* @param {Object} event
* @return {Void}
*/
click: function click(event) {
event.preventDefault();
Components.Run.make(Components.Direction.resolve(event.currentTarget.getAttribute('data-glide-dir')));
}
};
define(Controls, 'items', {
/**
* Gets collection of the controls HTML elements.
*
* @return {HTMLElement[]}
*/
get: function get() {
return Controls._c;
}
});
/**
* Swap active class of current navigation item:
* - after mounting to set it to initial index
* - after each move to the new index
*/
Events.on(['mount.after', 'move.after'], function () {
Controls.setActive();
});
/**
* Remove bindings and HTML Classes:
* - on destroying, to bring markup to its initial state
*/
Events.on('destroy', function () {
Controls.removeBindings();
Controls.removeActive();
Binder.destroy();
});
return Controls;
}
function Keyboard (Glide, Components, Events) {
/**
* Instance of the binder for DOM Events.
*
* @type {EventsBinder}
*/
var Binder = new EventsBinder();
var Keyboard = {
/**
* Binds keyboard events on component mount.
*
* @return {Void}
*/
mount: function mount() {
if (Glide.settings.keyboard) {
this.bind();
}
},
/**
* Adds keyboard press events.
*
* @return {Void}
*/
bind: function bind() {
Binder.on('keyup', document, this.press);
},
/**
* Removes keyboard press events.
*
* @return {Void}
*/
unbind: function unbind() {
Binder.off('keyup', document);
},
/**
* Handles keyboard's arrows press and moving glide foward and backward.
*
* @param {Object} event
* @return {Void}
*/
press: function press(event) {
if (event.keyCode === 39) {
Components.Run.make(Components.Direction.resolve('>'));
}
if (event.keyCode === 37) {
Components.Run.make(Components.Direction.resolve('<'));
}
}
};
/**
* Remove bindings from keyboard:
* - on destroying to remove added events
* - on updating to remove events before remounting
*/
Events.on(['destroy', 'update'], function () {
Keyboard.unbind();
});
/**
* Remount component
* - on updating to reflect potential changes in settings
*/
Events.on('update', function () {
Keyboard.mount();
});
/**
* Destroy binder:
* - on destroying to remove listeners
*/
Events.on('destroy', function () {
Binder.destroy();
});
return Keyboard;
}
function Autoplay (Glide, Components, Events) {
/**
* Instance of the binder for DOM Events.
*
* @type {EventsBinder}
*/
var Binder = new EventsBinder();
var Autoplay = {
/**
* Initializes autoplaying and events.
*
* @return {Void}
*/
mount: function mount() {
this.start();
if (Glide.settings.hoverpause) {
this.bind();
}
},
/**
* Starts autoplaying in configured interval.
*
* @param {Boolean|Number} force Run autoplaying with passed interval regardless of `autoplay` settings
* @return {Void}
*/
start: function start() {
var _this = this;
if (Glide.settings.autoplay) {
if (isUndefined(this._i)) {
this._i = setInterval(function () {
_this.stop();
Components.Run.make('>');
_this.start();
}, this.time);
}
}
},
/**
* Stops autorunning of the glide.
*
* @return {Void}
*/
stop: function stop() {
this._i = clearInterval(this._i);
},
/**
* Stops autoplaying while mouse is over glide's area.
*
* @return {Void}
*/
bind: function bind() {
var _this2 = this;
Binder.on('mouseover', Components.Html.root, function () {
_this2.stop();
});
Binder.on('mouseout', Components.Html.root, function () {
_this2.start();
});
},
/**
* Unbind mouseover events.
*
* @returns {Void}
*/
unbind: function unbind() {
Binder.off(['mouseover', 'mouseout'], Components.Html.root);
}
};
define(Autoplay, 'time', {
/**
* Gets time period value for the autoplay interval. Prioritizes
* times in `data-glide-autoplay` attrubutes over options.
*
* @return {Number}
*/
get: function get() {
var autoplay = Components.Html.slides[Glide.index].getAttribute('data-glide-autoplay');
if (autoplay) {
return toInt(autoplay);
}
return toInt(Glide.settings.autoplay);
}
});
/**
* Stop autoplaying and unbind events:
* - on destroying, to clear defined interval
* - on updating via API to reset interval that may changed
*/
Events.on(['destroy', 'update'], function () {
Autoplay.unbind();
});
/**
* Stop autoplaying:
* - before each run, to restart autoplaying
* - on pausing via API
* - on destroying, to clear defined interval
* - while starting a swipe
* - on updating via API to reset interval that may changed
*/
Events.on(['run.before', 'pause', 'destroy', 'swipe.start', 'update'], function () {
Autoplay.stop();
});
/**
* Start autoplaying:
* - after each run, to restart autoplaying
* - on playing via API
* - while ending a swipe
*/
Events.on(['run.after', 'play', 'swipe.end'], function () {
Autoplay.start();
});
/**
* Remount autoplaying:
* - on updating via API to reset interval that may changed
*/
Events.on('update', function () {
Autoplay.mount();
});
/**
* Destroy a binder:
* - on destroying glide instance to clearup listeners
*/
Events.on('destroy', function () {
Binder.destroy();
});
return Autoplay;
}
/**
* Sorts keys of breakpoint object so they will be ordered from lower to bigger.
*
* @param {Object} points
* @returns {Object}
*/
function sortBreakpoints(points) {
if (isObject(points)) {
return sortKeys(points);
} else {
warn('Breakpoints option must be an object');
}
return {};
}
function Breakpoints (Glide, Components, Events) {
/**
* Instance of the binder for DOM Events.
*
* @type {EventsBinder}
*/
var Binder = new EventsBinder();
/**
* Holds reference to settings.
*
* @type {Object}
*/
var settings = Glide.settings;
/**
* Holds reference to breakpoints object in settings. Sorts breakpoints
* from smaller to larger. It is required in order to proper
* matching currently active breakpoint settings.
*
* @type {Object}
*/
var points = sortBreakpoints(settings.breakpoints);
/**
* Cache initial settings before overwritting.
*
* @type {Object}
*/
var defaults = _extends({}, settings);
var Breakpoints = {
/**
* Matches settings for currectly matching media breakpoint.
*
* @param {Object} points
* @returns {Object}
*/
match: function match(points) {
if (typeof window.matchMedia !== 'undefined') {
for (var point in points) {
if (points.hasOwnProperty(point)) {
if (window.matchMedia('(max-width: ' + point + 'px)').matches) {
return points[point];
}
}
}
}
return defaults;
}
};
/**
* Overwrite instance settings with currently matching breakpoint settings.
* This happens right after component initialization.
*/
_extends(settings, Breakpoints.match(points));
/**
* Update glide with settings of matched brekpoint:
* - window resize to update slider
*/
Binder.on('resize', window, throttle(function () {
Glide.settings = mergeOptions(settings, Breakpoints.match(points));
}, Glide.settings.throttle));
/**
* Resort and update default settings:
* - on reinit via API, so breakpoint matching will be performed with options
*/
Events.on('update', function () {
points = sortBreakpoints(points);
defaults = _extends({}, settings);
});
/**
* Unbind resize listener:
* - on destroying, to bring markup to its initial state
*/
Events.on('destroy', function () {
Binder.off('resize', window);
});
return Breakpoints;
}
var COMPONENTS = {
// Required
Html: Html,
Translate: Translate,
Transition: Transition,
Direction: Direction,
Peek: Peek,
Sizes: Sizes,
Gaps: Gaps,
Move: Move,
Clones: Clones,
Resize: Resize,
Build: Build,
Run: Run,
// Optional
Swipe: Swipe,
Images: Images,
Anchors: Anchors,
Controls: Controls,
Keyboard: Keyboard,
Autoplay: Autoplay,
Breakpoints: Breakpoints
};
var Glide$1 = function (_Core) {
inherits(Glide$$1, _Core);
function Glide$$1() {
classCallCheck(this, Glide$$1);
return possibleConstructorReturn(this, (Glide$$1.__proto__ || Object.getPrototypeOf(Glide$$1)).apply(this, arguments));
}
createClass(Glide$$1, [{
key: 'mount',
value: function mount() {
var extensions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return get(Glide$$1.prototype.__proto__ || Object.getPrototypeOf(Glide$$1.prototype), 'mount', this).call(this, _extends({}, COMPONENTS, extensions));
}
}]);
return Glide$$1;
}(Glide);
return Glide$1;
})));
|
/**
* @license
* v1.2.10-5
* MIT (https://github.com/pnp/pnpjs/blob/master/LICENSE)
* Copyright (c) 2019 Microsoft
* docs: https://pnp.github.io/pnpjs/
* source: https://github.com/pnp/pnpjs
* bugs: https://github.com/pnp/pnpjs/issues
*/
/**
* Class used to subscribe ILogListener and log messages throughout an application
*
*/
class Logger {
/**
* Gets or sets the active log level to apply for log filtering
*/
static get activeLogLevel() {
return Logger.instance.activeLogLevel;
}
static set activeLogLevel(value) {
Logger.instance.activeLogLevel = value;
}
static get instance() {
if (Logger._instance === undefined || Logger._instance === null) {
Logger._instance = new LoggerImpl();
}
return Logger._instance;
}
/**
* Adds ILogListener instances to the set of subscribed listeners
*
* @param listeners One or more listeners to subscribe to this log
*/
static subscribe(...listeners) {
listeners.map(listener => Logger.instance.subscribe(listener));
}
/**
* Clears the subscribers collection, returning the collection before modifiction
*/
static clearSubscribers() {
return Logger.instance.clearSubscribers();
}
/**
* Gets the current subscriber count
*/
static get count() {
return Logger.instance.count;
}
/**
* Writes the supplied string to the subscribed listeners
*
* @param message The message to write
* @param level [Optional] if supplied will be used as the level of the entry (Default: LogLevel.Info)
*/
static write(message, level = 1 /* Info */) {
Logger.instance.log({ level: level, message: message });
}
/**
* Writes the supplied string to the subscribed listeners
*
* @param json The json object to stringify and write
* @param level [Optional] if supplied will be used as the level of the entry (Default: LogLevel.Info)
*/
static writeJSON(json, level = 1 /* Info */) {
this.write(JSON.stringify(json), level);
}
/**
* Logs the supplied entry to the subscribed listeners
*
* @param entry The message to log
*/
static log(entry) {
Logger.instance.log(entry);
}
/**
* Logs an error object to the subscribed listeners
*
* @param err The error object
*/
static error(err) {
Logger.instance.log({ data: err, level: 3 /* Error */, message: err.message });
}
}
class LoggerImpl {
constructor(activeLogLevel = 2 /* Warning */, subscribers = []) {
this.activeLogLevel = activeLogLevel;
this.subscribers = subscribers;
}
subscribe(listener) {
this.subscribers.push(listener);
}
clearSubscribers() {
const s = this.subscribers.slice(0);
this.subscribers.length = 0;
return s;
}
get count() {
return this.subscribers.length;
}
write(message, level = 1 /* Info */) {
this.log({ level: level, message: message });
}
log(entry) {
if (entry !== undefined && this.activeLogLevel <= entry.level) {
this.subscribers.map(subscriber => subscriber.log(entry));
}
}
}
/**
* A set of logging levels
*/
var LogLevel;
(function (LogLevel) {
LogLevel[LogLevel["Verbose"] = 0] = "Verbose";
LogLevel[LogLevel["Info"] = 1] = "Info";
LogLevel[LogLevel["Warning"] = 2] = "Warning";
LogLevel[LogLevel["Error"] = 3] = "Error";
LogLevel[LogLevel["Off"] = 99] = "Off";
})(LogLevel || (LogLevel = {}));
/**
* Implementation of LogListener which logs to the console
*
*/
class ConsoleListener {
/**
* Any associated data that a given logging listener may choose to log or ignore
*
* @param entry The information to be logged
*/
log(entry) {
const msg = this.format(entry);
switch (entry.level) {
case 0 /* Verbose */:
case 1 /* Info */:
console.log(msg);
break;
case 2 /* Warning */:
console.warn(msg);
break;
case 3 /* Error */:
console.error(msg);
break;
}
}
/**
* Formats the message
*
* @param entry The information to format into a string
*/
format(entry) {
const msg = [];
msg.push("Message: " + entry.message);
if (entry.data !== undefined) {
try {
msg.push(" Data: " + JSON.stringify(entry.data));
}
catch (e) {
msg.push(` Data: Error in stringify of supplied data ${e}`);
}
}
return msg.join("");
}
}
/**
* Implementation of LogListener which logs to the supplied function
*
*/
class FunctionListener {
/**
* Creates a new instance of the FunctionListener class
*
* @constructor
* @param method The method to which any logging data will be passed
*/
constructor(method) {
this.method = method;
}
/**
* Any associated data that a given logging listener may choose to log or ignore
*
* @param entry The information to be logged
*/
log(entry) {
this.method(entry);
}
}
export { Logger, LogLevel, ConsoleListener, FunctionListener };
//# sourceMappingURL=logging.js.map
|
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react"));
else if(typeof define === 'function' && define.amd)
define(["react"], factory);
else if(typeof exports === 'object')
exports["Cleave"] = factory(require("react"));
else
root["Cleave"] = factory(root["React"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_1__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
var React = __webpack_require__(1); // eslint-disable-line no-unused-vars
var CreateReactClass = __webpack_require__(2);
var NumeralFormatter = __webpack_require__(9);
var DateFormatter = __webpack_require__(10);
var TimeFormatter = __webpack_require__(11);
var PhoneFormatter = __webpack_require__(12);
var CreditCardDetector = __webpack_require__(13);
var Util = __webpack_require__(14);
var DefaultProperties = __webpack_require__(15);
var cleaveReactClass = CreateReactClass({
componentDidMount: function componentDidMount() {
this.init();
},
componentDidUpdate: function componentDidUpdate() {
var owner = this,
pps = owner.properties;
Util.setSelection(owner.element, owner.state.cursorPosition, pps.document);
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
var owner = this,
phoneRegionCode = (nextProps.options || {}).phoneRegionCode,
newValue = nextProps.value;
// update registed events
owner.updateRegisteredEvents(nextProps);
if (newValue !== undefined) {
newValue = newValue.toString();
if (newValue !== owner.properties.result) {
owner.properties.initValue = newValue;
owner.onInput(newValue, true);
}
}
// update phone region code
if (phoneRegionCode && phoneRegionCode !== owner.properties.phoneRegionCode) {
owner.properties.phoneRegionCode = phoneRegionCode;
owner.initPhoneFormatter();
owner.onInput(owner.properties.result);
}
},
updateRegisteredEvents: function updateRegisteredEvents(props) {
var owner = this,
_owner$registeredEven = owner.registeredEvents,
onKeyDown = _owner$registeredEven.onKeyDown,
onChange = _owner$registeredEven.onChange,
onFocus = _owner$registeredEven.onFocus,
onBlur = _owner$registeredEven.onBlur,
onInit = _owner$registeredEven.onInit;
if (props.onInit && props.onInit !== onInit) owner.registeredEvents.onInit = props.onInit;
if (props.onChange && props.onChange !== onChange) owner.registeredEvents.onChange = props.onChange;
if (props.onFocus && props.onFocus !== onFocus) owner.registeredEvents.onFocus = props.onFocus;
if (props.onBlur && props.onBlur !== onBlur) owner.registeredEvents.onBlur = props.onBlur;
if (props.onKeyDown && props.onKeyDown !== onKeyDown) owner.registeredEvents.onKeyDown = props.onKeyDown;
},
getInitialState: function getInitialState() {
var owner = this,
_owner$props = owner.props,
value = _owner$props.value,
options = _owner$props.options,
onKeyDown = _owner$props.onKeyDown,
onChange = _owner$props.onChange,
onFocus = _owner$props.onFocus,
onBlur = _owner$props.onBlur,
onInit = _owner$props.onInit;
owner.registeredEvents = {
onInit: onInit || Util.noop,
onChange: onChange || Util.noop,
onFocus: onFocus || Util.noop,
onBlur: onBlur || Util.noop,
onKeyDown: onKeyDown || Util.noop
};
if (!options) {
options = {};
}
options.initValue = value;
owner.properties = DefaultProperties.assign({}, options);
return {
value: owner.properties.result,
cursorPosition: 0
};
},
init: function init() {
var owner = this,
pps = owner.properties;
// so no need for this lib at all
if (!pps.numeral && !pps.phone && !pps.creditCard && !pps.time && !pps.date && pps.blocksLength === 0 && !pps.prefix) {
owner.onInput(pps.initValue);
owner.registeredEvents.onInit(owner);
return;
}
pps.maxLength = Util.getMaxLength(pps.blocks);
owner.isAndroid = Util.isAndroid();
owner.initPhoneFormatter();
owner.initDateFormatter();
owner.initTimeFormatter();
owner.initNumeralFormatter();
// avoid touch input field if value is null
// otherwise Firefox will add red box-shadow for <input required />
if (pps.initValue || pps.prefix && !pps.noImmediatePrefix) {
owner.onInput(pps.initValue);
}
owner.registeredEvents.onInit(owner);
},
initNumeralFormatter: function initNumeralFormatter() {
var owner = this,
pps = owner.properties;
if (!pps.numeral) {
return;
}
pps.numeralFormatter = new NumeralFormatter(pps.numeralDecimalMark, pps.numeralIntegerScale, pps.numeralDecimalScale, pps.numeralThousandsGroupStyle, pps.numeralPositiveOnly, pps.stripLeadingZeroes, pps.prefix, pps.signBeforePrefix, pps.delimiter);
},
initTimeFormatter: function initTimeFormatter() {
var owner = this,
pps = owner.properties;
if (!pps.time) {
return;
}
pps.timeFormatter = new TimeFormatter(pps.timePattern, pps.timeFormat);
pps.blocks = pps.timeFormatter.getBlocks();
pps.blocksLength = pps.blocks.length;
pps.maxLength = Util.getMaxLength(pps.blocks);
},
initDateFormatter: function initDateFormatter() {
var owner = this,
pps = owner.properties;
if (!pps.date) {
return;
}
pps.dateFormatter = new DateFormatter(pps.datePattern, pps.dateMin, pps.dateMax);
pps.blocks = pps.dateFormatter.getBlocks();
pps.blocksLength = pps.blocks.length;
pps.maxLength = Util.getMaxLength(pps.blocks);
},
initPhoneFormatter: function initPhoneFormatter() {
var owner = this,
pps = owner.properties;
if (!pps.phone) {
return;
}
// Cleave.AsYouTypeFormatter should be provided by
// external google closure lib
try {
pps.phoneFormatter = new PhoneFormatter(new pps.root.Cleave.AsYouTypeFormatter(pps.phoneRegionCode), pps.delimiter);
} catch (ex) {
throw new Error('Please include phone-type-formatter.{country}.js lib');
}
},
setRawValue: function setRawValue(value) {
var owner = this,
pps = owner.properties;
value = value !== undefined && value !== null ? value.toString() : '';
if (pps.numeral) {
value = value.replace('.', pps.numeralDecimalMark);
}
pps.postDelimiterBackspace = false;
owner.onChange({
target: { value: value },
// Methods to better resemble a SyntheticEvent
stopPropagation: Util.noop,
preventDefault: Util.noop,
persist: Util.noop
});
},
getRawValue: function getRawValue() {
var owner = this,
pps = owner.properties,
rawValue = pps.result;
if (pps.rawValueTrimPrefix) {
rawValue = Util.getPrefixStrippedValue(rawValue, pps.prefix, pps.prefixLength, pps.result, pps.delimiter, pps.delimiters);
}
if (pps.numeral) {
rawValue = pps.numeralFormatter ? pps.numeralFormatter.getRawValue(rawValue) : '';
} else {
rawValue = Util.stripDelimiters(rawValue, pps.delimiter, pps.delimiters);
}
return rawValue;
},
getISOFormatDate: function getISOFormatDate() {
var owner = this,
pps = owner.properties;
return pps.date ? pps.dateFormatter.getISOFormatDate() : '';
},
getISOFormatTime: function getISOFormatTime() {
var owner = this,
pps = owner.properties;
return pps.time ? pps.timeFormatter.getISOFormatTime() : '';
},
onInit: function onInit(owner) {
return owner;
},
onKeyDown: function onKeyDown(event) {
var owner = this,
pps = owner.properties,
charCode = event.which || event.keyCode;
// if we got any charCode === 8, this means, that this device correctly
// sends backspace keys in event, so we do not need to apply any hacks
owner.hasBackspaceSupport = owner.hasBackspaceSupport || charCode === 8;
if (!owner.hasBackspaceSupport && Util.isAndroidBackspaceKeydown(owner.lastInputValue, pps.result)) {
charCode = 8;
}
// hit backspace when last character is delimiter
var postDelimiter = Util.getPostDelimiter(pps.result, pps.delimiter, pps.delimiters);
if (charCode === 8 && postDelimiter) {
pps.postDelimiterBackspace = postDelimiter;
} else {
pps.postDelimiterBackspace = false;
}
owner.registeredEvents.onKeyDown(event);
},
onFocus: function onFocus(event) {
var owner = this,
pps = owner.properties;
event.target.rawValue = owner.getRawValue();
event.target.value = pps.result;
owner.registeredEvents.onFocus(event);
Util.fixPrefixCursor(owner.element, pps.prefix, pps.delimiter, pps.delimiters);
},
onBlur: function onBlur(event) {
var owner = this,
pps = owner.properties;
event.target.rawValue = owner.getRawValue();
event.target.value = pps.result;
owner.registeredEvents.onBlur(event);
},
onChange: function onChange(event) {
var owner = this,
pps = owner.properties;
owner.onInput(event.target.value);
event.target.rawValue = owner.getRawValue();
event.target.value = pps.result;
owner.registeredEvents.onChange(event);
},
onInput: function onInput(value, fromProps) {
var owner = this,
pps = owner.properties;
// case 1: delete one more character "4"
// 1234*| -> hit backspace -> 123|
// case 2: last character is not delimiter which is:
// 12|34* -> hit backspace -> 1|34*
var postDelimiterAfter = Util.getPostDelimiter(value, pps.delimiter, pps.delimiters);
if (!fromProps && !pps.numeral && pps.postDelimiterBackspace && !postDelimiterAfter) {
value = Util.headStr(value, value.length - pps.postDelimiterBackspace.length);
}
// phone formatter
if (pps.phone) {
if (pps.prefix && (!pps.noImmediatePrefix || value.length)) {
pps.result = pps.prefix + pps.phoneFormatter.format(value).slice(pps.prefix.length);
} else {
pps.result = pps.phoneFormatter.format(value);
}
owner.updateValueState();
return;
}
// numeral formatter
if (pps.numeral) {
// Do not show prefix when noImmediatePrefix is specified
// This mostly because we need to show user the native input placeholder
if (pps.prefix && pps.noImmediatePrefix && value.length === 0) {
pps.result = '';
} else {
pps.result = pps.numeralFormatter.format(value);
}
owner.updateValueState();
return;
}
// date
if (pps.date) {
value = pps.dateFormatter.getValidatedDate(value);
}
// time
if (pps.time) {
value = pps.timeFormatter.getValidatedTime(value);
}
// strip delimiters
value = Util.stripDelimiters(value, pps.delimiter, pps.delimiters);
// strip prefix
value = Util.getPrefixStrippedValue(value, pps.prefix, pps.prefixLength, pps.result, pps.delimiter, pps.delimiters, pps.noImmediatePrefix);
// strip non-numeric characters
value = pps.numericOnly ? Util.strip(value, /[^\d]/g) : value;
// convert case
value = pps.uppercase ? value.toUpperCase() : value;
value = pps.lowercase ? value.toLowerCase() : value;
// prevent from showing prefix when no immediate option enabled with empty input value
if (pps.prefix && (!pps.noImmediatePrefix || value.length)) {
value = pps.prefix + value;
// no blocks specified, no need to do formatting
if (pps.blocksLength === 0) {
pps.result = value;
owner.updateValueState();
return;
}
}
// update credit card props
if (pps.creditCard) {
owner.updateCreditCardPropsByValue(value);
}
// strip over length characters
value = pps.maxLength > 0 ? Util.headStr(value, pps.maxLength) : value;
// apply blocks
pps.result = Util.getFormattedValue(value, pps.blocks, pps.blocksLength, pps.delimiter, pps.delimiters, pps.delimiterLazyShow);
owner.updateValueState();
},
updateCreditCardPropsByValue: function updateCreditCardPropsByValue(value) {
var owner = this,
pps = owner.properties,
creditCardInfo;
// At least one of the first 4 characters has changed
if (Util.headStr(pps.result, 4) === Util.headStr(value, 4)) {
return;
}
creditCardInfo = CreditCardDetector.getInfo(value, pps.creditCardStrictMode);
pps.blocks = creditCardInfo.blocks;
pps.blocksLength = pps.blocks.length;
pps.maxLength = Util.getMaxLength(pps.blocks);
// credit card type changed
if (pps.creditCardType !== creditCardInfo.type) {
pps.creditCardType = creditCardInfo.type;
pps.onCreditCardTypeChanged.call(owner, pps.creditCardType);
}
},
updateValueState: function updateValueState() {
var owner = this,
pps = owner.properties;
if (!owner.element) {
owner.setState({ value: pps.result });
return;
}
var endPos = owner.element.selectionEnd;
var oldValue = owner.element.value;
var newValue = pps.result;
owner.lastInputValue = newValue;
endPos = Util.getNextCursorPosition(endPos, oldValue, newValue, pps.delimiter, pps.delimiters);
if (owner.isAndroid) {
window.setTimeout(function () {
owner.setState({ value: newValue, cursorPosition: endPos });
}, 1);
return;
}
owner.setState({ value: newValue, cursorPosition: endPos });
},
render: function render() {
var owner = this;
// eslint-disable-next-line
var _owner$props2 = owner.props,
value = _owner$props2.value,
options = _owner$props2.options,
onKeyDown = _owner$props2.onKeyDown,
onFocus = _owner$props2.onFocus,
onBlur = _owner$props2.onBlur,
onChange = _owner$props2.onChange,
onInit = _owner$props2.onInit,
htmlRef = _owner$props2.htmlRef,
propsToTransfer = _objectWithoutProperties(_owner$props2, ['value', 'options', 'onKeyDown', 'onFocus', 'onBlur', 'onChange', 'onInit', 'htmlRef']);
return React.createElement('input', _extends({
type: 'text',
ref: function ref(_ref) {
owner.element = _ref;
if (!htmlRef) {
return;
}
htmlRef.apply(this, arguments);
},
value: owner.state.value,
onKeyDown: owner.onKeyDown,
onChange: owner.onChange,
onFocus: owner.onFocus,
onBlur: owner.onBlur
}, propsToTransfer));
}
});
module.exports = cleaveReactClass;
/***/ }),
/* 1 */
/***/ (function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_1__;
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
'use strict';
var React = __webpack_require__(1);
var factory = __webpack_require__(3);
if (typeof React === 'undefined') {
throw Error(
'create-react-class could not find the React object. If you are using script tags, ' +
'make sure that React is being loaded before create-react-class.'
);
}
// Hack to grab NoopUpdateQueue from isomorphic React
var ReactNoopUpdateQueue = new React.Component().updater;
module.exports = factory(
React.Component,
React.isValidElement,
ReactNoopUpdateQueue
);
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
'use strict';
var _assign = __webpack_require__(4);
var emptyObject = __webpack_require__(5);
var _invariant = __webpack_require__(6);
if (process.env.NODE_ENV !== 'production') {
var warning = __webpack_require__(7);
}
var MIXINS_KEY = 'mixins';
// Helper function to allow the creation of anonymous functions which do not
// have .name set to the name of the variable being assigned to.
function identity(fn) {
return fn;
}
var ReactPropTypeLocationNames;
if (process.env.NODE_ENV !== 'production') {
ReactPropTypeLocationNames = {
prop: 'prop',
context: 'context',
childContext: 'child context'
};
} else {
ReactPropTypeLocationNames = {};
}
function factory(ReactComponent, isValidElement, ReactNoopUpdateQueue) {
/**
* Policies that describe methods in `ReactClassInterface`.
*/
var injectedMixins = [];
/**
* Composite components are higher-level components that compose other composite
* or host components.
*
* To create a new type of `ReactClass`, pass a specification of
* your new class to `React.createClass`. The only requirement of your class
* specification is that you implement a `render` method.
*
* var MyComponent = React.createClass({
* render: function() {
* return <div>Hello World</div>;
* }
* });
*
* The class specification supports a specific protocol of methods that have
* special meaning (e.g. `render`). See `ReactClassInterface` for
* more the comprehensive protocol. Any other properties and methods in the
* class specification will be available on the prototype.
*
* @interface ReactClassInterface
* @internal
*/
var ReactClassInterface = {
/**
* An array of Mixin objects to include when defining your component.
*
* @type {array}
* @optional
*/
mixins: 'DEFINE_MANY',
/**
* An object containing properties and methods that should be defined on
* the component's constructor instead of its prototype (static methods).
*
* @type {object}
* @optional
*/
statics: 'DEFINE_MANY',
/**
* Definition of prop types for this component.
*
* @type {object}
* @optional
*/
propTypes: 'DEFINE_MANY',
/**
* Definition of context types for this component.
*
* @type {object}
* @optional
*/
contextTypes: 'DEFINE_MANY',
/**
* Definition of context types this component sets for its children.
*
* @type {object}
* @optional
*/
childContextTypes: 'DEFINE_MANY',
// ==== Definition methods ====
/**
* Invoked when the component is mounted. Values in the mapping will be set on
* `this.props` if that prop is not specified (i.e. using an `in` check).
*
* This method is invoked before `getInitialState` and therefore cannot rely
* on `this.state` or use `this.setState`.
*
* @return {object}
* @optional
*/
getDefaultProps: 'DEFINE_MANY_MERGED',
/**
* Invoked once before the component is mounted. The return value will be used
* as the initial value of `this.state`.
*
* getInitialState: function() {
* return {
* isOn: false,
* fooBaz: new BazFoo()
* }
* }
*
* @return {object}
* @optional
*/
getInitialState: 'DEFINE_MANY_MERGED',
/**
* @return {object}
* @optional
*/
getChildContext: 'DEFINE_MANY_MERGED',
/**
* Uses props from `this.props` and state from `this.state` to render the
* structure of the component.
*
* No guarantees are made about when or how often this method is invoked, so
* it must not have side effects.
*
* render: function() {
* var name = this.props.name;
* return <div>Hello, {name}!</div>;
* }
*
* @return {ReactComponent}
* @required
*/
render: 'DEFINE_ONCE',
// ==== Delegate methods ====
/**
* Invoked when the component is initially created and about to be mounted.
* This may have side effects, but any external subscriptions or data created
* by this method must be cleaned up in `componentWillUnmount`.
*
* @optional
*/
componentWillMount: 'DEFINE_MANY',
/**
* Invoked when the component has been mounted and has a DOM representation.
* However, there is no guarantee that the DOM node is in the document.
*
* Use this as an opportunity to operate on the DOM when the component has
* been mounted (initialized and rendered) for the first time.
*
* @param {DOMElement} rootNode DOM element representing the component.
* @optional
*/
componentDidMount: 'DEFINE_MANY',
/**
* Invoked before the component receives new props.
*
* Use this as an opportunity to react to a prop transition by updating the
* state using `this.setState`. Current props are accessed via `this.props`.
*
* componentWillReceiveProps: function(nextProps, nextContext) {
* this.setState({
* likesIncreasing: nextProps.likeCount > this.props.likeCount
* });
* }
*
* NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop
* transition may cause a state change, but the opposite is not true. If you
* need it, you are probably looking for `componentWillUpdate`.
*
* @param {object} nextProps
* @optional
*/
componentWillReceiveProps: 'DEFINE_MANY',
/**
* Invoked while deciding if the component should be updated as a result of
* receiving new props, state and/or context.
*
* Use this as an opportunity to `return false` when you're certain that the
* transition to the new props/state/context will not require a component
* update.
*
* shouldComponentUpdate: function(nextProps, nextState, nextContext) {
* return !equal(nextProps, this.props) ||
* !equal(nextState, this.state) ||
* !equal(nextContext, this.context);
* }
*
* @param {object} nextProps
* @param {?object} nextState
* @param {?object} nextContext
* @return {boolean} True if the component should update.
* @optional
*/
shouldComponentUpdate: 'DEFINE_ONCE',
/**
* Invoked when the component is about to update due to a transition from
* `this.props`, `this.state` and `this.context` to `nextProps`, `nextState`
* and `nextContext`.
*
* Use this as an opportunity to perform preparation before an update occurs.
*
* NOTE: You **cannot** use `this.setState()` in this method.
*
* @param {object} nextProps
* @param {?object} nextState
* @param {?object} nextContext
* @param {ReactReconcileTransaction} transaction
* @optional
*/
componentWillUpdate: 'DEFINE_MANY',
/**
* Invoked when the component's DOM representation has been updated.
*
* Use this as an opportunity to operate on the DOM when the component has
* been updated.
*
* @param {object} prevProps
* @param {?object} prevState
* @param {?object} prevContext
* @param {DOMElement} rootNode DOM element representing the component.
* @optional
*/
componentDidUpdate: 'DEFINE_MANY',
/**
* Invoked when the component is about to be removed from its parent and have
* its DOM representation destroyed.
*
* Use this as an opportunity to deallocate any external resources.
*
* NOTE: There is no `componentDidUnmount` since your component will have been
* destroyed by that point.
*
* @optional
*/
componentWillUnmount: 'DEFINE_MANY',
/**
* Replacement for (deprecated) `componentWillMount`.
*
* @optional
*/
UNSAFE_componentWillMount: 'DEFINE_MANY',
/**
* Replacement for (deprecated) `componentWillReceiveProps`.
*
* @optional
*/
UNSAFE_componentWillReceiveProps: 'DEFINE_MANY',
/**
* Replacement for (deprecated) `componentWillUpdate`.
*
* @optional
*/
UNSAFE_componentWillUpdate: 'DEFINE_MANY',
// ==== Advanced methods ====
/**
* Updates the component's currently mounted DOM representation.
*
* By default, this implements React's rendering and reconciliation algorithm.
* Sophisticated clients may wish to override this.
*
* @param {ReactReconcileTransaction} transaction
* @internal
* @overridable
*/
updateComponent: 'OVERRIDE_BASE'
};
/**
* Similar to ReactClassInterface but for static methods.
*/
var ReactClassStaticInterface = {
/**
* This method is invoked after a component is instantiated and when it
* receives new props. Return an object to update state in response to
* prop changes. Return null to indicate no change to state.
*
* If an object is returned, its keys will be merged into the existing state.
*
* @return {object || null}
* @optional
*/
getDerivedStateFromProps: 'DEFINE_MANY_MERGED'
};
/**
* Mapping from class specification keys to special processing functions.
*
* Although these are declared like instance properties in the specification
* when defining classes using `React.createClass`, they are actually static
* and are accessible on the constructor instead of the prototype. Despite
* being static, they must be defined outside of the "statics" key under
* which all other static methods are defined.
*/
var RESERVED_SPEC_KEYS = {
displayName: function(Constructor, displayName) {
Constructor.displayName = displayName;
},
mixins: function(Constructor, mixins) {
if (mixins) {
for (var i = 0; i < mixins.length; i++) {
mixSpecIntoComponent(Constructor, mixins[i]);
}
}
},
childContextTypes: function(Constructor, childContextTypes) {
if (process.env.NODE_ENV !== 'production') {
validateTypeDef(Constructor, childContextTypes, 'childContext');
}
Constructor.childContextTypes = _assign(
{},
Constructor.childContextTypes,
childContextTypes
);
},
contextTypes: function(Constructor, contextTypes) {
if (process.env.NODE_ENV !== 'production') {
validateTypeDef(Constructor, contextTypes, 'context');
}
Constructor.contextTypes = _assign(
{},
Constructor.contextTypes,
contextTypes
);
},
/**
* Special case getDefaultProps which should move into statics but requires
* automatic merging.
*/
getDefaultProps: function(Constructor, getDefaultProps) {
if (Constructor.getDefaultProps) {
Constructor.getDefaultProps = createMergedResultFunction(
Constructor.getDefaultProps,
getDefaultProps
);
} else {
Constructor.getDefaultProps = getDefaultProps;
}
},
propTypes: function(Constructor, propTypes) {
if (process.env.NODE_ENV !== 'production') {
validateTypeDef(Constructor, propTypes, 'prop');
}
Constructor.propTypes = _assign({}, Constructor.propTypes, propTypes);
},
statics: function(Constructor, statics) {
mixStaticSpecIntoComponent(Constructor, statics);
},
autobind: function() {}
};
function validateTypeDef(Constructor, typeDef, location) {
for (var propName in typeDef) {
if (typeDef.hasOwnProperty(propName)) {
// use a warning instead of an _invariant so components
// don't show up in prod but only in __DEV__
if (process.env.NODE_ENV !== 'production') {
warning(
typeof typeDef[propName] === 'function',
'%s: %s type `%s` is invalid; it must be a function, usually from ' +
'React.PropTypes.',
Constructor.displayName || 'ReactClass',
ReactPropTypeLocationNames[location],
propName
);
}
}
}
}
function validateMethodOverride(isAlreadyDefined, name) {
var specPolicy = ReactClassInterface.hasOwnProperty(name)
? ReactClassInterface[name]
: null;
// Disallow overriding of base class methods unless explicitly allowed.
if (ReactClassMixin.hasOwnProperty(name)) {
_invariant(
specPolicy === 'OVERRIDE_BASE',
'ReactClassInterface: You are attempting to override ' +
'`%s` from your class specification. Ensure that your method names ' +
'do not overlap with React methods.',
name
);
}
// Disallow defining methods more than once unless explicitly allowed.
if (isAlreadyDefined) {
_invariant(
specPolicy === 'DEFINE_MANY' || specPolicy === 'DEFINE_MANY_MERGED',
'ReactClassInterface: You are attempting to define ' +
'`%s` on your component more than once. This conflict may be due ' +
'to a mixin.',
name
);
}
}
/**
* Mixin helper which handles policy validation and reserved
* specification keys when building React classes.
*/
function mixSpecIntoComponent(Constructor, spec) {
if (!spec) {
if (process.env.NODE_ENV !== 'production') {
var typeofSpec = typeof spec;
var isMixinValid = typeofSpec === 'object' && spec !== null;
if (process.env.NODE_ENV !== 'production') {
warning(
isMixinValid,
"%s: You're attempting to include a mixin that is either null " +
'or not an object. Check the mixins included by the component, ' +
'as well as any mixins they include themselves. ' +
'Expected object but got %s.',
Constructor.displayName || 'ReactClass',
spec === null ? null : typeofSpec
);
}
}
return;
}
_invariant(
typeof spec !== 'function',
"ReactClass: You're attempting to " +
'use a component class or function as a mixin. Instead, just use a ' +
'regular object.'
);
_invariant(
!isValidElement(spec),
"ReactClass: You're attempting to " +
'use a component as a mixin. Instead, just use a regular object.'
);
var proto = Constructor.prototype;
var autoBindPairs = proto.__reactAutoBindPairs;
// By handling mixins before any other properties, we ensure the same
// chaining order is applied to methods with DEFINE_MANY policy, whether
// mixins are listed before or after these methods in the spec.
if (spec.hasOwnProperty(MIXINS_KEY)) {
RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins);
}
for (var name in spec) {
if (!spec.hasOwnProperty(name)) {
continue;
}
if (name === MIXINS_KEY) {
// We have already handled mixins in a special case above.
continue;
}
var property = spec[name];
var isAlreadyDefined = proto.hasOwnProperty(name);
validateMethodOverride(isAlreadyDefined, name);
if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) {
RESERVED_SPEC_KEYS[name](Constructor, property);
} else {
// Setup methods on prototype:
// The following member methods should not be automatically bound:
// 1. Expected ReactClass methods (in the "interface").
// 2. Overridden methods (that were mixed in).
var isReactClassMethod = ReactClassInterface.hasOwnProperty(name);
var isFunction = typeof property === 'function';
var shouldAutoBind =
isFunction &&
!isReactClassMethod &&
!isAlreadyDefined &&
spec.autobind !== false;
if (shouldAutoBind) {
autoBindPairs.push(name, property);
proto[name] = property;
} else {
if (isAlreadyDefined) {
var specPolicy = ReactClassInterface[name];
// These cases should already be caught by validateMethodOverride.
_invariant(
isReactClassMethod &&
(specPolicy === 'DEFINE_MANY_MERGED' ||
specPolicy === 'DEFINE_MANY'),
'ReactClass: Unexpected spec policy %s for key %s ' +
'when mixing in component specs.',
specPolicy,
name
);
// For methods which are defined more than once, call the existing
// methods before calling the new property, merging if appropriate.
if (specPolicy === 'DEFINE_MANY_MERGED') {
proto[name] = createMergedResultFunction(proto[name], property);
} else if (specPolicy === 'DEFINE_MANY') {
proto[name] = createChainedFunction(proto[name], property);
}
} else {
proto[name] = property;
if (process.env.NODE_ENV !== 'production') {
// Add verbose displayName to the function, which helps when looking
// at profiling tools.
if (typeof property === 'function' && spec.displayName) {
proto[name].displayName = spec.displayName + '_' + name;
}
}
}
}
}
}
}
function mixStaticSpecIntoComponent(Constructor, statics) {
if (!statics) {
return;
}
for (var name in statics) {
var property = statics[name];
if (!statics.hasOwnProperty(name)) {
continue;
}
var isReserved = name in RESERVED_SPEC_KEYS;
_invariant(
!isReserved,
'ReactClass: You are attempting to define a reserved ' +
'property, `%s`, that shouldn\'t be on the "statics" key. Define it ' +
'as an instance property instead; it will still be accessible on the ' +
'constructor.',
name
);
var isAlreadyDefined = name in Constructor;
if (isAlreadyDefined) {
var specPolicy = ReactClassStaticInterface.hasOwnProperty(name)
? ReactClassStaticInterface[name]
: null;
_invariant(
specPolicy === 'DEFINE_MANY_MERGED',
'ReactClass: You are attempting to define ' +
'`%s` on your component more than once. This conflict may be ' +
'due to a mixin.',
name
);
Constructor[name] = createMergedResultFunction(Constructor[name], property);
return;
}
Constructor[name] = property;
}
}
/**
* Merge two objects, but throw if both contain the same key.
*
* @param {object} one The first object, which is mutated.
* @param {object} two The second object
* @return {object} one after it has been mutated to contain everything in two.
*/
function mergeIntoWithNoDuplicateKeys(one, two) {
_invariant(
one && two && typeof one === 'object' && typeof two === 'object',
'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.'
);
for (var key in two) {
if (two.hasOwnProperty(key)) {
_invariant(
one[key] === undefined,
'mergeIntoWithNoDuplicateKeys(): ' +
'Tried to merge two objects with the same key: `%s`. This conflict ' +
'may be due to a mixin; in particular, this may be caused by two ' +
'getInitialState() or getDefaultProps() methods returning objects ' +
'with clashing keys.',
key
);
one[key] = two[key];
}
}
return one;
}
/**
* Creates a function that invokes two functions and merges their return values.
*
* @param {function} one Function to invoke first.
* @param {function} two Function to invoke second.
* @return {function} Function that invokes the two argument functions.
* @private
*/
function createMergedResultFunction(one, two) {
return function mergedResult() {
var a = one.apply(this, arguments);
var b = two.apply(this, arguments);
if (a == null) {
return b;
} else if (b == null) {
return a;
}
var c = {};
mergeIntoWithNoDuplicateKeys(c, a);
mergeIntoWithNoDuplicateKeys(c, b);
return c;
};
}
/**
* Creates a function that invokes two functions and ignores their return vales.
*
* @param {function} one Function to invoke first.
* @param {function} two Function to invoke second.
* @return {function} Function that invokes the two argument functions.
* @private
*/
function createChainedFunction(one, two) {
return function chainedFunction() {
one.apply(this, arguments);
two.apply(this, arguments);
};
}
/**
* Binds a method to the component.
*
* @param {object} component Component whose method is going to be bound.
* @param {function} method Method to be bound.
* @return {function} The bound method.
*/
function bindAutoBindMethod(component, method) {
var boundMethod = method.bind(component);
if (process.env.NODE_ENV !== 'production') {
boundMethod.__reactBoundContext = component;
boundMethod.__reactBoundMethod = method;
boundMethod.__reactBoundArguments = null;
var componentName = component.constructor.displayName;
var _bind = boundMethod.bind;
boundMethod.bind = function(newThis) {
for (
var _len = arguments.length,
args = Array(_len > 1 ? _len - 1 : 0),
_key = 1;
_key < _len;
_key++
) {
args[_key - 1] = arguments[_key];
}
// User is trying to bind() an autobound method; we effectively will
// ignore the value of "this" that the user is trying to use, so
// let's warn.
if (newThis !== component && newThis !== null) {
if (process.env.NODE_ENV !== 'production') {
warning(
false,
'bind(): React component methods may only be bound to the ' +
'component instance. See %s',
componentName
);
}
} else if (!args.length) {
if (process.env.NODE_ENV !== 'production') {
warning(
false,
'bind(): You are binding a component method to the component. ' +
'React does this for you automatically in a high-performance ' +
'way, so you can safely remove this call. See %s',
componentName
);
}
return boundMethod;
}
var reboundMethod = _bind.apply(boundMethod, arguments);
reboundMethod.__reactBoundContext = component;
reboundMethod.__reactBoundMethod = method;
reboundMethod.__reactBoundArguments = args;
return reboundMethod;
};
}
return boundMethod;
}
/**
* Binds all auto-bound methods in a component.
*
* @param {object} component Component whose method is going to be bound.
*/
function bindAutoBindMethods(component) {
var pairs = component.__reactAutoBindPairs;
for (var i = 0; i < pairs.length; i += 2) {
var autoBindKey = pairs[i];
var method = pairs[i + 1];
component[autoBindKey] = bindAutoBindMethod(component, method);
}
}
var IsMountedPreMixin = {
componentDidMount: function() {
this.__isMounted = true;
}
};
var IsMountedPostMixin = {
componentWillUnmount: function() {
this.__isMounted = false;
}
};
/**
* Add more to the ReactClass base class. These are all legacy features and
* therefore not already part of the modern ReactComponent.
*/
var ReactClassMixin = {
/**
* TODO: This will be deprecated because state should always keep a consistent
* type signature and the only use case for this, is to avoid that.
*/
replaceState: function(newState, callback) {
this.updater.enqueueReplaceState(this, newState, callback);
},
/**
* Checks whether or not this composite component is mounted.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/
isMounted: function() {
if (process.env.NODE_ENV !== 'production') {
warning(
this.__didWarnIsMounted,
'%s: isMounted is deprecated. Instead, make sure to clean up ' +
'subscriptions and pending requests in componentWillUnmount to ' +
'prevent memory leaks.',
(this.constructor && this.constructor.displayName) ||
this.name ||
'Component'
);
this.__didWarnIsMounted = true;
}
return !!this.__isMounted;
}
};
var ReactClassComponent = function() {};
_assign(
ReactClassComponent.prototype,
ReactComponent.prototype,
ReactClassMixin
);
/**
* Creates a composite component class given a class specification.
* See https://facebook.github.io/react/docs/top-level-api.html#react.createclass
*
* @param {object} spec Class specification (which must define `render`).
* @return {function} Component constructor function.
* @public
*/
function createClass(spec) {
// To keep our warnings more understandable, we'll use a little hack here to
// ensure that Constructor.name !== 'Constructor'. This makes sure we don't
// unnecessarily identify a class without displayName as 'Constructor'.
var Constructor = identity(function(props, context, updater) {
// This constructor gets overridden by mocks. The argument is used
// by mocks to assert on what gets mounted.
if (process.env.NODE_ENV !== 'production') {
warning(
this instanceof Constructor,
'Something is calling a React component directly. Use a factory or ' +
'JSX instead. See: https://fb.me/react-legacyfactory'
);
}
// Wire up auto-binding
if (this.__reactAutoBindPairs.length) {
bindAutoBindMethods(this);
}
this.props = props;
this.context = context;
this.refs = emptyObject;
this.updater = updater || ReactNoopUpdateQueue;
this.state = null;
// ReactClasses doesn't have constructors. Instead, they use the
// getInitialState and componentWillMount methods for initialization.
var initialState = this.getInitialState ? this.getInitialState() : null;
if (process.env.NODE_ENV !== 'production') {
// We allow auto-mocks to proceed as if they're returning null.
if (
initialState === undefined &&
this.getInitialState._isMockFunction
) {
// This is probably bad practice. Consider warning here and
// deprecating this convenience.
initialState = null;
}
}
_invariant(
typeof initialState === 'object' && !Array.isArray(initialState),
'%s.getInitialState(): must return an object or null',
Constructor.displayName || 'ReactCompositeComponent'
);
this.state = initialState;
});
Constructor.prototype = new ReactClassComponent();
Constructor.prototype.constructor = Constructor;
Constructor.prototype.__reactAutoBindPairs = [];
injectedMixins.forEach(mixSpecIntoComponent.bind(null, Constructor));
mixSpecIntoComponent(Constructor, IsMountedPreMixin);
mixSpecIntoComponent(Constructor, spec);
mixSpecIntoComponent(Constructor, IsMountedPostMixin);
// Initialize the defaultProps property after all mixins have been merged.
if (Constructor.getDefaultProps) {
Constructor.defaultProps = Constructor.getDefaultProps();
}
if (process.env.NODE_ENV !== 'production') {
// This is a tag to indicate that the use of these method names is ok,
// since it's used with createClass. If it's not, then it's likely a
// mistake so we'll warn you to use the static property, property
// initializer or constructor respectively.
if (Constructor.getDefaultProps) {
Constructor.getDefaultProps.isReactClassApproved = {};
}
if (Constructor.prototype.getInitialState) {
Constructor.prototype.getInitialState.isReactClassApproved = {};
}
}
_invariant(
Constructor.prototype.render,
'createClass(...): Class specification must implement a `render` method.'
);
if (process.env.NODE_ENV !== 'production') {
warning(
!Constructor.prototype.componentShouldUpdate,
'%s has a method called ' +
'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' +
'The name is phrased as a question because the function is ' +
'expected to return a value.',
spec.displayName || 'A component'
);
warning(
!Constructor.prototype.componentWillRecieveProps,
'%s has a method called ' +
'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?',
spec.displayName || 'A component'
);
warning(
!Constructor.prototype.UNSAFE_componentWillRecieveProps,
'%s has a method called UNSAFE_componentWillRecieveProps(). ' +
'Did you mean UNSAFE_componentWillReceiveProps()?',
spec.displayName || 'A component'
);
}
// Reduce time spent doing lookups by setting these on the prototype.
for (var methodName in ReactClassInterface) {
if (!Constructor.prototype[methodName]) {
Constructor.prototype[methodName] = null;
}
}
return Constructor;
}
return createClass;
}
module.exports = factory;
/***/ }),
/* 4 */
/***/ (function(module, exports) {
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
'use strict';
/* eslint-disable no-unused-vars */
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
if (val === null || val === undefined) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
function shouldUseNative() {
try {
if (!Object.assign) {
return false;
}
// Detect buggy property enumeration order in older V8 versions.
// https://bugs.chromium.org/p/v8/issues/detail?id=4118
var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
test1[5] = 'de';
if (Object.getOwnPropertyNames(test1)[0] === '5') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test2 = {};
for (var i = 0; i < 10; i++) {
test2['_' + String.fromCharCode(i)] = i;
}
var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
return test2[n];
});
if (order2.join('') !== '0123456789') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test3 = {};
'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
test3[letter] = letter;
});
if (Object.keys(Object.assign({}, test3)).join('') !==
'abcdefghijklmnopqrst') {
return false;
}
return true;
} catch (err) {
// We don't expect any of the above to throw, but better to be safe.
return false;
}
}
module.exports = shouldUseNative() ? Object.assign : function (target, source) {
var from;
var to = toObject(target);
var symbols;
for (var s = 1; s < arguments.length; s++) {
from = Object(arguments[s]);
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
if (getOwnPropertySymbols) {
symbols = getOwnPropertySymbols(from);
for (var i = 0; i < symbols.length; i++) {
if (propIsEnumerable.call(from, symbols[i])) {
to[symbols[i]] = from[symbols[i]];
}
}
}
}
return to;
};
/***/ }),
/* 5 */
/***/ (function(module, exports) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
'use strict';
var emptyObject = {};
if (process.env.NODE_ENV !== 'production') {
Object.freeze(emptyObject);
}
module.exports = emptyObject;
/***/ }),
/* 6 */
/***/ (function(module, exports) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
'use strict';
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
var validateFormat = function validateFormat(format) {};
if (process.env.NODE_ENV !== 'production') {
validateFormat = function validateFormat(format) {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
};
}
function invariant(condition, format, a, b, c, d, e, f) {
validateFormat(format);
if (!condition) {
var error;
if (format === undefined) {
error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(format.replace(/%s/g, function () {
return args[argIndex++];
}));
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
}
module.exports = invariant;
/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {
/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
'use strict';
var emptyFunction = __webpack_require__(8);
/**
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical
* paths. Removing the logging code for production environments will keep the
* same logic and follow the same code paths.
*/
var warning = emptyFunction;
if (process.env.NODE_ENV !== 'production') {
var printWarning = function printWarning(format) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var argIndex = 0;
var message = 'Warning: ' + format.replace(/%s/g, function () {
return args[argIndex++];
});
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
};
warning = function warning(condition, format) {
if (format === undefined) {
throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument');
}
if (format.indexOf('Failed Composite propType: ') === 0) {
return; // Ignore CompositeComponent proptype check.
}
if (!condition) {
for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
args[_key2 - 2] = arguments[_key2];
}
printWarning.apply(undefined, [format].concat(args));
}
};
}
module.exports = warning;
/***/ }),
/* 8 */
/***/ (function(module, exports) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
function makeEmptyFunction(arg) {
return function () {
return arg;
};
}
/**
* This function accepts and discards inputs; it has no side effects. This is
* primarily useful idiomatically for overridable function endpoints which
* always need to be callable, since JS lacks a null-call idiom ala Cocoa.
*/
var emptyFunction = function emptyFunction() {};
emptyFunction.thatReturns = makeEmptyFunction;
emptyFunction.thatReturnsFalse = makeEmptyFunction(false);
emptyFunction.thatReturnsTrue = makeEmptyFunction(true);
emptyFunction.thatReturnsNull = makeEmptyFunction(null);
emptyFunction.thatReturnsThis = function () {
return this;
};
emptyFunction.thatReturnsArgument = function (arg) {
return arg;
};
module.exports = emptyFunction;
/***/ }),
/* 9 */
/***/ (function(module, exports) {
'use strict';
var NumeralFormatter = function NumeralFormatter(numeralDecimalMark, numeralIntegerScale, numeralDecimalScale, numeralThousandsGroupStyle, numeralPositiveOnly, stripLeadingZeroes, prefix, signBeforePrefix, delimiter) {
var owner = this;
owner.numeralDecimalMark = numeralDecimalMark || '.';
owner.numeralIntegerScale = numeralIntegerScale > 0 ? numeralIntegerScale : 0;
owner.numeralDecimalScale = numeralDecimalScale >= 0 ? numeralDecimalScale : 2;
owner.numeralThousandsGroupStyle = numeralThousandsGroupStyle || NumeralFormatter.groupStyle.thousand;
owner.numeralPositiveOnly = !!numeralPositiveOnly;
owner.stripLeadingZeroes = stripLeadingZeroes !== false;
owner.prefix = prefix || prefix === '' ? prefix : '';
owner.signBeforePrefix = !!signBeforePrefix;
owner.delimiter = delimiter || delimiter === '' ? delimiter : ',';
owner.delimiterRE = delimiter ? new RegExp('\\' + delimiter, 'g') : '';
};
NumeralFormatter.groupStyle = {
thousand: 'thousand',
lakh: 'lakh',
wan: 'wan',
none: 'none'
};
NumeralFormatter.prototype = {
getRawValue: function getRawValue(value) {
return value.replace(this.delimiterRE, '').replace(this.numeralDecimalMark, '.');
},
format: function format(value) {
var owner = this,
parts,
partSign,
partSignAndPrefix,
partInteger,
partDecimal = '';
// strip alphabet letters
value = value.replace(/[A-Za-z]/g, '')
// replace the first decimal mark with reserved placeholder
.replace(owner.numeralDecimalMark, 'M')
// strip non numeric letters except minus and "M"
// this is to ensure prefix has been stripped
.replace(/[^\dM-]/g, '')
// replace the leading minus with reserved placeholder
.replace(/^\-/, 'N')
// strip the other minus sign (if present)
.replace(/\-/g, '')
// replace the minus sign (if present)
.replace('N', owner.numeralPositiveOnly ? '' : '-')
// replace decimal mark
.replace('M', owner.numeralDecimalMark);
// strip any leading zeros
if (owner.stripLeadingZeroes) {
value = value.replace(/^(-)?0+(?=\d)/, '$1');
}
partSign = value.slice(0, 1) === '-' ? '-' : '';
if (typeof owner.prefix != 'undefined') {
if (owner.signBeforePrefix) {
partSignAndPrefix = partSign + owner.prefix;
} else {
partSignAndPrefix = owner.prefix + partSign;
}
} else {
partSignAndPrefix = partSign;
}
partInteger = value;
if (value.indexOf(owner.numeralDecimalMark) >= 0) {
parts = value.split(owner.numeralDecimalMark);
partInteger = parts[0];
partDecimal = owner.numeralDecimalMark + parts[1].slice(0, owner.numeralDecimalScale);
}
if (partSign === '-') {
partInteger = partInteger.slice(1);
}
if (owner.numeralIntegerScale > 0) {
partInteger = partInteger.slice(0, owner.numeralIntegerScale);
}
switch (owner.numeralThousandsGroupStyle) {
case NumeralFormatter.groupStyle.lakh:
partInteger = partInteger.replace(/(\d)(?=(\d\d)+\d$)/g, '$1' + owner.delimiter);
break;
case NumeralFormatter.groupStyle.wan:
partInteger = partInteger.replace(/(\d)(?=(\d{4})+$)/g, '$1' + owner.delimiter);
break;
case NumeralFormatter.groupStyle.thousand:
partInteger = partInteger.replace(/(\d)(?=(\d{3})+$)/g, '$1' + owner.delimiter);
break;
}
return partSignAndPrefix + partInteger.toString() + (owner.numeralDecimalScale > 0 ? partDecimal.toString() : '');
}
};
module.exports = NumeralFormatter;
/***/ }),
/* 10 */
/***/ (function(module, exports) {
'use strict';
var DateFormatter = function DateFormatter(datePattern, dateMin, dateMax) {
var owner = this;
owner.date = [];
owner.blocks = [];
owner.datePattern = datePattern;
owner.dateMin = dateMin.split('-').reverse().map(function (x) {
return parseInt(x, 10);
});
if (owner.dateMin.length === 2) owner.dateMin.unshift(0);
owner.dateMax = dateMax.split('-').reverse().map(function (x) {
return parseInt(x, 10);
});
if (owner.dateMax.length === 2) owner.dateMax.unshift(0);
owner.initBlocks();
};
DateFormatter.prototype = {
initBlocks: function initBlocks() {
var owner = this;
owner.datePattern.forEach(function (value) {
if (value === 'Y') {
owner.blocks.push(4);
} else {
owner.blocks.push(2);
}
});
},
getISOFormatDate: function getISOFormatDate() {
var owner = this,
date = owner.date;
return date[2] ? date[2] + '-' + owner.addLeadingZero(date[1]) + '-' + owner.addLeadingZero(date[0]) : '';
},
getBlocks: function getBlocks() {
return this.blocks;
},
getValidatedDate: function getValidatedDate(value) {
var owner = this,
result = '';
value = value.replace(/[^\d]/g, '');
owner.blocks.forEach(function (length, index) {
if (value.length > 0) {
var sub = value.slice(0, length),
sub0 = sub.slice(0, 1),
rest = value.slice(length);
switch (owner.datePattern[index]) {
case 'd':
if (sub === '00') {
sub = '01';
} else if (parseInt(sub0, 10) > 3) {
sub = '0' + sub0;
} else if (parseInt(sub, 10) > 31) {
sub = '31';
}
break;
case 'm':
if (sub === '00') {
sub = '01';
} else if (parseInt(sub0, 10) > 1) {
sub = '0' + sub0;
} else if (parseInt(sub, 10) > 12) {
sub = '12';
}
break;
}
result += sub;
// update remaining string
value = rest;
}
});
return this.getFixedDateString(result);
},
getFixedDateString: function getFixedDateString(value) {
var owner = this,
datePattern = owner.datePattern,
date = [],
dayIndex = 0,
monthIndex = 0,
yearIndex = 0,
dayStartIndex = 0,
monthStartIndex = 0,
yearStartIndex = 0,
day,
month,
year,
fullYearDone = false;
// mm-dd || dd-mm
if (value.length === 4 && datePattern[0].toLowerCase() !== 'y' && datePattern[1].toLowerCase() !== 'y') {
dayStartIndex = datePattern[0] === 'd' ? 0 : 2;
monthStartIndex = 2 - dayStartIndex;
day = parseInt(value.slice(dayStartIndex, dayStartIndex + 2), 10);
month = parseInt(value.slice(monthStartIndex, monthStartIndex + 2), 10);
date = this.getFixedDate(day, month, 0);
}
// yyyy-mm-dd || yyyy-dd-mm || mm-dd-yyyy || dd-mm-yyyy || dd-yyyy-mm || mm-yyyy-dd
if (value.length === 8) {
datePattern.forEach(function (type, index) {
switch (type) {
case 'd':
dayIndex = index;
break;
case 'm':
monthIndex = index;
break;
default:
yearIndex = index;
break;
}
});
yearStartIndex = yearIndex * 2;
dayStartIndex = dayIndex <= yearIndex ? dayIndex * 2 : dayIndex * 2 + 2;
monthStartIndex = monthIndex <= yearIndex ? monthIndex * 2 : monthIndex * 2 + 2;
day = parseInt(value.slice(dayStartIndex, dayStartIndex + 2), 10);
month = parseInt(value.slice(monthStartIndex, monthStartIndex + 2), 10);
year = parseInt(value.slice(yearStartIndex, yearStartIndex + 4), 10);
fullYearDone = value.slice(yearStartIndex, yearStartIndex + 4).length === 4;
date = this.getFixedDate(day, month, year);
}
// mm-yy || yy-mm
if (value.length === 4 && (datePattern[0] === 'y' || datePattern[1] === 'y')) {
monthStartIndex = datePattern[0] === 'm' ? 0 : 2;
yearStartIndex = 2 - monthStartIndex;
month = parseInt(value.slice(monthStartIndex, monthStartIndex + 2), 10);
year = parseInt(value.slice(yearStartIndex, yearStartIndex + 2), 10);
fullYearDone = value.slice(yearStartIndex, yearStartIndex + 2).length === 2;
date = [0, month, year];
}
// mm-yyyy || yyyy-mm
if (value.length === 6 && (datePattern[0] === 'Y' || datePattern[1] === 'Y')) {
monthStartIndex = datePattern[0] === 'm' ? 0 : 4;
yearStartIndex = 2 - 0.5 * monthStartIndex;
month = parseInt(value.slice(monthStartIndex, monthStartIndex + 2), 10);
year = parseInt(value.slice(yearStartIndex, yearStartIndex + 4), 10);
fullYearDone = value.slice(yearStartIndex, yearStartIndex + 4).length === 4;
date = [0, month, year];
}
date = owner.getRangeFixedDate(date);
owner.date = date;
var result = date.length === 0 ? value : datePattern.reduce(function (previous, current) {
switch (current) {
case 'd':
return previous + (date[0] === 0 ? '' : owner.addLeadingZero(date[0]));
case 'm':
return previous + (date[1] === 0 ? '' : owner.addLeadingZero(date[1]));
case 'y':
return previous + (fullYearDone ? owner.addLeadingZeroForYear(date[2], false) : '');
case 'Y':
return previous + (fullYearDone ? owner.addLeadingZeroForYear(date[2], true) : '');
}
}, '');
return result;
},
getRangeFixedDate: function getRangeFixedDate(date) {
var owner = this,
datePattern = owner.datePattern,
dateMin = owner.dateMin || [],
dateMax = owner.dateMax || [];
if (!date.length || dateMin.length < 3 && dateMax.length < 3) return date;
if (datePattern.find(function (x) {
return x.toLowerCase() === 'y';
}) && date[2] === 0) return date;
if (dateMax.length && (dateMax[2] < date[2] || dateMax[2] === date[2] && (dateMax[1] < date[1] || dateMax[1] === date[1] && dateMax[0] < date[0]))) return dateMax;
if (dateMin.length && (dateMin[2] > date[2] || dateMin[2] === date[2] && (dateMin[1] > date[1] || dateMin[1] === date[1] && dateMin[0] > date[0]))) return dateMin;
return date;
},
getFixedDate: function getFixedDate(day, month, year) {
day = Math.min(day, 31);
month = Math.min(month, 12);
year = parseInt(year || 0, 10);
if (month < 7 && month % 2 === 0 || month > 8 && month % 2 === 1) {
day = Math.min(day, month === 2 ? this.isLeapYear(year) ? 29 : 28 : 30);
}
return [day, month, year];
},
isLeapYear: function isLeapYear(year) {
return year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
},
addLeadingZero: function addLeadingZero(number) {
return (number < 10 ? '0' : '') + number;
},
addLeadingZeroForYear: function addLeadingZeroForYear(number, fullYearMode) {
if (fullYearMode) {
return (number < 10 ? '000' : number < 100 ? '00' : number < 1000 ? '0' : '') + number;
}
return (number < 10 ? '0' : '') + number;
}
};
module.exports = DateFormatter;
/***/ }),
/* 11 */
/***/ (function(module, exports) {
'use strict';
var TimeFormatter = function TimeFormatter(timePattern, timeFormat) {
var owner = this;
owner.time = [];
owner.blocks = [];
owner.timePattern = timePattern;
owner.timeFormat = timeFormat;
owner.initBlocks();
};
TimeFormatter.prototype = {
initBlocks: function initBlocks() {
var owner = this;
owner.timePattern.forEach(function () {
owner.blocks.push(2);
});
},
getISOFormatTime: function getISOFormatTime() {
var owner = this,
time = owner.time;
return time[2] ? owner.addLeadingZero(time[0]) + ':' + owner.addLeadingZero(time[1]) + ':' + owner.addLeadingZero(time[2]) : '';
},
getBlocks: function getBlocks() {
return this.blocks;
},
getTimeFormatOptions: function getTimeFormatOptions() {
var owner = this;
if (String(owner.timeFormat) === '12') {
return {
maxHourFirstDigit: 1,
maxHours: 12,
maxMinutesFirstDigit: 5,
maxMinutes: 60
};
}
return {
maxHourFirstDigit: 2,
maxHours: 23,
maxMinutesFirstDigit: 5,
maxMinutes: 60
};
},
getValidatedTime: function getValidatedTime(value) {
var owner = this,
result = '';
value = value.replace(/[^\d]/g, '');
var timeFormatOptions = owner.getTimeFormatOptions();
owner.blocks.forEach(function (length, index) {
if (value.length > 0) {
var sub = value.slice(0, length),
sub0 = sub.slice(0, 1),
rest = value.slice(length);
switch (owner.timePattern[index]) {
case 'h':
if (parseInt(sub0, 10) > timeFormatOptions.maxHourFirstDigit) {
sub = '0' + sub0;
} else if (parseInt(sub, 10) > timeFormatOptions.maxHours) {
sub = timeFormatOptions.maxHours + '';
}
break;
case 'm':
case 's':
if (parseInt(sub0, 10) > timeFormatOptions.maxMinutesFirstDigit) {
sub = '0' + sub0;
} else if (parseInt(sub, 10) > timeFormatOptions.maxMinutes) {
sub = timeFormatOptions.maxMinutes + '';
}
break;
}
result += sub;
// update remaining string
value = rest;
}
});
return this.getFixedTimeString(result);
},
getFixedTimeString: function getFixedTimeString(value) {
var owner = this,
timePattern = owner.timePattern,
time = [],
secondIndex = 0,
minuteIndex = 0,
hourIndex = 0,
secondStartIndex = 0,
minuteStartIndex = 0,
hourStartIndex = 0,
second,
minute,
hour;
if (value.length === 6) {
timePattern.forEach(function (type, index) {
switch (type) {
case 's':
secondIndex = index * 2;
break;
case 'm':
minuteIndex = index * 2;
break;
case 'h':
hourIndex = index * 2;
break;
}
});
hourStartIndex = hourIndex;
minuteStartIndex = minuteIndex;
secondStartIndex = secondIndex;
second = parseInt(value.slice(secondStartIndex, secondStartIndex + 2), 10);
minute = parseInt(value.slice(minuteStartIndex, minuteStartIndex + 2), 10);
hour = parseInt(value.slice(hourStartIndex, hourStartIndex + 2), 10);
time = this.getFixedTime(hour, minute, second);
}
if (value.length === 4 && owner.timePattern.indexOf('s') < 0) {
timePattern.forEach(function (type, index) {
switch (type) {
case 'm':
minuteIndex = index * 2;
break;
case 'h':
hourIndex = index * 2;
break;
}
});
hourStartIndex = hourIndex;
minuteStartIndex = minuteIndex;
second = 0;
minute = parseInt(value.slice(minuteStartIndex, minuteStartIndex + 2), 10);
hour = parseInt(value.slice(hourStartIndex, hourStartIndex + 2), 10);
time = this.getFixedTime(hour, minute, second);
}
owner.time = time;
return time.length === 0 ? value : timePattern.reduce(function (previous, current) {
switch (current) {
case 's':
return previous + owner.addLeadingZero(time[2]);
case 'm':
return previous + owner.addLeadingZero(time[1]);
case 'h':
return previous + owner.addLeadingZero(time[0]);
}
}, '');
},
getFixedTime: function getFixedTime(hour, minute, second) {
second = Math.min(parseInt(second || 0, 10), 60);
minute = Math.min(minute, 60);
hour = Math.min(hour, 60);
return [hour, minute, second];
},
addLeadingZero: function addLeadingZero(number) {
return (number < 10 ? '0' : '') + number;
}
};
module.exports = TimeFormatter;
/***/ }),
/* 12 */
/***/ (function(module, exports) {
'use strict';
var PhoneFormatter = function PhoneFormatter(formatter, delimiter) {
var owner = this;
owner.delimiter = delimiter || delimiter === '' ? delimiter : ' ';
owner.delimiterRE = delimiter ? new RegExp('\\' + delimiter, 'g') : '';
owner.formatter = formatter;
};
PhoneFormatter.prototype = {
setFormatter: function setFormatter(formatter) {
this.formatter = formatter;
},
format: function format(phoneNumber) {
var owner = this;
owner.formatter.clear();
// only keep number and +
phoneNumber = phoneNumber.replace(/[^\d+]/g, '');
// strip non-leading +
phoneNumber = phoneNumber.replace(/^\+/, 'B').replace(/\+/g, '').replace('B', '+');
// strip delimiter
phoneNumber = phoneNumber.replace(owner.delimiterRE, '');
var result = '',
current,
validated = false;
for (var i = 0, iMax = phoneNumber.length; i < iMax; i++) {
current = owner.formatter.inputDigit(phoneNumber.charAt(i));
// has ()- or space inside
if (/[\s()-]/g.test(current)) {
result = current;
validated = true;
} else {
if (!validated) {
result = current;
}
// else: over length input
// it turns to invalid number again
}
}
// strip ()
// e.g. US: 7161234567 returns (716) 123-4567
result = result.replace(/[()]/g, '');
// replace library delimiter with user customized delimiter
result = result.replace(/[\s-]/g, owner.delimiter);
return result;
}
};
module.exports = PhoneFormatter;
/***/ }),
/* 13 */
/***/ (function(module, exports) {
'use strict';
var CreditCardDetector = {
blocks: {
uatp: [4, 5, 6],
amex: [4, 6, 5],
diners: [4, 6, 4],
discover: [4, 4, 4, 4],
mastercard: [4, 4, 4, 4],
dankort: [4, 4, 4, 4],
instapayment: [4, 4, 4, 4],
jcb15: [4, 6, 5],
jcb: [4, 4, 4, 4],
maestro: [4, 4, 4, 4],
visa: [4, 4, 4, 4],
mir: [4, 4, 4, 4],
unionPay: [4, 4, 4, 4],
general: [4, 4, 4, 4]
},
re: {
// starts with 1; 15 digits, not starts with 1800 (jcb card)
uatp: /^(?!1800)1\d{0,14}/,
// starts with 34/37; 15 digits
amex: /^3[47]\d{0,13}/,
// starts with 6011/65/644-649; 16 digits
discover: /^(?:6011|65\d{0,2}|64[4-9]\d?)\d{0,12}/,
// starts with 300-305/309 or 36/38/39; 14 digits
diners: /^3(?:0([0-5]|9)|[689]\d?)\d{0,11}/,
// starts with 51-55/2221–2720; 16 digits
mastercard: /^(5[1-5]\d{0,2}|22[2-9]\d{0,1}|2[3-7]\d{0,2})\d{0,12}/,
// starts with 5019/4175/4571; 16 digits
dankort: /^(5019|4175|4571)\d{0,12}/,
// starts with 637-639; 16 digits
instapayment: /^63[7-9]\d{0,13}/,
// starts with 2131/1800; 15 digits
jcb15: /^(?:2131|1800)\d{0,11}/,
// starts with 2131/1800/35; 16 digits
jcb: /^(?:35\d{0,2})\d{0,12}/,
// starts with 50/56-58/6304/67; 16 digits
maestro: /^(?:5[0678]\d{0,2}|6304|67\d{0,2})\d{0,12}/,
// starts with 22; 16 digits
mir: /^220[0-4]\d{0,12}/,
// starts with 4; 16 digits
visa: /^4\d{0,15}/,
// starts with 62; 16 digits
unionPay: /^62\d{0,14}/
},
getStrictBlocks: function getStrictBlocks(block) {
var total = block.reduce(function (prev, current) {
return prev + current;
}, 0);
return block.concat(19 - total);
},
getInfo: function getInfo(value, strictMode) {
var blocks = CreditCardDetector.blocks,
re = CreditCardDetector.re;
// Some credit card can have up to 19 digits number.
// Set strictMode to true will remove the 16 max-length restrain,
// however, I never found any website validate card number like
// this, hence probably you don't want to enable this option.
strictMode = !!strictMode;
for (var key in re) {
if (re[key].test(value)) {
var matchedBlocks = blocks[key];
return {
type: key,
blocks: strictMode ? this.getStrictBlocks(matchedBlocks) : matchedBlocks
};
}
}
return {
type: 'unknown',
blocks: strictMode ? this.getStrictBlocks(blocks.general) : blocks.general
};
}
};
module.exports = CreditCardDetector;
/***/ }),
/* 14 */
/***/ (function(module, exports) {
'use strict';
var Util = {
noop: function noop() {},
strip: function strip(value, re) {
return value.replace(re, '');
},
getPostDelimiter: function getPostDelimiter(value, delimiter, delimiters) {
// single delimiter
if (delimiters.length === 0) {
return value.slice(-delimiter.length) === delimiter ? delimiter : '';
}
// multiple delimiters
var matchedDelimiter = '';
delimiters.forEach(function (current) {
if (value.slice(-current.length) === current) {
matchedDelimiter = current;
}
});
return matchedDelimiter;
},
getDelimiterREByDelimiter: function getDelimiterREByDelimiter(delimiter) {
return new RegExp(delimiter.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1'), 'g');
},
getNextCursorPosition: function getNextCursorPosition(prevPos, oldValue, newValue, delimiter, delimiters) {
// If cursor was at the end of value, just place it back.
// Because new value could contain additional chars.
if (oldValue.length === prevPos) {
return newValue.length;
}
return prevPos + this.getPositionOffset(prevPos, oldValue, newValue, delimiter, delimiters);
},
getPositionOffset: function getPositionOffset(prevPos, oldValue, newValue, delimiter, delimiters) {
var oldRawValue, newRawValue, lengthOffset;
oldRawValue = this.stripDelimiters(oldValue.slice(0, prevPos), delimiter, delimiters);
newRawValue = this.stripDelimiters(newValue.slice(0, prevPos), delimiter, delimiters);
lengthOffset = oldRawValue.length - newRawValue.length;
return lengthOffset !== 0 ? lengthOffset / Math.abs(lengthOffset) : 0;
},
stripDelimiters: function stripDelimiters(value, delimiter, delimiters) {
var owner = this;
// single delimiter
if (delimiters.length === 0) {
var delimiterRE = delimiter ? owner.getDelimiterREByDelimiter(delimiter) : '';
return value.replace(delimiterRE, '');
}
// multiple delimiters
delimiters.forEach(function (current) {
current.split('').forEach(function (letter) {
value = value.replace(owner.getDelimiterREByDelimiter(letter), '');
});
});
return value;
},
headStr: function headStr(str, length) {
return str.slice(0, length);
},
getMaxLength: function getMaxLength(blocks) {
return blocks.reduce(function (previous, current) {
return previous + current;
}, 0);
},
// strip prefix
// Before type | After type | Return value
// PEFIX-... | PEFIX-... | ''
// PREFIX-123 | PEFIX-123 | 123
// PREFIX-123 | PREFIX-23 | 23
// PREFIX-123 | PREFIX-1234 | 1234
getPrefixStrippedValue: function getPrefixStrippedValue(value, prefix, prefixLength, prevResult, delimiter, delimiters, noImmediatePrefix) {
// No prefix
if (prefixLength === 0) {
return value;
}
// Pre result prefix string does not match pre-defined prefix
if (prevResult.slice(0, prefixLength) !== prefix) {
// Check if the first time user entered something
if (noImmediatePrefix && !prevResult && value) return value;
return '';
}
var prevValue = this.stripDelimiters(prevResult, delimiter, delimiters);
// New value has issue, someone typed in between prefix letters
// Revert to pre value
if (value.slice(0, prefixLength) !== prefix) {
return prevValue.slice(prefixLength);
}
// No issue, strip prefix for new value
return value.slice(prefixLength);
},
getFirstDiffIndex: function getFirstDiffIndex(prev, current) {
var index = 0;
while (prev.charAt(index) === current.charAt(index)) {
if (prev.charAt(index++) === '') {
return -1;
}
}
return index;
},
getFormattedValue: function getFormattedValue(value, blocks, blocksLength, delimiter, delimiters, delimiterLazyShow) {
var result = '',
multipleDelimiters = delimiters.length > 0,
currentDelimiter;
// no options, normal input
if (blocksLength === 0) {
return value;
}
blocks.forEach(function (length, index) {
if (value.length > 0) {
var sub = value.slice(0, length),
rest = value.slice(length);
if (multipleDelimiters) {
currentDelimiter = delimiters[delimiterLazyShow ? index - 1 : index] || currentDelimiter;
} else {
currentDelimiter = delimiter;
}
if (delimiterLazyShow) {
if (index > 0) {
result += currentDelimiter;
}
result += sub;
} else {
result += sub;
if (sub.length === length && index < blocksLength - 1) {
result += currentDelimiter;
}
}
// update remaining string
value = rest;
}
});
return result;
},
// move cursor to the end
// the first time user focuses on an input with prefix
fixPrefixCursor: function fixPrefixCursor(el, prefix, delimiter, delimiters) {
if (!el) {
return;
}
var val = el.value,
appendix = delimiter || delimiters[0] || ' ';
if (!el.setSelectionRange || !prefix || prefix.length + appendix.length < val.length) {
return;
}
var len = val.length * 2;
// set timeout to avoid blink
setTimeout(function () {
el.setSelectionRange(len, len);
}, 1);
},
// Check if input field is fully selected
checkFullSelection: function checkFullSelection(value) {
try {
var selection = window.getSelection() || document.getSelection() || {};
return selection.toString().length === value.length;
} catch (ex) {
// Ignore
}
return false;
},
setSelection: function setSelection(element, position, doc) {
if (element !== this.getActiveElement(doc)) {
return;
}
// cursor is already in the end
if (element && element.value.length <= position) {
return;
}
if (element.createTextRange) {
var range = element.createTextRange();
range.move('character', position);
range.select();
} else {
try {
element.setSelectionRange(position, position);
} catch (e) {
// eslint-disable-next-line
console.warn('The input element type does not support selection');
}
}
},
getActiveElement: function getActiveElement(parent) {
var activeElement = parent.activeElement;
if (activeElement && activeElement.shadowRoot) {
return this.getActiveElement(activeElement.shadowRoot);
}
return activeElement;
},
isAndroid: function isAndroid() {
return navigator && /android/i.test(navigator.userAgent);
},
// On Android chrome, the keyup and keydown events
// always return key code 229 as a composition that
// buffers the user’s keystrokes
// see https://github.com/nosir/cleave.js/issues/147
isAndroidBackspaceKeydown: function isAndroidBackspaceKeydown(lastInputValue, currentInputValue) {
if (!this.isAndroid() || !lastInputValue || !currentInputValue) {
return false;
}
return currentInputValue === lastInputValue.slice(0, -1);
}
};
module.exports = Util;
/***/ }),
/* 15 */
/***/ (function(module, exports) {
'use strict';
/**
* Props Assignment
*
* Separate this, so react module can share the usage
*/
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var DefaultProperties = {
// Maybe change to object-assign
// for now just keep it as simple
assign: function assign(target, opts) {
target = target || {};
opts = opts || {};
// credit card
target.creditCard = !!opts.creditCard;
target.creditCardStrictMode = !!opts.creditCardStrictMode;
target.creditCardType = '';
target.onCreditCardTypeChanged = opts.onCreditCardTypeChanged || function () {};
// phone
target.phone = !!opts.phone;
target.phoneRegionCode = opts.phoneRegionCode || 'AU';
target.phoneFormatter = {};
// time
target.time = !!opts.time;
target.timePattern = opts.timePattern || ['h', 'm', 's'];
target.timeFormat = opts.timeFormat || '24';
target.timeFormatter = {};
// date
target.date = !!opts.date;
target.datePattern = opts.datePattern || ['d', 'm', 'Y'];
target.dateMin = opts.dateMin || '';
target.dateMax = opts.dateMax || '';
target.dateFormatter = {};
// numeral
target.numeral = !!opts.numeral;
target.numeralIntegerScale = opts.numeralIntegerScale > 0 ? opts.numeralIntegerScale : 0;
target.numeralDecimalScale = opts.numeralDecimalScale >= 0 ? opts.numeralDecimalScale : 2;
target.numeralDecimalMark = opts.numeralDecimalMark || '.';
target.numeralThousandsGroupStyle = opts.numeralThousandsGroupStyle || 'thousand';
target.numeralPositiveOnly = !!opts.numeralPositiveOnly;
target.stripLeadingZeroes = opts.stripLeadingZeroes !== false;
target.signBeforePrefix = !!opts.signBeforePrefix;
// others
target.numericOnly = target.creditCard || target.date || !!opts.numericOnly;
target.uppercase = !!opts.uppercase;
target.lowercase = !!opts.lowercase;
target.prefix = target.creditCard || target.date ? '' : opts.prefix || '';
target.noImmediatePrefix = !!opts.noImmediatePrefix;
target.prefixLength = target.prefix.length;
target.rawValueTrimPrefix = !!opts.rawValueTrimPrefix;
target.copyDelimiter = !!opts.copyDelimiter;
target.initValue = opts.initValue !== undefined && opts.initValue !== null ? opts.initValue.toString() : '';
target.delimiter = opts.delimiter || opts.delimiter === '' ? opts.delimiter : opts.date ? '/' : opts.time ? ':' : opts.numeral ? ',' : opts.phone ? ' ' : ' ';
target.delimiterLength = target.delimiter.length;
target.delimiterLazyShow = !!opts.delimiterLazyShow;
target.delimiters = opts.delimiters || [];
target.blocks = opts.blocks || [];
target.blocksLength = target.blocks.length;
target.root = (typeof global === 'undefined' ? 'undefined' : _typeof(global)) === 'object' && global ? global : window;
target.document = opts.document || target.root.document;
target.maxLength = 0;
target.backspace = false;
target.result = '';
target.onValueChanged = opts.onValueChanged || function () {};
return target;
}
};
module.exports = DefaultProperties;
/***/ })
/******/ ])
});
; |
// Knockout JavaScript library v3.1.0
// (c) Steven Sanderson - http://knockoutjs.com/
// License: MIT (http://www.opensource.org/licenses/mit-license.php)
(function () {
(function (p) {
var A = this || (0, eval)("this"), w = A.document, K = A.navigator, t = A.jQuery, C = A.JSON; (function (p) { "function" === typeof require && "object" === typeof exports && "object" === typeof module ? p(module.exports || exports) : "function" === typeof define && define.amd ? define(["exports"], p) : p(A.ko = {}) })(function (z) {
function G(a, c) { return null === a || typeof a in M ? a === c : !1 } function N(a, c) { var d; return function () { d || (d = setTimeout(function () { d = p; a() }, c)) } } function O(a, c) {
var d; return function () {
clearTimeout(d); d = setTimeout(a,
c)
}
} function H(b, c, d, e) { a.d[b] = { init: function (b, h, g, k, l) { var n, r; a.ba(function () { var g = a.a.c(h()), k = !d !== !g, s = !r; if (s || c || k !== n) s && a.ca.fa() && (r = a.a.lb(a.e.childNodes(b), !0)), k ? (s || a.e.U(b, a.a.lb(r)), a.gb(e ? e(l, g) : l, b)) : a.e.da(b), n = k }, null, { G: b }); return { controlsDescendantBindings: !0 } } }; a.g.aa[b] = !1; a.e.Q[b] = !0 } var a = "undefined" !== typeof z ? z : {}; a.b = function (b, c) { for (var d = b.split("."), e = a, f = 0; f < d.length - 1; f++) e = e[d[f]]; e[d[d.length - 1]] = c }; a.s = function (a, c, d) { a[c] = d }; a.version = "3.1.0"; a.b("version",
a.version); a.a = function () {
function b(a, b) { for (var c in a) a.hasOwnProperty(c) && b(c, a[c]) } function c(a, b) { if (b) for (var c in b) b.hasOwnProperty(c) && (a[c] = b[c]); return a } function d(a, b) { a.__proto__ = b; return a } var e = { __proto__: [] } instanceof Array, f = {}, h = {}; f[K && /Firefox\/2/i.test(K.userAgent) ? "KeyboardEvent" : "UIEvents"] = ["keyup", "keydown", "keypress"]; f.MouseEvents = "click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave".split(" "); b(f, function (a, b) {
if (b.length) for (var c = 0,
d = b.length; c < d; c++) h[b[c]] = a
}); var g = { propertychange: !0 }, k = w && function () { for (var a = 3, b = w.createElement("div"), c = b.getElementsByTagName("i") ; b.innerHTML = "\x3c!--[if gt IE " + ++a + "]><i></i><![endif]--\x3e", c[0];); return 4 < a ? a : p }(); return {
mb: ["authenticity_token", /^__RequestVerificationToken(_.*)?$/], r: function (a, b) { for (var c = 0, d = a.length; c < d; c++) b(a[c], c) }, l: function (a, b) {
if ("function" == typeof Array.prototype.indexOf) return Array.prototype.indexOf.call(a, b); for (var c = 0, d = a.length; c < d; c++) if (a[c] ===
b) return c; return -1
}, hb: function (a, b, c) { for (var d = 0, e = a.length; d < e; d++) if (b.call(c, a[d], d)) return a[d]; return null }, ma: function (b, c) { var d = a.a.l(b, c); 0 < d ? b.splice(d, 1) : 0 === d && b.shift() }, ib: function (b) { b = b || []; for (var c = [], d = 0, e = b.length; d < e; d++) 0 > a.a.l(c, b[d]) && c.push(b[d]); return c }, ya: function (a, b) { a = a || []; for (var c = [], d = 0, e = a.length; d < e; d++) c.push(b(a[d], d)); return c }, la: function (a, b) { a = a || []; for (var c = [], d = 0, e = a.length; d < e; d++) b(a[d], d) && c.push(a[d]); return c }, $: function (a, b) {
if (b instanceof Array) a.push.apply(a,
b); else for (var c = 0, d = b.length; c < d; c++) a.push(b[c]); return a
}, Y: function (b, c, d) { var e = a.a.l(a.a.Sa(b), c); 0 > e ? d && b.push(c) : d || b.splice(e, 1) }, na: e, extend: c, ra: d, sa: e ? d : c, A: b, Oa: function (a, b) { if (!a) return a; var c = {}, d; for (d in a) a.hasOwnProperty(d) && (c[d] = b(a[d], d, a)); return c }, Fa: function (b) { for (; b.firstChild;) a.removeNode(b.firstChild) }, ec: function (b) { b = a.a.R(b); for (var c = w.createElement("div"), d = 0, e = b.length; d < e; d++) c.appendChild(a.M(b[d])); return c }, lb: function (b, c) {
for (var d = 0, e = b.length, g = []; d <
e; d++) { var k = b[d].cloneNode(!0); g.push(c ? a.M(k) : k) } return g
}, U: function (b, c) { a.a.Fa(b); if (c) for (var d = 0, e = c.length; d < e; d++) b.appendChild(c[d]) }, Bb: function (b, c) { var d = b.nodeType ? [b] : b; if (0 < d.length) { for (var e = d[0], g = e.parentNode, k = 0, h = c.length; k < h; k++) g.insertBefore(c[k], e); k = 0; for (h = d.length; k < h; k++) a.removeNode(d[k]) } }, ea: function (a, b) {
if (a.length) {
for (b = 8 === b.nodeType && b.parentNode || b; a.length && a[0].parentNode !== b;) a.shift(); if (1 < a.length) {
var c = a[0], d = a[a.length - 1]; for (a.length = 0; c !== d;) if (a.push(c),
c = c.nextSibling, !c) return; a.push(d)
}
} return a
}, Db: function (a, b) { 7 > k ? a.setAttribute("selected", b) : a.selected = b }, ta: function (a) { return null === a || a === p ? "" : a.trim ? a.trim() : a.toString().replace(/^[\s\xa0]+|[\s\xa0]+$/g, "") }, oc: function (b, c) { for (var d = [], e = (b || "").split(c), g = 0, k = e.length; g < k; g++) { var h = a.a.ta(e[g]); "" !== h && d.push(h) } return d }, kc: function (a, b) { a = a || ""; return b.length > a.length ? !1 : a.substring(0, b.length) === b }, Sb: function (a, b) {
if (a === b) return !0; if (11 === a.nodeType) return !1; if (b.contains) return b.contains(3 ===
a.nodeType ? a.parentNode : a); if (b.compareDocumentPosition) return 16 == (b.compareDocumentPosition(a) & 16); for (; a && a != b;) a = a.parentNode; return !!a
}, Ea: function (b) { return a.a.Sb(b, b.ownerDocument.documentElement) }, eb: function (b) { return !!a.a.hb(b, a.a.Ea) }, B: function (a) { return a && a.tagName && a.tagName.toLowerCase() }, q: function (b, c, d) {
var e = k && g[c]; if (!e && t) t(b).bind(c, d); else if (e || "function" != typeof b.addEventListener) if ("undefined" != typeof b.attachEvent) {
var h = function (a) { d.call(b, a) }, f = "on" + c; b.attachEvent(f,
h); a.a.u.ja(b, function () { b.detachEvent(f, h) })
} else throw Error("Browser doesn't support addEventListener or attachEvent"); else b.addEventListener(c, d, !1)
}, ha: function (b, c) {
if (!b || !b.nodeType) throw Error("element must be a DOM node when calling triggerEvent"); var d; "input" === a.a.B(b) && b.type && "click" == c.toLowerCase() ? (d = b.type, d = "checkbox" == d || "radio" == d) : d = !1; if (t && !d) t(b).trigger(c); else if ("function" == typeof w.createEvent) if ("function" == typeof b.dispatchEvent) d = w.createEvent(h[c] || "HTMLEvents"),
d.initEvent(c, !0, !0, A, 0, 0, 0, 0, 0, !1, !1, !1, !1, 0, b), b.dispatchEvent(d); else throw Error("The supplied element doesn't support dispatchEvent"); else if (d && b.click) b.click(); else if ("undefined" != typeof b.fireEvent) b.fireEvent("on" + c); else throw Error("Browser doesn't support triggering events");
}, c: function (b) { return a.v(b) ? b() : b }, Sa: function (b) { return a.v(b) ? b.o() : b }, ua: function (b, c, d) { if (c) { var e = /\S+/g, g = b.className.match(e) || []; a.a.r(c.match(e), function (b) { a.a.Y(g, b, d) }); b.className = g.join(" ") } }, Xa: function (b,
c) { var d = a.a.c(c); if (null === d || d === p) d = ""; var e = a.e.firstChild(b); !e || 3 != e.nodeType || a.e.nextSibling(e) ? a.e.U(b, [b.ownerDocument.createTextNode(d)]) : e.data = d; a.a.Vb(b) }, Cb: function (a, b) { a.name = b; if (7 >= k) try { a.mergeAttributes(w.createElement("<input name='" + a.name + "'/>"), !1) } catch (c) { } }, Vb: function (a) { 9 <= k && (a = 1 == a.nodeType ? a : a.parentNode, a.style && (a.style.zoom = a.style.zoom)) }, Tb: function (a) { if (k) { var b = a.style.width; a.style.width = 0; a.style.width = b } }, ic: function (b, c) {
b = a.a.c(b); c = a.a.c(c); for (var d =
[], e = b; e <= c; e++) d.push(e); return d
}, R: function (a) { for (var b = [], c = 0, d = a.length; c < d; c++) b.push(a[c]); return b }, mc: 6 === k, nc: 7 === k, oa: k, ob: function (b, c) { for (var d = a.a.R(b.getElementsByTagName("input")).concat(a.a.R(b.getElementsByTagName("textarea"))), e = "string" == typeof c ? function (a) { return a.name === c } : function (a) { return c.test(a.name) }, g = [], k = d.length - 1; 0 <= k; k--) e(d[k]) && g.push(d[k]); return g }, fc: function (b) {
return "string" == typeof b && (b = a.a.ta(b)) ? C && C.parse ? C.parse(b) : (new Function("return " + b))() :
null
}, Ya: function (b, c, d) { if (!C || !C.stringify) throw Error("Cannot find JSON.stringify(). Some browsers (e.g., IE < 8) don't support it natively, but you can overcome this by adding a script reference to json2.js, downloadable from http://www.json.org/json2.js"); return C.stringify(a.a.c(b), c, d) }, gc: function (c, d, e) {
e = e || {}; var g = e.params || {}, k = e.includeFields || this.mb, h = c; if ("object" == typeof c && "form" === a.a.B(c)) for (var h = c.action, f = k.length - 1; 0 <= f; f--) for (var u = a.a.ob(c, k[f]), D = u.length - 1; 0 <= D; D--) g[u[D].name] =
u[D].value; d = a.a.c(d); var y = w.createElement("form"); y.style.display = "none"; y.action = h; y.method = "post"; for (var p in d) c = w.createElement("input"), c.name = p, c.value = a.a.Ya(a.a.c(d[p])), y.appendChild(c); b(g, function (a, b) { var c = w.createElement("input"); c.name = a; c.value = b; y.appendChild(c) }); w.body.appendChild(y); e.submitter ? e.submitter(y) : y.submit(); setTimeout(function () { y.parentNode.removeChild(y) }, 0)
}
}
}(); a.b("utils", a.a); a.b("utils.arrayForEach", a.a.r); a.b("utils.arrayFirst", a.a.hb); a.b("utils.arrayFilter",
a.a.la); a.b("utils.arrayGetDistinctValues", a.a.ib); a.b("utils.arrayIndexOf", a.a.l); a.b("utils.arrayMap", a.a.ya); a.b("utils.arrayPushAll", a.a.$); a.b("utils.arrayRemoveItem", a.a.ma); a.b("utils.extend", a.a.extend); a.b("utils.fieldsIncludedWithJsonPost", a.a.mb); a.b("utils.getFormFields", a.a.ob); a.b("utils.peekObservable", a.a.Sa); a.b("utils.postJson", a.a.gc); a.b("utils.parseJson", a.a.fc); a.b("utils.registerEventHandler", a.a.q); a.b("utils.stringifyJson", a.a.Ya); a.b("utils.range", a.a.ic); a.b("utils.toggleDomNodeCssClass",
a.a.ua); a.b("utils.triggerEvent", a.a.ha); a.b("utils.unwrapObservable", a.a.c); a.b("utils.objectForEach", a.a.A); a.b("utils.addOrRemoveItem", a.a.Y); a.b("unwrap", a.a.c); Function.prototype.bind || (Function.prototype.bind = function (a) { var c = this, d = Array.prototype.slice.call(arguments); a = d.shift(); return function () { return c.apply(a, d.concat(Array.prototype.slice.call(arguments))) } }); a.a.f = new function () {
function a(b, h) { var g = b[d]; if (!g || "null" === g || !e[g]) { if (!h) return p; g = b[d] = "ko" + c++; e[g] = {} } return e[g] }
var c = 0, d = "__ko__" + (new Date).getTime(), e = {}; return { get: function (c, d) { var e = a(c, !1); return e === p ? p : e[d] }, set: function (c, d, e) { if (e !== p || a(c, !1) !== p) a(c, !0)[d] = e }, clear: function (a) { var b = a[d]; return b ? (delete e[b], a[d] = null, !0) : !1 }, L: function () { return c++ + d } }
}; a.b("utils.domData", a.a.f); a.b("utils.domData.clear", a.a.f.clear); a.a.u = new function () {
function b(b, c) { var e = a.a.f.get(b, d); e === p && c && (e = [], a.a.f.set(b, d, e)); return e } function c(d) {
var e = b(d, !1); if (e) for (var e = e.slice(0), k = 0; k < e.length; k++) e[k](d);
a.a.f.clear(d); a.a.u.cleanExternalData(d); if (f[d.nodeType]) for (e = d.firstChild; d = e;) e = d.nextSibling, 8 === d.nodeType && c(d)
} var d = a.a.f.L(), e = { 1: !0, 8: !0, 9: !0 }, f = { 1: !0, 9: !0 }; return {
ja: function (a, c) { if ("function" != typeof c) throw Error("Callback must be a function"); b(a, !0).push(c) }, Ab: function (c, e) { var k = b(c, !1); k && (a.a.ma(k, e), 0 == k.length && a.a.f.set(c, d, p)) }, M: function (b) { if (e[b.nodeType] && (c(b), f[b.nodeType])) { var d = []; a.a.$(d, b.getElementsByTagName("*")); for (var k = 0, l = d.length; k < l; k++) c(d[k]) } return b },
removeNode: function (b) { a.M(b); b.parentNode && b.parentNode.removeChild(b) }, cleanExternalData: function (a) { t && "function" == typeof t.cleanData && t.cleanData([a]) }
}
}; a.M = a.a.u.M; a.removeNode = a.a.u.removeNode; a.b("cleanNode", a.M); a.b("removeNode", a.removeNode); a.b("utils.domNodeDisposal", a.a.u); a.b("utils.domNodeDisposal.addDisposeCallback", a.a.u.ja); a.b("utils.domNodeDisposal.removeDisposeCallback", a.a.u.Ab); (function () {
a.a.Qa = function (b) {
var c; if (t) if (t.parseHTML) c = t.parseHTML(b) || []; else {
if ((c = t.clean([b])) &&
c[0]) { for (b = c[0]; b.parentNode && 11 !== b.parentNode.nodeType;) b = b.parentNode; b.parentNode && b.parentNode.removeChild(b) }
} else {
var d = a.a.ta(b).toLowerCase(); c = w.createElement("div"); d = d.match(/^<(thead|tbody|tfoot)/) && [1, "<table>", "</table>"] || !d.indexOf("<tr") && [2, "<table><tbody>", "</tbody></table>"] || (!d.indexOf("<td") || !d.indexOf("<th")) && [3, "<table><tbody><tr>", "</tr></tbody></table>"] || [0, "", ""]; b = "ignored<div>" + d[1] + b + d[2] + "</div>"; for ("function" == typeof A.innerShiv ? c.appendChild(A.innerShiv(b)) :
c.innerHTML = b; d[0]--;) c = c.lastChild; c = a.a.R(c.lastChild.childNodes)
} return c
}; a.a.Va = function (b, c) { a.a.Fa(b); c = a.a.c(c); if (null !== c && c !== p) if ("string" != typeof c && (c = c.toString()), t) t(b).html(c); else for (var d = a.a.Qa(c), e = 0; e < d.length; e++) b.appendChild(d[e]) }
})(); a.b("utils.parseHtmlFragment", a.a.Qa); a.b("utils.setHtml", a.a.Va); a.w = function () {
function b(c, e) {
if (c) if (8 == c.nodeType) { var f = a.w.xb(c.nodeValue); null != f && e.push({ Rb: c, cc: f }) } else if (1 == c.nodeType) for (var f = 0, h = c.childNodes, g = h.length; f < g; f++) b(h[f],
e)
} var c = {}; return {
Na: function (a) { if ("function" != typeof a) throw Error("You can only pass a function to ko.memoization.memoize()"); var b = (4294967296 * (1 + Math.random()) | 0).toString(16).substring(1) + (4294967296 * (1 + Math.random()) | 0).toString(16).substring(1); c[b] = a; return "\x3c!--[ko_memo:" + b + "]--\x3e" }, Hb: function (a, b) { var f = c[a]; if (f === p) throw Error("Couldn't find any memo with ID " + a + ". Perhaps it's already been unmemoized."); try { return f.apply(null, b || []), !0 } finally { delete c[a] } }, Ib: function (c, e) {
var f =
[]; b(c, f); for (var h = 0, g = f.length; h < g; h++) { var k = f[h].Rb, l = [k]; e && a.a.$(l, e); a.w.Hb(f[h].cc, l); k.nodeValue = ""; k.parentNode && k.parentNode.removeChild(k) }
}, xb: function (a) { return (a = a.match(/^\[ko_memo\:(.*?)\]$/)) ? a[1] : null }
}
}(); a.b("memoization", a.w); a.b("memoization.memoize", a.w.Na); a.b("memoization.unmemoize", a.w.Hb); a.b("memoization.parseMemoText", a.w.xb); a.b("memoization.unmemoizeDomNodeAndDescendants", a.w.Ib); a.Ga = {
throttle: function (b, c) {
b.throttleEvaluation = c; var d = null; return a.h({
read: b, write: function (a) {
clearTimeout(d);
d = setTimeout(function () { b(a) }, c)
}
})
}, rateLimit: function (a, c) { var d, e, f; "number" == typeof c ? d = c : (d = c.timeout, e = c.method); f = "notifyWhenChangesStop" == e ? O : N; a.Ma(function (a) { return f(a, d) }) }, notify: function (a, c) { a.equalityComparer = "always" == c ? null : G }
}; var M = { undefined: 1, "boolean": 1, number: 1, string: 1 }; a.b("extenders", a.Ga); a.Fb = function (b, c, d) { this.target = b; this.za = c; this.Qb = d; this.sb = !1; a.s(this, "dispose", this.F) }; a.Fb.prototype.F = function () { this.sb = !0; this.Qb() }; a.N = function () {
a.a.sa(this, a.N.fn); this.H =
{}
}; var F = "change"; z = {
V: function (b, c, d) { var e = this; d = d || F; var f = new a.Fb(e, c ? b.bind(c) : b, function () { a.a.ma(e.H[d], f) }); e.o && e.o(); e.H[d] || (e.H[d] = []); e.H[d].push(f); return f }, notifySubscribers: function (b, c) { c = c || F; if (this.qb(c)) try { a.k.jb(); for (var d = this.H[c].slice(0), e = 0, f; f = d[e]; ++e) f.sb || f.za(b) } finally { a.k.end() } }, Ma: function (b) {
var c = this, d = a.v(c), e, f, h; c.ia || (c.ia = c.notifySubscribers, c.notifySubscribers = function (a, b) { b && b !== F ? "beforeChange" === b ? c.bb(a) : c.ia(a, b) : c.cb(a) }); var g = b(function () {
d &&
h === c && (h = c()); e = !1; c.Ka(f, h) && c.ia(f = h)
}); c.cb = function (a) { e = !0; h = a; g() }; c.bb = function (a) { e || (f = a, c.ia(a, "beforeChange")) }
}, qb: function (a) { return this.H[a] && this.H[a].length }, Wb: function () { var b = 0; a.a.A(this.H, function (a, d) { b += d.length }); return b }, Ka: function (a, c) { return !this.equalityComparer || !this.equalityComparer(a, c) }, extend: function (b) { var c = this; b && a.a.A(b, function (b, e) { var f = a.Ga[b]; "function" == typeof f && (c = f(c, e) || c) }); return c }
}; a.s(z, "subscribe", z.V); a.s(z, "extend", z.extend); a.s(z, "getSubscriptionsCount",
z.Wb); a.a.na && a.a.ra(z, Function.prototype); a.N.fn = z; a.tb = function (a) { return null != a && "function" == typeof a.V && "function" == typeof a.notifySubscribers }; a.b("subscribable", a.N); a.b("isSubscribable", a.tb); a.ca = a.k = function () {
function b(a) { d.push(e); e = a } function c() { e = d.pop() } var d = [], e, f = 0; return {
jb: b, end: c, zb: function (b) { if (e) { if (!a.tb(b)) throw Error("Only subscribable things can act as dependencies"); e.za(b, b.Kb || (b.Kb = ++f)) } }, t: function (a, d, e) { try { return b(), a.apply(d, e || []) } finally { c() } }, fa: function () { if (e) return e.ba.fa() },
pa: function () { if (e) return e.pa }
}
}(); a.b("computedContext", a.ca); a.b("computedContext.getDependenciesCount", a.ca.fa); a.b("computedContext.isInitial", a.ca.pa); a.m = function (b) {
function c() { if (0 < arguments.length) return c.Ka(d, arguments[0]) && (c.P(), d = arguments[0], c.O()), this; a.k.zb(c); return d } var d = b; a.N.call(c); a.a.sa(c, a.m.fn); c.o = function () { return d }; c.O = function () { c.notifySubscribers(d) }; c.P = function () { c.notifySubscribers(d, "beforeChange") }; a.s(c, "peek", c.o); a.s(c, "valueHasMutated", c.O); a.s(c, "valueWillMutate",
c.P); return c
}; a.m.fn = { equalityComparer: G }; var E = a.m.hc = "__ko_proto__"; a.m.fn[E] = a.m; a.a.na && a.a.ra(a.m.fn, a.N.fn); a.Ha = function (b, c) { return null === b || b === p || b[E] === p ? !1 : b[E] === c ? !0 : a.Ha(b[E], c) }; a.v = function (b) { return a.Ha(b, a.m) }; a.ub = function (b) { return "function" == typeof b && b[E] === a.m || "function" == typeof b && b[E] === a.h && b.Yb ? !0 : !1 }; a.b("observable", a.m); a.b("isObservable", a.v); a.b("isWriteableObservable", a.ub); a.T = function (b) {
b = b || []; if ("object" != typeof b || !("length" in b)) throw Error("The argument passed when initializing an observable array must be an array, or null, or undefined.");
b = a.m(b); a.a.sa(b, a.T.fn); return b.extend({ trackArrayChanges: !0 })
}; a.T.fn = {
remove: function (b) { for (var c = this.o(), d = [], e = "function" != typeof b || a.v(b) ? function (a) { return a === b } : b, f = 0; f < c.length; f++) { var h = c[f]; e(h) && (0 === d.length && this.P(), d.push(h), c.splice(f, 1), f--) } d.length && this.O(); return d }, removeAll: function (b) { if (b === p) { var c = this.o(), d = c.slice(0); this.P(); c.splice(0, c.length); this.O(); return d } return b ? this.remove(function (c) { return 0 <= a.a.l(b, c) }) : [] }, destroy: function (b) {
var c = this.o(), d =
"function" != typeof b || a.v(b) ? function (a) { return a === b } : b; this.P(); for (var e = c.length - 1; 0 <= e; e--) d(c[e]) && (c[e]._destroy = !0); this.O()
}, destroyAll: function (b) { return b === p ? this.destroy(function () { return !0 }) : b ? this.destroy(function (c) { return 0 <= a.a.l(b, c) }) : [] }, indexOf: function (b) { var c = this(); return a.a.l(c, b) }, replace: function (a, c) { var d = this.indexOf(a); 0 <= d && (this.P(), this.o()[d] = c, this.O()) }
}; a.a.r("pop push reverse shift sort splice unshift".split(" "), function (b) {
a.T.fn[b] = function () {
var a = this.o();
this.P(); this.kb(a, b, arguments); a = a[b].apply(a, arguments); this.O(); return a
}
}); a.a.r(["slice"], function (b) { a.T.fn[b] = function () { var a = this(); return a[b].apply(a, arguments) } }); a.a.na && a.a.ra(a.T.fn, a.m.fn); a.b("observableArray", a.T); var I = "arrayChange"; a.Ga.trackArrayChanges = function (b) {
function c() {
if (!d) {
d = !0; var c = b.notifySubscribers; b.notifySubscribers = function (a, b) { b && b !== F || ++f; return c.apply(this, arguments) }; var k = [].concat(b.o() || []); e = null; b.V(function (c) {
c = [].concat(c || []); if (b.qb(I)) {
var d;
if (!e || 1 < f) e = a.a.Aa(k, c, { sparse: !0 }); d = e; d.length && b.notifySubscribers(d, I)
} k = c; e = null; f = 0
})
}
} if (!b.kb) {
var d = !1, e = null, f = 0, h = b.V; b.V = b.subscribe = function (a, b, d) { d === I && c(); return h.apply(this, arguments) }; b.kb = function (b, c, l) {
function h(a, b, c) { return r[r.length] = { status: a, value: b, index: c } } if (d && !f) {
var r = [], m = b.length, q = l.length, s = 0; switch (c) {
case "push": s = m; case "unshift": for (c = 0; c < q; c++) h("added", l[c], s + c); break; case "pop": s = m - 1; case "shift": m && h("deleted", b[s], s); break; case "splice": c = Math.min(Math.max(0,
0 > l[0] ? m + l[0] : l[0]), m); for (var m = 1 === q ? m : Math.min(c + (l[1] || 0), m), q = c + q - 2, s = Math.max(m, q), B = [], u = [], D = 2; c < s; ++c, ++D) c < m && u.push(h("deleted", b[c], c)), c < q && B.push(h("added", l[D], c)); a.a.nb(u, B); break; default: return
} e = r
}
}
}
}; a.ba = a.h = function (b, c, d) {
function e() { q = !0; a.a.A(v, function (a, b) { b.F() }); v = {}; x = 0; n = !1 } function f() { var a = g.throttleEvaluation; a && 0 <= a ? (clearTimeout(t), t = setTimeout(h, a)) : g.wa ? g.wa() : h() } function h() {
if (!r && !q) {
if (y && y()) { if (!m) { p(); return } } else m = !1; r = !0; try {
var b = v, d = x; a.k.jb({
za: function (a,
c) { q || (d && b[c] ? (v[c] = b[c], ++x, delete b[c], --d) : v[c] || (v[c] = a.V(f), ++x)) }, ba: g, pa: !x
}); v = {}; x = 0; try { var e = c ? s.call(c) : s() } finally { a.k.end(), d && a.a.A(b, function (a, b) { b.F() }), n = !1 } g.Ka(l, e) && (g.notifySubscribers(l, "beforeChange"), l = e, g.wa && !g.throttleEvaluation || g.notifySubscribers(l))
} finally { r = !1 } x || p()
}
} function g() {
if (0 < arguments.length) {
if ("function" === typeof B) B.apply(c, arguments); else throw Error("Cannot write a value to a ko.computed unless you specify a 'write' option. If you wish to read the current value, don't pass any parameters.");
return this
} n && h(); a.k.zb(g); return l
} function k() { return n || 0 < x } var l, n = !0, r = !1, m = !1, q = !1, s = b; s && "object" == typeof s ? (d = s, s = d.read) : (d = d || {}, s || (s = d.read)); if ("function" != typeof s) throw Error("Pass a function that returns the value of the ko.computed"); var B = d.write, u = d.disposeWhenNodeIsRemoved || d.G || null, D = d.disposeWhen || d.Da, y = D, p = e, v = {}, x = 0, t = null; c || (c = d.owner); a.N.call(g); a.a.sa(g, a.h.fn); g.o = function () { n && !x && h(); return l }; g.fa = function () { return x }; g.Yb = "function" === typeof d.write; g.F = function () { p() };
g.ga = k; var w = g.Ma; g.Ma = function (a) { w.call(g, a); g.wa = function () { g.bb(l); n = !0; g.cb(g) } }; a.s(g, "peek", g.o); a.s(g, "dispose", g.F); a.s(g, "isActive", g.ga); a.s(g, "getDependenciesCount", g.fa); u && (m = !0, u.nodeType && (y = function () { return !a.a.Ea(u) || D && D() })); !0 !== d.deferEvaluation && h(); u && k() && u.nodeType && (p = function () { a.a.u.Ab(u, p); e() }, a.a.u.ja(u, p)); return g
}; a.$b = function (b) { return a.Ha(b, a.h) }; z = a.m.hc; a.h[z] = a.m; a.h.fn = { equalityComparer: G }; a.h.fn[z] = a.h; a.a.na && a.a.ra(a.h.fn, a.N.fn); a.b("dependentObservable",
a.h); a.b("computed", a.h); a.b("isComputed", a.$b); (function () {
function b(a, f, h) { h = h || new d; a = f(a); if ("object" != typeof a || null === a || a === p || a instanceof Date || a instanceof String || a instanceof Number || a instanceof Boolean) return a; var g = a instanceof Array ? [] : {}; h.save(a, g); c(a, function (c) { var d = f(a[c]); switch (typeof d) { case "boolean": case "number": case "string": case "function": g[c] = d; break; case "object": case "undefined": var n = h.get(d); g[c] = n !== p ? n : b(d, f, h) } }); return g } function c(a, b) {
if (a instanceof Array) {
for (var c =
0; c < a.length; c++) b(c); "function" == typeof a.toJSON && b("toJSON")
} else for (c in a) b(c)
} function d() { this.keys = []; this.ab = [] } a.Gb = function (c) { if (0 == arguments.length) throw Error("When calling ko.toJS, pass the object you want to convert."); return b(c, function (b) { for (var c = 0; a.v(b) && 10 > c; c++) b = b(); return b }) }; a.toJSON = function (b, c, d) { b = a.Gb(b); return a.a.Ya(b, c, d) }; d.prototype = {
save: function (b, c) { var d = a.a.l(this.keys, b); 0 <= d ? this.ab[d] = c : (this.keys.push(b), this.ab.push(c)) }, get: function (b) {
b = a.a.l(this.keys,
b); return 0 <= b ? this.ab[b] : p
}
}
})(); a.b("toJS", a.Gb); a.b("toJSON", a.toJSON); (function () {
a.i = {
p: function (b) { switch (a.a.B(b)) { case "option": return !0 === b.__ko__hasDomDataOptionValue__ ? a.a.f.get(b, a.d.options.Pa) : 7 >= a.a.oa ? b.getAttributeNode("value") && b.getAttributeNode("value").specified ? b.value : b.text : b.value; case "select": return 0 <= b.selectedIndex ? a.i.p(b.options[b.selectedIndex]) : p; default: return b.value } }, X: function (b, c, d) {
switch (a.a.B(b)) {
case "option": switch (typeof c) {
case "string": a.a.f.set(b, a.d.options.Pa,
p); "__ko__hasDomDataOptionValue__" in b && delete b.__ko__hasDomDataOptionValue__; b.value = c; break; default: a.a.f.set(b, a.d.options.Pa, c), b.__ko__hasDomDataOptionValue__ = !0, b.value = "number" === typeof c ? c : ""
} break; case "select": if ("" === c || null === c) c = p; for (var e = -1, f = 0, h = b.options.length, g; f < h; ++f) if (g = a.i.p(b.options[f]), g == c || "" == g && c === p) { e = f; break } if (d || 0 <= e || c === p && 1 < b.size) b.selectedIndex = e; break; default: if (null === c || c === p) c = ""; b.value = c
}
}
}
})(); a.b("selectExtensions", a.i); a.b("selectExtensions.readValue",
a.i.p); a.b("selectExtensions.writeValue", a.i.X); a.g = function () {
function b(b) {
b = a.a.ta(b); 123 === b.charCodeAt(0) && (b = b.slice(1, -1)); var c = [], d = b.match(e), g, m, q = 0; if (d) {
d.push(","); for (var s = 0, B; B = d[s]; ++s) {
var u = B.charCodeAt(0); if (44 === u) { if (0 >= q) { g && c.push(m ? { key: g, value: m.join("") } : { unknown: g }); g = m = q = 0; continue } } else if (58 === u) { if (!m) continue } else if (47 === u && s && 1 < B.length) (u = d[s - 1].match(f)) && !h[u[0]] && (b = b.substr(b.indexOf(B) + 1), d = b.match(e), d.push(","), s = -1, B = "/"); else if (40 === u || 123 === u || 91 ===
u)++q; else if (41 === u || 125 === u || 93 === u)--q; else if (!g && !m) { g = 34 === u || 39 === u ? B.slice(1, -1) : B; continue } m ? m.push(B) : m = [B]
}
} return c
} var c = ["true", "false", "null", "undefined"], d = /^(?:[$_a-z][$\w]*|(.+)(\.\s*[$_a-z][$\w]*|\[.+\]))$/i, e = RegExp("\"(?:[^\"\\\\]|\\\\.)*\"|'(?:[^'\\\\]|\\\\.)*'|/(?:[^/\\\\]|\\\\.)*/w*|[^\\s:,/][^,\"'{}()/:[\\]]*[^\\s,\"'{}()/:[\\]]|[^\\s]", "g"), f = /[\])"'A-Za-z0-9_$]+$/, h = { "in": 1, "return": 1, "typeof": 1 }, g = {}; return {
aa: [], W: g, Ra: b, qa: function (e, l) {
function f(b, e) {
var l, k = a.getBindingHandler(b);
if (k && k.preprocess ? e = k.preprocess(e, b, f) : 1) { if (k = g[b]) l = e, 0 <= a.a.l(c, l) ? l = !1 : (k = l.match(d), l = null === k ? !1 : k[1] ? "Object(" + k[1] + ")" + k[2] : l), k = l; k && m.push("'" + b + "':function(_z){" + l + "=_z}"); q && (e = "function(){return " + e + " }"); h.push("'" + b + "':" + e) }
} l = l || {}; var h = [], m = [], q = l.valueAccessors, s = "string" === typeof e ? b(e) : e; a.a.r(s, function (a) { f(a.key || a.unknown, a.value) }); m.length && f("_ko_property_writers", "{" + m.join(",") + " }"); return h.join(",")
}, bc: function (a, b) {
for (var c = 0; c < a.length; c++) if (a[c].key == b) return !0;
return !1
}, va: function (b, c, d, e, g) { if (b && a.v(b)) !a.ub(b) || g && b.o() === e || b(e); else if ((b = c.get("_ko_property_writers")) && b[d]) b[d](e) }
}
}(); a.b("expressionRewriting", a.g); a.b("expressionRewriting.bindingRewriteValidators", a.g.aa); a.b("expressionRewriting.parseObjectLiteral", a.g.Ra); a.b("expressionRewriting.preProcessBindings", a.g.qa); a.b("expressionRewriting._twoWayBindings", a.g.W); a.b("jsonExpressionRewriting", a.g); a.b("jsonExpressionRewriting.insertPropertyAccessorsIntoJson", a.g.qa); (function () {
function b(a) {
return 8 ==
a.nodeType && h.test(f ? a.text : a.nodeValue)
} function c(a) { return 8 == a.nodeType && g.test(f ? a.text : a.nodeValue) } function d(a, d) { for (var e = a, g = 1, k = []; e = e.nextSibling;) { if (c(e) && (g--, 0 === g)) return k; k.push(e); b(e) && g++ } if (!d) throw Error("Cannot find closing comment tag to match: " + a.nodeValue); return null } function e(a, b) { var c = d(a, b); return c ? 0 < c.length ? c[c.length - 1].nextSibling : a.nextSibling : null } var f = w && "\x3c!--test--\x3e" === w.createComment("test").text, h = f ? /^\x3c!--\s*ko(?:\s+([\s\S]+))?\s*--\x3e$/ : /^\s*ko(?:\s+([\s\S]+))?\s*$/,
g = f ? /^\x3c!--\s*\/ko\s*--\x3e$/ : /^\s*\/ko\s*$/, k = { ul: !0, ol: !0 }; a.e = {
Q: {}, childNodes: function (a) { return b(a) ? d(a) : a.childNodes }, da: function (c) { if (b(c)) { c = a.e.childNodes(c); for (var d = 0, e = c.length; d < e; d++) a.removeNode(c[d]) } else a.a.Fa(c) }, U: function (c, d) { if (b(c)) { a.e.da(c); for (var e = c.nextSibling, g = 0, k = d.length; g < k; g++) e.parentNode.insertBefore(d[g], e) } else a.a.U(c, d) }, yb: function (a, c) { b(a) ? a.parentNode.insertBefore(c, a.nextSibling) : a.firstChild ? a.insertBefore(c, a.firstChild) : a.appendChild(c) }, rb: function (c,
d, e) { e ? b(c) ? c.parentNode.insertBefore(d, e.nextSibling) : e.nextSibling ? c.insertBefore(d, e.nextSibling) : c.appendChild(d) : a.e.yb(c, d) }, firstChild: function (a) { return b(a) ? !a.nextSibling || c(a.nextSibling) ? null : a.nextSibling : a.firstChild }, nextSibling: function (a) { b(a) && (a = e(a)); return a.nextSibling && c(a.nextSibling) ? null : a.nextSibling }, Xb: b, lc: function (a) { return (a = (f ? a.text : a.nodeValue).match(h)) ? a[1] : null }, wb: function (d) {
if (k[a.a.B(d)]) {
var g = d.firstChild; if (g) {
do if (1 === g.nodeType) {
var f; f = g.firstChild;
var h = null; if (f) { do if (h) h.push(f); else if (b(f)) { var q = e(f, !0); q ? f = q : h = [f] } else c(f) && (h = [f]); while (f = f.nextSibling) } if (f = h) for (h = g.nextSibling, q = 0; q < f.length; q++) h ? d.insertBefore(f[q], h) : d.appendChild(f[q])
} while (g = g.nextSibling)
}
}
}
}
})(); a.b("virtualElements", a.e); a.b("virtualElements.allowedBindings", a.e.Q); a.b("virtualElements.emptyNode", a.e.da); a.b("virtualElements.insertAfter", a.e.rb); a.b("virtualElements.prepend", a.e.yb); a.b("virtualElements.setDomNodeChildren", a.e.U); (function () {
a.J = function () {
this.Nb =
{}
}; a.a.extend(a.J.prototype, {
nodeHasBindings: function (b) { switch (b.nodeType) { case 1: return null != b.getAttribute("data-bind"); case 8: return a.e.Xb(b); default: return !1 } }, getBindings: function (a, c) { var d = this.getBindingsString(a, c); return d ? this.parseBindingsString(d, c, a) : null }, getBindingAccessors: function (a, c) { var d = this.getBindingsString(a, c); return d ? this.parseBindingsString(d, c, a, { valueAccessors: !0 }) : null }, getBindingsString: function (b) {
switch (b.nodeType) {
case 1: return b.getAttribute("data-bind");
case 8: return a.e.lc(b); default: return null
}
}, parseBindingsString: function (b, c, d, e) { try { var f = this.Nb, h = b + (e && e.valueAccessors || ""), g; if (!(g = f[h])) { var k, l = "with($context){with($data||{}){return{" + a.g.qa(b, e) + "}}}"; k = new Function("$context", "$element", l); g = f[h] = k } return g(c, d) } catch (n) { throw n.message = "Unable to parse bindings.\nBindings value: " + b + "\nMessage: " + n.message, n; } }
}); a.J.instance = new a.J
})(); a.b("bindingProvider", a.J); (function () {
function b(a) { return function () { return a } } function c(a) { return a() }
function d(b) { return a.a.Oa(a.k.t(b), function (a, c) { return function () { return b()[c] } }) } function e(a, b) { return d(this.getBindings.bind(this, a, b)) } function f(b, c, d) { var e, g = a.e.firstChild(c), k = a.J.instance, f = k.preprocessNode; if (f) { for (; e = g;) g = a.e.nextSibling(e), f.call(k, e); g = a.e.firstChild(c) } for (; e = g;) g = a.e.nextSibling(e), h(b, e, d) } function h(b, c, d) { var e = !0, g = 1 === c.nodeType; g && a.e.wb(c); if (g && d || a.J.instance.nodeHasBindings(c)) e = k(c, null, b, d).shouldBindDescendants; e && !n[a.a.B(c)] && f(b, c, !g) } function g(b) {
var c =
[], d = {}, e = []; a.a.A(b, function y(g) { if (!d[g]) { var k = a.getBindingHandler(g); k && (k.after && (e.push(g), a.a.r(k.after, function (c) { if (b[c]) { if (-1 !== a.a.l(e, c)) throw Error("Cannot combine the following bindings, because they have a cyclic dependency: " + e.join(", ")); y(c) } }), e.length--), c.push({ key: g, pb: k })); d[g] = !0 } }); return c
} function k(b, d, k, f) {
var h = a.a.f.get(b, r); if (!d) { if (h) throw Error("You cannot apply bindings multiple times to the same element."); a.a.f.set(b, r, !0) } !h && f && a.Eb(b, k); var l; if (d && "function" !==
typeof d) l = d; else { var n = a.J.instance, m = n.getBindingAccessors || e, x = a.h(function () { (l = d ? d(k, b) : m.call(n, b, k)) && k.D && k.D(); return l }, null, { G: b }); l && x.ga() || (x = null) } var t; if (l) {
var w = x ? function (a) { return function () { return c(x()[a]) } } : function (a) { return l[a] }, z = function () { return a.a.Oa(x ? x() : l, c) }; z.get = function (a) { return l[a] && c(w(a)) }; z.has = function (a) { return a in l }; f = g(l); a.a.r(f, function (c) {
var d = c.pb.init, e = c.pb.update, g = c.key; if (8 === b.nodeType && !a.e.Q[g]) throw Error("The binding '" + g + "' cannot be used with virtual elements");
try { "function" == typeof d && a.k.t(function () { var a = d(b, w(g), z, k.$data, k); if (a && a.controlsDescendantBindings) { if (t !== p) throw Error("Multiple bindings (" + t + " and " + g + ") are trying to control descendant bindings of the same element. You cannot use these bindings together on the same element."); t = g } }), "function" == typeof e && a.h(function () { e(b, w(g), z, k.$data, k) }, null, { G: b }) } catch (f) { throw f.message = 'Unable to process binding "' + g + ": " + l[g] + '"\nMessage: ' + f.message, f; }
})
} return { shouldBindDescendants: t === p }
}
function l(b) { return b && b instanceof a.I ? b : new a.I(b) } a.d = {}; var n = { script: !0 }; a.getBindingHandler = function (b) { return a.d[b] }; a.I = function (b, c, d, e) {
var g = this, k = "function" == typeof b && !a.v(b), f, h = a.h(function () { var f = k ? b() : b, l = a.a.c(f); c ? (c.D && c.D(), a.a.extend(g, c), h && (g.D = h)) : (g.$parents = [], g.$root = l, g.ko = a); g.$rawData = f; g.$data = l; d && (g[d] = l); e && e(g, c, l); return g.$data }, null, { Da: function () { return f && !a.a.eb(f) }, G: !0 }); h.ga() && (g.D = h, h.equalityComparer = null, f = [], h.Jb = function (b) {
f.push(b); a.a.u.ja(b,
function (b) { a.a.ma(f, b); f.length || (h.F(), g.D = h = p) })
})
}; a.I.prototype.createChildContext = function (b, c, d) { return new a.I(b, this, c, function (a, b) { a.$parentContext = b; a.$parent = b.$data; a.$parents = (b.$parents || []).slice(0); a.$parents.unshift(a.$parent); d && d(a) }) }; a.I.prototype.extend = function (b) { return new a.I(this.D || this.$data, this, null, function (c, d) { c.$rawData = d.$rawData; a.a.extend(c, "function" == typeof b ? b() : b) }) }; var r = a.a.f.L(), m = a.a.f.L(); a.Eb = function (b, c) {
if (2 == arguments.length) a.a.f.set(b, m, c),
c.D && c.D.Jb(b); else return a.a.f.get(b, m)
}; a.xa = function (b, c, d) { 1 === b.nodeType && a.e.wb(b); return k(b, c, l(d), !0) }; a.Lb = function (c, e, g) { g = l(g); return a.xa(c, "function" === typeof e ? d(e.bind(null, g, c)) : a.a.Oa(e, b), g) }; a.gb = function (a, b) { 1 !== b.nodeType && 8 !== b.nodeType || f(l(a), b, !0) }; a.fb = function (a, b) {
!t && A.jQuery && (t = A.jQuery); if (b && 1 !== b.nodeType && 8 !== b.nodeType) throw Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node"); b = b || A.document.body; h(l(a),
b, !0)
}; a.Ca = function (b) { switch (b.nodeType) { case 1: case 8: var c = a.Eb(b); if (c) return c; if (b.parentNode) return a.Ca(b.parentNode) } return p }; a.Pb = function (b) { return (b = a.Ca(b)) ? b.$data : p }; a.b("bindingHandlers", a.d); a.b("applyBindings", a.fb); a.b("applyBindingsToDescendants", a.gb); a.b("applyBindingAccessorsToNode", a.xa); a.b("applyBindingsToNode", a.Lb); a.b("contextFor", a.Ca); a.b("dataFor", a.Pb)
})(); var L = { "class": "className", "for": "htmlFor" }; a.d.attr = {
update: function (b, c) {
var d = a.a.c(c()) || {}; a.a.A(d, function (c,
d) { d = a.a.c(d); var h = !1 === d || null === d || d === p; h && b.removeAttribute(c); 8 >= a.a.oa && c in L ? (c = L[c], h ? b.removeAttribute(c) : b[c] = d) : h || b.setAttribute(c, d.toString()); "name" === c && a.a.Cb(b, h ? "" : d.toString()) })
}
}; (function () {
a.d.checked = {
after: ["value", "attr"], init: function (b, c, d) {
function e() { return d.has("checkedValue") ? a.a.c(d.get("checkedValue")) : b.value } function f() {
var g = b.checked, f = r ? e() : g; if (!a.ca.pa() && (!k || g)) {
var h = a.k.t(c); l ? n !== f ? (g && (a.a.Y(h, f, !0), a.a.Y(h, n, !1)), n = f) : a.a.Y(h, f, g) : a.g.va(h, d, "checked",
f, !0)
}
} function h() { var d = a.a.c(c()); b.checked = l ? 0 <= a.a.l(d, e()) : g ? d : e() === d } var g = "checkbox" == b.type, k = "radio" == b.type; if (g || k) { var l = g && a.a.c(c()) instanceof Array, n = l ? e() : p, r = k || l; k && !b.name && a.d.uniqueName.init(b, function () { return !0 }); a.ba(f, null, { G: b }); a.a.q(b, "click", f); a.ba(h, null, { G: b }) }
}
}; a.g.W.checked = !0; a.d.checkedValue = { update: function (b, c) { b.value = a.a.c(c()) } }
})(); a.d.css = {
update: function (b, c) {
var d = a.a.c(c()); "object" == typeof d ? a.a.A(d, function (c, d) { d = a.a.c(d); a.a.ua(b, c, d) }) : (d = String(d ||
""), a.a.ua(b, b.__ko__cssValue, !1), b.__ko__cssValue = d, a.a.ua(b, d, !0))
}
}; a.d.enable = { update: function (b, c) { var d = a.a.c(c()); d && b.disabled ? b.removeAttribute("disabled") : d || b.disabled || (b.disabled = !0) } }; a.d.disable = { update: function (b, c) { a.d.enable.update(b, function () { return !a.a.c(c()) }) } }; a.d.event = {
init: function (b, c, d, e, f) {
var h = c() || {}; a.a.A(h, function (g) {
"string" == typeof g && a.a.q(b, g, function (b) {
var h, n = c()[g]; if (n) {
try { var r = a.a.R(arguments); e = f.$data; r.unshift(e); h = n.apply(e, r) } finally {
!0 !== h && (b.preventDefault ?
b.preventDefault() : b.returnValue = !1)
} !1 === d.get(g + "Bubble") && (b.cancelBubble = !0, b.stopPropagation && b.stopPropagation())
}
})
})
}
}; a.d.foreach = {
vb: function (b) { return function () { var c = b(), d = a.a.Sa(c); if (!d || "number" == typeof d.length) return { foreach: c, templateEngine: a.K.Ja }; a.a.c(c); return { foreach: d.data, as: d.as, includeDestroyed: d.includeDestroyed, afterAdd: d.afterAdd, beforeRemove: d.beforeRemove, afterRender: d.afterRender, beforeMove: d.beforeMove, afterMove: d.afterMove, templateEngine: a.K.Ja } } }, init: function (b,
c) { return a.d.template.init(b, a.d.foreach.vb(c)) }, update: function (b, c, d, e, f) { return a.d.template.update(b, a.d.foreach.vb(c), d, e, f) }
}; a.g.aa.foreach = !1; a.e.Q.foreach = !0; a.d.hasfocus = {
init: function (b, c, d) {
function e(e) { b.__ko_hasfocusUpdating = !0; var k = b.ownerDocument; if ("activeElement" in k) { var f; try { f = k.activeElement } catch (h) { f = k.body } e = f === b } k = c(); a.g.va(k, d, "hasfocus", e, !0); b.__ko_hasfocusLastValue = e; b.__ko_hasfocusUpdating = !1 } var f = e.bind(null, !0), h = e.bind(null, !1); a.a.q(b, "focus", f); a.a.q(b, "focusin",
f); a.a.q(b, "blur", h); a.a.q(b, "focusout", h)
}, update: function (b, c) { var d = !!a.a.c(c()); b.__ko_hasfocusUpdating || b.__ko_hasfocusLastValue === d || (d ? b.focus() : b.blur(), a.k.t(a.a.ha, null, [b, d ? "focusin" : "focusout"])) }
}; a.g.W.hasfocus = !0; a.d.hasFocus = a.d.hasfocus; a.g.W.hasFocus = !0; a.d.html = { init: function () { return { controlsDescendantBindings: !0 } }, update: function (b, c) { a.a.Va(b, c()) } }; H("if"); H("ifnot", !1, !0); H("with", !0, !1, function (a, c) { return a.createChildContext(c) }); var J = {}; a.d.options = {
init: function (b) {
if ("select" !==
a.a.B(b)) throw Error("options binding applies only to SELECT elements"); for (; 0 < b.length;) b.remove(0); return { controlsDescendantBindings: !0 }
}, update: function (b, c, d) {
function e() { return a.a.la(b.options, function (a) { return a.selected }) } function f(a, b, c) { var d = typeof b; return "function" == d ? b(a) : "string" == d ? a[b] : c } function h(c, d) { if (r.length) { var e = 0 <= a.a.l(r, a.i.p(d[0])); a.a.Db(d[0], e); m && !e && a.k.t(a.a.ha, null, [b, "change"]) } } var g = 0 != b.length && b.multiple ? b.scrollTop : null, k = a.a.c(c()), l = d.get("optionsIncludeDestroyed");
c = {}; var n, r; r = b.multiple ? a.a.ya(e(), a.i.p) : 0 <= b.selectedIndex ? [a.i.p(b.options[b.selectedIndex])] : []; k && ("undefined" == typeof k.length && (k = [k]), n = a.a.la(k, function (b) { return l || b === p || null === b || !a.a.c(b._destroy) }), d.has("optionsCaption") && (k = a.a.c(d.get("optionsCaption")), null !== k && k !== p && n.unshift(J))); var m = !1; c.beforeRemove = function (a) { b.removeChild(a) }; k = h; d.has("optionsAfterRender") && (k = function (b, c) { h(0, c); a.k.t(d.get("optionsAfterRender"), null, [c[0], b !== J ? b : p]) }); a.a.Ua(b, n, function (c, e, g) {
g.length &&
(r = g[0].selected ? [a.i.p(g[0])] : [], m = !0); e = b.ownerDocument.createElement("option"); c === J ? (a.a.Xa(e, d.get("optionsCaption")), a.i.X(e, p)) : (g = f(c, d.get("optionsValue"), c), a.i.X(e, a.a.c(g)), c = f(c, d.get("optionsText"), g), a.a.Xa(e, c)); return [e]
}, c, k); a.k.t(function () { d.get("valueAllowUnset") && d.has("value") ? a.i.X(b, a.a.c(d.get("value")), !0) : (b.multiple ? r.length && e().length < r.length : r.length && 0 <= b.selectedIndex ? a.i.p(b.options[b.selectedIndex]) !== r[0] : r.length || 0 <= b.selectedIndex) && a.a.ha(b, "change") }); a.a.Tb(b);
g && 20 < Math.abs(g - b.scrollTop) && (b.scrollTop = g)
}
}; a.d.options.Pa = a.a.f.L(); a.d.selectedOptions = {
after: ["options", "foreach"], init: function (b, c, d) { a.a.q(b, "change", function () { var e = c(), f = []; a.a.r(b.getElementsByTagName("option"), function (b) { b.selected && f.push(a.i.p(b)) }); a.g.va(e, d, "selectedOptions", f) }) }, update: function (b, c) {
if ("select" != a.a.B(b)) throw Error("values binding applies only to SELECT elements"); var d = a.a.c(c()); d && "number" == typeof d.length && a.a.r(b.getElementsByTagName("option"), function (b) {
var c =
0 <= a.a.l(d, a.i.p(b)); a.a.Db(b, c)
})
}
}; a.g.W.selectedOptions = !0; a.d.style = { update: function (b, c) { var d = a.a.c(c() || {}); a.a.A(d, function (c, d) { d = a.a.c(d); b.style[c] = d || "" }) } }; a.d.submit = { init: function (b, c, d, e, f) { if ("function" != typeof c()) throw Error("The value for a submit binding must be a function"); a.a.q(b, "submit", function (a) { var d, e = c(); try { d = e.call(f.$data, b) } finally { !0 !== d && (a.preventDefault ? a.preventDefault() : a.returnValue = !1) } }) } }; a.d.text = {
init: function () { return { controlsDescendantBindings: !0 } },
update: function (b, c) { a.a.Xa(b, c()) }
}; a.e.Q.text = !0; a.d.uniqueName = { init: function (b, c) { if (c()) { var d = "ko_unique_" + ++a.d.uniqueName.Ob; a.a.Cb(b, d) } } }; a.d.uniqueName.Ob = 0; a.d.value = {
after: ["options", "foreach"], init: function (b, c, d) {
function e() { g = !1; var e = c(), f = a.i.p(b); a.g.va(e, d, "value", f) } var f = ["change"], h = d.get("valueUpdate"), g = !1; h && ("string" == typeof h && (h = [h]), a.a.$(f, h), f = a.a.ib(f)); !a.a.oa || "input" != b.tagName.toLowerCase() || "text" != b.type || "off" == b.autocomplete || b.form && "off" == b.form.autocomplete ||
-1 != a.a.l(f, "propertychange") || (a.a.q(b, "propertychange", function () { g = !0 }), a.a.q(b, "focus", function () { g = !1 }), a.a.q(b, "blur", function () { g && e() })); a.a.r(f, function (c) { var d = e; a.a.kc(c, "after") && (d = function () { setTimeout(e, 0) }, c = c.substring(5)); a.a.q(b, c, d) })
}, update: function (b, c, d) { var e = a.a.c(c()); c = a.i.p(b); if (e !== c) if ("select" === a.a.B(b)) { var f = d.get("valueAllowUnset"); d = function () { a.i.X(b, e, f) }; d(); f || e === a.i.p(b) ? setTimeout(d, 0) : a.k.t(a.a.ha, null, [b, "change"]) } else a.i.X(b, e) }
}; a.g.W.value = !0; a.d.visible =
{ update: function (b, c) { var d = a.a.c(c()), e = "none" != b.style.display; d && !e ? b.style.display = "" : !d && e && (b.style.display = "none") } }; (function (b) { a.d[b] = { init: function (c, d, e, f, h) { return a.d.event.init.call(this, c, function () { var a = {}; a[b] = d(); return a }, e, f, h) } } })("click"); a.C = function () { }; a.C.prototype.renderTemplateSource = function () { throw Error("Override renderTemplateSource"); }; a.C.prototype.createJavaScriptEvaluatorBlock = function () { throw Error("Override createJavaScriptEvaluatorBlock"); }; a.C.prototype.makeTemplateSource =
function (b, c) { if ("string" == typeof b) { c = c || w; var d = c.getElementById(b); if (!d) throw Error("Cannot find template with ID " + b); return new a.n.j(d) } if (1 == b.nodeType || 8 == b.nodeType) return new a.n.Z(b); throw Error("Unknown template type: " + b); }; a.C.prototype.renderTemplate = function (a, c, d, e) { a = this.makeTemplateSource(a, e); return this.renderTemplateSource(a, c, d) }; a.C.prototype.isTemplateRewritten = function (a, c) { return !1 === this.allowTemplateRewriting ? !0 : this.makeTemplateSource(a, c).data("isRewritten") }; a.C.prototype.rewriteTemplate =
function (a, c, d) { a = this.makeTemplateSource(a, d); c = c(a.text()); a.text(c); a.data("isRewritten", !0) }; a.b("templateEngine", a.C); a.Za = function () {
function b(b, c, d, g) {
b = a.g.Ra(b); for (var k = a.g.aa, l = 0; l < b.length; l++) { var n = b[l].key; if (k.hasOwnProperty(n)) { var r = k[n]; if ("function" === typeof r) { if (n = r(b[l].value)) throw Error(n); } else if (!r) throw Error("This template engine does not support the '" + n + "' binding within its templates"); } } d = "ko.__tr_ambtns(function($context,$element){return(function(){return{ " + a.g.qa(b,
{ valueAccessors: !0 }) + " } })()},'" + d.toLowerCase() + "')"; return g.createJavaScriptEvaluatorBlock(d) + c
} var c = /(<([a-z]+\d*)(?:\s+(?!data-bind\s*=\s*)[a-z0-9\-]+(?:=(?:\"[^\"]*\"|\'[^\']*\'))?)*\s+)data-bind\s*=\s*(["'])([\s\S]*?)\3/gi, d = /\x3c!--\s*ko\b\s*([\s\S]*?)\s*--\x3e/g; return {
Ub: function (b, c, d) { c.isTemplateRewritten(b, d) || c.rewriteTemplate(b, function (b) { return a.Za.dc(b, c) }, d) }, dc: function (a, f) {
return a.replace(c, function (a, c, d, e, n) { return b(n, c, d, f) }).replace(d, function (a, c) {
return b(c, "\x3c!-- ko --\x3e",
"#comment", f)
})
}, Mb: function (b, c) { return a.w.Na(function (d, g) { var k = d.nextSibling; k && k.nodeName.toLowerCase() === c && a.xa(k, b, g) }) }
}
}(); a.b("__tr_ambtns", a.Za.Mb); (function () {
a.n = {}; a.n.j = function (a) { this.j = a }; a.n.j.prototype.text = function () { var b = a.a.B(this.j), b = "script" === b ? "text" : "textarea" === b ? "value" : "innerHTML"; if (0 == arguments.length) return this.j[b]; var c = arguments[0]; "innerHTML" === b ? a.a.Va(this.j, c) : this.j[b] = c }; var b = a.a.f.L() + "_"; a.n.j.prototype.data = function (c) {
if (1 === arguments.length) return a.a.f.get(this.j,
b + c); a.a.f.set(this.j, b + c, arguments[1])
}; var c = a.a.f.L(); a.n.Z = function (a) { this.j = a }; a.n.Z.prototype = new a.n.j; a.n.Z.prototype.text = function () { if (0 == arguments.length) { var b = a.a.f.get(this.j, c) || {}; b.$a === p && b.Ba && (b.$a = b.Ba.innerHTML); return b.$a } a.a.f.set(this.j, c, { $a: arguments[0] }) }; a.n.j.prototype.nodes = function () { if (0 == arguments.length) return (a.a.f.get(this.j, c) || {}).Ba; a.a.f.set(this.j, c, { Ba: arguments[0] }) }; a.b("templateSources", a.n); a.b("templateSources.domElement", a.n.j); a.b("templateSources.anonymousTemplate",
a.n.Z)
})(); (function () {
function b(b, c, d) { var e; for (c = a.e.nextSibling(c) ; b && (e = b) !== c;) b = a.e.nextSibling(e), d(e, b) } function c(c, d) {
if (c.length) {
var e = c[0], f = c[c.length - 1], h = e.parentNode, m = a.J.instance, q = m.preprocessNode; if (q) { b(e, f, function (a, b) { var c = a.previousSibling, d = q.call(m, a); d && (a === e && (e = d[0] || b), a === f && (f = d[d.length - 1] || c)) }); c.length = 0; if (!e) return; e === f ? c.push(e) : (c.push(e, f), a.a.ea(c, h)) } b(e, f, function (b) { 1 !== b.nodeType && 8 !== b.nodeType || a.fb(d, b) }); b(e, f, function (b) {
1 !== b.nodeType && 8 !==
b.nodeType || a.w.Ib(b, [d])
}); a.a.ea(c, h)
}
} function d(a) { return a.nodeType ? a : 0 < a.length ? a[0] : null } function e(b, e, h, n, r) {
r = r || {}; var m = b && d(b), m = m && m.ownerDocument, q = r.templateEngine || f; a.Za.Ub(h, q, m); h = q.renderTemplate(h, n, r, m); if ("number" != typeof h.length || 0 < h.length && "number" != typeof h[0].nodeType) throw Error("Template engine must return an array of DOM nodes"); m = !1; switch (e) {
case "replaceChildren": a.e.U(b, h); m = !0; break; case "replaceNode": a.a.Bb(b, h); m = !0; break; case "ignoreTargetNode": break; default: throw Error("Unknown renderMode: " +
e);
} m && (c(h, n), r.afterRender && a.k.t(r.afterRender, null, [h, n.$data])); return h
} var f; a.Wa = function (b) { if (b != p && !(b instanceof a.C)) throw Error("templateEngine must inherit from ko.templateEngine"); f = b }; a.Ta = function (b, c, h, n, r) {
h = h || {}; if ((h.templateEngine || f) == p) throw Error("Set a template engine before calling renderTemplate"); r = r || "replaceChildren"; if (n) {
var m = d(n); return a.h(function () {
var f = c && c instanceof a.I ? c : new a.I(a.a.c(c)), p = a.v(b) ? b() : "function" == typeof b ? b(f.$data, f) : b, f = e(n, r, p, f, h);
"replaceNode" == r && (n = f, m = d(n))
}, null, { Da: function () { return !m || !a.a.Ea(m) }, G: m && "replaceNode" == r ? m.parentNode : m })
} return a.w.Na(function (d) { a.Ta(b, c, h, d, "replaceNode") })
}; a.jc = function (b, d, f, h, r) {
function m(a, b) { c(b, s); f.afterRender && f.afterRender(b, a) } function q(a, c) { s = r.createChildContext(a, f.as, function (a) { a.$index = c }); var d = "function" == typeof b ? b(a, s) : b; return e(null, "ignoreTargetNode", d, s, f) } var s; return a.h(function () {
var b = a.a.c(d) || []; "undefined" == typeof b.length && (b = [b]); b = a.a.la(b, function (b) {
return f.includeDestroyed ||
b === p || null === b || !a.a.c(b._destroy)
}); a.k.t(a.a.Ua, null, [h, b, q, f, m])
}, null, { G: h })
}; var h = a.a.f.L(); a.d.template = {
init: function (b, c) { var d = a.a.c(c()); "string" == typeof d || d.name ? a.e.da(b) : (d = a.e.childNodes(b), d = a.a.ec(d), (new a.n.Z(b)).nodes(d)); return { controlsDescendantBindings: !0 } }, update: function (b, c, d, e, f) {
var m = c(), q; c = a.a.c(m); d = !0; e = null; "string" == typeof c ? c = {} : (m = c.name, "if" in c && (d = a.a.c(c["if"])), d && "ifnot" in c && (d = !a.a.c(c.ifnot)), q = a.a.c(c.data)); "foreach" in c ? e = a.jc(m || b, d && c.foreach ||
[], c, b, f) : d ? (f = "data" in c ? f.createChildContext(q, c.as) : f, e = a.Ta(m || b, f, c, b)) : a.e.da(b); f = e; (q = a.a.f.get(b, h)) && "function" == typeof q.F && q.F(); a.a.f.set(b, h, f && f.ga() ? f : p)
}
}; a.g.aa.template = function (b) { b = a.g.Ra(b); return 1 == b.length && b[0].unknown || a.g.bc(b, "name") ? null : "This template engine does not support anonymous templates nested within its templates" }; a.e.Q.template = !0
})(); a.b("setTemplateEngine", a.Wa); a.b("renderTemplate", a.Ta); a.a.nb = function (a, c, d) {
if (a.length && c.length) {
var e, f, h, g, k; for (e =
f = 0; (!d || e < d) && (g = a[f]) ; ++f) { for (h = 0; k = c[h]; ++h) if (g.value === k.value) { g.moved = k.index; k.moved = g.index; c.splice(h, 1); e = h = 0; break } e += h }
}
}; a.a.Aa = function () {
function b(b, d, e, f, h) {
var g = Math.min, k = Math.max, l = [], n, p = b.length, m, q = d.length, s = q - p || 1, t = p + q + 1, u, w, y; for (n = 0; n <= p; n++) for (w = u, l.push(u = []), y = g(q, n + s), m = k(0, n - 1) ; m <= y; m++) u[m] = m ? n ? b[n - 1] === d[m - 1] ? w[m - 1] : g(w[m] || t, u[m - 1] || t) + 1 : m + 1 : n + 1; g = []; k = []; s = []; n = p; for (m = q; n || m;) q = l[n][m] - 1, m && q === l[n][m - 1] ? k.push(g[g.length] = { status: e, value: d[--m], index: m }) :
n && q === l[n - 1][m] ? s.push(g[g.length] = { status: f, value: b[--n], index: n }) : (--m, --n, h.sparse || g.push({ status: "retained", value: d[m] })); a.a.nb(k, s, 10 * p); return g.reverse()
} return function (a, d, e) { e = "boolean" === typeof e ? { dontLimitMoves: e } : e || {}; a = a || []; d = d || []; return a.length <= d.length ? b(a, d, "added", "deleted", e) : b(d, a, "deleted", "added", e) }
}(); a.b("utils.compareArrays", a.a.Aa); (function () {
function b(b, c, f, h, g) {
var k = [], l = a.h(function () {
var l = c(f, g, a.a.ea(k, b)) || []; 0 < k.length && (a.a.Bb(k, l), h && a.k.t(h, null, [f,
l, g])); k.length = 0; a.a.$(k, l)
}, null, { G: b, Da: function () { return !a.a.eb(k) } }); return { S: k, h: l.ga() ? l : p }
} var c = a.a.f.L(); a.a.Ua = function (d, e, f, h, g) {
function k(b, c) { v = r[c]; u !== c && (z[b] = v); v.Ia(u++); a.a.ea(v.S, d); s.push(v); y.push(v) } function l(b, c) { if (b) for (var d = 0, e = c.length; d < e; d++) c[d] && a.a.r(c[d].S, function (a) { b(a, d, c[d].ka) }) } e = e || []; h = h || {}; var n = a.a.f.get(d, c) === p, r = a.a.f.get(d, c) || [], m = a.a.ya(r, function (a) { return a.ka }), q = a.a.Aa(m, e, h.dontLimitMoves), s = [], t = 0, u = 0, w = [], y = []; e = []; for (var z = [], m = [],
v, x = 0, A, C; A = q[x]; x++) switch (C = A.moved, A.status) { case "deleted": C === p && (v = r[t], v.h && v.h.F(), w.push.apply(w, a.a.ea(v.S, d)), h.beforeRemove && (e[x] = v, y.push(v))); t++; break; case "retained": k(x, t++); break; case "added": C !== p ? k(x, C) : (v = { ka: A.value, Ia: a.m(u++) }, s.push(v), y.push(v), n || (m[x] = v)) } l(h.beforeMove, z); a.a.r(w, h.beforeRemove ? a.M : a.removeNode); for (var x = 0, n = a.e.firstChild(d), E; v = y[x]; x++) {
v.S || a.a.extend(v, b(d, f, v.ka, g, v.Ia)); for (t = 0; q = v.S[t]; n = q.nextSibling, E = q, t++) q !== n && a.e.rb(d, q, E); !v.Zb && g && (g(v.ka,
v.S, v.Ia), v.Zb = !0)
} l(h.beforeRemove, e); l(h.afterMove, z); l(h.afterAdd, m); a.a.f.set(d, c, s)
}
})(); a.b("utils.setDomNodeChildrenFromArrayMapping", a.a.Ua); a.K = function () { this.allowTemplateRewriting = !1 }; a.K.prototype = new a.C; a.K.prototype.renderTemplateSource = function (b) { var c = (9 > a.a.oa ? 0 : b.nodes) ? b.nodes() : null; if (c) return a.a.R(c.cloneNode(!0).childNodes); b = b.text(); return a.a.Qa(b) }; a.K.Ja = new a.K; a.Wa(a.K.Ja); a.b("nativeTemplateEngine", a.K); (function () {
a.La = function () {
var a = this.ac = function () {
if (!t ||
!t.tmpl) return 0; try { if (0 <= t.tmpl.tag.tmpl.open.toString().indexOf("__")) return 2 } catch (a) { } return 1
}(); this.renderTemplateSource = function (b, e, f) {
f = f || {}; if (2 > a) throw Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later."); var h = b.data("precompiled"); h || (h = b.text() || "", h = t.template(null, "{{ko_with $item.koBindingContext}}" + h + "{{/ko_with}}"), b.data("precompiled", h)); b = [e.$data]; e = t.extend({ koBindingContext: e }, f.templateOptions); e = t.tmpl(h, b, e); e.appendTo(w.createElement("div"));
t.fragments = {}; return e
}; this.createJavaScriptEvaluatorBlock = function (a) { return "{{ko_code ((function() { return " + a + " })()) }}" }; this.addTemplate = function (a, b) { w.write("<script type='text/html' id='" + a + "'>" + b + "\x3c/script>") }; 0 < a && (t.tmpl.tag.ko_code = { open: "__.push($1 || '');" }, t.tmpl.tag.ko_with = { open: "with($1) {", close: "} " })
}; a.La.prototype = new a.C; var b = new a.La; 0 < b.ac && a.Wa(b); a.b("jqueryTmplTemplateEngine", a.La)
})()
})
})();
})(); |
/**
* A JavaScript implementation of the JSON-LD API.
*
* @author Dave Longley
*
* BSD 3-Clause License
* Copyright (c) 2011-2013 Digital Bazaar, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of the Digital Bazaar, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
(function() {
// determine if in-browser or using node.js
var _nodejs = (typeof module === 'object' && module.exports);
var _browser = !_nodejs && window;
// attaches jsonld API to the given object
var wrapper = function(jsonld) {
/* Core API */
/**
* Performs JSON-LD compaction.
*
* @param input the JSON-LD input to compact.
* @param ctx the context to compact with.
* @param [options] options to use:
* [base] the base IRI to use.
* [strict] use strict mode (default: true).
* [compactArrays] true to compact arrays to single values when
* appropriate, false not to (default: true).
* [graph] true to always output a top-level graph (default: false).
* [skipExpansion] true to assume the input is expanded and skip
* expansion, false not to, defaults to false.
* [loadContext(url, callback(err, url, result))] the context loader.
* @param callback(err, compacted, ctx) called once the operation completes.
*/
jsonld.compact = function(input, ctx, options, callback) {
// get arguments
if(typeof options === 'function') {
callback = options;
options = {};
}
// nothing to compact
if(input === null) {
return callback(null, null);
}
// set default options
if(!('base' in options)) {
options.base = '';
}
if(!('strict' in options)) {
options.strict = true;
}
if(!('compactArrays' in options)) {
options.compactArrays = true;
}
if(!('graph' in options)) {
options.graph = false;
}
if(!('skipExpansion' in options)) {
options.skipExpansion = false;
}
if(!('loadContext' in options)) {
options.loadContext = jsonld.loadContext;
}
var expand = function(input, options, callback) {
if(options.skipExpansion) {
return callback(null, input);
}
jsonld.expand(input, options, callback);
};
// expand input then do compaction
expand(input, options, function(err, expanded) {
if(err) {
return callback(new JsonLdError(
'Could not expand input before compaction.',
'jsonld.CompactError', {cause: err}));
}
// process context
var activeCtx = _getInitialContext(options);
jsonld.processContext(activeCtx, ctx, options, function(err, activeCtx) {
if(err) {
return callback(new JsonLdError(
'Could not process context before compaction.',
'jsonld.CompactError', {cause: err}));
}
try {
// do compaction
var compacted = new Processor().compact(
activeCtx, null, expanded, options);
cleanup(null, compacted, activeCtx, options);
}
catch(ex) {
callback(ex);
}
});
});
// performs clean up after compaction
function cleanup(err, compacted, activeCtx, options) {
if(err) {
return callback(err);
}
if(options.compactArrays && !options.graph && _isArray(compacted)) {
// simplify to a single item
if(compacted.length === 1) {
compacted = compacted[0];
}
// simplify to an empty object
else if(compacted.length === 0) {
compacted = {};
}
}
// always use array if graph option is on
else if(options.graph && _isObject(compacted)) {
compacted = [compacted];
}
// follow @context key
if(_isObject(ctx) && '@context' in ctx) {
ctx = ctx['@context'];
}
// build output context
ctx = _clone(ctx);
if(!_isArray(ctx)) {
ctx = [ctx];
}
// remove empty contexts
var tmp = ctx;
ctx = [];
for(var i in tmp) {
if(!_isObject(tmp[i]) || Object.keys(tmp[i]).length > 0) {
ctx.push(tmp[i]);
}
}
// remove array if only one context
var hasContext = (ctx.length > 0);
if(ctx.length === 1) {
ctx = ctx[0];
}
// add context
if(hasContext || options.graph) {
if(_isArray(compacted)) {
// use '@graph' keyword
var kwgraph = _compactIri(activeCtx, '@graph');
var graph = compacted;
compacted = {};
if(hasContext) {
compacted['@context'] = ctx;
}
compacted[kwgraph] = graph;
}
else if(_isObject(compacted)) {
// reorder keys so @context is first
var graph = compacted;
compacted = {'@context': ctx};
for(var key in graph) {
compacted[key] = graph[key];
}
}
}
callback(null, compacted, activeCtx);
}
};
/**
* Performs JSON-LD expansion.
*
* @param input the JSON-LD input to expand.
* @param [options] the options to use:
* [base] the base IRI to use.
* [renameBlankNodes] true to rename blank nodes, false not to,
* defaults to true.
* [keepFreeFloatingNodes] true to keep free-floating nodes,
* false not to, defaults to false.
* [loadContext(url, callback(err, url, result))] the context loader.
* @param callback(err, expanded) called once the operation completes.
*/
jsonld.expand = function(input) {
// get arguments
var options = {};
var callback;
var callbackArg = 1;
if(arguments.length > 2) {
options = arguments[1] || {};
callbackArg += 1;
}
callback = arguments[callbackArg];
// set default options
if(!('base' in options)) {
options.base = '';
}
if(!('loadContext' in options)) {
options.loadContext = jsonld.loadContext;
}
if(!('renameBlankNodes' in options)) {
options.renameBlankNodes = true;
}
if(!('keepFreeFloatingNodes' in options)) {
options.keepFreeFloatingNodes = false;
}
// retrieve all @context URLs in the input
input = _clone(input);
_retrieveContextUrls(input, options, function(err, input) {
if(err) {
return callback(err);
}
try {
// do expansion
var activeCtx = _getInitialContext(options);
var expanded = new Processor().expand(
activeCtx, null, input, options, false);
// optimize away @graph with no other properties
if(_isObject(expanded) && ('@graph' in expanded) &&
Object.keys(expanded).length === 1) {
expanded = expanded['@graph'];
}
else if(expanded === null) {
expanded = [];
}
// normalize to an array
if(!_isArray(expanded)) {
expanded = [expanded];
}
callback(null, expanded);
}
catch(ex) {
callback(ex);
}
});
};
/**
* Performs JSON-LD flattening.
*
* @param input the JSON-LD to flatten.
* @param ctx the context to use to compact the flattened output, or null.
* @param [options] the options to use:
* [base] the base IRI to use.
* [loadContext(url, callback(err, url, result))] the context loader.
* @param callback(err, flattened) called once the operation completes.
*/
jsonld.flatten = function(input, ctx, options, callback) {
// get arguments
if(typeof options === 'function') {
callback = options;
options = {};
}
// set default options
if(!('base' in options)) {
options.base = '';
}
if(!('loadContext' in options)) {
options.loadContext = jsonld.loadContext;
}
// expand input
jsonld.expand(input, options, function(err, _input) {
if(err) {
return callback(new JsonLdError(
'Could not expand input before flattening.',
'jsonld.FlattenError', {cause: err}));
}
try {
// do flattening
var flattened = new Processor().flatten(_input);
}
catch(ex) {
return callback(ex);
}
if(ctx === null) {
return callback(null, flattened);
}
// compact result (force @graph option to true, skip expansion)
options.graph = true;
options.skipExpansion = true;
jsonld.compact(flattened, ctx, options, function(err, compacted) {
if(err) {
return callback(new JsonLdError(
'Could not compact flattened output.',
'jsonld.FlattenError', {cause: err}));
}
callback(null, compacted);
});
});
};
/**
* Performs JSON-LD framing.
*
* @param input the JSON-LD input to frame.
* @param frame the JSON-LD frame to use.
* @param [options] the framing options.
* [base] the base IRI to use.
* [embed] default @embed flag (default: true).
* [explicit] default @explicit flag (default: false).
* [omitDefault] default @omitDefault flag (default: false).
* [loadContext(url, callback(err, url, result))] the context loader.
* @param callback(err, framed) called once the operation completes.
*/
jsonld.frame = function(input, frame) {
// get arguments
var options = {};
var callbackArg = 2;
if(arguments.length > 3) {
options = arguments[2] || {};
callbackArg += 1;
}
var callback = arguments[callbackArg];
// set default options
if(!('base' in options)) {
options.base = '';
}
if(!('loadContext' in options)) {
options.loadContext = jsonld.loadContext;
}
if(!('embed' in options)) {
options.embed = true;
}
options.explicit = options.explicit || false;
options.omitDefault = options.omitDefault || false;
// preserve frame context
var ctx = frame['@context'] || {};
// expand input
jsonld.expand(input, options, function(err, expanded) {
if(err) {
return callback(new JsonLdError(
'Could not expand input before framing.',
'jsonld.FrameError', {cause: err}));
}
// expand frame
var opts = _clone(options);
opts.keepFreeFloatingNodes = true;
jsonld.expand(frame, opts, function(err, expandedFrame) {
if(err) {
return callback(new JsonLdError(
'Could not expand frame before framing.',
'jsonld.FrameError', {cause: err}));
}
try {
// do framing
var framed = new Processor().frame(expanded, expandedFrame, options);
}
catch(ex) {
return callback(ex);
}
// compact result (force @graph option to true, skip expansion)
opts.graph = true;
opts.skipExpansion = true;
jsonld.compact(framed, ctx, opts, function(err, compacted, ctx) {
if(err) {
return callback(new JsonLdError(
'Could not compact framed output.',
'jsonld.FrameError', {cause: err}));
}
// get graph alias
var graph = _compactIri(ctx, '@graph');
// remove @preserve from results
compacted[graph] = _removePreserve(ctx, compacted[graph], opts);
callback(null, compacted);
});
});
});
};
/**
* Performs JSON-LD objectification.
*
* @param input the JSON-LD input to objectify.
* @param ctx the JSON-LD context to apply.
* @param [options] the framing options.
* [base] the base IRI to use.
* [loadContext(url, callback(err, url, result))] the context loader.
* @param callback(err, objectified) called once the operation completes.
*/
jsonld.objectify = function(input, ctx) {
// get arguments
var options = {};
var callbackArg = 2;
if(arguments.length > 3) {
options = arguments[2] || {};
callbackArg += 1;
}
var callback = arguments[callbackArg];
// set default options
if(!('base' in options)) {
options.base = '';
}
if(!('loadContext' in options)) {
options.loadContext = jsonld.loadContext;
}
// expand input
jsonld.expand(input, options, function(err, _input) {
if(err) {
return callback(new JsonLdError(
'Could not expand input before framing.',
'jsonld.FrameError', {cause: err}));
}
try {
// flatten the graph
var flattened = new Processor().flatten(_input);
}
catch(ex) {
return callback(ex);
}
// compact result (force @graph option to true, skip expansion)
options.graph = true;
options.skipExpansion = true;
jsonld.compact(flattened, ctx, options, function(err, compacted, ctx) {
if(err) {
return callback(new JsonLdError(
'Could not compact flattened output.',
'jsonld.FrameError', {cause: err}));
}
// get graph alias
var graph = _compactIri(ctx, '@graph');
// remove @preserve from results (named graphs?)
compacted[graph] = _removePreserve(ctx, compacted[graph], options);
var top = compacted[graph][0];
var recurse = function(subject) {
// can't replace just a string
if(!_isObject(subject) && !_isArray(subject)) {
return;
}
// bottom out recursion on re-visit
if(_isObject(subject)) {
if(recurse.visited[subject['@id']]) {
return;
}
recurse.visited[subject['@id']] = true;
}
// each array element *or* object key
for(var k in subject) {
var obj = subject[k];
var isid = (jsonld.getContextValue(ctx, k, '@type') === '@id');
// can't replace a non-object or non-array unless it's an @id
if(!_isArray(obj) && !_isObject(obj) && !isid) {
continue;
}
if(_isString(obj) && isid) {
subject[k] = obj = top[obj];
recurse(obj);
}
else if(_isArray(obj)) {
for(var i=0; i<obj.length; i++) {
if(_isString(obj[i]) && isid) {
obj[i] = top[obj[i]];
}
else if(_isObject(obj[i]) && '@id' in obj[i]) {
obj[i] = top[obj[i]['@id']];
}
recurse(obj[i]);
}
}
else if(_isObject(obj)) {
var sid = obj['@id'];
subject[k] = obj = top[sid];
recurse(obj);
}
}
};
recurse.visited = {};
recurse(top);
compacted.of_type = {};
for(var s in top) {
if(!('@type' in top[s])) {
continue;
}
var types = top[s]['@type'];
if(!_isArray(types)) {
types = [types];
}
for(var t in types) {
if(!(types[t] in compacted.of_type)) {
compacted.of_type[types[t]] = [];
}
compacted.of_type[types[t]].push(top[s]);
}
}
callback(null, compacted);
});
});
};
/**
* Performs RDF dataset normalization on the given JSON-LD input. The output
* is an RDF dataset unless the 'format' option is used.
*
* @param input the JSON-LD input to normalize.
* @param [options] the options to use:
* [base] the base IRI to use.
* [format] the format if output is a string:
* 'application/nquads' for N-Quads.
* [loadContext(url, callback(err, url, result))] the context loader.
* @param callback(err, normalized) called once the operation completes.
*/
jsonld.normalize = function(input, options, callback) {
// get arguments
if(typeof options === 'function') {
callback = options;
options = {};
}
options = options || {};
// set default options
if(!('base' in options)) {
options.base = '';
}
if(!('loadContext' in options)) {
options.loadContext = jsonld.loadContext;
}
// convert to RDF dataset then do normalization
var opts = _clone(options);
delete opts.format;
jsonld.toRDF(input, opts, function(err, dataset) {
if(err) {
return callback(new JsonLdError(
'Could not convert input to RDF dataset before normalization.',
'jsonld.NormalizeError', {cause: err}));
}
// do normalization
new Processor().normalize(dataset, options, callback);
});
};
/**
* Converts an RDF dataset to JSON-LD.
*
* @param dataset a serialized string of RDF in a format specified by the
* format option or an RDF dataset to convert.
* @param [options] the options to use:
* [format] the format if input is not an array:
* 'application/nquads' for N-Quads (default).
* [useRdfType] true to use rdf:type, false to use @type
* (default: false).
* [useNativeTypes] true to convert XSD types into native types
* (boolean, integer, double), false not to (default: true).
*
* @param callback(err, output) called once the operation completes.
*/
jsonld.fromRDF = function(dataset, options, callback) {
// get arguments
if(typeof options === 'function') {
callback = options;
options = {};
}
options = options || {};
// set default options
if(!('useRdfType' in options)) {
options.useRdfType = false;
}
if(!('useNativeTypes' in options)) {
options.useNativeTypes = true;
}
if(!('format' in options) && _isString(dataset)) {
// set default format to nquads
if(!('format' in options)) {
options.format = 'application/nquads';
}
}
// handle special format
if(options.format) {
// supported formats
if(options.format in _rdfParsers) {
dataset = _rdfParsers[options.format](dataset);
}
else {
throw new JsonLdError(
'Unknown input format.',
'jsonld.UnknownFormat', {format: options.format});
}
}
// convert from RDF
new Processor().fromRDF(dataset, options, callback);
};
/**
* Outputs the RDF dataset found in the given JSON-LD object.
*
* @param input the JSON-LD input.
* @param [options] the options to use:
* [base] the base IRI to use.
* [format] the format to use to output a string:
* 'application/nquads' for N-Quads (default).
* [loadContext(url, callback(err, url, result))] the context loader.
* @param callback(err, dataset) called once the operation completes.
*/
jsonld.toRDF = function(input, options, callback) {
// get arguments
if(typeof options === 'function') {
callback = options;
options = {};
}
options = options || {};
// set default options
if(!('base' in options)) {
options.base = '';
}
if(!('loadContext' in options)) {
options.loadContext = jsonld.loadContext;
}
// expand input
jsonld.expand(input, options, function(err, expanded) {
if(err) {
return callback(new JsonLdError(
'Could not expand input before conversion to RDF.',
'jsonld.RdfError', {cause: err}));
}
// create node map for default graph (and any named graphs)
var namer = new UniqueNamer('_:b');
var nodeMap = {'@default': {}};
_createNodeMap(expanded, nodeMap, '@default', namer);
try {
// output RDF dataset
var dataset = Processor.prototype.toRDF(nodeMap);
if(options.format) {
if(options.format === 'application/nquads') {
return callback(null, _toNQuads(dataset));
}
throw new JsonLdError(
'Unknown output format.',
'jsonld.UnknownFormat', {format: options.format});
}
callback(null, dataset);
}
catch(ex) {
callback(ex);
}
});
};
/**
* Relabels all blank nodes in the given JSON-LD input.
*
* @param input the JSON-LD input.
*/
jsonld.relabelBlankNodes = function(input) {
_labelBlankNodes(new UniqueNamer('_:b', input));
};
/**
* The default context loader for external @context URLs.
*
* @param loadContext(url, callback(err, url, result)) the context loader.
*/
jsonld.loadContext = function(url, callback) {
return callback(new JsonLdError(
'Could not retrieve @context URL. URL derefencing not implemented.',
'jsonld.ContextUrlError'), url);
};
/* Utility API */
// define nextTick
if(typeof process === 'undefined' || !process.nextTick) {
if(typeof setImmediate === 'function') {
jsonld.nextTick = function(callback) {
setImmediate(callback);
};
}
else {
jsonld.nextTick = function(callback) {
setTimeout(callback, 0);
};
}
}
else {
jsonld.nextTick = process.nextTick;
}
/**
* Creates a simple context cache.
*
* @param size the maximum size of the cache.
*/
jsonld.ContextCache = function(size) {
this.order = [];
this.cache = {};
this.size = size || 50;
this.expires = 30*60*1000;
};
jsonld.ContextCache.prototype.get = function(url) {
if(url in this.cache) {
var entry = this.cache[url];
if(entry.expires >= +new Date()) {
return entry.ctx;
}
delete this.cache[url];
this.order.splice(this.order.indexOf(url), 1);
}
return null;
};
jsonld.ContextCache.prototype.set = function(url, ctx) {
if(this.order.length === this.size) {
delete this.cache[this.order.shift()];
}
this.order.push(url);
this.cache[url] = {ctx: ctx, expires: (+new Date() + this.expires)};
};
/**
* Creates an active context cache.
*
* @param size the maximum size of the cache.
*/
jsonld.ActiveContextCache = function(size) {
this.order = [];
this.cache = {};
this.size = size || 100;
};
jsonld.ActiveContextCache.prototype.get = function(activeCtx, localCtx) {
var key1 = JSON.stringify(activeCtx);
var key2 = JSON.stringify(localCtx);
var level1 = this.cache[key1];
if(level1 && key2 in level1) {
// get shareable copy of cached active context
return level1[key2].share();
}
return null;
};
jsonld.ActiveContextCache.prototype.set = function(
activeCtx, localCtx, result) {
if(this.order.length === this.size) {
var entry = this.order.shift();
delete this.cache[entry.activeCtx][entry.localCtx];
}
var key1 = JSON.stringify(activeCtx);
var key2 = JSON.stringify(localCtx);
this.order.push({activeCtx: key1, localCtx: key2});
if(!(key1 in this.cache)) {
this.cache[key1] = {};
}
this.cache[key1][key2] = result;
};
/**
* Default JSON-LD cache.
*/
jsonld.cache = {
activeCtx: new jsonld.ActiveContextCache()
};
/**
* Context loaders.
*/
jsonld.contextLoaders = {};
/**
* The built-in jquery context loader.
*
* @param $ the jquery instance to use.
* @param options the options to use:
* secure: require all URLs to use HTTPS.
*
* @return the jquery context loader.
*/
jsonld.contextLoaders['jquery'] = function($, options) {
options = options || {};
var cache = new jsonld.ContextCache();
return function(url, callback) {
if(options.secure && url.indexOf('https') !== 0) {
return callback(new JsonLdError(
'URL could not be dereferenced; secure mode is enabled and ' +
'the URL\'s scheme is not "https".',
'jsonld.InvalidUrl', {url: url}), url);
}
var ctx = cache.get(url);
if(ctx !== null) {
return callback(null, url, ctx);
}
$.ajax({
url: url,
dataType: 'json',
crossDomain: true,
success: function(data, textStatus, jqXHR) {
cache.set(url, data);
callback(null, url, data);
},
error: function(jqXHR, textStatus, err) {
callback(new JsonLdError(
'URL could not be dereferenced, an error occurred.',
'jsonld.LoadContextError', {url: url, cause: err}), url);
}
});
};
};
/**
* The built-in node context loader.
*
* @param options the options to use:
* secure: require all URLs to use HTTPS.
* maxRedirects: the maximum number of redirects to permit, none by
* default.
*
* @return the node context loader.
*/
jsonld.contextLoaders['node'] = function(options) {
options = options || {};
var maxRedirects = ('maxRedirects' in options) ? options.maxRedirects : -1;
var request = require('request');
var http = require('http');
var cache = new jsonld.ContextCache();
function loadContext(url, redirects, callback) {
if(options.secure && url.indexOf('https') !== 0) {
return callback(new JsonLdError(
'URL could not be dereferenced; secure mode is enabled and ' +
'the URL\'s scheme is not "https".',
'jsonld.InvalidUrl', {url: url}), url);
}
var ctx = cache.get(url);
if(ctx !== null) {
return callback(null, url, ctx);
}
request({
url: url,
strictSSL: true,
followRedirect: false
}, function(err, res, body) {
// handle error
if(err) {
return callback(new JsonLdError(
'URL could not be dereferenced, an error occurred.',
'jsonld.LoadContextError', {url: url, cause: err}), url);
}
var statusText = http.STATUS_CODES[res.statusCode];
if(res.statusCode >= 400) {
return callback(new JsonLdError(
'URL could not be dereferenced: ' + statusText,
'jsonld.InvalidUrl', {url: url, httpStatusCode: res.statusCode}),
url);
}
// handle redirect
if(res.statusCode >= 300 && res.statusCode < 400 &&
res.headers.location) {
if(redirects.length === maxRedirects) {
return callback(new JsonLdError(
'URL could not be dereferenced; there were too many redirects.',
'jsonld.TooManyRedirects',
{url: url, httpStatusCode: res.statusCode, redirects: redirects}),
url);
}
if(redirects.indexOf(url) !== -1) {
return callback(new JsonLdError(
'URL could not be dereferenced; infinite redirection was detected.',
'jsonld.InfiniteRedirectDetected',
{url: url, httpStatusCode: res.statusCode, redirects: redirects}),
url);
}
redirects.push(url);
return loadContext(res.headers.location, redirects, callback);
}
// cache for each redirected URL
redirects.push(url);
for(var i = 0; i < redirects.length; ++i) {
cache.set(redirects[i], body);
}
callback(err, url, body);
});
}
return function(url, callback) {
loadContext(url, [], callback);
};
};
/**
* Assigns the default context loader for external @context URLs to a built-in
* default. Supported types currently include: 'jquery'.
*
* To use the jquery context loader, the 'data' parameter must be a reference
* to the main jquery object.
*
* @param type the type to set.
* @param [params] the parameters required to use the context loader.
*/
jsonld.useContextLoader = function(type) {
if(!(type in jsonld.contextLoaders)) {
throw new JsonLdError(
'Unknown @context loader type: "' + type + '"',
'jsonld.UnknownContextLoader',
{type: type});
}
// set context loader
jsonld.loadContext = jsonld.contextLoaders[type].apply(
jsonld, Array.prototype.slice.call(arguments, 1));
};
/**
* Processes a local context, resolving any URLs as necessary, and returns a
* new active context in its callback.
*
* @param activeCtx the current active context.
* @param localCtx the local context to process.
* @param [options] the options to use:
* [loadContext(url, callback(err, url, result))] the context loader.
* @param callback(err, ctx) called once the operation completes.
*/
jsonld.processContext = function(activeCtx, localCtx) {
// get arguments
var options = {};
var callbackArg = 2;
if(arguments.length > 3) {
options = arguments[2] || {};
callbackArg += 1;
}
var callback = arguments[callbackArg];
// set default options
if(!('base' in options)) {
options.base = '';
}
if(!('loadContext' in options)) {
options.loadContext = jsonld.loadContext;
}
// return initial context early for null context
if(localCtx === null) {
return callback(null, _getInitialContext(options));
}
// retrieve URLs in localCtx
localCtx = _clone(localCtx);
if(_isObject(localCtx) && !('@context' in localCtx)) {
localCtx = {'@context': localCtx};
}
_retrieveContextUrls(localCtx, options, function(err, ctx) {
if(err) {
return callback(err);
}
try {
// process context
ctx = new Processor().processContext(activeCtx, ctx, options);
callback(null, ctx);
}
catch(ex) {
callback(ex);
}
});
};
/**
* Returns true if the given subject has the given property.
*
* @param subject the subject to check.
* @param property the property to look for.
*
* @return true if the subject has the given property, false if not.
*/
jsonld.hasProperty = function(subject, property) {
var rval = false;
if(property in subject) {
var value = subject[property];
rval = (!_isArray(value) || value.length > 0);
}
return rval;
};
/**
* Determines if the given value is a property of the given subject.
*
* @param subject the subject to check.
* @param property the property to check.
* @param value the value to check.
*
* @return true if the value exists, false if not.
*/
jsonld.hasValue = function(subject, property, value) {
var rval = false;
if(jsonld.hasProperty(subject, property)) {
var val = subject[property];
var isList = _isList(val);
if(_isArray(val) || isList) {
if(isList) {
val = val['@list'];
}
for(var i in val) {
if(jsonld.compareValues(value, val[i])) {
rval = true;
break;
}
}
}
// avoid matching the set of values with an array value parameter
else if(!_isArray(value)) {
rval = jsonld.compareValues(value, val);
}
}
return rval;
};
/**
* Adds a value to a subject. If the value is an array, all values in the
* array will be added.
*
* @param subject the subject to add the value to.
* @param property the property that relates the value to the subject.
* @param value the value to add.
* @param [options] the options to use:
* [propertyIsArray] true if the property is always an array, false
* if not (default: false).
* [allowDuplicate] true to allow duplicates, false not to (uses a
* simple shallow comparison of subject ID or value) (default: true).
*/
jsonld.addValue = function(subject, property, value, options) {
options = options || {};
if(!('propertyIsArray' in options)) {
options.propertyIsArray = false;
}
if(!('allowDuplicate' in options)) {
options.allowDuplicate = true;
}
if(_isArray(value)) {
if(value.length === 0 && options.propertyIsArray &&
!(property in subject)) {
subject[property] = [];
}
for(var i in value) {
jsonld.addValue(subject, property, value[i], options);
}
}
else if(property in subject) {
// check if subject already has value if duplicates not allowed
var hasValue = (!options.allowDuplicate &&
jsonld.hasValue(subject, property, value));
// make property an array if value not present or always an array
if(!_isArray(subject[property]) &&
(!hasValue || options.propertyIsArray)) {
subject[property] = [subject[property]];
}
// add new value
if(!hasValue) {
subject[property].push(value);
}
}
else {
// add new value as set or single value
subject[property] = options.propertyIsArray ? [value] : value;
}
};
/**
* Gets all of the values for a subject's property as an array.
*
* @param subject the subject.
* @param property the property.
*
* @return all of the values for a subject's property as an array.
*/
jsonld.getValues = function(subject, property) {
var rval = subject[property] || [];
if(!_isArray(rval)) {
rval = [rval];
}
return rval;
};
/**
* Removes a property from a subject.
*
* @param subject the subject.
* @param property the property.
*/
jsonld.removeProperty = function(subject, property) {
delete subject[property];
};
/**
* Removes a value from a subject.
*
* @param subject the subject.
* @param property the property that relates the value to the subject.
* @param value the value to remove.
* @param [options] the options to use:
* [propertyIsArray] true if the property is always an array, false
* if not (default: false).
*/
jsonld.removeValue = function(subject, property, value, options) {
options = options || {};
if(!('propertyIsArray' in options)) {
options.propertyIsArray = false;
}
// filter out value
var values = jsonld.getValues(subject, property).filter(function(e) {
return !jsonld.compareValues(e, value);
});
if(values.length === 0) {
jsonld.removeProperty(subject, property);
}
else if(values.length === 1 && !options.propertyIsArray) {
subject[property] = values[0];
}
else {
subject[property] = values;
}
};
/**
* Compares two JSON-LD values for equality. Two JSON-LD values will be
* considered equal if:
*
* 1. They are both primitives of the same type and value.
* 2. They are both @values with the same @value, @type, @language,
* and @index, OR
* 3. They are both @lists with the same @list and @index, OR
* 4. They both have @ids they are the same.
*
* @param v1 the first value.
* @param v2 the second value.
*
* @return true if v1 and v2 are considered equal, false if not.
*/
jsonld.compareValues = function(v1, v2) {
// 1. equal primitives
if(v1 === v2) {
return true;
}
// 2. equal @values
if(_isValue(v1) && _isValue(v2) &&
v1['@value'] === v2['@value'] &&
v1['@type'] === v2['@type'] &&
v1['@language'] === v2['@language'] &&
v1['@index'] === v2['@index']) {
return true;
}
// 3. equal @lists
if(_isList(v1) && _isList(v2)) {
if(v1['@index'] !== v2['@index']) {
return false;
}
var list1 = v1['@list'];
var list2 = v2['@list'];
if(list1.length !== list2.length) {
return false;
}
for(var i = 0; i < list1.length; ++i) {
if(!jsonld.compareValues(list1[i], list2[i])) {
return false;
}
}
return true;
}
// 4. equal @ids
if(_isObject(v1) && ('@id' in v1) && _isObject(v2) && ('@id' in v2)) {
return v1['@id'] === v2['@id'];
}
return false;
};
/**
* Gets the value for the given active context key and type, null if none is
* set.
*
* @param ctx the active context.
* @param key the context key.
* @param [type] the type of value to get (eg: '@id', '@type'), if not
* specified gets the entire entry for a key, null if not found.
*
* @return the value.
*/
jsonld.getContextValue = function(ctx, key, type) {
var rval = null;
// return null for invalid key
if(key === null) {
return rval;
}
// get default language
if(type === '@language' && (type in ctx)) {
rval = ctx[type];
}
// get specific entry information
if(ctx.mappings[key]) {
var entry = ctx.mappings[key];
// return whole entry
if(_isUndefined(type)) {
rval = entry;
}
// return entry value for type
else if(type in entry) {
rval = entry[type];
}
}
return rval;
};
/** Registered RDF dataset parsers hashed by content-type. */
var _rdfParsers = {};
/**
* Registers an RDF dataset parser by content-type, for use with
* jsonld.fromRDF.
*
* @param contentType the content-type for the parser.
* @param parser(input) the parser function (takes a string as a parameter
* and returns an RDF dataset).
*/
jsonld.registerRDFParser = function(contentType, parser) {
_rdfParsers[contentType] = parser;
};
/**
* Unregisters an RDF dataset parser by content-type.
*
* @param contentType the content-type for the parser.
*/
jsonld.unregisterRDFParser = function(contentType) {
delete _rdfParsers[contentType];
};
if(_nodejs) {
// needed for serialization of XML literals
if(typeof XMLSerializer === 'undefined') {
var XMLSerializer = null;
}
if(typeof Node === 'undefined') {
var Node = {
ELEMENT_NODE: 1,
ATTRIBUTE_NODE: 2,
TEXT_NODE: 3,
CDATA_SECTION_NODE: 4,
ENTITY_REFERENCE_NODE: 5,
ENTITY_NODE: 6,
PROCESSING_INSTRUCTION_NODE: 7,
COMMENT_NODE: 8,
DOCUMENT_NODE: 9,
DOCUMENT_TYPE_NODE: 10,
DOCUMENT_FRAGMENT_NODE: 11,
NOTATION_NODE:12
};
}
}
// constants
var XSD_BOOLEAN = 'http://www.w3.org/2001/XMLSchema#boolean';
var XSD_DOUBLE = 'http://www.w3.org/2001/XMLSchema#double';
var XSD_INTEGER = 'http://www.w3.org/2001/XMLSchema#integer';
var XSD_STRING = 'http://www.w3.org/2001/XMLSchema#string';
var RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
var RDF_FIRST = RDF + 'first';
var RDF_REST = RDF + 'rest';
var RDF_NIL = RDF + 'nil';
var RDF_TYPE = RDF + 'type';
var RDF_PLAIN_LITERAL = RDF + 'PlainLiteral';
var RDF_XML_LITERAL = RDF + 'XMLLiteral';
var RDF_OBJECT = RDF + 'object';
var RDF_LANGSTRING = RDF + 'langString';
var MAX_CONTEXT_URLS = 10;
/**
* A JSON-LD Error.
*
* @param msg the error message.
* @param type the error type.
* @param details the error details.
*/
var JsonLdError = function(msg, type, details) {
if(_nodejs) {
Error.call(this);
Error.captureStackTrace(this, this.constructor);
}
this.name = type || 'jsonld.Error';
this.message = msg || 'An unspecified JSON-LD error occurred.';
this.details = details || {};
};
if(_nodejs) {
require('util').inherits(JsonLdError, Error);
}
/**
* Constructs a new JSON-LD Processor.
*/
var Processor = function() {};
/**
* Recursively compacts an element using the given active context. All values
* must be in expanded form before this method is called.
*
* @param activeCtx the active context to use.
* @param activeProperty the compacted property associated with the element
* to compact, null for none.
* @param element the element to compact.
* @param options the compaction options.
*
* @return the compacted value.
*/
Processor.prototype.compact = function(
activeCtx, activeProperty, element, options) {
// recursively compact array
if(_isArray(element)) {
var rval = [];
for(var i in element) {
// compact, dropping any null values
var compacted = this.compact(
activeCtx, activeProperty, element[i], options);
if(compacted !== null) {
rval.push(compacted);
}
}
if(options.compactArrays && rval.length === 1) {
// use single element if no container is specified
var container = jsonld.getContextValue(
activeCtx, activeProperty, '@container');
if(container === null) {
rval = rval[0];
}
}
return rval;
}
// recursively compact object
if(_isObject(element)) {
// do value compaction on @values and subject references
if(_isValue(element) || _isSubjectReference(element)) {
return _compactValue(activeCtx, activeProperty, element);
}
// shallow copy element and arrays so keys and values can be removed
// during property generator compaction
var shallow = {};
for(var expandedProperty in element) {
if(_isArray(element[expandedProperty])) {
shallow[expandedProperty] = element[expandedProperty].slice();
}
else {
shallow[expandedProperty] = element[expandedProperty];
}
}
element = shallow;
// process element keys in order
var keys = Object.keys(element).sort();
var rval = {};
for(var ki = 0; ki < keys.length; ++ki) {
var expandedProperty = keys[ki];
// skip key if removed during property generator duplicate handling
if(!(expandedProperty in element)) {
continue;
}
var expandedValue = element[expandedProperty];
// compact @id and @type(s)
if(expandedProperty === '@id' || expandedProperty === '@type') {
var compactedValue;
// compact single @id
if(_isString(expandedValue)) {
compactedValue = _compactIri(
activeCtx, expandedValue, null,
{vocab: (expandedProperty === '@type')});
}
// expanded value must be a @type array
else {
compactedValue = [];
for(var vi = 0; vi < expandedValue.length; ++vi) {
compactedValue.push(_compactIri(
activeCtx, expandedValue[vi], null, {vocab: true}));
}
}
// use keyword alias and add value
var alias = _compactIri(activeCtx, expandedProperty);
var isArray = (_isArray(compactedValue) && expandedValue.length === 0);
jsonld.addValue(
rval, alias, compactedValue, {propertyIsArray: isArray});
continue;
}
// handle @index property
if(expandedProperty === '@index') {
// drop @index if inside an @index container
var container = jsonld.getContextValue(
activeCtx, activeProperty, '@container');
if(container === '@index') {
continue;
}
// use keyword alias and add value
var alias = _compactIri(activeCtx, expandedProperty);
jsonld.addValue(rval, alias, expandedValue);
continue;
}
// Note: expanded value must be an array due to expansion algorithm.
// preserve empty arrays
if(expandedValue.length === 0) {
var itemActiveProperty = _compactIri(
activeCtx, expandedProperty, expandedValue, {vocab: true}, element);
jsonld.addValue(
rval, itemActiveProperty, expandedValue, {propertyIsArray: true});
}
// recusively process array values
for(var vi = 0; vi < expandedValue.length; ++vi) {
var expandedItem = expandedValue[vi];
// compact property and get container type
var itemActiveProperty = _compactIri(
activeCtx, expandedProperty, expandedItem, {vocab: true}, element);
var container = jsonld.getContextValue(
activeCtx, itemActiveProperty, '@container');
// remove any duplicates that were (presumably) generated by a
// property generator
var mapping = activeCtx.mappings[itemActiveProperty];
if(mapping && mapping.propertyGenerator) {
_findPropertyGeneratorDuplicates(
activeCtx, element, expandedProperty, expandedItem,
itemActiveProperty, true);
}
// get @list value if appropriate
var isList = _isList(expandedItem);
var list = null;
if(isList) {
list = expandedItem['@list'];
}
// recursively compact expanded item
var compactedItem = this.compact(
activeCtx, itemActiveProperty, isList ? list : expandedItem, options);
// handle @list
if(isList) {
// ensure @list value is an array
if(!_isArray(compactedItem)) {
compactedItem = [compactedItem];
}
if(container !== '@list') {
// wrap using @list alias
var wrapper = {};
wrapper[_compactIri(activeCtx, '@list')] = compactedItem;
compactedItem = wrapper;
// include @index from expanded @list, if any
if('@index' in expandedItem) {
compactedItem[_compactIri(activeCtx, '@index')] =
expandedItem['@index'];
}
}
// can't use @list container for more than 1 list
else if(itemActiveProperty in rval) {
throw new JsonLdError(
'JSON-LD compact error; property has a "@list" @container ' +
'rule but there is more than a single @list that matches ' +
'the compacted term in the document. Compaction might mix ' +
'unwanted items into the list.',
'jsonld.SyntaxError');
}
}
// handle language and index maps
if(container === '@language' || container === '@index') {
// get or create the map object
var mapObject;
if(itemActiveProperty in rval) {
mapObject = rval[itemActiveProperty];
}
else {
rval[itemActiveProperty] = mapObject = {};
}
// if container is a language map, simplify compacted value to
// a simple string
if(container === '@language' && _isValue(compactedItem)) {
compactedItem = compactedItem['@value'];
}
// add compact value to map object using key from expanded value
// based on the container type
jsonld.addValue(mapObject, expandedItem[container], compactedItem);
}
else {
// use an array if: compactArrays flag is false,
// @container is @set or @list , value is an empty
// array, or key is @graph
var isArray = (!options.compactArrays || container === '@set' ||
container === '@list' ||
(_isArray(compactedItem) && compactedItem.length === 0) ||
expandedProperty === '@list' || expandedProperty === '@graph');
// add compact value
jsonld.addValue(
rval, itemActiveProperty, compactedItem,
{propertyIsArray: isArray});
}
}
}
return rval;
}
// only primitives remain which are already compact
return element;
};
/**
* Recursively expands an element using the given context. Any context in
* the element will be removed. All context URLs must have been retrieved
* before calling this method.
*
* @param activeCtx the context to use.
* @param activeProperty the property for the element, null for none.
* @param element the element to expand.
* @param options the expansion options.
* @param insideList true if the element is a list, false if not.
*
* @return the expanded value.
*/
Processor.prototype.expand = function(
activeCtx, activeProperty, element, options, insideList) {
var self = this;
if(typeof element === 'undefined') {
throw new JsonLdError(
'Invalid JSON-LD syntax; undefined element.',
'jsonld.SyntaxError');
}
// nothing to expand
if(element === null) {
return null;
}
// recursively expand array
if(_isArray(element)) {
var rval = [];
for(var i in element) {
// expand element
var e = self.expand(
activeCtx, activeProperty, element[i], options, insideList);
if(insideList && (_isArray(e) || _isList(e))) {
// lists of lists are illegal
throw new JsonLdError(
'Invalid JSON-LD syntax; lists of lists are not permitted.',
'jsonld.SyntaxError');
}
// drop null values
else if(e !== null) {
if(_isArray(e)) {
rval = rval.concat(e);
}
else {
rval.push(e);
}
}
}
return rval;
}
// recursively expand object
if(_isObject(element)) {
// if element has a context, process it
if('@context' in element) {
activeCtx = self.processContext(activeCtx, element['@context'], options);
}
// expand the active property
var expandedActiveProperty = _expandIri(
activeCtx, activeProperty, {vocab: true});
var rval = {};
var keys = Object.keys(element).sort();
for(var ki = 0; ki < keys.length; ++ki) {
var key = keys[ki];
var value = element[key];
var expandedProperty;
var expandedValue;
// skip @context
if(key === '@context') {
continue;
}
// expand key using property generator
var mapping = activeCtx.mappings[key];
if(mapping && mapping.propertyGenerator) {
expandedProperty = mapping['@id'];
}
// expand key to IRI
else {
expandedProperty = _expandIri(activeCtx, key, {vocab: true});
}
// drop non-absolute IRI keys that aren't keywords
if(expandedProperty === null ||
!(_isArray(expandedProperty) ||
_isAbsoluteIri(expandedProperty) ||
_isKeyword(expandedProperty))) {
continue;
}
// syntax error if @id is not a string
if(expandedProperty === '@id' && !_isString(value)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; "@id" value must a string.',
'jsonld.SyntaxError', {value: value});
}
// validate @type value
if(expandedProperty === '@type') {
_validateTypeValue(value);
}
// @graph must be an array or an object
if(expandedProperty === '@graph' &&
!(_isObject(value) || _isArray(value))) {
throw new JsonLdError(
'Invalid JSON-LD syntax; "@value" value must not be an ' +
'object or an array.',
'jsonld.SyntaxError', {value: value});
}
// @value must not be an object or an array
if(expandedProperty === '@value' &&
(_isObject(value) || _isArray(value))) {
throw new JsonLdError(
'Invalid JSON-LD syntax; "@value" value must not be an ' +
'object or an array.',
'jsonld.SyntaxError', {value: value});
}
// @language must be a string
if(expandedProperty === '@language') {
if(!_isString(value)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; "@language" value must be a string.',
'jsonld.SyntaxError', {value: value});
}
// ensure language value is lowercase
value = value.toLowerCase();
}
// preserve @index
if(expandedProperty === '@index') {
if(!_isString(value)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; "@index" value must be a string.',
'jsonld.SyntaxError', {value: value});
}
}
var container = jsonld.getContextValue(activeCtx, key, '@container');
// handle language map container (skip if value is not an object)
if(container === '@language' && _isObject(value)) {
expandedValue = _expandLanguageMap(value);
}
// handle index container (skip if value is not an object)
else if(container === '@index' && _isObject(value)) {
expandedValue = (function _expandIndexMap(activeProperty) {
var rval = [];
var keys = Object.keys(value).sort();
for(var ki = 0; ki < keys.length; ++ki) {
var key = keys[ki];
var val = value[key];
if(!_isArray(val)) {
val = [val];
}
val = self.expand(activeCtx, activeProperty, val, options, false);
for(var vi = 0; vi < val.length; ++vi) {
var item = val[vi];
if(!('@index' in item)) {
item['@index'] = key;
}
rval.push(item);
}
}
return rval;
})(key);
}
else {
// recurse into @list or @set
var isList = (expandedProperty === '@list');
if(isList || expandedProperty === '@set') {
var nextActiveProperty = activeProperty;
if(isList && expandedActiveProperty === '@graph') {
nextActiveProperty = null;
}
expandedValue = self.expand(
activeCtx, nextActiveProperty, value, options, isList);
if(isList && _isList(expandedValue)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; lists of lists are not permitted.',
'jsonld.SyntaxError');
}
}
else {
// recursively expand value with key as new active property
expandedValue = self.expand(activeCtx, key, value, options, false);
}
}
// drop null values if property is not @value
if(expandedValue === null && expandedProperty !== '@value') {
continue;
}
// convert expanded value to @list if container specifies it
if(expandedProperty !== '@list' && !_isList(expandedValue) &&
container === '@list') {
// ensure expanded value is an array
expandedValue = (_isArray(expandedValue) ?
expandedValue : [expandedValue]);
expandedValue = {'@list': expandedValue};
}
// add copy of value for each property from property generator
if(_isArray(expandedProperty)) {
expandedValue = _labelBlankNodes(activeCtx.namer, expandedValue);
for(var i = 0; i < expandedProperty.length; ++i) {
jsonld.addValue(
rval, expandedProperty[i], _clone(expandedValue),
{propertyIsArray: true});
}
}
// add value for property
else {
// use an array except for certain keywords
var useArray =
['@index', '@id', '@type', '@value', '@language'].indexOf(
expandedProperty) === -1;
jsonld.addValue(
rval, expandedProperty, expandedValue, {propertyIsArray: useArray});
}
}
// get property count on expanded output
keys = Object.keys(rval);
var count = keys.length;
if('@value' in rval) {
// @value must only have @language or @type
if('@type' in rval && '@language' in rval) {
throw new JsonLdError(
'Invalid JSON-LD syntax; an element containing "@value" may not ' +
'contain both "@type" and "@language".',
'jsonld.SyntaxError', {element: rval});
}
var validCount = count - 1;
if('@type' in rval) {
validCount -= 1;
}
if('@index' in rval) {
validCount -= 1;
}
if('@language' in rval) {
validCount -= 1;
}
if(validCount !== 0) {
throw new JsonLdError(
'Invalid JSON-LD syntax; an element containing "@value" may only ' +
'have an "@index" property and at most one other property ' +
'which can be "@type" or "@language".',
'jsonld.SyntaxError', {element: rval});
}
// drop null @values
if(rval['@value'] === null) {
rval = null;
}
// drop @language if @value isn't a string
else if('@language' in rval && !_isString(rval['@value'])) {
delete rval['@language'];
}
}
// convert @type to an array
else if('@type' in rval && !_isArray(rval['@type'])) {
rval['@type'] = [rval['@type']];
}
// handle @set and @list
else if('@set' in rval || '@list' in rval) {
if(count > 1 && (count !== 2 && '@index' in rval)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; if an element has the property "@set" ' +
'or "@list", then it can have at most one other property that is ' +
'"@index".',
'jsonld.SyntaxError', {element: rval});
}
// optimize away @set
if('@set' in rval) {
rval = rval['@set'];
keys = Object.keys(rval);
count = keys.length;
}
}
// drop objects with only @language
else if(count === 1 && '@language' in rval) {
rval = null;
}
// drop certain top-level objects that do not occur in lists
if(_isObject(rval) &&
!options.keepFreeFloatingNodes && !insideList &&
(activeProperty === null || expandedActiveProperty === '@graph')) {
// drop empty object or top-level @value
if(count === 0 || ('@value' in rval)) {
rval = null;
}
else {
// drop nodes that generate no triples
var hasTriples = false;
var ignore = ['@graph', '@type'];
for(var ki = 0; !hasTriples && ki < keys.length; ++ki) {
if(!_isKeyword(keys[ki]) || ignore.indexOf(keys[ki]) !== -1) {
hasTriples = true;
}
}
if(!hasTriples) {
rval = null;
}
}
}
return rval;
}
// drop top-level scalars that are not in lists
if(!insideList &&
(activeProperty === null ||
_expandIri(activeCtx, activeProperty, {vocab: true}) === '@graph')) {
return null;
}
// expand element according to value expansion rules
return _expandValue(activeCtx, activeProperty, element);
};
/**
* Performs JSON-LD flattening.
*
* @param input the expanded JSON-LD to flatten.
*
* @return the flattened output.
*/
Processor.prototype.flatten = function(input) {
// produce a map of all subjects and name each bnode
var namer = new UniqueNamer('_:b');
var graphs = {'@default': {}};
_createNodeMap(input, graphs, '@default', namer);
// add all non-default graphs to default graph
var defaultGraph = graphs['@default'];
var graphNames = Object.keys(graphs).sort();
for(var i = 0; i < graphNames.length; ++i) {
var graphName = graphNames[i];
if(graphName === '@default') {
continue;
}
var nodeMap = graphs[graphName];
var subject = defaultGraph[graphName];
if(!subject) {
defaultGraph[graphName] = subject = {
'@id': graphName,
'@graph': []
};
}
else if(!('@graph' in subject)) {
subject['@graph'] = [];
}
var graph = subject['@graph'];
var ids = Object.keys(nodeMap).sort();
for(var ii = 0; ii < ids.length; ++ii) {
var id = ids[ii];
graph.push(nodeMap[id]);
}
}
// produce flattened output
var flattened = [];
var keys = Object.keys(defaultGraph).sort();
for(var ki = 0; ki < keys.length; ++ki) {
var key = keys[ki];
flattened.push(defaultGraph[key]);
}
return flattened;
};
/**
* Performs JSON-LD framing.
*
* @param input the expanded JSON-LD to frame.
* @param frame the expanded JSON-LD frame to use.
* @param options the framing options.
*
* @return the framed output.
*/
Processor.prototype.frame = function(input, frame, options) {
// create framing state
var state = {
options: options,
graphs: {'@default': {}, '@merged': {}}
};
// produce a map of all graphs and name each bnode
// FIXME: currently uses subjects from @merged graph only
namer = new UniqueNamer('_:b');
_createNodeMap(input, state.graphs, '@merged', namer);
state.subjects = state.graphs['@merged'];
// frame the subjects
var framed = [];
_frame(state, Object.keys(state.subjects).sort(), frame, framed, null);
return framed;
};
/**
* Performs normalization on the given RDF dataset.
*
* @param dataset the RDF dataset to normalize.
* @param options the normalization options.
* @param callback(err, normalized) called once the operation completes.
*/
Processor.prototype.normalize = function(dataset, options, callback) {
// create quads and map bnodes to their associated quads
var quads = [];
var bnodes = {};
for(var graphName in dataset) {
var triples = dataset[graphName];
if(graphName === '@default') {
graphName = null;
}
for(var ti = 0; ti < triples.length; ++ti) {
var quad = triples[ti];
if(graphName !== null) {
if(graphName.indexOf('_:') === 0) {
quad.name = {type: 'blank node', value: graphName};
}
else {
quad.name = {type: 'IRI', value: graphName};
}
}
quads.push(quad);
var attrs = ['subject', 'object', 'name'];
for(var ai = 0; ai < attrs.length; ++ai) {
var attr = attrs[ai];
if(quad[attr] && quad[attr].type === 'blank node') {
var id = quad[attr].value;
if(id in bnodes) {
bnodes[id].quads.push(quad);
}
else {
bnodes[id] = {quads: [quad]};
}
}
}
}
}
// mapping complete, start canonical naming
var namer = new UniqueNamer('_:c14n');
return hashBlankNodes(Object.keys(bnodes));
// generates unique and duplicate hashes for bnodes
function hashBlankNodes(unnamed) {
var nextUnnamed = [];
var duplicates = {};
var unique = {};
// hash quads for each unnamed bnode
jsonld.nextTick(function() {hashUnnamed(0);});
function hashUnnamed(i) {
if(i === unnamed.length) {
// done, name blank nodes
return nameBlankNodes(unique, duplicates, nextUnnamed);
}
// hash unnamed bnode
var bnode = unnamed[i];
var hash = _hashQuads(bnode, bnodes, namer);
// store hash as unique or a duplicate
if(hash in duplicates) {
duplicates[hash].push(bnode);
nextUnnamed.push(bnode);
}
else if(hash in unique) {
duplicates[hash] = [unique[hash], bnode];
nextUnnamed.push(unique[hash]);
nextUnnamed.push(bnode);
delete unique[hash];
}
else {
unique[hash] = bnode;
}
// hash next unnamed bnode
jsonld.nextTick(function() {hashUnnamed(i + 1);});
}
}
// names unique hash bnodes
function nameBlankNodes(unique, duplicates, unnamed) {
// name unique bnodes in sorted hash order
var named = false;
var hashes = Object.keys(unique).sort();
for(var i = 0; i < hashes.length; ++i) {
var bnode = unique[hashes[i]];
namer.getName(bnode);
named = true;
}
// continue to hash bnodes if a bnode was assigned a name
if(named) {
hashBlankNodes(unnamed);
}
// name the duplicate hash bnodes
else {
nameDuplicates(duplicates);
}
}
// names duplicate hash bnodes
function nameDuplicates(duplicates) {
// enumerate duplicate hash groups in sorted order
var hashes = Object.keys(duplicates).sort();
// process each group
processGroup(0);
function processGroup(i) {
if(i === hashes.length) {
// done, create JSON-LD array
return createArray();
}
// name each group member
var group = duplicates[hashes[i]];
var results = [];
nameGroupMember(group, 0);
function nameGroupMember(group, n) {
if(n === group.length) {
// name bnodes in hash order
results.sort(function(a, b) {
a = a.hash;
b = b.hash;
return (a < b) ? -1 : ((a > b) ? 1 : 0);
});
for(var r in results) {
// name all bnodes in path namer in key-entry order
// Note: key-order is preserved in javascript
for(var key in results[r].pathNamer.existing) {
namer.getName(key);
}
}
return processGroup(i + 1);
}
// skip already-named bnodes
var bnode = group[n];
if(namer.isNamed(bnode)) {
return nameGroupMember(group, n + 1);
}
// hash bnode paths
var pathNamer = new UniqueNamer('_:b');
pathNamer.getName(bnode);
_hashPaths(bnode, bnodes, namer, pathNamer,
function(err, result) {
if(err) {
return callback(err);
}
results.push(result);
nameGroupMember(group, n + 1);
});
}
}
}
// creates the sorted array of RDF quads
function createArray() {
var normalized = [];
/* Note: At this point all bnodes in the set of RDF quads have been
assigned canonical names, which have been stored in the 'namer' object.
Here each quad is updated by assigning each of its bnodes its new name
via the 'namer' object. */
// update bnode names in each quad and serialize
for(var i = 0; i < quads.length; ++i) {
var quad = quads[i];
var attrs = ['subject', 'object', 'name'];
for(var ai = 0; ai < attrs.length; ++ai) {
var attr = attrs[ai];
if(quad[attr] && quad[attr].type === 'blank node' &&
quad[attr].value.indexOf('_:c14n') !== 0) {
quad[attr].value = namer.getName(quad[attr].value);
}
}
normalized.push(_toNQuad(quad, quad.name ? quad.name.value : null));
}
// sort normalized output
normalized.sort();
// handle output format
if(options.format) {
if(options.format === 'application/nquads') {
return callback(null, normalized.join(''));
}
return callback(new JsonLdError(
'Unknown output format.',
'jsonld.UnknownFormat', {format: options.format}));
}
// output RDF dataset
callback(null, _parseNQuads(normalized.join('')));
}
};
/**
* Converts an RDF dataset to JSON-LD.
*
* @param dataset the RDF dataset.
* @param options the RDF conversion options.
* @param callback(err, output) called once the operation completes.
*/
Processor.prototype.fromRDF = function(dataset, options, callback) {
// prepare graph map (maps graph name => subjects, lists)
var defaultGraph = {subjects: {}, listMap: {}};
var graphs = {'@default': defaultGraph};
for(var graphName in dataset) {
var triples = dataset[graphName];
for(var ti = 0; ti < triples.length; ++ti) {
var triple = triples[ti];
// get subject, predicate, object
var s = triple.subject.value;
var p = triple.predicate.value;
var o = triple.object;
// create a graph entry as needed
var graph;
if(!(graphName in graphs)) {
graph = graphs[graphName] = {subjects: {}, listMap: {}};
}
else {
graph = graphs[graphName];
}
// handle element in @list
if(p === RDF_FIRST) {
// create list entry as needed
var listMap = graph.listMap;
var entry;
if(!(s in listMap)) {
entry = listMap[s] = {};
}
else {
entry = listMap[s];
}
// set object value
entry.first = _RDFToObject(o, options.useNativeTypes);
continue;
}
// handle other element in @list
if(p === RDF_REST) {
// set next in list
if(o.type === 'blank node') {
// create list entry as needed
var listMap = graph.listMap;
var entry;
if(!(s in listMap)) {
entry = listMap[s] = {};
}
else {
entry = listMap[s];
}
entry.rest = o.value;
}
continue;
}
// add graph subject to default graph as needed
if(graphName !== '@default' && !(graphName in defaultGraph.subjects)) {
defaultGraph.subjects[graphName] = {'@id': graphName};
}
// add subject to graph as needed
var subjects = graph.subjects;
var value;
if(!(s in subjects)) {
value = subjects[s] = {'@id': s};
}
// use existing subject value
else {
value = subjects[s];
}
// convert to @type unless options indicate to treat rdf:type as property
if(p === RDF_TYPE && !options.useRdfType) {
// add value of object as @type
jsonld.addValue(value, '@type', o.value, {propertyIsArray: true});
}
else {
// add property to value as needed
var object = _RDFToObject(o, options.useNativeTypes);
jsonld.addValue(value, p, object, {propertyIsArray: true});
// a bnode might be the beginning of a list, so add it to the list map
if(o.type === 'blank node') {
var id = object['@id'];
var listMap = graph.listMap;
var entry;
if(!(id in listMap)) {
entry = listMap[id] = {};
}
else {
entry = listMap[id];
}
entry.head = object;
}
}
}
}
// build @lists
for(var graphName in graphs) {
var graph = graphs[graphName];
// find list head
var listMap = graph.listMap;
for(var subject in listMap) {
var entry = listMap[subject];
// head found, build lists
if('head' in entry && 'first' in entry) {
// replace bnode @id with @list
delete entry.head['@id'];
var list = entry.head['@list'] = [entry.first];
while('rest' in entry) {
var rest = entry.rest;
entry = listMap[rest];
if(!('first' in entry)) {
throw new JsonLdError(
'Invalid RDF list entry.',
'jsonld.RdfError', {bnode: rest});
}
list.push(entry.first);
}
}
}
}
// build default graph in subject @id order
var output = [];
var subjects = defaultGraph.subjects;
var ids = Object.keys(subjects).sort();
for(var i = 0; i < ids.length; ++i) {
var id = ids[i];
// add subject to default graph
var subject = subjects[id];
output.push(subject);
// output named graph in subject @id order
if(id in graphs) {
var graph = subject['@graph'] = [];
var subjects_ = graphs[id].subjects;
var ids_ = Object.keys(subjects_).sort();
for(var i_ = 0; i_ < ids_.length; ++i_) {
graph.push(subjects_[ids_[i_]]);
}
}
}
callback(null, output);
};
/**
* Adds RDF triples for each graph in the given node map to an RDF dataset.
*
* @param nodeMap the node map.
*
* @return the RDF dataset.
*/
Processor.prototype.toRDF = function(nodeMap) {
var namer = new UniqueNamer('_:b');
var dataset = {};
for(var graphName in nodeMap) {
var graph = nodeMap[graphName];
if(graphName.indexOf('_:') === 0) {
graphName = namer.getName(graphName);
}
dataset[graphName] = _graphToRDF(graph, namer);
}
return dataset;
};
/**
* Processes a local context and returns a new active context.
*
* @param activeCtx the current active context.
* @param localCtx the local context to process.
* @param options the context processing options.
*
* @return the new active context.
*/
Processor.prototype.processContext = function(activeCtx, localCtx, options) {
var rval = null;
// get context from cache if available
if(jsonld.cache.activeCtx) {
rval = jsonld.cache.activeCtx.get(activeCtx, localCtx);
if(rval) {
rval.namer = activeCtx.namer;
return rval;
}
}
// initialize the resulting context
rval = activeCtx.clone();
// normalize local context to an array of @context objects
if(_isObject(localCtx) && '@context' in localCtx &&
_isArray(localCtx['@context'])) {
localCtx = localCtx['@context'];
}
var ctxs = _isArray(localCtx) ? localCtx : [localCtx];
// process each context in order
for(var i in ctxs) {
var ctx = ctxs[i];
// reset to initial context, keeping namer
if(ctx === null) {
rval = _getInitialContext(options);
rval.namer = activeCtx.namer;
continue;
}
// dereference @context key if present
if(_isObject(ctx) && '@context' in ctx) {
ctx = ctx['@context'];
}
// context must be an object by now, all URLs retrieved before this call
if(!_isObject(ctx)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; @context must be an object.',
'jsonld.SyntaxError', {context: ctx});
}
// define context mappings for keys in local context
var defined = {};
// handle @base
if('@base' in ctx) {
var base = ctx['@base'];
// reset base
if(base === null) {
base = options.base;
}
else if(!_isString(base)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; the value of "@base" in a ' +
'@context must be a string or null.',
'jsonld.SyntaxError', {context: ctx});
}
else if(base !== '' && !_isAbsoluteIri(base)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; the value of "@base" in a ' +
'@context must be an absolute IRI or the empty string.',
'jsonld.SyntaxError', {context: ctx});
}
else {
base = jsonld.url.parse(base || '');
base.pathname = base.pathname || '';
rval['@base'] = base;
}
defined['@base'] = true;
}
// handle @vocab
if('@vocab' in ctx) {
var value = ctx['@vocab'];
if(value === null) {
delete rval['@vocab'];
}
else if(!_isString(value)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; the value of "@vocab" in a ' +
'@context must be a string or null.',
'jsonld.SyntaxError', {context: ctx});
}
else if(!_isAbsoluteIri(value)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; the value of "@vocab" in a ' +
'@context must be an absolute IRI.',
'jsonld.SyntaxError', {context: ctx});
}
else {
rval['@vocab'] = value;
}
defined['@vocab'] = true;
}
// handle @language
if('@language' in ctx) {
var value = ctx['@language'];
if(value === null) {
delete rval['@language'];
}
else if(!_isString(value)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; the value of "@language" in a ' +
'@context must be a string or null.',
'jsonld.SyntaxError', {context: ctx});
}
else {
rval['@language'] = value.toLowerCase();
}
defined['@language'] = true;
}
// process all other keys
for(var key in ctx) {
_createTermDefinition(rval, ctx, key, defined);
}
}
// cache result
if(jsonld.cache.activeCtx) {
jsonld.cache.activeCtx.set(activeCtx, localCtx, rval);
}
return rval;
};
/**
* Expands a language map.
*
* @param languageMap the language map to expand.
*
* @return the expanded language map.
*/
function _expandLanguageMap(languageMap) {
var rval = [];
var keys = Object.keys(languageMap).sort();
for(var ki = 0; ki < keys.length; ++ki) {
var key = keys[ki];
var val = languageMap[key];
if(!_isArray(val)) {
val = [val];
}
for(var vi = 0; vi < val.length; ++vi) {
var item = val[vi];
if(!_isString(item)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; language map values must be strings.',
'jsonld.SyntaxError', {languageMap: languageMap});
}
rval.push({
'@value': item,
'@language': key.toLowerCase()
});
}
}
return rval;
}
/**
* Labels the blank nodes in the given value using the given UniqueNamer.
*
* @param namer the UniqueNamer to use.
* @param element the element with blank nodes to rename.
*
* @return the element.
*/
function _labelBlankNodes(namer, element) {
if(_isArray(element)) {
for(var i = 0; i < element.length; ++i) {
element[i] = _labelBlankNodes(namer, element[i]);
}
}
else if(_isList(element)) {
element['@list'] = _labelBlankNodes(namer, element['@list']);
}
else if(_isObject(element)) {
// rename blank node
if(_isBlankNode(element)) {
element['@id'] = namer.getName(element['@id']);
}
// recursively apply to all keys
var keys = Object.keys(element).sort();
for(var ki = 0; ki < keys.length; ++ki) {
var key = keys[ki];
if(key !== '@id') {
element[key] = _labelBlankNodes(namer, element[key]);
}
}
}
return element;
}
/**
* Expands the given value by using the coercion and keyword rules in the
* given context.
*
* @param activeCtx the active context to use.
* @param activeProperty the active property the value is associated with.
* @param value the value to expand.
*
* @return the expanded value.
*/
function _expandValue(activeCtx, activeProperty, value) {
// nothing to expand
if(value === null) {
return null;
}
// special-case expand @id and @type (skips '@id' expansion)
var expandedProperty = _expandIri(activeCtx, activeProperty, {vocab: true});
if(expandedProperty === '@id') {
return _expandIri(activeCtx, value, {base: true});
}
else if(expandedProperty === '@type') {
return _expandIri(activeCtx, value, {vocab: true, base: true});
}
// get type definition from context
var type = jsonld.getContextValue(activeCtx, activeProperty, '@type');
// do @id expansion (automatic for @graph)
if(type === '@id' || (expandedProperty === '@graph' && _isString(value))) {
return {'@id': _expandIri(activeCtx, value, {base: true})};
}
// do @id expansion w/vocab
if(type === '@vocab') {
return {'@id': _expandIri(activeCtx, value, {vocab: true, base: true})};
}
// do not expand keyword values
if(_isKeyword(expandedProperty)) {
return value;
}
rval = {};
// other type
if(type !== null) {
// rename blank node if requested
if(activeCtx.namer && type.indexOf('_:') === 0) {
type = activeCtx.namer.getName(type);
}
rval['@type'] = type;
}
// check for language tagging for strings
else if(_isString(value)) {
var language = jsonld.getContextValue(
activeCtx, activeProperty, '@language');
if(language !== null) {
rval['@language'] = language;
}
}
rval['@value'] = value;
return rval;
}
/**
* Creates an array of RDF triples for the given graph.
*
* @param graph the graph to create RDF triples for.
* @param namer a UniqueNamer for assigning blank node names.
*
* @return the array of RDF triples for the given graph.
*/
function _graphToRDF(graph, namer) {
var rval = [];
for(var id in graph) {
var node = graph[id];
for(var property in node) {
var items = node[property];
if(property === '@type') {
property = RDF_TYPE;
}
else if(_isKeyword(property)) {
continue;
}
for(var i = 0; i < items.length; ++i) {
var item = items[i];
// RDF subject
var subject = {};
if(id.indexOf('_:') === 0) {
subject.type = 'blank node';
subject.value = namer.getName(id);
}
else {
subject.type = 'IRI';
subject.value = id;
}
// RDF predicate
var predicate = {type: 'IRI'};
predicate.value = property;
// convert @list to triples
if(_isList(item)) {
_listToRDF(item['@list'], namer, subject, predicate, rval);
}
// convert value or node object to triple
else {
var object = _objectToRDF(item, namer);
rval.push({subject: subject, predicate: predicate, object: object});
}
}
}
}
return rval;
}
/**
* Converts a @list value into linked list of blank node RDF triples
* (an RDF collection).
*
* @param list the @list value.
* @param namer a UniqueNamer for assigning blank node names.
* @param subject the subject for the head of the list.
* @param predicate the predicate for the head of the list.
* @param triples the array of triples to append to.
*/
function _listToRDF(list, namer, subject, predicate, triples) {
var first = {type: 'IRI', value: RDF_FIRST};
var rest = {type: 'IRI', value: RDF_REST};
var nil = {type: 'IRI', value: RDF_NIL};
for(var i = 0; i < list.length; ++i) {
var item = list[i];
var blankNode = {type: 'blank node', value: namer.getName()};
triples.push({subject: subject, predicate: predicate, object: blankNode});
subject = blankNode;
predicate = first;
var object = _objectToRDF(item, namer);
triples.push({subject: subject, predicate: predicate, object: object});
predicate = rest;
}
triples.push({subject: subject, predicate: predicate, object: nil});
}
/**
* Converts a JSON-LD value object to an RDF literal or a JSON-LD string or
* node object to an RDF resource.
*
* @param item the JSON-LD value or node object.
* @param namer the UniqueNamer to use to assign blank node names.
*
* @return the RDF literal or RDF resource.
*/
function _objectToRDF(item, namer) {
var object = {};
// convert value object to RDF
if(_isValue(item)) {
object.type = 'literal';
var value = item['@value'];
var datatype = item['@type'] || null;
// convert to XSD datatypes as appropriate
if(_isBoolean(value)) {
object.value = value.toString();
object.datatype = datatype || XSD_BOOLEAN;
}
else if(_isDouble(value)) {
// canonical double representation
object.value = value.toExponential(15).replace(/(\d)0*e\+?/, '$1E');
object.datatype = datatype || XSD_DOUBLE;
}
else if(_isNumber(value)) {
object.value = value.toFixed(0);
object.datatype = datatype || XSD_INTEGER;
}
else if('@language' in item) {
object.value = value;
object.datatype = datatype || RDF_LANGSTRING;
object.language = item['@language'];
}
else {
object.value = value;
object.datatype = datatype || XSD_STRING;
}
}
// convert string/node object to RDF
else {
var id = _isObject(item) ? item['@id'] : item;
if(id.indexOf('_:') === 0) {
object.type = 'blank node';
object.value = namer.getName(id);
}
else {
object.type = 'IRI';
object.value = id;
}
}
return object;
}
/**
* Converts an RDF triple object to a JSON-LD object.
*
* @param o the RDF triple object to convert.
* @param useNativeTypes true to output native types, false not to.
*
* @return the JSON-LD object.
*/
function _RDFToObject(o, useNativeTypes) {
// convert empty list
if(o.type === 'IRI' && o.value === RDF_NIL) {
return {'@list': []};
}
// convert IRI/blank node object to JSON-LD
if(o.type === 'IRI' || o.type === 'blank node') {
return {'@id': o.value};
}
// convert literal to JSON-LD
var rval = {'@value': o.value};
// add language
if('language' in o) {
rval['@language'] = o.language;
}
// add datatype
else {
var type = o.datatype;
// use native types for certain xsd types
if(useNativeTypes) {
if(type === XSD_BOOLEAN) {
if(rval['@value'] === 'true') {
rval['@value'] = true;
}
else if(rval['@value'] === 'false') {
rval['@value'] = false;
}
}
else if(_isNumeric(rval['@value'])) {
if(type === XSD_INTEGER) {
var i = parseInt(rval['@value']);
if(i.toFixed(0) === rval['@value']) {
rval['@value'] = i;
}
}
else if(type === XSD_DOUBLE) {
rval['@value'] = parseFloat(rval['@value']);
}
}
// do not add native type
if([XSD_BOOLEAN, XSD_INTEGER, XSD_DOUBLE, XSD_STRING]
.indexOf(type) === -1) {
rval['@type'] = type;
}
}
else {
rval['@type'] = type;
}
}
return rval;
}
/**
* Compares two RDF triples for equality.
*
* @param t1 the first triple.
* @param t2 the second triple.
*
* @return true if the triples are the same, false if not.
*/
function _compareRDFTriples(t1, t2) {
var attrs = ['subject', 'predicate', 'object'];
for(var i = 0; i < attrs.length; ++i) {
var attr = attrs[i];
if(t1[attr].type !== t2[attr].type || t1[attr].value !== t2[attr].value) {
return false;
}
}
if(t1.object.language !== t2.object.language) {
return false;
}
if(t1.object.datatype !== t2.object.datatype) {
return false;
}
return true;
}
/**
* Hashes all of the quads about a blank node.
*
* @param id the ID of the bnode to hash quads for.
* @param bnodes the mapping of bnodes to quads.
* @param namer the canonical bnode namer.
*
* @return the new hash.
*/
function _hashQuads(id, bnodes, namer) {
// return cached hash
if('hash' in bnodes[id]) {
return bnodes[id].hash;
}
// serialize all of bnode's quads
var quads = bnodes[id].quads;
var nquads = [];
for(var i = 0; i < quads.length; ++i) {
nquads.push(_toNQuad(
quads[i], quads[i].name ? quads[i].name.value : null, id));
}
// sort serialized quads
nquads.sort();
// return hashed quads
var hash = bnodes[id].hash = sha1.hash(nquads);
return hash;
}
/**
* Produces a hash for the paths of adjacent bnodes for a bnode,
* incorporating all information about its subgraph of bnodes. This
* method will recursively pick adjacent bnode permutations that produce the
* lexicographically-least 'path' serializations.
*
* @param id the ID of the bnode to hash paths for.
* @param bnodes the map of bnode quads.
* @param namer the canonical bnode namer.
* @param pathNamer the namer used to assign names to adjacent bnodes.
* @param callback(err, result) called once the operation completes.
*/
function _hashPaths(id, bnodes, namer, pathNamer, callback) {
// create SHA-1 digest
var md = sha1.create();
// group adjacent bnodes by hash, keep properties and references separate
var groups = {};
var groupHashes;
var quads = bnodes[id].quads;
jsonld.nextTick(function() {groupNodes(0);});
function groupNodes(i) {
if(i === quads.length) {
// done, hash groups
groupHashes = Object.keys(groups).sort();
return hashGroup(0);
}
// get adjacent bnode
var quad = quads[i];
var bnode = _getAdjacentBlankNodeName(quad.subject, id);
var direction = null;
if(bnode !== null) {
// normal property
direction = 'p';
}
else {
bnode = _getAdjacentBlankNodeName(quad.object, id);
if(bnode !== null) {
// reverse property
direction = 'r';
}
}
if(bnode !== null) {
// get bnode name (try canonical, path, then hash)
var name;
if(namer.isNamed(bnode)) {
name = namer.getName(bnode);
}
else if(pathNamer.isNamed(bnode)) {
name = pathNamer.getName(bnode);
}
else {
name = _hashQuads(bnode, bnodes, namer);
}
// hash direction, property, and bnode name/hash
var md = sha1.create();
md.update(direction);
md.update(quad.predicate.value);
md.update(name);
var groupHash = md.digest();
// add bnode to hash group
if(groupHash in groups) {
groups[groupHash].push(bnode);
}
else {
groups[groupHash] = [bnode];
}
}
jsonld.nextTick(function() {groupNodes(i + 1);});
}
// hashes a group of adjacent bnodes
function hashGroup(i) {
if(i === groupHashes.length) {
// done, return SHA-1 digest and path namer
return callback(null, {hash: md.digest(), pathNamer: pathNamer});
}
// digest group hash
var groupHash = groupHashes[i];
md.update(groupHash);
// choose a path and namer from the permutations
var chosenPath = null;
var chosenNamer = null;
var permutator = new Permutator(groups[groupHash]);
jsonld.nextTick(function() {permutate();});
function permutate() {
var permutation = permutator.next();
var pathNamerCopy = pathNamer.clone();
// build adjacent path
var path = '';
var recurse = [];
for(var n in permutation) {
var bnode = permutation[n];
// use canonical name if available
if(namer.isNamed(bnode)) {
path += namer.getName(bnode);
}
else {
// recurse if bnode isn't named in the path yet
if(!pathNamerCopy.isNamed(bnode)) {
recurse.push(bnode);
}
path += pathNamerCopy.getName(bnode);
}
// skip permutation if path is already >= chosen path
if(chosenPath !== null && path.length >= chosenPath.length &&
path > chosenPath) {
return nextPermutation(true);
}
}
// does the next recursion
nextRecursion(0);
function nextRecursion(n) {
if(n === recurse.length) {
// done, do next permutation
return nextPermutation(false);
}
// do recursion
var bnode = recurse[n];
_hashPaths(bnode, bnodes, namer, pathNamerCopy,
function(err, result) {
if(err) {
return callback(err);
}
path += pathNamerCopy.getName(bnode) + '<' + result.hash + '>';
pathNamerCopy = result.pathNamer;
// skip permutation if path is already >= chosen path
if(chosenPath !== null && path.length >= chosenPath.length &&
path > chosenPath) {
return nextPermutation(true);
}
// do next recursion
nextRecursion(n + 1);
});
}
// stores the results of this permutation and runs the next
function nextPermutation(skipped) {
if(!skipped && (chosenPath === null || path < chosenPath)) {
chosenPath = path;
chosenNamer = pathNamerCopy;
}
// do next permutation
if(permutator.hasNext()) {
jsonld.nextTick(function() {permutate();});
}
else {
// digest chosen path and update namer
md.update(chosenPath);
pathNamer = chosenNamer;
// hash the next group
hashGroup(i + 1);
}
}
}
}
}
/**
* A helper function that gets the blank node name from an RDF quad node
* (subject or object). If the node is a blank node and its value
* does not match the given blank node ID, it will be returned.
*
* @param node the RDF quad node.
* @param id the ID of the blank node to look next to.
*
* @return the adjacent blank node name or null if none was found.
*/
function _getAdjacentBlankNodeName(node, id) {
return (node.type === 'blank node' && node.value !== id ? node.value : null);
}
/**
* Recursively flattens the subjects in the given JSON-LD expanded input
* into a node map.
*
* @param input the JSON-LD expanded input.
* @param graphs a map of graph name to subject map.
* @param graph the name of the current graph.
* @param namer the blank node namer.
* @param name the name assigned to the current input if it is a bnode.
* @param list the list to append to, null for none.
*/
function _createNodeMap(input, graphs, graph, namer, name, list) {
// recurse through array
if(_isArray(input)) {
for(var i in input) {
_createNodeMap(input[i], graphs, graph, namer, undefined, list);
}
return;
}
// add non-object to list
if(!_isObject(input)) {
if(list) {
list.push(input);
}
return;
}
// add entries for @type
if('@type' in input) {
var types = input['@type'];
if(!_isArray(types)) {
types = [types];
}
for(var ti = 0; ti < types.length; ++ti) {
var type = types[ti];
var id = (type.indexOf('_:') === 0) ? namer.getName(type) : type;
if(!(id in graphs[graph])) {
graphs[graph][id] = {'@id': id};
}
}
}
// add values to list
if(_isValue(input)) {
if(list) {
list.push(input);
}
return;
}
// Note: At this point, input must be a subject.
// get name for subject
if(_isUndefined(name)) {
name = _isBlankNode(input) ? namer.getName(input['@id']) : input['@id'];
}
// add subject reference to list
if(list) {
list.push({'@id': name});
}
// create new subject or merge into existing one
var subjects = graphs[graph];
var subject = subjects[name] = subjects[name] || {};
subject['@id'] = name;
var properties = Object.keys(input).sort();
for(var pi = 0; pi < properties.length; ++pi) {
var property = properties[pi];
// skip @id
if(property === '@id') {
continue;
}
// recurse into graph
if(property === '@graph') {
// add graph subjects map entry
if(!(name in graphs)) {
graphs[name] = {};
}
var g = (graph === '@merged') ? graph : name;
_createNodeMap(input[property], graphs, g, namer);
continue;
}
// copy non-@type keywords
if(property !== '@type' && _isKeyword(property)) {
subject[property] = input[property];
continue;
}
// iterate over objects (ensure property is added for empty arrays)
var objects = input[property];
if(objects.length === 0) {
jsonld.addValue(subject, property, [], {propertyIsArray: true});
continue;
}
for(var oi = 0; oi < objects.length; ++oi) {
var o = objects[oi];
// handle embedded subject or subject reference
if(_isSubject(o) || _isSubjectReference(o)) {
// rename blank node @id
var id = _isBlankNode(o) ? namer.getName(o['@id']) : o['@id'];
// add reference and recurse
jsonld.addValue(
subject, property, {'@id': id},
{propertyIsArray: true, allowDuplicate: false});
_createNodeMap(o, graphs, graph, namer, id);
}
// handle @list
else if(_isList(o)) {
var _list = [];
_createNodeMap(o['@list'], graphs, graph, namer, name, _list);
o = {'@list': _list};
jsonld.addValue(
subject, property, o,
{propertyIsArray: true, allowDuplicate: false});
}
// handle @value
else {
_createNodeMap(o, graphs, graph, namer, name);
jsonld.addValue(
subject, property, o, {propertyIsArray: true, allowDuplicate: false});
}
}
}
}
/**
* Frames subjects according to the given frame.
*
* @param state the current framing state.
* @param subjects the subjects to filter.
* @param frame the frame.
* @param parent the parent subject or top-level array.
* @param property the parent property, initialized to null.
*/
function _frame(state, subjects, frame, parent, property) {
// validate the frame
_validateFrame(state, frame);
frame = frame[0];
// filter out subjects that match the frame
var matches = _filterSubjects(state, subjects, frame);
// get flags for current frame
var options = state.options;
var embedOn = _getFrameFlag(frame, options, 'embed');
var explicitOn = _getFrameFlag(frame, options, 'explicit');
// add matches to output
var ids = Object.keys(matches).sort();
for(var idx in ids) {
var id = ids[idx];
/* Note: In order to treat each top-level match as a compartmentalized
result, create an independent copy of the embedded subjects map when the
property is null, which only occurs at the top-level. */
if(property === null) {
state.embeds = {};
}
// start output
var output = {};
output['@id'] = id;
// prepare embed meta info
var embed = {parent: parent, property: property};
// if embed is on and there is an existing embed
if(embedOn && (id in state.embeds)) {
// only overwrite an existing embed if it has already been added to its
// parent -- otherwise its parent is somewhere up the tree from this
// embed and the embed would occur twice once the tree is added
embedOn = false;
// existing embed's parent is an array
var existing = state.embeds[id];
if(_isArray(existing.parent)) {
for(var i in existing.parent) {
if(jsonld.compareValues(output, existing.parent[i])) {
embedOn = true;
break;
}
}
}
// existing embed's parent is an object
else if(jsonld.hasValue(existing.parent, existing.property, output)) {
embedOn = true;
}
// existing embed has already been added, so allow an overwrite
if(embedOn) {
_removeEmbed(state, id);
}
}
// not embedding, add output without any other properties
if(!embedOn) {
_addFrameOutput(state, parent, property, output);
}
else {
// add embed meta info
state.embeds[id] = embed;
// iterate over subject properties
var subject = matches[id];
var props = Object.keys(subject).sort();
for(var i in props) {
var prop = props[i];
// copy keywords to output
if(_isKeyword(prop)) {
output[prop] = _clone(subject[prop]);
continue;
}
// if property isn't in the frame
if(!(prop in frame)) {
// if explicit is off, embed values
if(!explicitOn) {
_embedValues(state, subject, prop, output);
}
continue;
}
// add objects
var objects = subject[prop];
for(var i in objects) {
var o = objects[i];
// recurse into list
if(_isList(o)) {
// add empty list
var list = {'@list': []};
_addFrameOutput(state, output, prop, list);
// add list objects
var src = o['@list'];
for(var n in src) {
o = src[n];
// recurse into subject reference
if(_isSubjectReference(o)) {
_frame(state, [o['@id']], frame[prop], list, '@list');
}
// include other values automatically
else {
_addFrameOutput(state, list, '@list', _clone(o));
}
}
continue;
}
// recurse into subject reference
if(_isSubjectReference(o)) {
_frame(state, [o['@id']], frame[prop], output, prop);
}
// include other values automatically
else {
_addFrameOutput(state, output, prop, _clone(o));
}
}
}
// handle defaults
var props = Object.keys(frame).sort();
for(var i in props) {
var prop = props[i];
// skip keywords
if(_isKeyword(prop)) {
continue;
}
// if omit default is off, then include default values for properties
// that appear in the next frame but are not in the matching subject
var next = frame[prop][0];
var omitDefaultOn = _getFrameFlag(next, options, 'omitDefault');
if(!omitDefaultOn && !(prop in output)) {
var preserve = '@null';
if('@default' in next) {
preserve = _clone(next['@default']);
}
if(!_isArray(preserve)) {
preserve = [preserve];
}
output[prop] = [{'@preserve': preserve}];
}
}
// add output to parent
_addFrameOutput(state, parent, property, output);
}
}
}
/**
* Gets the frame flag value for the given flag name.
*
* @param frame the frame.
* @param options the framing options.
* @param name the flag name.
*
* @return the flag value.
*/
function _getFrameFlag(frame, options, name) {
var flag = '@' + name;
return (flag in frame) ? frame[flag][0] : options[name];
}
/**
* Validates a JSON-LD frame, throwing an exception if the frame is invalid.
*
* @param state the current frame state.
* @param frame the frame to validate.
*/
function _validateFrame(state, frame) {
if(!_isArray(frame) || frame.length !== 1 || !_isObject(frame[0])) {
throw new JsonLdError(
'Invalid JSON-LD syntax; a JSON-LD frame must be a single object.',
'jsonld.SyntaxError', {frame: frame});
}
}
/**
* Returns a map of all of the subjects that match a parsed frame.
*
* @param state the current framing state.
* @param subjects the set of subjects to filter.
* @param frame the parsed frame.
*
* @return all of the matched subjects.
*/
function _filterSubjects(state, subjects, frame) {
// filter subjects in @id order
var rval = {};
for(var i in subjects) {
var id = subjects[i];
var subject = state.subjects[id];
if(_filterSubject(subject, frame)) {
rval[id] = subject;
}
}
return rval;
}
/**
* Returns true if the given subject matches the given frame.
*
* @param subject the subject to check.
* @param frame the frame to check.
*
* @return true if the subject matches, false if not.
*/
function _filterSubject(subject, frame) {
// check @type (object value means 'any' type, fall through to ducktyping)
if('@type' in frame &&
!(frame['@type'].length === 1 && _isObject(frame['@type'][0]))) {
var types = frame['@type'];
for(var i in types) {
// any matching @type is a match
if(jsonld.hasValue(subject, '@type', types[i])) {
return true;
}
}
return false;
}
// check ducktype
for(var key in frame) {
// only not a duck if @id or non-keyword isn't in subject
if((key === '@id' || !_isKeyword(key)) && !(key in subject)) {
return false;
}
}
return true;
}
/**
* Embeds values for the given subject and property into the given output
* during the framing algorithm.
*
* @param state the current framing state.
* @param subject the subject.
* @param property the property.
* @param output the output.
*/
function _embedValues(state, subject, property, output) {
// embed subject properties in output
var objects = subject[property];
for(var i in objects) {
var o = objects[i];
// recurse into @list
if(_isList(o)) {
var list = {'@list': []};
_addFrameOutput(state, output, property, list);
return _embedValues(state, o, '@list', list['@list']);
}
// handle subject reference
if(_isSubjectReference(o)) {
var id = o['@id'];
// embed full subject if isn't already embedded
if(!(id in state.embeds)) {
// add embed
var embed = {parent: output, property: property};
state.embeds[id] = embed;
// recurse into subject
o = {};
var s = state.subjects[id];
for(var prop in s) {
// copy keywords
if(_isKeyword(prop)) {
o[prop] = _clone(s[prop]);
continue;
}
_embedValues(state, s, prop, o);
}
}
_addFrameOutput(state, output, property, o);
}
// copy non-subject value
else {
_addFrameOutput(state, output, property, _clone(o));
}
}
}
/**
* Removes an existing embed.
*
* @param state the current framing state.
* @param id the @id of the embed to remove.
*/
function _removeEmbed(state, id) {
// get existing embed
var embeds = state.embeds;
var embed = embeds[id];
var parent = embed.parent;
var property = embed.property;
// create reference to replace embed
var subject = {'@id': id};
// remove existing embed
if(_isArray(parent)) {
// replace subject with reference
for(var i in parent) {
if(jsonld.compareValues(parent[i], subject)) {
parent[i] = subject;
break;
}
}
}
else {
// replace subject with reference
var useArray = _isArray(parent[property]);
jsonld.removeValue(parent, property, subject, {propertyIsArray: useArray});
jsonld.addValue(parent, property, subject, {propertyIsArray: useArray});
}
// recursively remove dependent dangling embeds
var removeDependents = function(id) {
// get embed keys as a separate array to enable deleting keys in map
var ids = Object.keys(embeds);
for(var i in ids) {
var next = ids[i];
if(next in embeds && _isObject(embeds[next].parent) &&
embeds[next].parent['@id'] === id) {
delete embeds[next];
removeDependents(next);
}
}
};
removeDependents(id);
}
/**
* Adds framing output to the given parent.
*
* @param state the current framing state.
* @param parent the parent to add to.
* @param property the parent property.
* @param output the output to add.
*/
function _addFrameOutput(state, parent, property, output) {
if(_isObject(parent)) {
jsonld.addValue(parent, property, output, {propertyIsArray: true});
}
else {
parent.push(output);
}
}
/**
* Removes the @preserve keywords as the last step of the framing algorithm.
*
* @param ctx the active context used to compact the input.
* @param input the framed, compacted output.
* @param options the compaction options used.
*
* @return the resulting output.
*/
function _removePreserve(ctx, input, options) {
// recurse through arrays
if(_isArray(input)) {
var output = [];
for(var i in input) {
var result = _removePreserve(ctx, input[i], options);
// drop nulls from arrays
if(result !== null) {
output.push(result);
}
}
input = output;
}
else if(_isObject(input)) {
// remove @preserve
if('@preserve' in input) {
if(input['@preserve'] === '@null') {
return null;
}
return input['@preserve'];
}
// skip @values
if(_isValue(input)) {
return input;
}
// recurse through @lists
if(_isList(input)) {
input['@list'] = _removePreserve(ctx, input['@list'], options);
return input;
}
// recurse through properties
for(var prop in input) {
var result = _removePreserve(ctx, input[prop], options);
var container = jsonld.getContextValue(ctx, prop, '@container');
if(options.compactArrays && _isArray(result) && result.length === 1 &&
container === null) {
result = result[0];
}
input[prop] = result;
}
}
return input;
}
/**
* Compares two strings first based on length and then lexicographically.
*
* @param a the first string.
* @param b the second string.
*
* @return -1 if a < b, 1 if a > b, 0 if a == b.
*/
function _compareShortestLeast(a, b) {
if(a.length < b.length) {
return -1;
}
else if(b.length < a.length) {
return 1;
}
else if(a === b) {
return 0;
}
return (a < b) ? -1 : 1;
}
/**
* Picks the preferred compaction term from the given inverse context entry.
*
* @param activeCtx the active context.
* @param iri the IRI to pick the term for.
* @param value the value to pick the term for.
* @param parent the parent of the value (required for property generators).
* @param containers the preferred containers.
* @param typeOrLanguage either '@type' or '@language'.
* @param typeOrLanguageValue the preferred value for '@type' or '@language'.
*
* @return the preferred term.
*/
function _selectTerm(
activeCtx, iri, value, parent, containers,
typeOrLanguage, typeOrLanguageValue) {
containers.push('@none');
if(typeOrLanguageValue === null) {
typeOrLanguageValue = '@null';
}
// options for the value of @type or @language
var options;
// determine options for @id based on whether or not value compacts to a term
if(typeOrLanguageValue === '@id' && _isSubjectReference(value)) {
// try to compact value to a term
var term = _compactIri(
activeCtx, value['@id'], null, {vocab: true});
if(term in activeCtx.mappings &&
activeCtx.mappings[term] &&
activeCtx.mappings[term]['@id'] === value['@id']) {
// prefer @vocab
options = ['@vocab', '@id', '@none'];
}
else {
// prefer @id
options = ['@id', '@vocab', '@none'];
}
}
else {
options = [typeOrLanguageValue, '@none'];
}
var term = null;
var containerMap = activeCtx.inverse[iri];
for(var ci = 0; term === null && ci < containers.length; ++ci) {
// if container not available in the map, continue
var container = containers[ci];
if(!(container in containerMap)) {
continue;
}
var typeOrLanguageValueMap = containerMap[container][typeOrLanguage];
for(var oi = 0; term === null && oi < options.length; ++oi) {
// if type/language option not available in the map, continue
var option = options[oi];
if(!(option in typeOrLanguageValueMap)) {
continue;
}
var termInfo = typeOrLanguageValueMap[option];
// see if a property generator matches
if(_isObject(parent)) {
for(var pi = 0; pi < termInfo.propertyGenerators.length; ++pi) {
var propertyGenerator = termInfo.propertyGenerators[pi];
var match = _findPropertyGeneratorDuplicates(
activeCtx, parent, iri, value, propertyGenerator, false);
if(match) {
term = propertyGenerator;
break;
}
}
}
// no matching property generator, use a simple term instead
if(term === null) {
term = termInfo.term;
}
}
}
return term;
}
/**
* Compacts an IRI or keyword into a term or prefix if it can be. If the
* IRI has an associated value it may be passed.
*
* @param activeCtx the active context to use.
* @param iri the IRI to compact.
* @param value the value to check or null.
* @param relativeTo options for how to compact IRIs:
* base: true to resolve against the base IRI, false not to.
* vocab: true to split after @vocab, false not to.
* @param parent the parent element for the value.
*
* @return the compacted term, prefix, keyword alias, or the original IRI.
*/
function _compactIri(activeCtx, iri, value, relativeTo, parent) {
// can't compact null
if(iri === null) {
return iri;
}
// term is a keyword
if(_isKeyword(iri)) {
// return alias if available
var aliases = activeCtx.keywords[iri];
return (aliases.length > 0) ? aliases[0] : iri;
}
// default value and parent to null
if(_isUndefined(value)) {
value = null;
}
if(_isUndefined(parent)) {
parent = null;
}
relativeTo = relativeTo || {};
// use inverse context to pick a term if iri is relative to vocab
if(relativeTo.vocab && iri in activeCtx.getInverse()) {
var defaultLanguage = activeCtx['@language'] || '@none';
// prefer @index if available in value
var containers = [];
if(_isObject(value) && '@index' in value) {
containers.push('@index');
}
// defaults for term selection based on type/language
var typeOrLanguage = '@language';
var typeOrLanguageValue = '@null';
// choose the most specific term that works for all elements in @list
if(_isList(value)) {
// only select @list containers if @index is NOT in value
if(!('@index' in value)) {
containers.push('@list');
}
var list = value['@list'];
var commonLanguage = (list.length === 0) ? defaultLanguage : null;
var commonType = null;
for(var i = 0; i < list.length; ++i) {
var item = list[i];
var itemLanguage = '@none';
var itemType = '@none';
if(_isValue(item)) {
if('@language' in item) {
itemLanguage = item['@language'];
}
else if('@type' in item) {
itemType = item['@type'];
}
// plain literal
else {
itemLanguage = '@null';
}
}
else {
itemType = '@id';
}
if(commonLanguage === null) {
commonLanguage = itemLanguage;
}
else if(itemLanguage !== commonLanguage && _isValue(item)) {
commonLanguage = '@none';
}
if(commonType === null) {
commonType = itemType;
}
else if(itemType !== commonType) {
commonType = '@none';
}
// there are different languages and types in the list, so choose
// the most generic term, no need to keep iterating the list
if(commonLanguage === '@none' && commonType === '@none') {
break;
}
}
commonLanguage = commonLanguage || '@none';
commonType = commonType || '@none';
if(commonType !== '@none') {
typeOrLanguage = '@type';
typeOrLanguageValue = commonType;
}
else {
typeOrLanguageValue = commonLanguage;
}
}
else {
if(_isValue(value)) {
if('@language' in value && !('@index' in value)) {
containers.push('@language');
typeOrLanguageValue = value['@language'];
}
else if('@type' in value) {
typeOrLanguage = '@type';
typeOrLanguageValue = value['@type'];
}
}
else {
typeOrLanguage = '@type';
typeOrLanguageValue = '@id';
}
containers.push('@set');
}
// do term selection
var term = _selectTerm(
activeCtx, iri, value, parent,
containers, typeOrLanguage, typeOrLanguageValue);
if(term !== null) {
return term;
}
}
// no term match, check for possible CURIEs
var choice = null;
for(var term in activeCtx.mappings) {
// skip terms with colons, they can't be prefixes
if(term.indexOf(':') !== -1) {
continue;
}
// skip entries with @ids that are not partial matches
var definition = activeCtx.mappings[term];
if(!definition || definition.propertyGenerator ||
definition['@id'] === iri || iri.indexOf(definition['@id']) !== 0) {
continue;
}
// a CURIE is usable if:
// 1. it has no mapping, OR
// 2. value is null, which means we're not compacting an @value, AND
// the mapping matches the IRI)
var curie = term + ':' + iri.substr(definition['@id'].length);
var isUsableCurie = (!(curie in activeCtx.mappings) ||
(value === null && activeCtx.mappings[curie] &&
activeCtx.mappings[curie]['@id'] === iri));
// select curie if it is shorter or the same length but lexicographically
// less than the current choice
if(isUsableCurie && (choice === null ||
_compareShortestLeast(curie, choice) < 0)) {
choice = curie;
}
}
// return chosen curie
if(choice !== null) {
return choice;
}
// no matching terms or curies, use @vocab if available
if(relativeTo.vocab) {
if('@vocab' in activeCtx) {
// determine if vocab is a prefix of the iri
var vocab = activeCtx['@vocab'];
if(iri.indexOf(vocab) === 0 && iri !== vocab) {
// use suffix as relative iri if it is not a term in the active context
var suffix = iri.substr(vocab.length);
if(!(suffix in activeCtx.mappings)) {
return suffix;
}
}
}
}
// compact IRI relative to base
else {
return _removeBase(activeCtx['@base'], iri);
}
// return IRI as is
return iri;
}
/**
* Performs value compaction on an object with '@value' or '@id' as the only
* property.
*
* @param activeCtx the active context.
* @param activeProperty the active property that points to the value.
* @param value the value to compact.
*
* @return the compaction result.
*/
function _compactValue(activeCtx, activeProperty, value) {
// value is a @value
if(_isValue(value)) {
// get context rules
var type = jsonld.getContextValue(activeCtx, activeProperty, '@type');
var language = jsonld.getContextValue(
activeCtx, activeProperty, '@language');
var container = jsonld.getContextValue(
activeCtx, activeProperty, '@container');
// whether or not the value has an @index that must be preserved
var preserveIndex = (('@index' in value) &&
container !== '@index');
// if there's no @index to preserve ...
if(!preserveIndex) {
// matching @type or @language specified in context, compact value
if(value['@type'] === type || value['@language'] === language) {
return value['@value'];
}
}
// return just the value of @value if all are true:
// 1. @value is the only key or @index isn't being preserved
// 2. there is no default language or @value is not a string or
// the key has a mapping with a null @language
var keyCount = Object.keys(value).length;
var isValueOnlyKey = (keyCount === 1 ||
(keyCount === 2 && ('@index' in value) && !preserveIndex));
var hasDefaultLanguage = ('@language' in activeCtx);
var isValueString = _isString(value['@value']);
var hasNullMapping = (activeCtx.mappings[activeProperty] &&
activeCtx.mappings[activeProperty]['@language'] === null);
if(isValueOnlyKey &&
(!hasDefaultLanguage || !isValueString || hasNullMapping)) {
return value['@value'];
}
var rval = {};
// preserve @index
if(preserveIndex) {
rval[_compactIri(activeCtx, '@index')] = value['@index'];
}
// compact @type IRI
if('@type' in value) {
rval[_compactIri(activeCtx, '@type')] = _compactIri(
activeCtx, value['@type'], null, {vocab: true});
}
// alias @language
else if('@language' in value) {
rval[_compactIri(activeCtx, '@language')] = value['@language'];
}
// alias @value
rval[_compactIri(activeCtx, '@value')] = value['@value'];
return rval;
}
// value is a subject reference
var expandedProperty = _expandIri(activeCtx, activeProperty, {vocab: true});
var type = jsonld.getContextValue(activeCtx, activeProperty, '@type');
var compacted = _compactIri(
activeCtx, value['@id'], null, {vocab: type === '@vocab'});
// compact to scalar
if(type === '@id' || type === '@vocab' || expandedProperty === '@graph') {
return compacted;
}
var rval = {};
rval[_compactIri(activeCtx, '@id')] = compacted;
return rval;
}
/**
* Finds and, if specified, removes any duplicate values that were presumably
* generated by a property generator in the given element.
*
* @param activeCtx the active context.
* @param element the element to remove duplicates from.
* @param expandedProperty the property to map to a property generator.
* @param value the value to compare against when duplicate checking.
* @param activeProperty the property generator term.
* @param remove true to remove the duplicates found, false not to.
*
* @return true if duplicates were found for every IRI.
*/
function _findPropertyGeneratorDuplicates(
activeCtx, element, expandedProperty, value, activeProperty, remove) {
var rval = true;
// get property generator IRIs
var iris = activeCtx.mappings[activeProperty]['@id'];
// for each IRI that isn't 'expandedProperty', remove a single duplicate
// from element, if found
for(var i = 0; rval && i < iris.length; ++i) {
var iri = iris[i];
if(iri === expandedProperty) {
continue;
}
rval = false;
if(!(iri in element)) {
break;
}
var prospects = element[iri];
// handle empty array case
if(_isArray(value) && value.length === 0) {
rval = true;
if(remove) {
delete element[iri];
}
continue;
}
// handle other cases
for(var pi = 0; pi < prospects.length; ++pi) {
var prospect = prospects[pi];
if(jsonld.compareValues(prospect, value)) {
// duplicate found
rval = true;
if(remove) {
// remove it in place
prospects.splice(pi, 1);
if(prospects.length === 0) {
delete element[iri];
}
}
break;
}
}
}
return rval;
}
/**
* Creates a term definition during context processing.
*
* @param activeCtx the current active context.
* @param localCtx the local context being processed.
* @param term the term in the local context to define the mapping for.
* @param defined a map of defining/defined keys to detect cycles and prevent
* double definitions.
*/
function _createTermDefinition(activeCtx, localCtx, term, defined) {
if(term in defined) {
// term already defined
if(defined[term]) {
return;
}
// cycle detected
throw new JsonLdError(
'Cyclical context definition detected.',
'jsonld.CyclicalContext', {context: localCtx, term: term});
}
// now defining term
defined[term] = false;
if(_isKeyword(term)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; keywords cannot be overridden.',
'jsonld.SyntaxError', {context: localCtx});
}
if(activeCtx.mappings[term]) {
// if term is a keyword alias, remove it
var kw = activeCtx.mappings[term]['@id'];
if(_isKeyword(kw)) {
var aliases = activeCtx.keywords[kw];
aliases.splice(aliases.indexOf(term), 1);
}
}
// get context term value
var value = localCtx[term];
// clear context entry
if(value === null || (_isObject(value) && value['@id'] === null)) {
activeCtx.mappings[term] = null;
defined[term] = true;
return;
}
if(_isString(value)) {
// expand value to a full IRI
var id = _expandIri(
activeCtx, value, {vocab: true, base: true}, localCtx, defined);
if(_isKeyword(id)) {
// disallow aliasing @context and @preserve
if(id === '@context' || id === '@preserve') {
throw new JsonLdError(
'Invalid JSON-LD syntax; @context and @preserve cannot be aliased.',
'jsonld.SyntaxError');
}
// uniquely add term as a keyword alias and resort
var aliases = activeCtx.keywords[id];
if(aliases.indexOf(term) === -1) {
aliases.push(term);
aliases.sort(_compareShortestLeast);
}
}
// define/redefine term to expanded IRI/keyword
activeCtx.mappings[term] = {'@id': id};
defined[term] = true;
return;
}
if(!_isObject(value)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; @context property values must be ' +
'strings or objects.',
'jsonld.SyntaxError', {context: localCtx});
}
// create new mapping
var mapping = {};
mapping.propertyGenerator = false;
if('@id' in value) {
var id = value['@id'];
// handle property generator
if(_isArray(id)) {
if(activeCtx.namer === null) {
throw new JsonLdError(
'Incompatible JSON-LD options; a property generator was found ' +
'in the @context, but blank node renaming has been disabled; ' +
'it must be enabled to use property generators.',
'jsonld.OptionsError', {context: localCtx});
}
var propertyGenerator = [];
var ids = id;
for(var i = 0; i < ids.length; ++i) {
// expand @id
id = ids[i];
if(_isString(id)) {
id = _expandIri(
activeCtx, id, {vocab: true, base: true}, localCtx, defined);
}
if(!_isString(id) || _isKeyword(id)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; property generators must consist of an ' +
'@id array containing only strings and no string can be "@type".',
'jsonld.SyntaxError', {context: localCtx});
}
propertyGenerator.push(id);
}
// add sorted property generator as @id in mapping
mapping['@id'] = propertyGenerator.sort();
mapping.propertyGenerator = true;
}
else if(!_isString(id)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; a @context @id value must be an array ' +
'of strings or a string.',
'jsonld.SyntaxError', {context: localCtx});
}
else {
// expand and add @id mapping
mapping['@id'] = _expandIri(
activeCtx, id, {vocab: true, base: true}, localCtx, defined);
}
}
else {
// see if the term has a prefix
var colon = term.indexOf(':');
if(colon !== -1) {
var prefix = term.substr(0, colon);
if(prefix in localCtx) {
// define parent prefix
_createTermDefinition(activeCtx, localCtx, prefix, defined);
}
// set @id based on prefix parent
if(activeCtx.mappings[prefix]) {
var suffix = term.substr(colon + 1);
mapping['@id'] = activeCtx.mappings[prefix]['@id'] + suffix;
}
// term is an absolute IRI
else {
mapping['@id'] = term;
}
}
else {
// non-IRIs *must* define @ids if @vocab is not available
if(!('@vocab' in activeCtx)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; @context terms must define an @id.',
'jsonld.SyntaxError', {context: localCtx, term: term});
}
// prepend vocab to term
mapping['@id'] = activeCtx['@vocab'] + term;
}
}
if('@type' in value) {
var type = value['@type'];
if(!_isString(type)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; @context @type values must be strings.',
'jsonld.SyntaxError', {context: localCtx});
}
if(type !== '@id') {
// expand @type to full IRI
type = _expandIri(
activeCtx, type, {vocab: true, base: true}, localCtx, defined);
}
// add @type to mapping
mapping['@type'] = type;
}
if('@container' in value) {
var container = value['@container'];
if(container !== '@list' && container !== '@set' &&
container !== '@index' && container !== '@language') {
throw new JsonLdError(
'Invalid JSON-LD syntax; @context @container value must be ' +
'one of the following: @list, @set, @index, or @language.',
'jsonld.SyntaxError', {context: localCtx});
}
// add @container to mapping
mapping['@container'] = container;
}
if('@language' in value && !('@type' in value)) {
var language = value['@language'];
if(language !== null && !_isString(language)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; @context @language value must be ' +
'a string or null.',
'jsonld.SyntaxError', {context: localCtx});
}
// add @language to mapping
if(language !== null) {
language = language.toLowerCase();
}
mapping['@language'] = language;
}
// define term mapping
activeCtx.mappings[term] = mapping;
defined[term] = true;
}
/**
* Expands a string to a full IRI. The string may be a term, a prefix, a
* relative IRI, or an absolute IRI. The associated absolute IRI will be
* returned.
*
* @param activeCtx the current active context.
* @param value the string to expand.
* @param relativeTo options for how to resolve relative IRIs:
* base: true to resolve against the base IRI, false not to.
* vocab: true to concatenate after @vocab, false not to.
* @param localCtx the local context being processed (only given if called
* during context processing).
* @param defined a map for tracking cycles in context definitions (only given
* if called during context processing).
*
* @return the expanded value.
*/
function _expandIri(activeCtx, value, relativeTo, localCtx, defined) {
// already expanded
if(value === null || _isKeyword(value)) {
return value;
}
// define term dependency if not defined
if(localCtx && value in localCtx && defined[value] !== true) {
_createTermDefinition(activeCtx, localCtx, value, defined);
}
relativeTo = relativeTo || {};
var rval = null;
if(relativeTo.vocab) {
// term dependency cannot be a property generator
var mapping = activeCtx.mappings[value];
if(localCtx && mapping && mapping.propertyGenerator) {
throw new JsonLdError(
'Invalid JSON-LD syntax; a term definition cannot have a property ' +
'generator as a dependency.',
'jsonld.SyntaxError', {context: localCtx, value: value});
}
// value is explicitly ignored with a null mapping
if(mapping === null) {
return null;
}
// value is a term
if(mapping && !mapping.propertyGenerator) {
rval = mapping['@id'];
}
}
if(rval === null) {
// split value into prefix:suffix
var colon = value.indexOf(':');
if(colon !== -1) {
var prefix = value.substr(0, colon);
var suffix = value.substr(colon + 1);
// do not expand blank nodes (prefix of '_') or already-absolute
// IRIs (suffix of '//')
if(prefix !== '_' && suffix.indexOf('//') !== 0) {
// prefix dependency not defined, define it
if(localCtx && prefix in localCtx) {
_createTermDefinition(activeCtx, localCtx, prefix, defined);
}
// use mapping if prefix is defined and not a property generator
var mapping = activeCtx.mappings[prefix];
if(mapping && !mapping.propertyGenerator) {
rval = activeCtx.mappings[prefix]['@id'] + suffix;
}
}
}
}
if(rval === null) {
rval = value;
}
// keywords need no expanding (aliasing already handled by now)
if(_isKeyword(rval)) {
return rval;
}
if(_isAbsoluteIri(rval)) {
// rename blank node if requested
if(!localCtx && rval.indexOf('_:') === 0 && activeCtx.namer) {
rval = activeCtx.namer.getName(rval);
}
}
// prepend vocab
else if(relativeTo.vocab && '@vocab' in activeCtx) {
rval = activeCtx['@vocab'] + rval;
}
// prepend base
else if(relativeTo.base) {
rval = _prependBase(activeCtx['@base'], rval);
}
if(localCtx) {
// value must now be an absolute IRI
if(!_isAbsoluteIri(rval)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; a @context value does not expand to ' +
'an absolute IRI.',
'jsonld.SyntaxError', {context: localCtx, value: value});
}
}
return rval;
}
/**
* Prepends a base IRI to the given relative IRI.
*
* @param base the base IRI.
* @param iri the relative IRI.
*
* @return the absolute IRI.
*/
function _prependBase(base, iri) {
// already an absolute IRI
if(iri.indexOf(':') !== -1) {
return iri;
}
if(_isString(base)) {
base = jsonld.url.parse(base || '');
base.pathname = base.pathname || '';
}
var authority = (base.host || '');
var rel = jsonld.url.parse(iri);
rel.pathname = (rel.pathname || '');
// per RFC3986 normalize slashes and dots in path
var path;
// IRI contains authority
if(rel.href.indexOf('//') === 0) {
path = rel.href.substr(2);
authority = path.substr(0, path.lastIndexOf('/'));
path = path.substr(authority.length);
}
// IRI represents an absolute path
else if(rel.pathname.indexOf('/') === 0) {
path = rel.pathname;
}
else {
path = base.pathname;
// use up to last directory for base
if(rel.pathname !== '') {
path = path.substr(0, path.lastIndexOf('/') + 1) + rel.pathname;
}
}
var segments = path.split('/');
// remove '.' and '' (do not remove trailing empty path)
segments = segments.filter(function(e, i) {
return e !== '.' && (e !== '' || i === segments.length - 1);
});
// remove as many '..' as possible
for(var i = 0; i < segments.length;) {
var segment = segments[i];
if(segment === '..') {
// too many reverse dots
if(i === 0) {
var last = segments[segments.length - 1];
if(last !== '..') {
segments = [last];
}
else {
segments = [];
}
break;
}
// remove '..' and previous segment
segments.splice(i - 1, 2);
i -= 1;
}
else {
i += 1;
}
}
path = '/' + segments.join('/');
// add query and hash
if(rel.query) {
path += '?' + rel.query;
}
if(rel.hash) {
path += rel.hash;
}
var rval = (base.protocol || '') + '//';
if(base.auth) {
rval += base.auth + '@';
}
rval += authority + path;
return rval;
}
/**
* Removes a base IRI from the given absolute IRI.
*
* @param base the base IRI.
* @param iri the absolute IRI.
*
* @return the relative IRI if relative to base, otherwise the absolute IRI.
*/
function _removeBase(base, iri) {
if(_isString(base)) {
base = jsonld.url.parse(base || '');
base.pathname = base.pathname || '';
}
// establish base root
var root = (base.protocol || '') + '//';
if(base.auth) {
root += base.auth + '@';
}
root += (base.host || '');
// IRI not relative to base
if(iri.indexOf(root) !== 0) {
return iri;
}
// remove root from IRI and parse remainder
var rel = jsonld.url.parse(iri.substr(root.length));
// remove path segments that match
var baseSegments = base.pathname.split('/');
var iriSegments = rel.pathname.split('/');
while(baseSegments.length > 0 && iriSegments.length > 0) {
if(baseSegments[0] !== iriSegments[0]) {
break;
}
baseSegments.shift();
iriSegments.shift();
}
// use '../' for each non-matching base segment
var rval = '';
if(baseSegments.length > 0) {
// do not count the last segment if it isn't a path (doesn't end in '/')
if(base.pathname.indexOf('/', base.pathname.length - 1) === -1) {
baseSegments.pop();
}
for(var i = 0; i < baseSegments.length; ++i) {
rval += '../';
}
}
// prepend remaining segments
rval += iriSegments.join('/');
// add query and hash
if(rel.query) {
rval += '?' + rel.query;
}
if(rel.hash) {
rval += rel.hash;
}
if(rval === '') {
rval = './';
}
return rval;
}
/**
* Gets the initial context.
*
* @param options the options to use.
* base the document base IRI.
*
* @return the initial context.
*/
function _getInitialContext(options) {
var namer = null;
if(options.renameBlankNodes) {
namer = new UniqueNamer('_:b');
}
var base = jsonld.url.parse(options.base || '');
base.pathname = base.pathname || '';
return {
'@base': base,
mappings: {},
keywords: {
'@context': [],
'@container': [],
'@default': [],
'@embed': [],
'@explicit': [],
'@graph': [],
'@id': [],
'@index': [],
'@language': [],
'@list': [],
'@omitDefault': [],
'@preserve': [],
'@set': [],
'@type': [],
'@value': [],
'@vocab': []
},
namer: namer,
inverse: null,
getInverse: _createInverseContext,
clone: _cloneActiveContext,
share: _shareActiveContext
};
/**
* Generates an inverse context for use in the compaction algorithm, if
* not already generated for the given active context.
*
* @return the inverse context.
*/
function _createInverseContext() {
var activeCtx = this;
// lazily create inverse
if(activeCtx.inverse) {
return activeCtx.inverse;
}
var inverse = activeCtx.inverse = {};
// handle default language
var defaultLanguage = activeCtx['@language'] || '@none';
// create term selections for each mapping in the context, ordered by
// shortest and then lexicographically least
var mappings = activeCtx.mappings;
var terms = Object.keys(mappings).sort(_compareShortestLeast);
for(var i = 0; i < terms.length; ++i) {
var term = terms[i];
var mapping = mappings[term];
if(mapping === null) {
continue;
}
var container = mapping['@container'] || '@none';
// iterate over every IRI in the mapping
var ids = mapping['@id'];
if(!_isArray(ids)) {
ids = [ids];
}
for(var ii = 0; ii < ids.length; ++ii) {
var iri = ids[ii];
var entry = inverse[iri];
// initialize entry
if(!entry) {
inverse[iri] = entry = {};
}
// add new entry
if(!entry[container]) {
entry[container] = {
'@language': {},
'@type': {}
};
}
entry = entry[container];
// consider updating @language entry if @type is not specified
if(!('@type' in mapping)) {
// if a @language is specified, update its specific entry
if('@language' in mapping) {
var language = mapping['@language'] || '@null';
_addPreferredTerm(mapping, term, entry['@language'], language);
}
// add an entry for the default language and for no @language
else {
_addPreferredTerm(
mapping, term, entry['@language'], defaultLanguage);
_addPreferredTerm(mapping, term, entry['@language'], '@none');
}
}
// consider updating @type entry if @language is not specified
if(!('@language' in mapping)) {
var type = mapping['@type'] || '@none';
_addPreferredTerm(mapping, term, entry['@type'], type);
}
}
}
return inverse;
}
/**
* Adds or updates the term or property generator for the given entry.
*
* @param mapping the term mapping.
* @param term the term to add.
* @param entry the inverse context typeOrLanguage entry to add to.
* @param typeOrLanguageValue the key in the entry to add to.
*/
function _addPreferredTerm(mapping, term, entry, typeOrLanguageValue) {
if(!(typeOrLanguageValue in entry)) {
entry[typeOrLanguageValue] = {term: null, propertyGenerators: []};
}
var e = entry[typeOrLanguageValue];
if(mapping.propertyGenerator) {
e.propertyGenerators.push(term);
}
else if(e.term === null) {
e.term = term;
}
}
/**
* Clones an active context, creating a child active context.
*
* @return a clone (child) of the active context.
*/
function _cloneActiveContext() {
var child = {};
child['@base'] = this['@base'];
child.keywords = _clone(this.keywords);
child.mappings = _clone(this.mappings);
child.namer = this.namer;
child.clone = this.clone;
child.share = this.share;
child.inverse = null;
child.getInverse = this.getInverse;
if('@language' in this) {
child['@language'] = this['@language'];
}
if('@vocab' in this) {
child['@vocab'] = this['@vocab'];
}
return child;
}
/**
* Returns a copy of this active context that can be shared between
* different processing algorithms. This method only copies the parts
* of the active context that can't be shared.
*
* @return a shareable copy of this active context.
*/
function _shareActiveContext() {
var rval = {};
rval['@base'] = this['@base'];
rval.keywords = this.keywords;
rval.mappings = this.mappings;
rval.namer = null;
if(this.namer) {
rval.namer = new UniqueNamer('_:b');
}
rval.clone = this.clone;
rval.share = this.share;
rval.inverse = this.inverse;
rval.getInverse = this.getInverse;
if('@language' in this) {
rval['@language'] = this['@language'];
}
if('@vocab' in this) {
rval['@vocab'] = this['@vocab'];
}
return rval;
}
}
/**
* Returns whether or not the given value is a keyword.
*
* @param v the value to check.
*
* @return true if the value is a keyword, false if not.
*/
function _isKeyword(v) {
if(!_isString(v)) {
return false;
}
switch(v) {
case '@context':
case '@container':
case '@default':
case '@embed':
case '@explicit':
case '@graph':
case '@id':
case '@index':
case '@language':
case '@list':
case '@omitDefault':
case '@preserve':
case '@set':
case '@type':
case '@value':
case '@vocab':
return true;
}
return false;
}
/**
* Returns true if the given value is an Object.
*
* @param v the value to check.
*
* @return true if the value is an Object, false if not.
*/
function _isObject(v) {
return (Object.prototype.toString.call(v) === '[object Object]');
}
/**
* Returns true if the given value is an empty Object.
*
* @param v the value to check.
*
* @return true if the value is an empty Object, false if not.
*/
function _isEmptyObject(v) {
return _isObject(v) && Object.keys(v).length === 0;
}
/**
* Returns true if the given value is an Array.
*
* @param v the value to check.
*
* @return true if the value is an Array, false if not.
*/
function _isArray(v) {
return Array.isArray(v);
}
/**
* Throws an exception if the given value is not a valid @type value.
*
* @param v the value to check.
*/
function _validateTypeValue(v) {
// can be a string or an empty object
if(_isString(v) || _isEmptyObject(v)) {
return;
}
// must be an array
var isValid = false;
if(_isArray(v)) {
// must contain only strings
isValid = true;
for(var i in v) {
if(!(_isString(v[i]))) {
isValid = false;
break;
}
}
}
if(!isValid) {
throw new JsonLdError(
'Invalid JSON-LD syntax; "@type" value must a string, an array of ' +
'strings, or an empty object.', 'jsonld.SyntaxError', {value: v});
}
}
/**
* Returns true if the given value is a String.
*
* @param v the value to check.
*
* @return true if the value is a String, false if not.
*/
function _isString(v) {
return (typeof v === 'string' ||
Object.prototype.toString.call(v) === '[object String]');
}
/**
* Returns true if the given value is a Number.
*
* @param v the value to check.
*
* @return true if the value is a Number, false if not.
*/
function _isNumber(v) {
return (typeof v === 'number' ||
Object.prototype.toString.call(v) === '[object Number]');
}
/**
* Returns true if the given value is a double.
*
* @param v the value to check.
*
* @return true if the value is a double, false if not.
*/
function _isDouble(v) {
return _isNumber(v) && String(v).indexOf('.') !== -1;
}
/**
* Returns true if the given value is numeric.
*
* @param v the value to check.
*
* @return true if the value is numeric, false if not.
*/
function _isNumeric(v) {
return !isNaN(parseFloat(v)) && isFinite(v);
}
/**
* Returns true if the given value is a Boolean.
*
* @param v the value to check.
*
* @return true if the value is a Boolean, false if not.
*/
function _isBoolean(v) {
return (typeof v === 'boolean' ||
Object.prototype.toString.call(v) === '[object Boolean]');
}
/**
* Returns true if the given value is undefined.
*
* @param v the value to check.
*
* @return true if the value is undefined, false if not.
*/
function _isUndefined(v) {
return (typeof v === 'undefined');
}
/**
* Returns true if the given value is a subject with properties.
*
* @param v the value to check.
*
* @return true if the value is a subject with properties, false if not.
*/
function _isSubject(v) {
// Note: A value is a subject if all of these hold true:
// 1. It is an Object.
// 2. It is not a @value, @set, or @list.
// 3. It has more than 1 key OR any existing key is not @id.
var rval = false;
if(_isObject(v) &&
!(('@value' in v) || ('@set' in v) || ('@list' in v))) {
var keyCount = Object.keys(v).length;
rval = (keyCount > 1 || !('@id' in v));
}
return rval;
}
/**
* Returns true if the given value is a subject reference.
*
* @param v the value to check.
*
* @return true if the value is a subject reference, false if not.
*/
function _isSubjectReference(v) {
// Note: A value is a subject reference if all of these hold true:
// 1. It is an Object.
// 2. It has a single key: @id.
return (_isObject(v) && Object.keys(v).length === 1 && ('@id' in v));
}
/**
* Returns true if the given value is a @value.
*
* @param v the value to check.
*
* @return true if the value is a @value, false if not.
*/
function _isValue(v) {
// Note: A value is a @value if all of these hold true:
// 1. It is an Object.
// 2. It has the @value property.
return _isObject(v) && ('@value' in v);
}
/**
* Returns true if the given value is a @list.
*
* @param v the value to check.
*
* @return true if the value is a @list, false if not.
*/
function _isList(v) {
// Note: A value is a @list if all of these hold true:
// 1. It is an Object.
// 2. It has the @list property.
return _isObject(v) && ('@list' in v);
}
/**
* Returns true if the given value is a blank node.
*
* @param v the value to check.
*
* @return true if the value is a blank node, false if not.
*/
function _isBlankNode(v) {
// Note: A value is a blank node if all of these hold true:
// 1. It is an Object.
// 2. If it has an @id key its value begins with '_:'.
// 3. It has no keys OR is not a @value, @set, or @list.
var rval = false;
if(_isObject(v)) {
if('@id' in v) {
rval = (v['@id'].indexOf('_:') === 0);
}
else {
rval = (Object.keys(v).length === 0 ||
!(('@value' in v) || ('@set' in v) || ('@list' in v)));
}
}
return rval;
}
/**
* Returns true if the given value is an absolute IRI, false if not.
*
* @param v the value to check.
*
* @return true if the value is an absolute IRI, false if not.
*/
function _isAbsoluteIri(v) {
return _isString(v) && v.indexOf(':') !== -1;
}
/**
* Clones an object, array, or string/number.
*
* @param value the value to clone.
*
* @return the cloned value.
*/
function _clone(value) {
if(value && typeof value === 'object') {
var rval = _isArray(value) ? [] : {};
for(var i in value) {
rval[i] = _clone(value[i]);
}
return rval;
}
return value;
}
/**
* Finds all @context URLs in the given JSON-LD input.
*
* @param input the JSON-LD input.
* @param urls a map of URLs (url => false/@contexts).
* @param replace true to replace the URLs in the given input with the
* @contexts from the urls map, false not to.
* @param base the base IRI to use to resolve relative IRIs.
*
* @return true if new URLs to retrieve were found, false if not.
*/
function _findContextUrls(input, urls, replace, base) {
var count = Object.keys(urls).length;
if(_isArray(input)) {
for(var i in input) {
_findContextUrls(input[i], urls, replace, base);
}
return (count < Object.keys(urls).length);
}
else if(_isObject(input)) {
for(var key in input) {
if(key !== '@context') {
_findContextUrls(input[key], urls, replace, base);
continue;
}
// get @context
var ctx = input[key];
// array @context
if(_isArray(ctx)) {
var length = ctx.length;
for(var i = 0; i < length; ++i) {
var _ctx = ctx[i];
if(_isString(_ctx)) {
_ctx = _prependBase(base, _ctx);
// replace w/@context if requested
if(replace) {
_ctx = urls[_ctx];
if(_isArray(_ctx)) {
// add flattened context
Array.prototype.splice.apply(ctx, [i, 1].concat(_ctx));
i += _ctx.length;
length += _ctx.length;
}
else {
ctx[i] = _ctx;
}
}
// @context URL found
else if(!(_ctx in urls)) {
urls[_ctx] = false;
}
}
}
}
// string @context
else if(_isString(ctx)) {
ctx = _prependBase(base, ctx);
// replace w/@context if requested
if(replace) {
input[key] = urls[ctx];
}
// @context URL found
else if(!(ctx in urls)) {
urls[ctx] = false;
}
}
}
return (count < Object.keys(urls).length);
}
return false;
}
/**
* Retrieves external @context URLs using the given context loader. Every
* instance of @context in the input that refers to a URL will be replaced
* with the JSON @context found at that URL.
*
* @param input the JSON-LD input with possible contexts.
* @param options the options to use:
* loadContext(url, callback(err, url, result)) the context loader.
* @param callback(err, input) called once the operation completes.
*/
function _retrieveContextUrls(input, options, callback) {
// if any error occurs during URL resolution, quit
var error = null;
var regex = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
// recursive context loader
var loadContext = options.loadContext;
var retrieve = function(input, cycles, loadContext, base, callback) {
if(Object.keys(cycles).length > MAX_CONTEXT_URLS) {
error = new JsonLdError(
'Maximum number of @context URLs exceeded.',
'jsonld.ContextUrlError', {max: MAX_CONTEXT_URLS});
return callback(error);
}
// for tracking the URLs to retrieve
var urls = {};
// finished will be called once the URL queue is empty
var finished = function() {
// replace all URLs in the input
_findContextUrls(input, urls, true, base);
callback(null, input);
};
// find all URLs in the given input
if(!_findContextUrls(input, urls, false, base)) {
// no new URLs in input
finished();
}
// queue all unretrieved URLs
var queue = [];
for(var url in urls) {
if(urls[url] === false) {
// validate URL
if(!regex.test(url)) {
error = new JsonLdError(
'Malformed URL.', 'jsonld.InvalidUrl', {url: url});
return callback(error);
}
queue.push(url);
}
}
// retrieve URLs in queue
var count = queue.length;
for(var i in queue) {
(function(url) {
// check for context URL cycle
if(url in cycles) {
error = new JsonLdError(
'Cyclical @context URLs detected.',
'jsonld.ContextUrlError', {url: url});
return callback(error);
}
var _cycles = _clone(cycles);
_cycles[url] = true;
loadContext(url, function(err, finalUrl, ctx) {
// short-circuit if there was an error with another URL
if(error) {
return;
}
// parse string context as JSON
if(!err && _isString(ctx)) {
try {
ctx = JSON.parse(ctx);
}
catch(ex) {
err = ex;
}
}
// ensure ctx is an object
if(err) {
err = new JsonLdError(
'Derefencing a URL did not result in a valid JSON-LD object. ' +
'Possible causes are an inaccessible URL perhaps due to ' +
'a same-origin policy (ensure the server uses CORS if you are ' +
'using client-side JavaScript), too many redirects, or a ' +
'non-JSON response.',
'jsonld.InvalidUrl', {url: url, cause: err});
}
else if(!_isObject(ctx)) {
err = new JsonLdError(
'Derefencing a URL did not result in a JSON object. The ' +
'response was valid JSON, but it was not a JSON object.',
'jsonld.InvalidUrl', {url: url, cause: err});
}
if(err) {
error = err;
return callback(error);
}
// use empty context if no @context key is present
if(!('@context' in ctx)) {
ctx = {'@context': {}};
}
// recurse
retrieve(ctx, _cycles, loadContext, url, function(err, ctx) {
if(err) {
return callback(err);
}
urls[url] = ctx['@context'];
count -= 1;
if(count === 0) {
finished();
}
});
});
}(queue[i]));
}
};
retrieve(input, {}, loadContext, options.base, callback);
}
// define js 1.8.5 Object.keys method if not present
if(!Object.keys) {
Object.keys = function(o) {
if(o !== Object(o)) {
throw new TypeError('Object.keys called on non-object');
}
var rval = [];
for(var p in o) {
if(Object.prototype.hasOwnProperty.call(o, p)) {
rval.push(p);
}
}
return rval;
};
}
/**
* Parses RDF in the form of N-Quads.
*
* @param input the N-Quads input to parse.
*
* @return an RDF dataset.
*/
function _parseNQuads(input) {
// define partial regexes
var iri = '(?:<([^:]+:[^>]*)>)';
var bnode = '(_:(?:[A-Za-z][A-Za-z0-9]*))';
var plain = '"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"';
var datatype = '(?:\\^\\^' + iri + ')';
var language = '(?:@([a-z]+(?:-[a-z0-9]+)*))';
var literal = '(?:' + plain + '(?:' + datatype + '|' + language + ')?)';
var ws = '[ \\t]+';
var wso = '[ \\t]*';
var eoln = /(?:\r\n)|(?:\n)|(?:\r)/g;
var empty = new RegExp('^' + wso + '$');
// define quad part regexes
var subject = '(?:' + iri + '|' + bnode + ')' + ws;
var property = iri + ws;
var object = '(?:' + iri + '|' + bnode + '|' + literal + ')' + wso;
var graphName = '(?:\\.|(?:(?:' + iri + '|' + bnode + ')' + wso + '\\.))';
// full quad regex
var quad = new RegExp(
'^' + wso + subject + property + object + graphName + wso + '$');
// build RDF dataset
var dataset = {};
// split N-Quad input into lines
var lines = input.split(eoln);
var lineNumber = 0;
for(var li = 0; li < lines.length; ++li) {
var line = lines[li];
lineNumber++;
// skip empty lines
if(empty.test(line)) {
continue;
}
// parse quad
var match = line.match(quad);
if(match === null) {
throw new JsonLdError(
'Error while parsing N-Quads; invalid quad.',
'jsonld.ParseError', {line: lineNumber});
}
// create RDF triple
var triple = {};
// get subject
if(!_isUndefined(match[1])) {
triple.subject = {type: 'IRI', value: match[1]};
}
else {
triple.subject = {type: 'blank node', value: match[2]};
}
// get predicate
triple.predicate = {type: 'IRI', value: match[3]};
// get object
if(!_isUndefined(match[4])) {
triple.object = {type: 'IRI', value: match[4]};
}
else if(!_isUndefined(match[5])) {
triple.object = {type: 'blank node', value: match[5]};
}
else {
triple.object = {type: 'literal'};
if(!_isUndefined(match[7])) {
triple.object.datatype = match[7];
}
else if(!_isUndefined(match[8])) {
triple.object.datatype = RDF_LANGSTRING;
triple.object.language = match[8];
}
else {
triple.object.datatype = XSD_STRING;
}
var unescaped = match[6]
.replace(/\\"/g, '"')
.replace(/\\t/g, '\t')
.replace(/\\n/g, '\n')
.replace(/\\r/g, '\r')
.replace(/\\\\/g, '\\');
triple.object.value = unescaped;
}
// get graph name ('@default' is used for the default graph)
var name = '@default';
if(!_isUndefined(match[9])) {
name = match[9];
}
else if(!_isUndefined(match[10])) {
name = match[10];
}
// initialize graph in dataset
if(!(name in dataset)) {
dataset[name] = [triple];
}
// add triple if unique to its graph
else {
var unique = true;
var triples = dataset[name];
for(var ti = 0; unique && ti < triples.length; ++ti) {
if(_compareRDFTriples(triples[ti], triple)) {
unique = false;
}
}
if(unique) {
triples.push(triple);
}
}
}
return dataset;
}
// register the N-Quads RDF parser
jsonld.registerRDFParser('application/nquads', _parseNQuads);
/**
* Converts an RDF dataset to N-Quads.
*
* @param dataset the RDF dataset to convert.
*
* @return the N-Quads string.
*/
function _toNQuads(dataset) {
var quads = [];
for(var graphName in dataset) {
var triples = dataset[graphName];
for(var ti = 0; ti < triples.length; ++ti) {
var triple = triples[ti];
if(graphName === '@default') {
graphName = null;
}
quads.push(_toNQuad(triple, graphName));
}
}
quads.sort();
return quads.join('');
}
/**
* Converts an RDF triple and graph name to an N-Quad string (a single quad).
*
* @param triple the RDF triple to convert.
* @param graphName the name of the graph containing the triple, null for
* the default graph.
* @param bnode the bnode the quad is mapped to (optional, for use
* during normalization only).
*
* @return the N-Quad string.
*/
function _toNQuad(triple, graphName, bnode) {
var s = triple.subject;
var p = triple.predicate;
var o = triple.object;
var g = graphName;
var quad = '';
// subject is an IRI or bnode
if(s.type === 'IRI') {
quad += '<' + s.value + '>';
}
// normalization mode
else if(bnode) {
quad += (s.value === bnode) ? '_:a' : '_:z';
}
// normal mode
else {
quad += s.value;
}
// predicate is always an IRI
quad += ' <' + p.value + '> ';
// object is IRI, bnode, or literal
if(o.type === 'IRI') {
quad += '<' + o.value + '>';
}
else if(o.type === 'blank node') {
// normalization mode
if(bnode) {
quad += (o.value === bnode) ? '_:a' : '_:z';
}
// normal mode
else {
quad += o.value;
}
}
else {
var escaped = o.value
.replace(/\\/g, '\\\\')
.replace(/\t/g, '\\t')
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r')
.replace(/\"/g, '\\"');
quad += '"' + escaped + '"';
if(o.datatype === RDF_LANGSTRING) {
quad += '@' + o.language;
}
else if(o.datatype !== XSD_STRING) {
quad += '^^<' + o.datatype + '>';
}
}
// graph
if(g !== null) {
if(g.indexOf('_:') !== 0) {
quad += ' <' + g + '>';
}
else if(bnode) {
quad += ' _:g';
}
else {
quad += ' ' + g;
}
}
quad += ' .\n';
return quad;
}
/**
* Parses the RDF dataset found via the data object from the RDFa API.
*
* @param data the RDFa API data object.
*
* @return the RDF dataset.
*/
function _parseRdfaApiData(data) {
var dataset = {};
dataset['@default'] = [];
var subjects = data.getSubjects();
for(var si = 0; si < subjects.length; ++si) {
var subject = subjects[si];
if(subject === null) {
continue;
}
// get all related triples
var triples = data.getSubjectTriples(subject);
if(triples === null) {
continue;
}
var predicates = triples.predicates;
for(var predicate in predicates) {
// iterate over objects
var objects = predicates[predicate].objects;
for(var oi = 0; oi < objects.length; ++oi) {
var object = objects[oi];
// create RDF triple
var triple = {};
// add subject
if(subject.indexOf('_:') === 0) {
triple.subject = {type: 'blank node', value: subject};
}
else {
triple.subject = {type: 'IRI', value: subject};
}
// add predicate
triple.predicate = {type: 'IRI', value: predicate};
// serialize XML literal
var value = object.value;
if(object.type === RDF_XML_LITERAL) {
// initialize XMLSerializer
if(!XMLSerializer) {
_defineXMLSerializer();
}
var serializer = new XMLSerializer();
value = '';
for(var x = 0; x < object.value.length; x++) {
if(object.value[x].nodeType === Node.ELEMENT_NODE) {
value += serializer.serializeToString(object.value[x]);
}
else if(object.value[x].nodeType === Node.TEXT_NODE) {
value += object.value[x].nodeValue;
}
}
}
// add object
triple.object = {};
// object is an IRI
if(object.type === RDF_OBJECT) {
if(object.value.indexOf('_:') === 0) {
triple.object.type = 'blank node';
}
else {
triple.object.type = 'IRI';
}
}
// literal
else {
triple.object.type = 'literal';
if(object.type === RDF_PLAIN_LITERAL) {
if(object.language) {
triple.object.datatype = RDF_LANGSTRING;
triple.object.language = object.language;
}
else {
triple.object.datatype = XSD_STRING;
}
}
else {
triple.object.datatype = object.type;
}
}
triple.object.value = value;
// add triple to dataset in default graph
dataset['@default'].push(triple);
}
}
}
return dataset;
}
// register the RDFa API RDF parser
jsonld.registerRDFParser('rdfa-api', _parseRdfaApiData);
/**
* Creates a new UniqueNamer. A UniqueNamer issues unique names, keeping
* track of any previously issued names.
*
* @param prefix the prefix to use ('<prefix><counter>').
*/
function UniqueNamer(prefix) {
this.prefix = prefix;
this.counter = 0;
this.existing = {};
};
/**
* Copies this UniqueNamer.
*
* @return a copy of this UniqueNamer.
*/
UniqueNamer.prototype.clone = function() {
var copy = new UniqueNamer(this.prefix);
copy.counter = this.counter;
copy.existing = _clone(this.existing);
return copy;
};
/**
* Gets the new name for the given old name, where if no old name is given
* a new name will be generated.
*
* @param [oldName] the old name to get the new name for.
*
* @return the new name.
*/
UniqueNamer.prototype.getName = function(oldName) {
// return existing old name
if(oldName && oldName in this.existing) {
return this.existing[oldName];
}
// get next name
var name = this.prefix + this.counter;
this.counter += 1;
// save mapping
if(oldName) {
this.existing[oldName] = name;
}
return name;
};
/**
* Returns true if the given oldName has already been assigned a new name.
*
* @param oldName the oldName to check.
*
* @return true if the oldName has been assigned a new name, false if not.
*/
UniqueNamer.prototype.isNamed = function(oldName) {
return (oldName in this.existing);
};
/**
* A Permutator iterates over all possible permutations of the given array
* of elements.
*
* @param list the array of elements to iterate over.
*/
Permutator = function(list) {
// original array
this.list = list.sort();
// indicates whether there are more permutations
this.done = false;
// directional info for permutation algorithm
this.left = {};
for(var i in list) {
this.left[list[i]] = true;
}
};
/**
* Returns true if there is another permutation.
*
* @return true if there is another permutation, false if not.
*/
Permutator.prototype.hasNext = function() {
return !this.done;
};
/**
* Gets the next permutation. Call hasNext() to ensure there is another one
* first.
*
* @return the next permutation.
*/
Permutator.prototype.next = function() {
// copy current permutation
var rval = this.list.slice();
/* Calculate the next permutation using the Steinhaus-Johnson-Trotter
permutation algorithm. */
// get largest mobile element k
// (mobile: element is greater than the one it is looking at)
var k = null;
var pos = 0;
var length = this.list.length;
for(var i = 0; i < length; ++i) {
var element = this.list[i];
var left = this.left[element];
if((k === null || element > k) &&
((left && i > 0 && element > this.list[i - 1]) ||
(!left && i < (length - 1) && element > this.list[i + 1]))) {
k = element;
pos = i;
}
}
// no more permutations
if(k === null) {
this.done = true;
}
else {
// swap k and the element it is looking at
var swap = this.left[k] ? pos - 1 : pos + 1;
this.list[pos] = this.list[swap];
this.list[swap] = k;
// reverse the direction of all elements larger than k
for(var i = 0; i < length; ++i) {
if(this.list[i] > k) {
this.left[this.list[i]] = !this.left[this.list[i]];
}
}
}
return rval;
};
// SHA-1 API
var sha1 = jsonld.sha1 = {};
if(_nodejs) {
var crypto = require('crypto');
sha1.create = function() {
var md = crypto.createHash('sha1');
return {
update: function(data) {
md.update(data, 'utf8');
},
digest: function() {
return md.digest('hex');
}
};
};
}
else {
sha1.create = function() {
return new sha1.MessageDigest();
};
}
/**
* Hashes the given array of quads and returns its hexadecimal SHA-1 message
* digest.
*
* @param nquads the list of serialized quads to hash.
*
* @return the hexadecimal SHA-1 message digest.
*/
sha1.hash = function(nquads) {
var md = sha1.create();
for(var i in nquads) {
md.update(nquads[i]);
}
return md.digest();
};
// only define sha1 MessageDigest for non-nodejs
if(!_nodejs) {
/**
* Creates a simple byte buffer for message digest operations.
*/
sha1.Buffer = function() {
this.data = '';
this.read = 0;
};
/**
* Puts a 32-bit integer into this buffer in big-endian order.
*
* @param i the 32-bit integer.
*/
sha1.Buffer.prototype.putInt32 = function(i) {
this.data += (
String.fromCharCode(i >> 24 & 0xFF) +
String.fromCharCode(i >> 16 & 0xFF) +
String.fromCharCode(i >> 8 & 0xFF) +
String.fromCharCode(i & 0xFF));
};
/**
* Gets a 32-bit integer from this buffer in big-endian order and
* advances the read pointer by 4.
*
* @return the word.
*/
sha1.Buffer.prototype.getInt32 = function() {
var rval = (
this.data.charCodeAt(this.read) << 24 ^
this.data.charCodeAt(this.read + 1) << 16 ^
this.data.charCodeAt(this.read + 2) << 8 ^
this.data.charCodeAt(this.read + 3));
this.read += 4;
return rval;
};
/**
* Gets the bytes in this buffer.
*
* @return a string full of UTF-8 encoded characters.
*/
sha1.Buffer.prototype.bytes = function() {
return this.data.slice(this.read);
};
/**
* Gets the number of bytes in this buffer.
*
* @return the number of bytes in this buffer.
*/
sha1.Buffer.prototype.length = function() {
return this.data.length - this.read;
};
/**
* Compacts this buffer.
*/
sha1.Buffer.prototype.compact = function() {
this.data = this.data.slice(this.read);
this.read = 0;
};
/**
* Converts this buffer to a hexadecimal string.
*
* @return a hexadecimal string.
*/
sha1.Buffer.prototype.toHex = function() {
var rval = '';
for(var i = this.read; i < this.data.length; ++i) {
var b = this.data.charCodeAt(i);
if(b < 16) {
rval += '0';
}
rval += b.toString(16);
}
return rval;
};
/**
* Creates a SHA-1 message digest object.
*
* @return a message digest object.
*/
sha1.MessageDigest = function() {
// do initialization as necessary
if(!_sha1.initialized) {
_sha1.init();
}
this.blockLength = 64;
this.digestLength = 20;
// length of message so far (does not including padding)
this.messageLength = 0;
// input buffer
this.input = new sha1.Buffer();
// for storing words in the SHA-1 algorithm
this.words = new Array(80);
// SHA-1 state contains five 32-bit integers
this.state = {
h0: 0x67452301,
h1: 0xEFCDAB89,
h2: 0x98BADCFE,
h3: 0x10325476,
h4: 0xC3D2E1F0
};
};
/**
* Updates the digest with the given string input.
*
* @param msg the message input to update with.
*/
sha1.MessageDigest.prototype.update = function(msg) {
// UTF-8 encode message
msg = unescape(encodeURIComponent(msg));
// update message length and input buffer
this.messageLength += msg.length;
this.input.data += msg;
// process input
_sha1.update(this.state, this.words, this.input);
// compact input buffer every 2K or if empty
if(this.input.read > 2048 || this.input.length() === 0) {
this.input.compact();
}
};
/**
* Produces the digest.
*
* @return the digest as a hexadecimal string.
*/
sha1.MessageDigest.prototype.digest = function() {
/* Determine the number of bytes that must be added to the message
to ensure its length is congruent to 448 mod 512. In other words,
a 64-bit integer that gives the length of the message will be
appended to the message and whatever the length of the message is
plus 64 bits must be a multiple of 512. So the length of the
message must be congruent to 448 mod 512 because 512 - 64 = 448.
In order to fill up the message length it must be filled with
padding that begins with 1 bit followed by all 0 bits. Padding
must *always* be present, so if the message length is already
congruent to 448 mod 512, then 512 padding bits must be added. */
// 512 bits == 64 bytes, 448 bits == 56 bytes, 64 bits = 8 bytes
// _padding starts with 1 byte with first bit is set in it which
// is byte value 128, then there may be up to 63 other pad bytes
var len = this.messageLength;
var padBytes = new sha1.Buffer();
padBytes.data += this.input.bytes();
padBytes.data += _sha1.padding.substr(0, 64 - ((len + 8) % 64));
/* Now append length of the message. The length is appended in bits
as a 64-bit number in big-endian order. Since we store the length
in bytes, we must multiply it by 8 (or left shift by 3). So here
store the high 3 bits in the low end of the first 32-bits of the
64-bit number and the lower 5 bits in the high end of the second
32-bits. */
padBytes.putInt32((len >>> 29) & 0xFF);
padBytes.putInt32((len << 3) & 0xFFFFFFFF);
_sha1.update(this.state, this.words, padBytes);
var rval = new sha1.Buffer();
rval.putInt32(this.state.h0);
rval.putInt32(this.state.h1);
rval.putInt32(this.state.h2);
rval.putInt32(this.state.h3);
rval.putInt32(this.state.h4);
return rval.toHex();
};
// private SHA-1 data
var _sha1 = {
padding: null,
initialized: false
};
/**
* Initializes the constant tables.
*/
_sha1.init = function() {
// create padding
_sha1.padding = String.fromCharCode(128);
var c = String.fromCharCode(0x00);
var n = 64;
while(n > 0) {
if(n & 1) {
_sha1.padding += c;
}
n >>>= 1;
if(n > 0) {
c += c;
}
}
// now initialized
_sha1.initialized = true;
};
/**
* Updates a SHA-1 state with the given byte buffer.
*
* @param s the SHA-1 state to update.
* @param w the array to use to store words.
* @param input the input byte buffer.
*/
_sha1.update = function(s, w, input) {
// consume 512 bit (64 byte) chunks
var t, a, b, c, d, e, f, i;
var len = input.length();
while(len >= 64) {
// the w array will be populated with sixteen 32-bit big-endian words
// and then extended into 80 32-bit words according to SHA-1 algorithm
// and for 32-79 using Max Locktyukhin's optimization
// initialize hash value for this chunk
a = s.h0;
b = s.h1;
c = s.h2;
d = s.h3;
e = s.h4;
// round 1
for(i = 0; i < 16; ++i) {
t = input.getInt32();
w[i] = t;
f = d ^ (b & (c ^ d));
t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t;
e = d;
d = c;
c = (b << 30) | (b >>> 2);
b = a;
a = t;
}
for(; i < 20; ++i) {
t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]);
t = (t << 1) | (t >>> 31);
w[i] = t;
f = d ^ (b & (c ^ d));
t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t;
e = d;
d = c;
c = (b << 30) | (b >>> 2);
b = a;
a = t;
}
// round 2
for(; i < 32; ++i) {
t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]);
t = (t << 1) | (t >>> 31);
w[i] = t;
f = b ^ c ^ d;
t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t;
e = d;
d = c;
c = (b << 30) | (b >>> 2);
b = a;
a = t;
}
for(; i < 40; ++i) {
t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]);
t = (t << 2) | (t >>> 30);
w[i] = t;
f = b ^ c ^ d;
t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t;
e = d;
d = c;
c = (b << 30) | (b >>> 2);
b = a;
a = t;
}
// round 3
for(; i < 60; ++i) {
t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]);
t = (t << 2) | (t >>> 30);
w[i] = t;
f = (b & c) | (d & (b ^ c));
t = ((a << 5) | (a >>> 27)) + f + e + 0x8F1BBCDC + t;
e = d;
d = c;
c = (b << 30) | (b >>> 2);
b = a;
a = t;
}
// round 4
for(; i < 80; ++i) {
t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]);
t = (t << 2) | (t >>> 30);
w[i] = t;
f = b ^ c ^ d;
t = ((a << 5) | (a >>> 27)) + f + e + 0xCA62C1D6 + t;
e = d;
d = c;
c = (b << 30) | (b >>> 2);
b = a;
a = t;
}
// update hash state
s.h0 += a;
s.h1 += b;
s.h2 += c;
s.h3 += d;
s.h4 += e;
len -= 64;
}
};
} // end non-nodejs
if(!XMLSerializer) {
function _defineXMLSerializer() {
XMLSerializer = require('xmldom').XMLSerializer;
}
} // end _defineXMLSerializer
// define URL parser
jsonld.url = {};
if(_nodejs) {
jsonld.url.parse = require('url').parse;
}
else {
// parseUri 1.2.2
// (c) Steven Levithan <stevenlevithan.com>
// MIT License
var parseUri = {};
parseUri.options = {
key: ['href','protocol','host','userInfo','user','password','hostname','port','relative','path','directory','file','query','hash'],
parser: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/
};
jsonld.url.parse = function(str) {
var o = parseUri.options;
var m = o.parser.exec(str);
var uri = {};
var i = 14;
while(i--) {
uri[o.key[i]] = m[i] || '';
}
// normalize to node.js API
if(uri.host && uri.path === '') {
uri.path = '/';
}
uri.pathname = uri.path;
if(uri.query) {
uri.path = uri.path + '?' + uri.query;
}
uri.protocol += ':';
if(uri.hash) {
uri.hash = '#' + uri.hash;
}
return uri;
};
}
if(_nodejs) {
// use node context loader by default
jsonld.useContextLoader('node');
}
// end of jsonld API factory
return jsonld;
};
// external APIs:
// used to generate a new jsonld API instance
var factory = function() {
return wrapper(function() {
return factory();
});
};
// the shared global jsonld API instance
wrapper(factory);
// export nodejs API
if(_nodejs) {
module.exports = factory;
}
// export AMD API
else if(typeof define === 'function' && define.amd) {
define('jsonld', [], function() {
return factory;
});
}
// export simple browser API
else if(_browser) {
window.jsonld = window.jsonld || factory;
}
})();
|
var BrowseNextRequest_Schema = {
name: "BrowseNextRequest",
documentation: "Continues one or more browse operations.",
fields: [
{name: "requestHeader", fieldType: "RequestHeader", documentation: "A standard header included in all requests sent to a server."},
/*
*
* A Boolean parameter with the following values:
* TRUE: passed continuationPoints shall be reset to free resources in the Server. The continuation points
* are released and the results and diagnosticInfos arrays are empty.
* FALSE: passed continuationPoints shall be used to get the next set of browse information.
*
* A Client shall always use the continuation point returned by a Browse or
* BrowseNext response to free the resources for the continuation point in the
* Server. If the Client does not want to get the next set of browse information,
* BrowseNext shall be called with this parameter set to TRUE.
*/
{name: "releaseContinuationPoints", fieldType: "Boolean", documentation: "If TRUE the continuation points are released and no results are returned." },
/*
* A list of Server-defined opaque values that represent continuation points. The value for a continuation point
* was returned to the Client in a previous Browse or BrowseNext response. These values are used to identify the
* previously processed Browse or BrowseNext request that is being continued and the point in the result set
* from which the browse response is to continue
* Clients may mix continuation points from different Browse or BrowseNext responses.
*/
{name: "continuationPoints", isArray: true, fieldType: "ContinuationPoint", documentation: "The maximum number of references to return in the response."}
]
};
exports.BrowseNextRequest_Schema = BrowseNextRequest_Schema;
|
define({main:{"ar-LB":{identity:{version:{_number:"$Revision: 11914 $",_cldrVersion:"29"},language:"ar",territory:"LB"},dates:{timeZoneNames:{hourFormat:"+HH:mm;-HH:mm",gmtFormat:"جرينتش{0}",gmtZeroFormat:"جرينتش",regionFormat:"توقيت {0}","regionFormat-type-daylight":"توقيت {0} الصيفي","regionFormat-type-standard":"توقيت {0} الرسمي",fallbackFormat:"{1} ({0})",zone:{America:{Anchorage:{exemplarCity:"أنشوراج"},Bogota:{exemplarCity:"بوغوتا"},Buenos_Aires:{exemplarCity:"بوينوس أيرس"},Caracas:{exemplarCity:"كاراكاس"},
Chicago:{exemplarCity:"شيكاغو"},Chihuahua:{exemplarCity:"تشيواوا"},Costa_Rica:{exemplarCity:"كوستاريكا"},Denver:{exemplarCity:"دنفر"},Edmonton:{exemplarCity:"ايدمونتون"},El_Salvador:{exemplarCity:"السلفادور"},Godthab:{exemplarCity:"غودثاب"},Guatemala:{exemplarCity:"غواتيمالا"},Guayaquil:{exemplarCity:"غواياكويل"},Halifax:{exemplarCity:"هاليفاكس"},Indianapolis:{exemplarCity:"إنديانابوليس"},Lima:{exemplarCity:"ليما"},Los_Angeles:{exemplarCity:"لوس انجلوس"},Managua:{exemplarCity:"ماناغوا"},Mazatlan:{exemplarCity:"مازاتلان"},
Mexico_City:{exemplarCity:"مدينة المكسيك"},New_York:{exemplarCity:"نيويورك"},Noronha:{exemplarCity:"نوروناه"},Panama:{exemplarCity:"بنما"},Phoenix:{exemplarCity:"فينكس"},Puerto_Rico:{exemplarCity:"بورتوريكو"},Regina:{exemplarCity:"ريجينا"},Santiago:{exemplarCity:"سانتياغو"},Sao_Paulo:{exemplarCity:"ساو باولو"},St_Johns:{exemplarCity:"سانت جونس"},Tijuana:{exemplarCity:"تيخوانا"},Toronto:{exemplarCity:"تورونتو"},Vancouver:{exemplarCity:"فانكوفر"},Winnipeg:{exemplarCity:"وينيبيج"}},Atlantic:{Azores:{exemplarCity:"أزورس"},
Cape_Verde:{exemplarCity:"الرأس الأخضر"},Reykjavik:{exemplarCity:"ريكيافيك"}},Europe:{Amsterdam:{exemplarCity:"أمستردام"},Athens:{exemplarCity:"أثينا"},Belgrade:{exemplarCity:"بلغراد"},Berlin:{exemplarCity:"برلين"},Brussels:{exemplarCity:"بروكسل"},Bucharest:{exemplarCity:"بوخارست"},Budapest:{exemplarCity:"بودابست"},Copenhagen:{exemplarCity:"كوبنهاغن"},Dublin:{exemplarCity:"دبلن"},Helsinki:{exemplarCity:"هلسنكي"},Istanbul:{exemplarCity:"إسطنبول"},Kiev:{exemplarCity:"كييف"},Lisbon:{exemplarCity:"لشبونة"},
London:{exemplarCity:"لندن"},Luxembourg:{exemplarCity:"لوكسمبورغ"},Madrid:{exemplarCity:"مدريد"},Moscow:{exemplarCity:"موسكو"},Oslo:{exemplarCity:"أوسلو"},Paris:{exemplarCity:"باريس"},Prague:{exemplarCity:"براغ"},Riga:{exemplarCity:"ريغا"},Rome:{exemplarCity:"روما"},Sofia:{exemplarCity:"صوفيا"},Stockholm:{exemplarCity:"ستوكهولم"},Tallinn:{exemplarCity:"تالين"},Tirane:{exemplarCity:"تيرانا"},Vienna:{exemplarCity:"فيينا"},Vilnius:{exemplarCity:"فيلنيوس"},Warsaw:{exemplarCity:"وارسو"},Zurich:{exemplarCity:"زيورخ"}},
Africa:{Algiers:{exemplarCity:"الجزائر"},Cairo:{exemplarCity:"القاهرة"},Casablanca:{exemplarCity:"الدار البيضاء"},Djibouti:{exemplarCity:"جيبوتي"},Harare:{exemplarCity:"هراري"},Johannesburg:{exemplarCity:"جوهانسبرغ"},Khartoum:{exemplarCity:"الخرطوم"},Lagos:{exemplarCity:"لاغوس"},Mogadishu:{exemplarCity:"مقديشيو"},Nairobi:{exemplarCity:"نيروبي"},Nouakchott:{exemplarCity:"نواكشوط"},Tripoli:{exemplarCity:"طرابلس"},Tunis:{exemplarCity:"تونس"}},Asia:{Aden:{exemplarCity:"عدن"},Almaty:{exemplarCity:"ألماتي"},
Amman:{exemplarCity:"عمان"},Baghdad:{exemplarCity:"بغداد"},Bahrain:{exemplarCity:"البحرين"},Baku:{exemplarCity:"باكو"},Bangkok:{exemplarCity:"بانكوك"},Beirut:{exemplarCity:"بيروت"},Calcutta:{exemplarCity:"كالكتا"},Colombo:{exemplarCity:"كولومبو"},Damascus:{exemplarCity:"دمشق"},Dhaka:{exemplarCity:"دكا"},Dubai:{exemplarCity:"دبي"},Hong_Kong:{exemplarCity:"هونغ كونغ"},Irkutsk:{exemplarCity:"ايركيتسك"},Jakarta:{exemplarCity:"جاكرتا"},Jerusalem:{exemplarCity:"القدس"},Kabul:{exemplarCity:"كابول"},Kamchatka:{exemplarCity:"كامتشاتكا"},
Karachi:{exemplarCity:"كراتشي"},Krasnoyarsk:{exemplarCity:"كراسنويارسك"},Kuala_Lumpur:{exemplarCity:"كوالا لامبور"},Kuwait:{exemplarCity:"الكويت"},Magadan:{exemplarCity:"مجادن"},Manila:{exemplarCity:"مانيلا"},Muscat:{exemplarCity:"مسقط"},Nicosia:{exemplarCity:"نيقوسيا"},Novosibirsk:{exemplarCity:"نوفوسبيرسك"},Qatar:{exemplarCity:"قطر"},Rangoon:{exemplarCity:"رانغون"},Riyadh:{exemplarCity:"الرياض"},Saigon:{exemplarCity:"مدينة هو تشي منة"},Seoul:{exemplarCity:"سول"},Shanghai:{exemplarCity:"شنغهاي"},
Singapore:{exemplarCity:"سنغافورة"},Taipei:{exemplarCity:"تايبيه"},Tashkent:{exemplarCity:"طشقند"},Tehran:{exemplarCity:"طهران"},Tokyo:{exemplarCity:"طوكيو"},Vladivostok:{exemplarCity:"فلاديفوستك"},Yakutsk:{exemplarCity:"ياكتسك"},Yekaterinburg:{exemplarCity:"يكاترنبيرج"}},Australia:{Adelaide:{exemplarCity:"أديليد"},Brisbane:{exemplarCity:"برسيبان"},Darwin:{exemplarCity:"دارون"},Hobart:{exemplarCity:"هوبارت"},Perth:{exemplarCity:"برثا"},Sydney:{exemplarCity:"سيدني"}},Pacific:{Auckland:{exemplarCity:"أوكلاند"},
Fiji:{exemplarCity:"فيجي"},Guam:{exemplarCity:"غوام"},Honolulu:{exemplarCity:"هونولولو"},Midway:{exemplarCity:"ميدواي"},Pago_Pago:{exemplarCity:"باغو باغو"},Tongatapu:{exemplarCity:"تونغاتابو"}}},metazone:{Afghanistan:{"long":{standard:"توقيت أفغانستان"}},Africa_Central:{"long":{standard:"توقيت وسط أفريقيا"}},Africa_Eastern:{"long":{standard:"توقيت شرق أفريقيا"}},Africa_Southern:{"long":{standard:"توقيت جنوب أفريقيا"}},Africa_Western:{"long":{generic:"توقيت غرب أفريقيا",standard:"توقيت غرب أفريقيا الرسمي",
daylight:"توقيت غرب أفريقيا الصيفي"}},Alaska:{"long":{generic:"توقيت ألاسكا",standard:"التوقيت الرسمي لألاسكا",daylight:"توقيت ألاسكا الصيفي"}},America_Central:{"long":{generic:"التوقيت المركزي لأمريكا الشمالية",standard:"التوقيت الرسمي المركزي لأمريكا الشمالية",daylight:"التوقيت الصيفي المركزي لأمريكا الشمالية"}},America_Eastern:{"long":{generic:"التوقيت الشرقي لأمريكا الشمالية",standard:"التوقيت الرسمي الشرقي لأمريكا الشمالية",daylight:"التوقيت الصيفي الشرقي لأمريكا الشمالية"}},America_Mountain:{"long":{generic:"التوقيت الجبلي لأمريكا الشمالية",
standard:"التوقيت الجبلي الرسمي لأمريكا الشمالية",daylight:"التوقيت الجبلي الصيفي لأمريكا الشمالية"}},America_Pacific:{"long":{generic:"توقيت المحيط الهادي",standard:"توقيت المحيط الهادي الرسمي",daylight:"توقيت المحيط الهادي الصيفي"}},Arabian:{"long":{generic:"التوقيت العربي",standard:"التوقيت العربي الرسمي",daylight:"التوقيت العربي الصيفي"}},Argentina:{"long":{generic:"توقيت الأرجنتين",standard:"توقيت الأرجنتين الرسمي",daylight:"توقيت الأرجنتين الصيفي"}},Atlantic:{"long":{generic:"توقيت الأطلسي",
standard:"التوقيت الرسمي الأطلسي",daylight:"التوقيت الصيفي الأطلسي"}},Australia_Central:{"long":{generic:"توقيت وسط أستراليا",standard:"توقيت وسط أستراليا الرسمي",daylight:"توقيت وسط أستراليا الصيفي"}},Australia_Eastern:{"long":{generic:"توقيت شرق أستراليا",standard:"توقيت شرق أستراليا الرسمي",daylight:"توقيت شرق أستراليا الصيفي"}},Australia_Western:{"long":{generic:"توقيت غرب أستراليا",standard:"توقيت غرب أستراليا الرسمي",daylight:"توقيت غرب أستراليا الصيفي"}},Azerbaijan:{"long":{generic:"توقيت أذربيجان",
standard:"توقيت أذربيجان الرسمي",daylight:"توقيت أذربيجان الصيفي"}},Azores:{"long":{generic:"توقيت أزورس",standard:"توقيت أزورس الرسمي",daylight:"توقيت أزورس الصيفي"}},Bangladesh:{"long":{generic:"توقيت بنجلاديش",standard:"توقيت بنجلاديش الرسمي",daylight:"توقيت بنجلاديش الصيفي"}},Brasilia:{"long":{generic:"توقيت برازيليا",standard:"توقيت برازيليا الرسمي",daylight:"توقيت برازيليا الصيفي"}},Cape_Verde:{"long":{generic:"توقيت الرأس الأخضر",standard:"توقيت الرأس الأخضر الرسمي",daylight:"توقيت الرأس الأخضر الصيفي"}},
Chamorro:{"long":{standard:"توقيت تشامورو"}},Chile:{"long":{generic:"توقيت شيلي",standard:"توقيت شيلي الرسمي",daylight:"توقيت شيلي الصيفي"}},China:{"long":{generic:"توقيت الصين",standard:"توقيت الصين الرسمي",daylight:"توقيت الصين الصيفي"}},Colombia:{"long":{generic:"توقيت كولومبيا",standard:"توقيت كولومبيا الرسمي",daylight:"توقيت كولومبيا الصيفي"}},Ecuador:{"long":{standard:"توقيت الإكوادور"}},Europe_Central:{"long":{generic:"توقيت وسط أوروبا",standard:"توقيت وسط أوروبا الرسمي",daylight:"توقيت وسط أوروبا الصيفي"}},
Europe_Eastern:{"long":{generic:"توقيت شرق أوروبا",standard:"توقيت شرق أوروبا الرسمي",daylight:"توقيت شرق أوروبا الصيفي"}},Europe_Western:{"long":{generic:"توقيت غرب أوروبا",standard:"توقيت غرب أوروبا الرسمي",daylight:"توقيت غرب أوروبا الصيفي"}},Fiji:{"long":{generic:"توقيت فيجي",standard:"توقيت فيجي الرسمي",daylight:"توقيت فيجي الصيفي"}},GMT:{"long":{standard:"توقيت غرينتش"}},Greenland_Western:{"long":{generic:"توقيت غرب غرينلاند",standard:"توقيت غرب غرينلاند الرسمي",daylight:"توقيت غرب غرينلاند الصيفي"}},
Guam:{"long":{standard:"توقيت غوام"}},Gulf:{"long":{standard:"توقيت الخليج"}},Hawaii_Aleutian:{"long":{generic:"توقيت هاواي ألوتيان",standard:"توقيت هاواي ألوتيان الرسمي",daylight:"توقيت هاواي ألوتيان الصيفي"}},Hong_Kong:{"long":{generic:"توقيت هونغ كونغ",standard:"توقيت هونغ كونغ الرسمي",daylight:"توقيت هونغ كونغ الصيفي"}},India:{"long":{standard:"توقيت الهند"}},Indochina:{"long":{standard:"توقيت الهند الصينية"}},Indonesia_Western:{"long":{standard:"توقيت غرب إندونيسيا"}},Iran:{"long":{generic:"توقيت إيران",
standard:"توقيت إيران الرسمي",daylight:"توقيت إيران الصيفي"}},Irkutsk:{"long":{generic:"توقيت إركوتسك",standard:"توقيت إركوتسك الرسمي",daylight:"توقيت إركوتسك الصيفي"}},Israel:{"long":{generic:"توقيت إسرائيل",standard:"توقيت إسرائيل الرسمي",daylight:"توقيت إسرائيل الصيفي"}},Japan:{"long":{generic:"توقيت اليابان",standard:"توقيت اليابان الرسمي",daylight:"توقيت اليابان الصيفي"}},Kamchatka:{"long":{generic:"توقيت كامشاتكا",standard:"توقيت بيتروبافلوفسك-كامتشاتسكي",daylight:"توقيت بيتروبافلوفسك-كامتشاتسكي الصيفي"}},
Kazakhstan_Eastern:{"long":{standard:"توقيت شرق كازاخستان"}},Korea:{"long":{generic:"توقيت كوريا",standard:"توقيت كوريا الرسمي",daylight:"توقيت كوريا الصيفي"}},Krasnoyarsk:{"long":{generic:"توقيت كراسنويارسك",standard:"توقيت كراسنويارسك الرسمي",daylight:"التوقيت الصيفي لكراسنويارسك"}},Magadan:{"long":{generic:"توقيت ماغادان",standard:"توقيت ماغادان الرسمي",daylight:"توقيت ماغادان الصيفي"}},Malaysia:{"long":{standard:"توقيت ماليزيا"}},Moscow:{"long":{generic:"توقيت موسكو",standard:"توقيت موسكو الرسمي",
daylight:"توقيت موسكو الصيفي"}},Myanmar:{"long":{standard:"توقيت ميانمار"}},New_Zealand:{"long":{generic:"توقيت نيوزيلندا",standard:"توقيت نيوزيلندا الرسمي",daylight:"توقيت نيوزيلندا الصيفي"}},Newfoundland:{"long":{generic:"توقيت نيوفاوندلاند",standard:"توقيت نيوفاوندلاند الرسمي",daylight:"توقيت نيوفاوندلاند الصيفي"}},Noronha:{"long":{generic:"توقيت فيرناندو دي نورونها",standard:"توقيت فرناندو دي نورونها الرسمي",daylight:"توقيت فرناندو دي نورونها الصيفي"}},Novosibirsk:{"long":{generic:"توقيت نوفوسيبيرسك",
standard:"توقيت نوفوسيبيرسك الرسمي",daylight:"توقيت نوفوسيبيرسك الصيفي"}},Pakistan:{"long":{generic:"توقيت باكستان",standard:"توقيت باكستان الرسمي",daylight:"توقيت باكستان الصيفي"}},Peru:{"long":{generic:"توقيت بيرو",standard:"توقيت بيرو الرسمي",daylight:"توقيت بيرو الصيفي"}},Philippines:{"long":{generic:"توقيت الفيلبين",standard:"توقيت الفيلبين الرسمي",daylight:"توقيت الفيلبين الصيفي"}},Samoa:{"long":{generic:"توقيت ساموا",standard:"توقيت ساموا الرسمي",daylight:"توقيت ساموا الصيفي"}},Singapore:{"long":{standard:"توقيت سنغافورة"}},
Taipei:{"long":{generic:"توقيت تايبيه",standard:"توقيت تايبيه الرسمي",daylight:"توقيت تايبيه الصيفي"}},Tonga:{"long":{generic:"توقيت تونغا",standard:"توقيت تونغا الرسمي",daylight:"توقيت تونغا الصيفي"}},Uzbekistan:{"long":{generic:"توقيت أوزبكستان",standard:"توقيت أوزبكستان الرسمي",daylight:"توقيت أوزبكستان الصيفي"}},Venezuela:{"long":{standard:"توقيت فنزويلا"}},Vladivostok:{"long":{generic:"توقيت فلاديفوستوك",standard:"توقيت فلاديفوستوك الرسمي",daylight:"توقيت فلاديفوستوك الصيفي"}},Yakutsk:{"long":{generic:"توقيت ياكوتسك",
standard:"توقيت ياكوتسك الرسمي",daylight:"توقيت ياكوتسك الصيفي"}},Yekaterinburg:{"long":{generic:"توقيت يكاترينبورغ",standard:"توقيت يكاترينبورغ الرسمي",daylight:"توقيت يكاترينبورغ الصيفي"}}}}}}}}); |
/*
All of the code within the ZingChart software is developed and copyrighted by ZingChart, Inc., and may not be copied,
replicated, or used in any other software or application without prior permission from ZingChart. All usage must coincide with the
ZingChart End User License Agreement which can be requested by email at support@zingchart.com.
Build 2.8.1
*/
eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('0.l.k("4");0.m=0.j.d({$i:5(a){n b=3;b.b(a);b.o="4";b.1.p="g";b.1[0.9[e]]=c;b.1[0.9[h]]=f;b.1["r-w"]=c;b.z=2 0.7(b)},q:5(a){v(a){8"x":6 2 0.s(3);8"y":6 2 0.B(3)}}});0.7=0.t.d({u:5(){6 2 0.A(3,"4")}});',38,38,'ZC|AJ|new|this|hbubble|function|return|A5H|case|_|||true|C5|23|false|yx|56||MZ|push|VV|A6R|var|AE|layout|M9|enable|U1|LD|ABW|switch|scroll|||B0|R1|U0'.split('|'),0,{})); |
/**
* tooltipster http://iamceege.github.io/tooltipster/
* A rockin' custom tooltip jQuery plugin
* Developed by Caleb Jacob and Louis Ameline
* MIT license
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module unless amdModuleId is set
define(["jquery"], function (a0) {
return (factory(a0));
});
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory(require("jquery"));
} else {
factory(jQuery);
}
}(this, function ($) {
// This file will be UMDified by a build task.
var defaults = {
animation: 'fade',
animationDuration: 350,
content: null,
contentAsHTML: false,
contentCloning: false,
debug: true,
delay: 300,
delayTouch: [300, 500],
functionInit: null,
functionBefore: null,
functionReady: null,
functionAfter: null,
functionFormat: null,
IEmin: 6,
interactive: false,
multiple: false,
// will default to document.body, or must be an element positioned at (0, 0)
// in the document, typically like the very top views of an app.
parent: null,
plugins: ['sideTip'],
repositionOnScroll: false,
restoration: 'none',
selfDestruction: true,
theme: [],
timer: 0,
trackerInterval: 500,
trackOrigin: false,
trackTooltip: false,
trigger: 'hover',
triggerClose: {
click: false,
mouseleave: false,
originClick: false,
scroll: false,
tap: false,
touchleave: false
},
triggerOpen: {
click: false,
mouseenter: false,
tap: false,
touchstart: false
},
updateAnimation: 'rotate',
zIndex: 9999999
},
// we'll avoid using the 'window' global as a good practice but npm's
// jquery@<2.1.0 package actually requires a 'window' global, so not sure
// it's useful at all
win = (typeof window != 'undefined') ? window : null,
// env will be proxied by the core for plugins to have access its properties
env = {
// detect if this device can trigger touch events. Better have a false
// positive (unused listeners, that's ok) than a false negative.
// https://github.com/Modernizr/Modernizr/blob/master/feature-detects/touchevents.js
// http://stackoverflow.com/questions/4817029/whats-the-best-way-to-detect-a-touch-screen-device-using-javascript
hasTouchCapability: !!(
win
&& ( 'ontouchstart' in win
|| (win.DocumentTouch && win.document instanceof win.DocumentTouch)
|| win.navigator.maxTouchPoints
)
),
hasTransitions: transitionSupport(),
IE: false,
// don't set manually, it will be updated by a build task after the manifest
semVer: '4.2.5',
window: win
},
core = function() {
// core variables
// the core emitters
this.__$emitterPrivate = $({});
this.__$emitterPublic = $({});
this.__instancesLatestArr = [];
// collects plugin constructors
this.__plugins = {};
// proxy env variables for plugins who might use them
this._env = env;
};
// core methods
core.prototype = {
/**
* A function to proxy the public methods of an object onto another
*
* @param {object} constructor The constructor to bridge
* @param {object} obj The object that will get new methods (an instance or the core)
* @param {string} pluginName A plugin name for the console log message
* @return {core}
* @private
*/
__bridge: function(constructor, obj, pluginName) {
// if it's not already bridged
if (!obj[pluginName]) {
var fn = function() {};
fn.prototype = constructor;
var pluginInstance = new fn();
// the _init method has to exist in instance constructors but might be missing
// in core constructors
if (pluginInstance.__init) {
pluginInstance.__init(obj);
}
$.each(constructor, function(methodName, fn) {
// don't proxy "private" methods, only "protected" and public ones
if (methodName.indexOf('__') != 0) {
// if the method does not exist yet
if (!obj[methodName]) {
obj[methodName] = function() {
return pluginInstance[methodName].apply(pluginInstance, Array.prototype.slice.apply(arguments));
};
// remember to which plugin this method corresponds (several plugins may
// have methods of the same name, we need to be sure)
obj[methodName].bridged = pluginInstance;
}
else if (defaults.debug) {
console.log('The '+ methodName +' method of the '+ pluginName
+' plugin conflicts with another plugin or native methods');
}
}
});
obj[pluginName] = pluginInstance;
}
return this;
},
/**
* For mockup in Node env if need be, for testing purposes
*
* @return {core}
* @private
*/
__setWindow: function(window) {
env.window = window;
return this;
},
/**
* Returns a ruler, a tool to help measure the size of a tooltip under
* various settings. Meant for plugins
*
* @see Ruler
* @return {object} A Ruler instance
* @protected
*/
_getRuler: function($tooltip) {
return new Ruler($tooltip);
},
/**
* For internal use by plugins, if needed
*
* @return {core}
* @protected
*/
_off: function() {
this.__$emitterPrivate.off.apply(this.__$emitterPrivate, Array.prototype.slice.apply(arguments));
return this;
},
/**
* For internal use by plugins, if needed
*
* @return {core}
* @protected
*/
_on: function() {
this.__$emitterPrivate.on.apply(this.__$emitterPrivate, Array.prototype.slice.apply(arguments));
return this;
},
/**
* For internal use by plugins, if needed
*
* @return {core}
* @protected
*/
_one: function() {
this.__$emitterPrivate.one.apply(this.__$emitterPrivate, Array.prototype.slice.apply(arguments));
return this;
},
/**
* Returns (getter) or adds (setter) a plugin
*
* @param {string|object} plugin Provide a string (in the full form
* "namespace.name") to use as as getter, an object to use as a setter
* @return {object|core}
* @protected
*/
_plugin: function(plugin) {
var self = this;
// getter
if (typeof plugin == 'string') {
var pluginName = plugin,
p = null;
// if the namespace is provided, it's easy to search
if (pluginName.indexOf('.') > 0) {
p = self.__plugins[pluginName];
}
// otherwise, return the first name that matches
else {
$.each(self.__plugins, function(i, plugin) {
if (plugin.name.substring(plugin.name.length - pluginName.length - 1) == '.'+ pluginName) {
p = plugin;
return false;
}
});
}
return p;
}
// setter
else {
// force namespaces
if (plugin.name.indexOf('.') < 0) {
throw new Error('Plugins must be namespaced');
}
self.__plugins[plugin.name] = plugin;
// if the plugin has core features
if (plugin.core) {
// bridge non-private methods onto the core to allow new core methods
self.__bridge(plugin.core, self, plugin.name);
}
return this;
}
},
/**
* Trigger events on the core emitters
*
* @returns {core}
* @protected
*/
_trigger: function() {
var args = Array.prototype.slice.apply(arguments);
if (typeof args[0] == 'string') {
args[0] = { type: args[0] };
}
// note: the order of emitters matters
this.__$emitterPrivate.trigger.apply(this.__$emitterPrivate, args);
this.__$emitterPublic.trigger.apply(this.__$emitterPublic, args);
return this;
},
/**
* Returns instances of all tooltips in the page or an a given element
*
* @param {string|HTML object collection} selector optional Use this
* parameter to restrict the set of objects that will be inspected
* for the retrieval of instances. By default, all instances in the
* page are returned.
* @return {array} An array of instance objects
* @public
*/
instances: function(selector) {
var instances = [],
sel = selector || '.tooltipstered';
$(sel).each(function() {
var $this = $(this),
ns = $this.data('tooltipster-ns');
if (ns) {
$.each(ns, function(i, namespace) {
instances.push($this.data(namespace));
});
}
});
return instances;
},
/**
* Returns the Tooltipster objects generated by the last initializing call
*
* @return {array} An array of instance objects
* @public
*/
instancesLatest: function() {
return this.__instancesLatestArr;
},
/**
* For public use only, not to be used by plugins (use ::_off() instead)
*
* @return {core}
* @public
*/
off: function() {
this.__$emitterPublic.off.apply(this.__$emitterPublic, Array.prototype.slice.apply(arguments));
return this;
},
/**
* For public use only, not to be used by plugins (use ::_on() instead)
*
* @return {core}
* @public
*/
on: function() {
this.__$emitterPublic.on.apply(this.__$emitterPublic, Array.prototype.slice.apply(arguments));
return this;
},
/**
* For public use only, not to be used by plugins (use ::_one() instead)
*
* @return {core}
* @public
*/
one: function() {
this.__$emitterPublic.one.apply(this.__$emitterPublic, Array.prototype.slice.apply(arguments));
return this;
},
/**
* Returns all HTML elements which have one or more tooltips
*
* @param {string} selector optional Use this to restrict the results
* to the descendants of an element
* @return {array} An array of HTML elements
* @public
*/
origins: function(selector) {
var sel = selector ?
selector +' ' :
'';
return $(sel +'.tooltipstered').toArray();
},
/**
* Change default options for all future instances
*
* @param {object} d The options that should be made defaults
* @return {core}
* @public
*/
setDefaults: function(d) {
$.extend(defaults, d);
return this;
},
/**
* For users to trigger their handlers on the public emitter
*
* @returns {core}
* @public
*/
triggerHandler: function() {
this.__$emitterPublic.triggerHandler.apply(this.__$emitterPublic, Array.prototype.slice.apply(arguments));
return this;
}
};
// $.tooltipster will be used to call core methods
$.tooltipster = new core();
// the Tooltipster instance class (mind the capital T)
$.Tooltipster = function(element, options) {
// list of instance variables
// stack of custom callbacks provided as parameters to API methods
this.__callbacks = {
close: [],
open: []
};
// the schedule time of DOM removal
this.__closingTime;
// this will be the user content shown in the tooltip. A capital "C" is used
// because there is also a method called content()
this.__Content;
// for the size tracker
this.__contentBcr;
// to disable the tooltip after destruction
this.__destroyed = false;
// we can't emit directly on the instance because if a method with the same
// name as the event exists, it will be called by jQuery. Se we use a plain
// object as emitter. This emitter is for internal use by plugins,
// if needed.
this.__$emitterPrivate = $({});
// this emitter is for the user to listen to events without risking to mess
// with our internal listeners
this.__$emitterPublic = $({});
this.__enabled = true;
// the reference to the gc interval
this.__garbageCollector;
// various position and size data recomputed before each repositioning
this.__Geometry;
// the tooltip position, saved after each repositioning by a plugin
this.__lastPosition;
// a unique namespace per instance
this.__namespace = 'tooltipster-'+ Math.round(Math.random()*1000000);
this.__options;
// will be used to support origins in scrollable areas
this.__$originParents;
this.__pointerIsOverOrigin = false;
// to remove themes if needed
this.__previousThemes = [];
// the state can be either: appearing, stable, disappearing, closed
this.__state = 'closed';
// timeout references
this.__timeouts = {
close: [],
open: null
};
// store touch events to be able to detect emulated mouse events
this.__touchEvents = [];
// the reference to the tracker interval
this.__tracker = null;
// the element to which this tooltip is associated
this._$origin;
// this will be the tooltip element (jQuery wrapped HTML element).
// It's the job of a plugin to create it and append it to the DOM
this._$tooltip;
// launch
this.__init(element, options);
};
$.Tooltipster.prototype = {
/**
* @param origin
* @param options
* @private
*/
__init: function(origin, options) {
var self = this;
self._$origin = $(origin);
self.__options = $.extend(true, {}, defaults, options);
// some options may need to be reformatted
self.__optionsFormat();
// don't run on old IE if asked no to
if ( !env.IE
|| env.IE >= self.__options.IEmin
) {
// note: the content is null (empty) by default and can stay that
// way if the plugin remains initialized but not fed any content. The
// tooltip will just not appear.
// let's save the initial value of the title attribute for later
// restoration if need be.
var initialTitle = null;
// it will already have been saved in case of multiple tooltips
if (self._$origin.data('tooltipster-initialTitle') === undefined) {
initialTitle = self._$origin.attr('title');
// we do not want initialTitle to be "undefined" because
// of how jQuery's .data() method works
if (initialTitle === undefined) initialTitle = null;
self._$origin.data('tooltipster-initialTitle', initialTitle);
}
// If content is provided in the options, it has precedence over the
// title attribute.
// Note: an empty string is considered content, only 'null' represents
// the absence of content.
// Also, an existing title="" attribute will result in an empty string
// content
if (self.__options.content !== null) {
self.__contentSet(self.__options.content);
}
else {
var selector = self._$origin.attr('data-tooltip-content'),
$el;
if (selector){
$el = $(selector);
}
if ($el && $el[0]) {
self.__contentSet($el.first());
}
else {
self.__contentSet(initialTitle);
}
}
self._$origin
// strip the title off of the element to prevent the default tooltips
// from popping up
.removeAttr('title')
// to be able to find all instances on the page later (upon window
// events in particular)
.addClass('tooltipstered');
// set listeners on the origin
self.__prepareOrigin();
// set the garbage collector
self.__prepareGC();
// init plugins
$.each(self.__options.plugins, function(i, pluginName) {
self._plug(pluginName);
});
// to detect swiping
if (env.hasTouchCapability) {
$(env.window.document.body).on('touchmove.'+ self.__namespace +'-triggerOpen', function(event) {
self._touchRecordEvent(event);
});
}
self
// prepare the tooltip when it gets created. This event must
// be fired by a plugin
._on('created', function() {
self.__prepareTooltip();
})
// save position information when it's sent by a plugin
._on('repositioned', function(e) {
self.__lastPosition = e.position;
});
}
else {
self.__options.disabled = true;
}
},
/**
* Insert the content into the appropriate HTML element of the tooltip
*
* @returns {self}
* @private
*/
__contentInsert: function() {
var self = this,
$el = self._$tooltip.find('.tooltipster-content'),
formattedContent = self.__Content,
format = function(content) {
formattedContent = content;
};
self._trigger({
type: 'format',
content: self.__Content,
format: format
});
if (self.__options.functionFormat) {
formattedContent = self.__options.functionFormat.call(
self,
self,
{ origin: self._$origin[0] },
self.__Content
);
}
if (typeof formattedContent === 'string' && !self.__options.contentAsHTML) {
$el.text(formattedContent);
}
else {
$el
.empty()
.append(formattedContent);
}
return self;
},
/**
* Save the content, cloning it beforehand if need be
*
* @param content
* @returns {self}
* @private
*/
__contentSet: function(content) {
// clone if asked. Cloning the object makes sure that each instance has its
// own version of the content (in case a same object were provided for several
// instances)
// reminder: typeof null === object
if (content instanceof $ && this.__options.contentCloning) {
content = content.clone(true);
}
this.__Content = content;
this._trigger({
type: 'updated',
content: content
});
return this;
},
/**
* Error message about a method call made after destruction
*
* @private
*/
__destroyError: function() {
throw new Error('This tooltip has been destroyed and cannot execute your method call.');
},
/**
* Gather all information about dimensions and available space,
* called before every repositioning
*
* @private
* @returns {object}
*/
__geometry: function() {
var self = this,
$target = self._$origin,
originIsArea = self._$origin.is('area');
// if this._$origin is a map area, the target we'll need
// the dimensions of is actually the image using the map,
// not the area itself
if (originIsArea) {
var mapName = self._$origin.parent().attr('name');
$target = $('img[usemap="#'+ mapName +'"]');
}
var bcr = $target[0].getBoundingClientRect(),
$document = $(env.window.document),
$window = $(env.window),
$parent = $target,
// some useful properties of important elements
geo = {
// available space for the tooltip, see down below
available: {
document: null,
window: null
},
document: {
size: {
height: $document.height(),
width: $document.width()
}
},
window: {
scroll: {
// the second ones are for IE compatibility
left: env.window.scrollX || env.window.document.documentElement.scrollLeft,
top: env.window.scrollY || env.window.document.documentElement.scrollTop
},
size: {
height: $window.height(),
width: $window.width()
}
},
origin: {
// the origin has a fixed lineage if itself or one of its
// ancestors has a fixed position
fixedLineage: false,
// relative to the document
offset: {},
size: {
height: bcr.bottom - bcr.top,
width: bcr.right - bcr.left
},
usemapImage: originIsArea ? $target[0] : null,
// relative to the window
windowOffset: {
bottom: bcr.bottom,
left: bcr.left,
right: bcr.right,
top: bcr.top
}
}
},
geoFixed = false;
// if the element is a map area, some properties may need
// to be recalculated
if (originIsArea) {
var shape = self._$origin.attr('shape'),
coords = self._$origin.attr('coords');
if (coords) {
coords = coords.split(',');
$.map(coords, function(val, i) {
coords[i] = parseInt(val);
});
}
// if the image itself is the area, nothing more to do
if (shape != 'default') {
switch(shape) {
case 'circle':
var circleCenterLeft = coords[0],
circleCenterTop = coords[1],
circleRadius = coords[2],
areaTopOffset = circleCenterTop - circleRadius,
areaLeftOffset = circleCenterLeft - circleRadius;
geo.origin.size.height = circleRadius * 2;
geo.origin.size.width = geo.origin.size.height;
geo.origin.windowOffset.left += areaLeftOffset;
geo.origin.windowOffset.top += areaTopOffset;
break;
case 'rect':
var areaLeft = coords[0],
areaTop = coords[1],
areaRight = coords[2],
areaBottom = coords[3];
geo.origin.size.height = areaBottom - areaTop;
geo.origin.size.width = areaRight - areaLeft;
geo.origin.windowOffset.left += areaLeft;
geo.origin.windowOffset.top += areaTop;
break;
case 'poly':
var areaSmallestX = 0,
areaSmallestY = 0,
areaGreatestX = 0,
areaGreatestY = 0,
arrayAlternate = 'even';
for (var i = 0; i < coords.length; i++) {
var areaNumber = coords[i];
if (arrayAlternate == 'even') {
if (areaNumber > areaGreatestX) {
areaGreatestX = areaNumber;
if (i === 0) {
areaSmallestX = areaGreatestX;
}
}
if (areaNumber < areaSmallestX) {
areaSmallestX = areaNumber;
}
arrayAlternate = 'odd';
}
else {
if (areaNumber > areaGreatestY) {
areaGreatestY = areaNumber;
if (i == 1) {
areaSmallestY = areaGreatestY;
}
}
if (areaNumber < areaSmallestY) {
areaSmallestY = areaNumber;
}
arrayAlternate = 'even';
}
}
geo.origin.size.height = areaGreatestY - areaSmallestY;
geo.origin.size.width = areaGreatestX - areaSmallestX;
geo.origin.windowOffset.left += areaSmallestX;
geo.origin.windowOffset.top += areaSmallestY;
break;
}
}
}
// user callback through an event
var edit = function(r) {
geo.origin.size.height = r.height,
geo.origin.windowOffset.left = r.left,
geo.origin.windowOffset.top = r.top,
geo.origin.size.width = r.width
};
self._trigger({
type: 'geometry',
edit: edit,
geometry: {
height: geo.origin.size.height,
left: geo.origin.windowOffset.left,
top: geo.origin.windowOffset.top,
width: geo.origin.size.width
}
});
// calculate the remaining properties with what we got
geo.origin.windowOffset.right = geo.origin.windowOffset.left + geo.origin.size.width;
geo.origin.windowOffset.bottom = geo.origin.windowOffset.top + geo.origin.size.height;
geo.origin.offset.left = geo.origin.windowOffset.left + geo.window.scroll.left;
geo.origin.offset.top = geo.origin.windowOffset.top + geo.window.scroll.top;
geo.origin.offset.bottom = geo.origin.offset.top + geo.origin.size.height;
geo.origin.offset.right = geo.origin.offset.left + geo.origin.size.width;
// the space that is available to display the tooltip relatively to the document
geo.available.document = {
bottom: {
height: geo.document.size.height - geo.origin.offset.bottom,
width: geo.document.size.width
},
left: {
height: geo.document.size.height,
width: geo.origin.offset.left
},
right: {
height: geo.document.size.height,
width: geo.document.size.width - geo.origin.offset.right
},
top: {
height: geo.origin.offset.top,
width: geo.document.size.width
}
};
// the space that is available to display the tooltip relatively to the viewport
// (the resulting values may be negative if the origin overflows the viewport)
geo.available.window = {
bottom: {
// the inner max is here to make sure the available height is no bigger
// than the viewport height (when the origin is off screen at the top).
// The outer max just makes sure that the height is not negative (when
// the origin overflows at the bottom).
height: Math.max(geo.window.size.height - Math.max(geo.origin.windowOffset.bottom, 0), 0),
width: geo.window.size.width
},
left: {
height: geo.window.size.height,
width: Math.max(geo.origin.windowOffset.left, 0)
},
right: {
height: geo.window.size.height,
width: Math.max(geo.window.size.width - Math.max(geo.origin.windowOffset.right, 0), 0)
},
top: {
height: Math.max(geo.origin.windowOffset.top, 0),
width: geo.window.size.width
}
};
while ($parent[0].tagName.toLowerCase() != 'html') {
if ($parent.css('position') == 'fixed') {
geo.origin.fixedLineage = true;
break;
}
$parent = $parent.parent();
}
return geo;
},
/**
* Some options may need to be formated before being used
*
* @returns {self}
* @private
*/
__optionsFormat: function() {
if (typeof this.__options.animationDuration == 'number') {
this.__options.animationDuration = [this.__options.animationDuration, this.__options.animationDuration];
}
if (typeof this.__options.delay == 'number') {
this.__options.delay = [this.__options.delay, this.__options.delay];
}
if (typeof this.__options.delayTouch == 'number') {
this.__options.delayTouch = [this.__options.delayTouch, this.__options.delayTouch];
}
if (typeof this.__options.theme == 'string') {
this.__options.theme = [this.__options.theme];
}
// determine the future parent
if (this.__options.parent === null) {
this.__options.parent = $(env.window.document.body);
}
else if (typeof this.__options.parent == 'string') {
this.__options.parent = $(this.__options.parent);
}
if (this.__options.trigger == 'hover') {
this.__options.triggerOpen = {
mouseenter: true,
touchstart: true
};
this.__options.triggerClose = {
mouseleave: true,
originClick: true,
touchleave: true
};
}
else if (this.__options.trigger == 'click') {
this.__options.triggerOpen = {
click: true,
tap: true
};
this.__options.triggerClose = {
click: true,
tap: true
};
}
// for the plugins
this._trigger('options');
return this;
},
/**
* Schedules or cancels the garbage collector task
*
* @returns {self}
* @private
*/
__prepareGC: function() {
var self = this;
// in case the selfDestruction option has been changed by a method call
if (self.__options.selfDestruction) {
// the GC task
self.__garbageCollector = setInterval(function() {
var now = new Date().getTime();
// forget the old events
self.__touchEvents = $.grep(self.__touchEvents, function(event, i) {
// 1 minute
return now - event.time > 60000;
});
// auto-destruct if the origin is gone
if (!bodyContains(self._$origin)) {
self.close(function(){
self.destroy();
});
}
}, 20000);
}
else {
clearInterval(self.__garbageCollector);
}
return self;
},
/**
* Sets listeners on the origin if the open triggers require them.
* Unlike the listeners set at opening time, these ones
* remain even when the tooltip is closed. It has been made a
* separate method so it can be called when the triggers are
* changed in the options. Closing is handled in _open()
* because of the bindings that may be needed on the tooltip
* itself
*
* @returns {self}
* @private
*/
__prepareOrigin: function() {
var self = this;
// in case we're resetting the triggers
self._$origin.off('.'+ self.__namespace +'-triggerOpen');
// if the device is touch capable, even if only mouse triggers
// are asked, we need to listen to touch events to know if the mouse
// events are actually emulated (so we can ignore them)
if (env.hasTouchCapability) {
self._$origin.on(
'touchstart.'+ self.__namespace +'-triggerOpen ' +
'touchend.'+ self.__namespace +'-triggerOpen ' +
'touchcancel.'+ self.__namespace +'-triggerOpen',
function(event){
self._touchRecordEvent(event);
}
);
}
// mouse click and touch tap work the same way
if ( self.__options.triggerOpen.click
|| (self.__options.triggerOpen.tap && env.hasTouchCapability)
) {
var eventNames = '';
if (self.__options.triggerOpen.click) {
eventNames += 'click.'+ self.__namespace +'-triggerOpen ';
}
if (self.__options.triggerOpen.tap && env.hasTouchCapability) {
eventNames += 'touchend.'+ self.__namespace +'-triggerOpen';
}
self._$origin.on(eventNames, function(event) {
if (self._touchIsMeaningfulEvent(event)) {
self._open(event);
}
});
}
// mouseenter and touch start work the same way
if ( self.__options.triggerOpen.mouseenter
|| (self.__options.triggerOpen.touchstart && env.hasTouchCapability)
) {
var eventNames = '';
if (self.__options.triggerOpen.mouseenter) {
eventNames += 'mouseenter.'+ self.__namespace +'-triggerOpen ';
}
if (self.__options.triggerOpen.touchstart && env.hasTouchCapability) {
eventNames += 'touchstart.'+ self.__namespace +'-triggerOpen';
}
self._$origin.on(eventNames, function(event) {
if ( self._touchIsTouchEvent(event)
|| !self._touchIsEmulatedEvent(event)
) {
self.__pointerIsOverOrigin = true;
self._openShortly(event);
}
});
}
// info for the mouseleave/touchleave close triggers when they use a delay
if ( self.__options.triggerClose.mouseleave
|| (self.__options.triggerClose.touchleave && env.hasTouchCapability)
) {
var eventNames = '';
if (self.__options.triggerClose.mouseleave) {
eventNames += 'mouseleave.'+ self.__namespace +'-triggerOpen ';
}
if (self.__options.triggerClose.touchleave && env.hasTouchCapability) {
eventNames += 'touchend.'+ self.__namespace +'-triggerOpen touchcancel.'+ self.__namespace +'-triggerOpen';
}
self._$origin.on(eventNames, function(event) {
if (self._touchIsMeaningfulEvent(event)) {
self.__pointerIsOverOrigin = false;
}
});
}
return self;
},
/**
* Do the things that need to be done only once after the tooltip
* HTML element it has been created. It has been made a separate
* method so it can be called when options are changed. Remember
* that the tooltip may actually exist in the DOM before it is
* opened, and present after it has been closed: it's the display
* plugin that takes care of handling it.
*
* @returns {self}
* @private
*/
__prepareTooltip: function() {
var self = this,
p = self.__options.interactive ? 'auto' : '';
// this will be useful to know quickly if the tooltip is in
// the DOM or not
self._$tooltip
.attr('id', self.__namespace)
.css({
// pointer events
'pointer-events': p,
zIndex: self.__options.zIndex
});
// themes
// remove the old ones and add the new ones
$.each(self.__previousThemes, function(i, theme) {
self._$tooltip.removeClass(theme);
});
$.each(self.__options.theme, function(i, theme) {
self._$tooltip.addClass(theme);
});
self.__previousThemes = $.merge([], self.__options.theme);
return self;
},
/**
* Handles the scroll on any of the parents of the origin (when the
* tooltip is open)
*
* @param {object} event
* @returns {self}
* @private
*/
__scrollHandler: function(event) {
var self = this;
if (self.__options.triggerClose.scroll) {
self._close(event);
}
else {
// if the origin or tooltip have been removed: do nothing, the tracker will
// take care of it later
if (bodyContains(self._$origin) && bodyContains(self._$tooltip)) {
var geo = null;
// if the scroll happened on the window
if (event.target === env.window.document) {
// if the origin has a fixed lineage, window scroll will have no
// effect on its position nor on the position of the tooltip
if (!self.__Geometry.origin.fixedLineage) {
// we don't need to do anything unless repositionOnScroll is true
// because the tooltip will already have moved with the window
// (and of course with the origin)
if (self.__options.repositionOnScroll) {
self.reposition(event);
}
}
}
// if the scroll happened on another parent of the tooltip, it means
// that it's in a scrollable area and now needs to have its position
// adjusted or recomputed, depending ont the repositionOnScroll
// option. Also, if the origin is partly hidden due to a parent that
// hides its overflow, we'll just hide (not close) the tooltip.
else {
geo = self.__geometry();
var overflows = false;
// a fixed position origin is not affected by the overflow hiding
// of a parent
if (self._$origin.css('position') != 'fixed') {
self.__$originParents.each(function(i, el) {
var $el = $(el),
overflowX = $el.css('overflow-x'),
overflowY = $el.css('overflow-y');
if (overflowX != 'visible' || overflowY != 'visible') {
var bcr = el.getBoundingClientRect();
if (overflowX != 'visible') {
if ( geo.origin.windowOffset.left < bcr.left
|| geo.origin.windowOffset.right > bcr.right
) {
overflows = true;
return false;
}
}
if (overflowY != 'visible') {
if ( geo.origin.windowOffset.top < bcr.top
|| geo.origin.windowOffset.bottom > bcr.bottom
) {
overflows = true;
return false;
}
}
}
// no need to go further if fixed, for the same reason as above
if ($el.css('position') == 'fixed') {
return false;
}
});
}
if (overflows) {
self._$tooltip.css('visibility', 'hidden');
}
else {
self._$tooltip.css('visibility', 'visible');
// reposition
if (self.__options.repositionOnScroll) {
self.reposition(event);
}
// or just adjust offset
else {
// we have to use offset and not windowOffset because this way,
// only the scroll distance of the scrollable areas are taken into
// account (the scrolltop value of the main window must be
// ignored since the tooltip already moves with it)
var offsetLeft = geo.origin.offset.left - self.__Geometry.origin.offset.left,
offsetTop = geo.origin.offset.top - self.__Geometry.origin.offset.top;
// add the offset to the position initially computed by the display plugin
self._$tooltip.css({
left: self.__lastPosition.coord.left + offsetLeft,
top: self.__lastPosition.coord.top + offsetTop
});
}
}
}
self._trigger({
type: 'scroll',
event: event,
geo: geo
});
}
}
return self;
},
/**
* Changes the state of the tooltip
*
* @param {string} state
* @returns {self}
* @private
*/
__stateSet: function(state) {
this.__state = state;
this._trigger({
type: 'state',
state: state
});
return this;
},
/**
* Clear appearance timeouts
*
* @returns {self}
* @private
*/
__timeoutsClear: function() {
// there is only one possible open timeout: the delayed opening
// when the mouseenter/touchstart open triggers are used
clearTimeout(this.__timeouts.open);
this.__timeouts.open = null;
// ... but several close timeouts: the delayed closing when the
// mouseleave close trigger is used and the timer option
$.each(this.__timeouts.close, function(i, timeout) {
clearTimeout(timeout);
});
this.__timeouts.close = [];
return this;
},
/**
* Start the tracker that will make checks at regular intervals
*
* @returns {self}
* @private
*/
__trackerStart: function() {
var self = this,
$content = self._$tooltip.find('.tooltipster-content');
// get the initial content size
if (self.__options.trackTooltip) {
self.__contentBcr = $content[0].getBoundingClientRect();
}
self.__tracker = setInterval(function() {
// if the origin or tooltip elements have been removed.
// Note: we could destroy the instance now if the origin has
// been removed but we'll leave that task to our garbage collector
if (!bodyContains(self._$origin) || !bodyContains(self._$tooltip)) {
self._close();
}
// if everything is alright
else {
// compare the former and current positions of the origin to reposition
// the tooltip if need be
if (self.__options.trackOrigin) {
var g = self.__geometry(),
identical = false;
// compare size first (a change requires repositioning too)
if (areEqual(g.origin.size, self.__Geometry.origin.size)) {
// for elements that have a fixed lineage (see __geometry()), we track the
// top and left properties (relative to window)
if (self.__Geometry.origin.fixedLineage) {
if (areEqual(g.origin.windowOffset, self.__Geometry.origin.windowOffset)) {
identical = true;
}
}
// otherwise, track total offset (relative to document)
else {
if (areEqual(g.origin.offset, self.__Geometry.origin.offset)) {
identical = true;
}
}
}
if (!identical) {
// close the tooltip when using the mouseleave close trigger
// (see https://github.com/iamceege/tooltipster/pull/253)
if (self.__options.triggerClose.mouseleave) {
self._close();
}
else {
self.reposition();
}
}
}
if (self.__options.trackTooltip) {
var currentBcr = $content[0].getBoundingClientRect();
if ( currentBcr.height !== self.__contentBcr.height
|| currentBcr.width !== self.__contentBcr.width
) {
self.reposition();
self.__contentBcr = currentBcr;
}
}
}
}, self.__options.trackerInterval);
return self;
},
/**
* Closes the tooltip (after the closing delay)
*
* @param event
* @param callback
* @param force Set to true to override a potential refusal of the user's function
* @returns {self}
* @protected
*/
_close: function(event, callback, force) {
var self = this,
ok = true;
self._trigger({
type: 'close',
event: event,
stop: function() {
ok = false;
}
});
// a destroying tooltip (force == true) may not refuse to close
if (ok || force) {
// save the method custom callback and cancel any open method custom callbacks
if (callback) self.__callbacks.close.push(callback);
self.__callbacks.open = [];
// clear open/close timeouts
self.__timeoutsClear();
var finishCallbacks = function() {
// trigger any close method custom callbacks and reset them
$.each(self.__callbacks.close, function(i,c) {
c.call(self, self, {
event: event,
origin: self._$origin[0]
});
});
self.__callbacks.close = [];
};
if (self.__state != 'closed') {
var necessary = true,
d = new Date(),
now = d.getTime(),
newClosingTime = now + self.__options.animationDuration[1];
// the tooltip may already already be disappearing, but if a new
// call to close() is made after the animationDuration was changed
// to 0 (for example), we ought to actually close it sooner than
// previously scheduled. In that case it should be noted that the
// browser will not adapt the animation duration to the new
// animationDuration that was set after the start of the closing
// animation.
// Note: the same thing could be considered at opening, but is not
// really useful since the tooltip is actually opened immediately
// upon a call to _open(). Since it would not make the opening
// animation finish sooner, its sole impact would be to trigger the
// state event and the open callbacks sooner than the actual end of
// the opening animation, which is not great.
if (self.__state == 'disappearing') {
if ( newClosingTime > self.__closingTime
// in case closing is actually overdue because the script
// execution was suspended. See #679
&& self.__options.animationDuration[1] > 0
) {
necessary = false;
}
}
if (necessary) {
self.__closingTime = newClosingTime;
if (self.__state != 'disappearing') {
self.__stateSet('disappearing');
}
var finish = function() {
// stop the tracker
clearInterval(self.__tracker);
// a "beforeClose" option has been asked several times but would
// probably useless since the content element is still accessible
// via ::content(), and because people can always use listeners
// inside their content to track what's going on. For the sake of
// simplicity, this has been denied. Bur for the rare people who
// really need the option (for old browsers or for the case where
// detaching the content is actually destructive, for file or
// password inputs for example), this event will do the work.
self._trigger({
type: 'closing',
event: event
});
// unbind listeners which are no longer needed
self._$tooltip
.off('.'+ self.__namespace +'-triggerClose')
.removeClass('tooltipster-dying');
// orientationchange, scroll and resize listeners
$(env.window).off('.'+ self.__namespace +'-triggerClose');
// scroll listeners
self.__$originParents.each(function(i, el) {
$(el).off('scroll.'+ self.__namespace +'-triggerClose');
});
// clear the array to prevent memory leaks
self.__$originParents = null;
$(env.window.document.body).off('.'+ self.__namespace +'-triggerClose');
self._$origin.off('.'+ self.__namespace +'-triggerClose');
self._off('dismissable');
// a plugin that would like to remove the tooltip from the
// DOM when closed should bind on this
self.__stateSet('closed');
// trigger event
self._trigger({
type: 'after',
event: event
});
// call our constructor custom callback function
if (self.__options.functionAfter) {
self.__options.functionAfter.call(self, self, {
event: event,
origin: self._$origin[0]
});
}
// call our method custom callbacks functions
finishCallbacks();
};
if (env.hasTransitions) {
self._$tooltip.css({
'-moz-animation-duration': self.__options.animationDuration[1] + 'ms',
'-ms-animation-duration': self.__options.animationDuration[1] + 'ms',
'-o-animation-duration': self.__options.animationDuration[1] + 'ms',
'-webkit-animation-duration': self.__options.animationDuration[1] + 'ms',
'animation-duration': self.__options.animationDuration[1] + 'ms',
'transition-duration': self.__options.animationDuration[1] + 'ms'
});
self._$tooltip
// clear both potential open and close tasks
.clearQueue()
.removeClass('tooltipster-show')
// for transitions only
.addClass('tooltipster-dying');
if (self.__options.animationDuration[1] > 0) {
self._$tooltip.delay(self.__options.animationDuration[1]);
}
self._$tooltip.queue(finish);
}
else {
self._$tooltip
.stop()
.fadeOut(self.__options.animationDuration[1], finish);
}
}
}
// if the tooltip is already closed, we still need to trigger
// the method custom callbacks
else {
finishCallbacks();
}
}
return self;
},
/**
* For internal use by plugins, if needed
*
* @returns {self}
* @protected
*/
_off: function() {
this.__$emitterPrivate.off.apply(this.__$emitterPrivate, Array.prototype.slice.apply(arguments));
return this;
},
/**
* For internal use by plugins, if needed
*
* @returns {self}
* @protected
*/
_on: function() {
this.__$emitterPrivate.on.apply(this.__$emitterPrivate, Array.prototype.slice.apply(arguments));
return this;
},
/**
* For internal use by plugins, if needed
*
* @returns {self}
* @protected
*/
_one: function() {
this.__$emitterPrivate.one.apply(this.__$emitterPrivate, Array.prototype.slice.apply(arguments));
return this;
},
/**
* Opens the tooltip right away.
*
* @param event
* @param callback Will be called when the opening animation is over
* @returns {self}
* @protected
*/
_open: function(event, callback) {
var self = this;
// if the destruction process has not begun and if this was not
// triggered by an unwanted emulated click event
if (!self.__destroying) {
// check that the origin is still in the DOM
if ( bodyContains(self._$origin)
// if the tooltip is enabled
&& self.__enabled
) {
var ok = true;
// if the tooltip is not open yet, we need to call functionBefore.
// otherwise we can jst go on
if (self.__state == 'closed') {
// trigger an event. The event.stop function allows the callback
// to prevent the opening of the tooltip
self._trigger({
type: 'before',
event: event,
stop: function() {
ok = false;
}
});
if (ok && self.__options.functionBefore) {
// call our custom function before continuing
ok = self.__options.functionBefore.call(self, self, {
event: event,
origin: self._$origin[0]
});
}
}
if (ok !== false) {
// if there is some content
if (self.__Content !== null) {
// save the method callback and cancel close method callbacks
if (callback) {
self.__callbacks.open.push(callback);
}
self.__callbacks.close = [];
// get rid of any appearance timeouts
self.__timeoutsClear();
var extraTime,
finish = function() {
if (self.__state != 'stable') {
self.__stateSet('stable');
}
// trigger any open method custom callbacks and reset them
$.each(self.__callbacks.open, function(i,c) {
c.call(self, self, {
origin: self._$origin[0],
tooltip: self._$tooltip[0]
});
});
self.__callbacks.open = [];
};
// if the tooltip is already open
if (self.__state !== 'closed') {
// the timer (if any) will start (or restart) right now
extraTime = 0;
// if it was disappearing, cancel that
if (self.__state === 'disappearing') {
self.__stateSet('appearing');
if (env.hasTransitions) {
self._$tooltip
.clearQueue()
.removeClass('tooltipster-dying')
.addClass('tooltipster-show');
if (self.__options.animationDuration[0] > 0) {
self._$tooltip.delay(self.__options.animationDuration[0]);
}
self._$tooltip.queue(finish);
}
else {
// in case the tooltip was currently fading out, bring it back
// to life
self._$tooltip
.stop()
.fadeIn(finish);
}
}
// if the tooltip is already open, we still need to trigger the method
// custom callback
else if (self.__state == 'stable') {
finish();
}
}
// if the tooltip isn't already open, open it
else {
// a plugin must bind on this and store the tooltip in this._$tooltip
self.__stateSet('appearing');
// the timer (if any) will start when the tooltip has fully appeared
// after its transition
extraTime = self.__options.animationDuration[0];
// insert the content inside the tooltip
self.__contentInsert();
// reposition the tooltip and attach to the DOM
self.reposition(event, true);
// animate in the tooltip. If the display plugin wants no css
// animations, it may override the animation option with a
// dummy value that will produce no effect
if (env.hasTransitions) {
// note: there seems to be an issue with start animations which
// are randomly not played on fast devices in both Chrome and FF,
// couldn't find a way to solve it yet. It seems that applying
// the classes before appending to the DOM helps a little, but
// it messes up some CSS transitions. The issue almost never
// happens when delay[0]==0 though
self._$tooltip
.addClass('tooltipster-'+ self.__options.animation)
.addClass('tooltipster-initial')
.css({
'-moz-animation-duration': self.__options.animationDuration[0] + 'ms',
'-ms-animation-duration': self.__options.animationDuration[0] + 'ms',
'-o-animation-duration': self.__options.animationDuration[0] + 'ms',
'-webkit-animation-duration': self.__options.animationDuration[0] + 'ms',
'animation-duration': self.__options.animationDuration[0] + 'ms',
'transition-duration': self.__options.animationDuration[0] + 'ms'
});
setTimeout(
function() {
// a quick hover may have already triggered a mouseleave
if (self.__state != 'closed') {
self._$tooltip
.addClass('tooltipster-show')
.removeClass('tooltipster-initial');
if (self.__options.animationDuration[0] > 0) {
self._$tooltip.delay(self.__options.animationDuration[0]);
}
self._$tooltip.queue(finish);
}
},
0
);
}
else {
// old browsers will have to live with this
self._$tooltip
.css('display', 'none')
.fadeIn(self.__options.animationDuration[0], finish);
}
// checks if the origin is removed while the tooltip is open
self.__trackerStart();
// NOTE: the listeners below have a '-triggerClose' namespace
// because we'll remove them when the tooltip closes (unlike
// the '-triggerOpen' listeners). So some of them are actually
// not about close triggers, rather about positioning.
$(env.window)
// reposition on resize
.on('resize.'+ self.__namespace +'-triggerClose', function(e) {
var $ae = $(document.activeElement);
// reposition only if the resize event was not triggered upon the opening
// of a virtual keyboard due to an input field being focused within the tooltip
// (otherwise the repositioning would lose the focus)
if ( (!$ae.is('input') && !$ae.is('textarea'))
|| !$.contains(self._$tooltip[0], $ae[0])
) {
self.reposition(e);
}
})
// same as below for parents
.on('scroll.'+ self.__namespace +'-triggerClose', function(e) {
self.__scrollHandler(e);
});
self.__$originParents = self._$origin.parents();
// scrolling may require the tooltip to be moved or even
// repositioned in some cases
self.__$originParents.each(function(i, parent) {
$(parent).on('scroll.'+ self.__namespace +'-triggerClose', function(e) {
self.__scrollHandler(e);
});
});
if ( self.__options.triggerClose.mouseleave
|| (self.__options.triggerClose.touchleave && env.hasTouchCapability)
) {
// we use an event to allow users/plugins to control when the mouseleave/touchleave
// close triggers will come to action. It allows to have more triggering elements
// than just the origin and the tooltip for example, or to cancel/delay the closing,
// or to make the tooltip interactive even if it wasn't when it was open, etc.
self._on('dismissable', function(event) {
if (event.dismissable) {
if (event.delay) {
timeout = setTimeout(function() {
// event.event may be undefined
self._close(event.event);
}, event.delay);
self.__timeouts.close.push(timeout);
}
else {
self._close(event);
}
}
else {
clearTimeout(timeout);
}
});
// now set the listeners that will trigger 'dismissable' events
var $elements = self._$origin,
eventNamesIn = '',
eventNamesOut = '',
timeout = null;
// if we have to allow interaction, bind on the tooltip too
if (self.__options.interactive) {
$elements = $elements.add(self._$tooltip);
}
if (self.__options.triggerClose.mouseleave) {
eventNamesIn += 'mouseenter.'+ self.__namespace +'-triggerClose ';
eventNamesOut += 'mouseleave.'+ self.__namespace +'-triggerClose ';
}
if (self.__options.triggerClose.touchleave && env.hasTouchCapability) {
eventNamesIn += 'touchstart.'+ self.__namespace +'-triggerClose';
eventNamesOut += 'touchend.'+ self.__namespace +'-triggerClose touchcancel.'+ self.__namespace +'-triggerClose';
}
$elements
// close after some time spent outside of the elements
.on(eventNamesOut, function(event) {
// it's ok if the touch gesture ended up to be a swipe,
// it's still a "touch leave" situation
if ( self._touchIsTouchEvent(event)
|| !self._touchIsEmulatedEvent(event)
) {
var delay = (event.type == 'mouseleave') ?
self.__options.delay :
self.__options.delayTouch;
self._trigger({
delay: delay[1],
dismissable: true,
event: event,
type: 'dismissable'
});
}
})
// suspend the mouseleave timeout when the pointer comes back
// over the elements
.on(eventNamesIn, function(event) {
// it's also ok if the touch event is a swipe gesture
if ( self._touchIsTouchEvent(event)
|| !self._touchIsEmulatedEvent(event)
) {
self._trigger({
dismissable: false,
event: event,
type: 'dismissable'
});
}
});
}
// close the tooltip when the origin gets a mouse click (common behavior of
// native tooltips)
if (self.__options.triggerClose.originClick) {
self._$origin.on('click.'+ self.__namespace + '-triggerClose', function(event) {
// we could actually let a tap trigger this but this feature just
// does not make sense on touch devices
if ( !self._touchIsTouchEvent(event)
&& !self._touchIsEmulatedEvent(event)
) {
self._close(event);
}
});
}
// set the same bindings for click and touch on the body to close the tooltip
if ( self.__options.triggerClose.click
|| (self.__options.triggerClose.tap && env.hasTouchCapability)
) {
// don't set right away since the click/tap event which triggered this method
// (if it was a click/tap) is going to bubble up to the body, we don't want it
// to close the tooltip immediately after it opened
setTimeout(function() {
if (self.__state != 'closed') {
var eventNames = '',
$body = $(env.window.document.body);
if (self.__options.triggerClose.click) {
eventNames += 'click.'+ self.__namespace +'-triggerClose ';
}
if (self.__options.triggerClose.tap && env.hasTouchCapability) {
eventNames += 'touchend.'+ self.__namespace +'-triggerClose';
}
$body.on(eventNames, function(event) {
if (self._touchIsMeaningfulEvent(event)) {
self._touchRecordEvent(event);
if (!self.__options.interactive || !$.contains(self._$tooltip[0], event.target)) {
self._close(event);
}
}
});
// needed to detect and ignore swiping
if (self.__options.triggerClose.tap && env.hasTouchCapability) {
$body.on('touchstart.'+ self.__namespace +'-triggerClose', function(event) {
self._touchRecordEvent(event);
});
}
}
}, 0);
}
self._trigger('ready');
// call our custom callback
if (self.__options.functionReady) {
self.__options.functionReady.call(self, self, {
origin: self._$origin[0],
tooltip: self._$tooltip[0]
});
}
}
// if we have a timer set, let the countdown begin
if (self.__options.timer > 0) {
var timeout = setTimeout(function() {
self._close();
}, self.__options.timer + extraTime);
self.__timeouts.close.push(timeout);
}
}
}
}
}
return self;
},
/**
* When using the mouseenter/touchstart open triggers, this function will
* schedule the opening of the tooltip after the delay, if there is one
*
* @param event
* @returns {self}
* @protected
*/
_openShortly: function(event) {
var self = this,
ok = true;
if (self.__state != 'stable' && self.__state != 'appearing') {
// if a timeout is not already running
if (!self.__timeouts.open) {
self._trigger({
type: 'start',
event: event,
stop: function() {
ok = false;
}
});
if (ok) {
var delay = (event.type.indexOf('touch') == 0) ?
self.__options.delayTouch :
self.__options.delay;
if (delay[0]) {
self.__timeouts.open = setTimeout(function() {
self.__timeouts.open = null;
// open only if the pointer (mouse or touch) is still over the origin.
// The check on the "meaningful event" can only be made here, after some
// time has passed (to know if the touch was a swipe or not)
if (self.__pointerIsOverOrigin && self._touchIsMeaningfulEvent(event)) {
// signal that we go on
self._trigger('startend');
self._open(event);
}
else {
// signal that we cancel
self._trigger('startcancel');
}
}, delay[0]);
}
else {
// signal that we go on
self._trigger('startend');
self._open(event);
}
}
}
}
return self;
},
/**
* Meant for plugins to get their options
*
* @param {string} pluginName The name of the plugin that asks for its options
* @param {object} defaultOptions The default options of the plugin
* @returns {object} The options
* @protected
*/
_optionsExtract: function(pluginName, defaultOptions) {
var self = this,
options = $.extend(true, {}, defaultOptions);
// if the plugin options were isolated in a property named after the
// plugin, use them (prevents conflicts with other plugins)
var pluginOptions = self.__options[pluginName];
// if not, try to get them as regular options
if (!pluginOptions){
pluginOptions = {};
$.each(defaultOptions, function(optionName, value) {
var o = self.__options[optionName];
if (o !== undefined) {
pluginOptions[optionName] = o;
}
});
}
// let's merge the default options and the ones that were provided. We'd want
// to do a deep copy but not let jQuery merge arrays, so we'll do a shallow
// extend on two levels, that will be enough if options are not more than 1
// level deep
$.each(options, function(optionName, value) {
if (pluginOptions[optionName] !== undefined) {
if (( typeof value == 'object'
&& !(value instanceof Array)
&& value != null
)
&&
( typeof pluginOptions[optionName] == 'object'
&& !(pluginOptions[optionName] instanceof Array)
&& pluginOptions[optionName] != null
)
) {
$.extend(options[optionName], pluginOptions[optionName]);
}
else {
options[optionName] = pluginOptions[optionName];
}
}
});
return options;
},
/**
* Used at instantiation of the plugin, or afterwards by plugins that activate themselves
* on existing instances
*
* @param {object} pluginName
* @returns {self}
* @protected
*/
_plug: function(pluginName) {
var plugin = $.tooltipster._plugin(pluginName);
if (plugin) {
// if there is a constructor for instances
if (plugin.instance) {
// proxy non-private methods on the instance to allow new instance methods
$.tooltipster.__bridge(plugin.instance, this, plugin.name);
}
}
else {
throw new Error('The "'+ pluginName +'" plugin is not defined');
}
return this;
},
/**
* This will return true if the event is a mouse event which was
* emulated by the browser after a touch event. This allows us to
* really dissociate mouse and touch triggers.
*
* There is a margin of error if a real mouse event is fired right
* after (within the delay shown below) a touch event on the same
* element, but hopefully it should not happen often.
*
* @returns {boolean}
* @protected
*/
_touchIsEmulatedEvent: function(event) {
var isEmulated = false,
now = new Date().getTime();
for (var i = this.__touchEvents.length - 1; i >= 0; i--) {
var e = this.__touchEvents[i];
// delay, in milliseconds. It's supposed to be 300ms in
// most browsers (350ms on iOS) to allow a double tap but
// can be less (check out FastClick for more info)
if (now - e.time < 500) {
if (e.target === event.target) {
isEmulated = true;
}
}
else {
break;
}
}
return isEmulated;
},
/**
* Returns false if the event was an emulated mouse event or
* a touch event involved in a swipe gesture.
*
* @param {object} event
* @returns {boolean}
* @protected
*/
_touchIsMeaningfulEvent: function(event) {
return (
(this._touchIsTouchEvent(event) && !this._touchSwiped(event.target))
|| (!this._touchIsTouchEvent(event) && !this._touchIsEmulatedEvent(event))
);
},
/**
* Checks if an event is a touch event
*
* @param {object} event
* @returns {boolean}
* @protected
*/
_touchIsTouchEvent: function(event){
return event.type.indexOf('touch') == 0;
},
/**
* Store touch events for a while to detect swiping and emulated mouse events
*
* @param {object} event
* @returns {self}
* @protected
*/
_touchRecordEvent: function(event) {
if (this._touchIsTouchEvent(event)) {
event.time = new Date().getTime();
this.__touchEvents.push(event);
}
return this;
},
/**
* Returns true if a swipe happened after the last touchstart event fired on
* event.target.
*
* We need to differentiate a swipe from a tap before we let the event open
* or close the tooltip. A swipe is when a touchmove (scroll) event happens
* on the body between the touchstart and the touchend events of an element.
*
* @param {object} target The HTML element that may have triggered the swipe
* @returns {boolean}
* @protected
*/
_touchSwiped: function(target) {
var swiped = false;
for (var i = this.__touchEvents.length - 1; i >= 0; i--) {
var e = this.__touchEvents[i];
if (e.type == 'touchmove') {
swiped = true;
break;
}
else if (
e.type == 'touchstart'
&& target === e.target
) {
break;
}
}
return swiped;
},
/**
* Triggers an event on the instance emitters
*
* @returns {self}
* @protected
*/
_trigger: function() {
var args = Array.prototype.slice.apply(arguments);
if (typeof args[0] == 'string') {
args[0] = { type: args[0] };
}
// add properties to the event
args[0].instance = this;
args[0].origin = this._$origin ? this._$origin[0] : null;
args[0].tooltip = this._$tooltip ? this._$tooltip[0] : null;
// note: the order of emitters matters
this.__$emitterPrivate.trigger.apply(this.__$emitterPrivate, args);
$.tooltipster._trigger.apply($.tooltipster, args);
this.__$emitterPublic.trigger.apply(this.__$emitterPublic, args);
return this;
},
/**
* Deactivate a plugin on this instance
*
* @returns {self}
* @protected
*/
_unplug: function(pluginName) {
var self = this;
// if the plugin has been activated on this instance
if (self[pluginName]) {
var plugin = $.tooltipster._plugin(pluginName);
// if there is a constructor for instances
if (plugin.instance) {
// unbridge
$.each(plugin.instance, function(methodName, fn) {
// if the method exists (privates methods do not) and comes indeed from
// this plugin (may be missing or come from a conflicting plugin).
if ( self[methodName]
&& self[methodName].bridged === self[pluginName]
) {
delete self[methodName];
}
});
}
// destroy the plugin
if (self[pluginName].__destroy) {
self[pluginName].__destroy();
}
// remove the reference to the plugin instance
delete self[pluginName];
}
return self;
},
/**
* @see self::_close
* @returns {self}
* @public
*/
close: function(callback) {
if (!this.__destroyed) {
this._close(null, callback);
}
else {
this.__destroyError();
}
return this;
},
/**
* Sets or gets the content of the tooltip
*
* @returns {mixed|self}
* @public
*/
content: function(content) {
var self = this;
// getter method
if (content === undefined) {
return self.__Content;
}
// setter method
else {
if (!self.__destroyed) {
// change the content
self.__contentSet(content);
if (self.__Content !== null) {
// update the tooltip if it is open
if (self.__state !== 'closed') {
// reset the content in the tooltip
self.__contentInsert();
// reposition and resize the tooltip
self.reposition();
// if we want to play a little animation showing the content changed
if (self.__options.updateAnimation) {
if (env.hasTransitions) {
// keep the reference in the local scope
var animation = self.__options.updateAnimation;
self._$tooltip.addClass('tooltipster-update-'+ animation);
// remove the class after a while. The actual duration of the
// update animation may be shorter, it's set in the CSS rules
setTimeout(function() {
if (self.__state != 'closed') {
self._$tooltip.removeClass('tooltipster-update-'+ animation);
}
}, 1000);
}
else {
self._$tooltip.fadeTo(200, 0.5, function() {
if (self.__state != 'closed') {
self._$tooltip.fadeTo(200, 1);
}
});
}
}
}
}
else {
self._close();
}
}
else {
self.__destroyError();
}
return self;
}
},
/**
* Destroys the tooltip
*
* @returns {self}
* @public
*/
destroy: function() {
var self = this;
if (!self.__destroyed) {
if(self.__state != 'closed'){
// no closing delay
self.option('animationDuration', 0)
// force closing
._close(null, null, true);
}
else {
// there might be an open timeout still running
self.__timeoutsClear();
}
// send event
self._trigger('destroy');
self.__destroyed = true;
self._$origin
.removeData(self.__namespace)
// remove the open trigger listeners
.off('.'+ self.__namespace +'-triggerOpen');
// remove the touch listener
$(env.window.document.body).off('.' + self.__namespace +'-triggerOpen');
var ns = self._$origin.data('tooltipster-ns');
// if the origin has been removed from DOM, its data may
// well have been destroyed in the process and there would
// be nothing to clean up or restore
if (ns) {
// if there are no more tooltips on this element
if (ns.length === 1) {
// optional restoration of a title attribute
var title = null;
if (self.__options.restoration == 'previous') {
title = self._$origin.data('tooltipster-initialTitle');
}
else if (self.__options.restoration == 'current') {
// old school technique to stringify when outerHTML is not supported
title = (typeof self.__Content == 'string') ?
self.__Content :
$('<div></div>').append(self.__Content).html();
}
if (title) {
self._$origin.attr('title', title);
}
// final cleaning
self._$origin.removeClass('tooltipstered');
self._$origin
.removeData('tooltipster-ns')
.removeData('tooltipster-initialTitle');
}
else {
// remove the instance namespace from the list of namespaces of
// tooltips present on the element
ns = $.grep(ns, function(el, i) {
return el !== self.__namespace;
});
self._$origin.data('tooltipster-ns', ns);
}
}
// last event
self._trigger('destroyed');
// unbind private and public event listeners
self._off();
self.off();
// remove external references, just in case
self.__Content = null;
self.__$emitterPrivate = null;
self.__$emitterPublic = null;
self.__options.parent = null;
self._$origin = null;
self._$tooltip = null;
// make sure the object is no longer referenced in there to prevent
// memory leaks
$.tooltipster.__instancesLatestArr = $.grep($.tooltipster.__instancesLatestArr, function(el, i) {
return self !== el;
});
clearInterval(self.__garbageCollector);
}
else {
self.__destroyError();
}
// we return the scope rather than true so that the call to
// .tooltipster('destroy') actually returns the matched elements
// and applies to all of them
return self;
},
/**
* Disables the tooltip
*
* @returns {self}
* @public
*/
disable: function() {
if (!this.__destroyed) {
// close first, in case the tooltip would not disappear on
// its own (no close trigger)
this._close();
this.__enabled = false;
return this;
}
else {
this.__destroyError();
}
return this;
},
/**
* Returns the HTML element of the origin
*
* @returns {self}
* @public
*/
elementOrigin: function() {
if (!this.__destroyed) {
return this._$origin[0];
}
else {
this.__destroyError();
}
},
/**
* Returns the HTML element of the tooltip
*
* @returns {self}
* @public
*/
elementTooltip: function() {
return this._$tooltip ? this._$tooltip[0] : null;
},
/**
* Enables the tooltip
*
* @returns {self}
* @public
*/
enable: function() {
this.__enabled = true;
return this;
},
/**
* Alias, deprecated in 4.0.0
*
* @param {function} callback
* @returns {self}
* @public
*/
hide: function(callback) {
return this.close(callback);
},
/**
* Returns the instance
*
* @returns {self}
* @public
*/
instance: function() {
return this;
},
/**
* For public use only, not to be used by plugins (use ::_off() instead)
*
* @returns {self}
* @public
*/
off: function() {
if (!this.__destroyed) {
this.__$emitterPublic.off.apply(this.__$emitterPublic, Array.prototype.slice.apply(arguments));
}
return this;
},
/**
* For public use only, not to be used by plugins (use ::_on() instead)
*
* @returns {self}
* @public
*/
on: function() {
if (!this.__destroyed) {
this.__$emitterPublic.on.apply(this.__$emitterPublic, Array.prototype.slice.apply(arguments));
}
else {
this.__destroyError();
}
return this;
},
/**
* For public use only, not to be used by plugins
*
* @returns {self}
* @public
*/
one: function() {
if (!this.__destroyed) {
this.__$emitterPublic.one.apply(this.__$emitterPublic, Array.prototype.slice.apply(arguments));
}
else {
this.__destroyError();
}
return this;
},
/**
* @see self::_open
* @returns {self}
* @public
*/
open: function(callback) {
if (!this.__destroyed) {
this._open(null, callback);
}
else {
this.__destroyError();
}
return this;
},
/**
* Get or set options. For internal use and advanced users only.
*
* @param {string} o Option name
* @param {mixed} val optional A new value for the option
* @return {mixed|self} If val is omitted, the value of the option
* is returned, otherwise the instance itself is returned
* @public
*/
option: function(o, val) {
// getter
if (val === undefined) {
return this.__options[o];
}
// setter
else {
if (!this.__destroyed) {
// change value
this.__options[o] = val;
// format
this.__optionsFormat();
// re-prepare the triggers if needed
if ($.inArray(o, ['trigger', 'triggerClose', 'triggerOpen']) >= 0) {
this.__prepareOrigin();
}
if (o === 'selfDestruction') {
this.__prepareGC();
}
}
else {
this.__destroyError();
}
return this;
}
},
/**
* This method is in charge of setting the position and size properties of the tooltip.
* All the hard work is delegated to the display plugin.
* Note: The tooltip may be detached from the DOM at the moment the method is called
* but must be attached by the end of the method call.
*
* @param {object} event For internal use only. Defined if an event such as
* window resizing triggered the repositioning
* @param {boolean} tooltipIsDetached For internal use only. Set this to true if you
* know that the tooltip not being in the DOM is not an issue (typically when the
* tooltip element has just been created but has not been added to the DOM yet).
* @returns {self}
* @public
*/
reposition: function(event, tooltipIsDetached) {
var self = this;
if (!self.__destroyed) {
// if the tooltip is still open and the origin is still in the DOM
if (self.__state != 'closed' && bodyContains(self._$origin)) {
// if the tooltip has not been removed from DOM manually (or if it
// has been detached on purpose)
if (tooltipIsDetached || bodyContains(self._$tooltip)) {
if (!tooltipIsDetached) {
// detach in case the tooltip overflows the window and adds
// scrollbars to it, so __geometry can be accurate
self._$tooltip.detach();
}
// refresh the geometry object before passing it as a helper
self.__Geometry = self.__geometry();
// let a plugin fo the rest
self._trigger({
type: 'reposition',
event: event,
helper: {
geo: self.__Geometry
}
});
}
}
}
else {
self.__destroyError();
}
return self;
},
/**
* Alias, deprecated in 4.0.0
*
* @param callback
* @returns {self}
* @public
*/
show: function(callback) {
return this.open(callback);
},
/**
* Returns some properties about the instance
*
* @returns {object}
* @public
*/
status: function() {
return {
destroyed: this.__destroyed,
enabled: this.__enabled,
open: this.__state !== 'closed',
state: this.__state
};
},
/**
* For public use only, not to be used by plugins
*
* @returns {self}
* @public
*/
triggerHandler: function() {
if (!this.__destroyed) {
this.__$emitterPublic.triggerHandler.apply(this.__$emitterPublic, Array.prototype.slice.apply(arguments));
}
else {
this.__destroyError();
}
return this;
}
};
$.fn.tooltipster = function() {
// for using in closures
var args = Array.prototype.slice.apply(arguments),
// common mistake: an HTML element can't be in several tooltips at the same time
contentCloningWarning = 'You are using a single HTML element as content for several tooltips. You probably want to set the contentCloning option to TRUE.';
// this happens with $(sel).tooltipster(...) when $(sel) does not match anything
if (this.length === 0) {
// still chainable
return this;
}
// this happens when calling $(sel).tooltipster('methodName or options')
// where $(sel) matches one or more elements
else {
// method calls
if (typeof args[0] === 'string') {
var v = '#*$~&';
this.each(function() {
// retrieve the namepaces of the tooltip(s) that exist on that element.
// We will interact with the first tooltip only.
var ns = $(this).data('tooltipster-ns'),
// self represents the instance of the first tooltipster plugin
// associated to the current HTML object of the loop
self = ns ? $(this).data(ns[0]) : null;
// if the current element holds a tooltipster instance
if (self) {
if (typeof self[args[0]] === 'function') {
if ( this.length > 1
&& args[0] == 'content'
&& ( args[1] instanceof $
|| (typeof args[1] == 'object' && args[1] != null && args[1].tagName)
)
&& !self.__options.contentCloning
&& self.__options.debug
) {
console.log(contentCloningWarning);
}
// note : args[1] and args[2] may not be defined
var resp = self[args[0]](args[1], args[2]);
}
else {
throw new Error('Unknown method "'+ args[0] +'"');
}
// if the function returned anything other than the instance
// itself (which implies chaining, except for the `instance` method)
if (resp !== self || args[0] === 'instance') {
v = resp;
// return false to stop .each iteration on the first element
// matched by the selector
return false;
}
}
else {
throw new Error('You called Tooltipster\'s "'+ args[0] +'" method on an uninitialized element');
}
});
return (v !== '#*$~&') ? v : this;
}
// first argument is undefined or an object: the tooltip is initializing
else {
// reset the array of last initialized objects
$.tooltipster.__instancesLatestArr = [];
// is there a defined value for the multiple option in the options object ?
var multipleIsSet = args[0] && args[0].multiple !== undefined,
// if the multiple option is set to true, or if it's not defined but
// set to true in the defaults
multiple = (multipleIsSet && args[0].multiple) || (!multipleIsSet && defaults.multiple),
// same for content
contentIsSet = args[0] && args[0].content !== undefined,
content = (contentIsSet && args[0].content) || (!contentIsSet && defaults.content),
// same for contentCloning
contentCloningIsSet = args[0] && args[0].contentCloning !== undefined,
contentCloning =
(contentCloningIsSet && args[0].contentCloning)
|| (!contentCloningIsSet && defaults.contentCloning),
// same for debug
debugIsSet = args[0] && args[0].debug !== undefined,
debug = (debugIsSet && args[0].debug) || (!debugIsSet && defaults.debug);
if ( this.length > 1
&& ( content instanceof $
|| (typeof content == 'object' && content != null && content.tagName)
)
&& !contentCloning
&& debug
) {
console.log(contentCloningWarning);
}
// create a tooltipster instance for each element if it doesn't
// already have one or if the multiple option is set, and attach the
// object to it
this.each(function() {
var go = false,
$this = $(this),
ns = $this.data('tooltipster-ns'),
obj = null;
if (!ns) {
go = true;
}
else if (multiple) {
go = true;
}
else if (debug) {
console.log('Tooltipster: one or more tooltips are already attached to the element below. Ignoring.');
console.log(this);
}
if (go) {
obj = new $.Tooltipster(this, args[0]);
// save the reference of the new instance
if (!ns) ns = [];
ns.push(obj.__namespace);
$this.data('tooltipster-ns', ns);
// save the instance itself
$this.data(obj.__namespace, obj);
// call our constructor custom function.
// we do this here and not in ::init() because we wanted
// the object to be saved in $this.data before triggering
// it
if (obj.__options.functionInit) {
obj.__options.functionInit.call(obj, obj, {
origin: this
});
}
// and now the event, for the plugins and core emitter
obj._trigger('init');
}
$.tooltipster.__instancesLatestArr.push(obj);
});
return this;
}
}
};
// Utilities
/**
* A class to check if a tooltip can fit in given dimensions
*
* @param {object} $tooltip The jQuery wrapped tooltip element, or a clone of it
*/
function Ruler($tooltip) {
// list of instance variables
this.$container;
this.constraints = null;
this.__$tooltip;
this.__init($tooltip);
}
Ruler.prototype = {
/**
* Move the tooltip into an invisible div that does not allow overflow to make
* size tests. Note: the tooltip may or may not be attached to the DOM at the
* moment this method is called, it does not matter.
*
* @param {object} $tooltip The object to test. May be just a clone of the
* actual tooltip.
* @private
*/
__init: function($tooltip) {
this.__$tooltip = $tooltip;
this.__$tooltip
.css({
// for some reason we have to specify top and left 0
left: 0,
// any overflow will be ignored while measuring
overflow: 'hidden',
// positions at (0,0) without the div using 100% of the available width
position: 'absolute',
top: 0
})
// overflow must be auto during the test. We re-set this in case
// it were modified by the user
.find('.tooltipster-content')
.css('overflow', 'auto');
this.$container = $('<div class="tooltipster-ruler"></div>')
.append(this.__$tooltip)
.appendTo(env.window.document.body);
},
/**
* Force the browser to redraw (re-render) the tooltip immediately. This is required
* when you changed some CSS properties and need to make something with it
* immediately, without waiting for the browser to redraw at the end of instructions.
*
* @see http://stackoverflow.com/questions/3485365/how-can-i-force-webkit-to-redraw-repaint-to-propagate-style-changes
* @private
*/
__forceRedraw: function() {
// note: this would work but for Webkit only
//this.__$tooltip.close();
//this.__$tooltip[0].offsetHeight;
//this.__$tooltip.open();
// works in FF too
var $p = this.__$tooltip.parent();
this.__$tooltip.detach();
this.__$tooltip.appendTo($p);
},
/**
* Set maximum dimensions for the tooltip. A call to ::measure afterwards
* will tell us if the content overflows or if it's ok
*
* @param {int} width
* @param {int} height
* @return {Ruler}
* @public
*/
constrain: function(width, height) {
this.constraints = {
width: width,
height: height
};
this.__$tooltip.css({
// we disable display:flex, otherwise the content would overflow without
// creating horizontal scrolling (which we need to detect).
display: 'block',
// reset any previous height
height: '',
// we'll check if horizontal scrolling occurs
overflow: 'auto',
// we'll set the width and see what height is generated and if there
// is horizontal overflow
width: width
});
return this;
},
/**
* Reset the tooltip content overflow and remove the test container
*
* @returns {Ruler}
* @public
*/
destroy: function() {
// in case the element was not a clone
this.__$tooltip
.detach()
.find('.tooltipster-content')
.css({
// reset to CSS value
display: '',
overflow: ''
});
this.$container.remove();
},
/**
* Removes any constraints
*
* @returns {Ruler}
* @public
*/
free: function() {
this.constraints = null;
// reset to natural size
this.__$tooltip.css({
display: '',
height: '',
overflow: 'visible',
width: ''
});
return this;
},
/**
* Returns the size of the tooltip. When constraints are applied, also returns
* whether the tooltip fits in the provided dimensions.
* The idea is to see if the new height is small enough and if the content does
* not overflow horizontally.
*
* @param {int} width
* @param {int} height
* @returns {object} An object with a bool `fits` property and a `size` property
* @public
*/
measure: function() {
this.__forceRedraw();
var tooltipBcr = this.__$tooltip[0].getBoundingClientRect(),
result = { size: {
// bcr.width/height are not defined in IE8- but in this
// case, bcr.right/bottom will have the same value
// except in iOS 8+ where tooltipBcr.bottom/right are wrong
// after scrolling for reasons yet to be determined.
// tooltipBcr.top/left might not be 0, see issue #514
height: tooltipBcr.height || (tooltipBcr.bottom - tooltipBcr.top),
width: tooltipBcr.width || (tooltipBcr.right - tooltipBcr.left)
}};
if (this.constraints) {
// note: we used to use offsetWidth instead of boundingRectClient but
// it returned rounded values, causing issues with sub-pixel layouts.
// note2: noticed that the bcrWidth of text content of a div was once
// greater than the bcrWidth of its container by 1px, causing the final
// tooltip box to be too small for its content. However, evaluating
// their widths one against the other (below) surprisingly returned
// equality. Happened only once in Chrome 48, was not able to reproduce
// => just having fun with float position values...
var $content = this.__$tooltip.find('.tooltipster-content'),
height = this.__$tooltip.outerHeight(),
contentBcr = $content[0].getBoundingClientRect(),
fits = {
height: height <= this.constraints.height,
width: (
// this condition accounts for min-width property that
// may apply
tooltipBcr.width <= this.constraints.width
// the -1 is here because scrollWidth actually returns
// a rounded value, and may be greater than bcr.width if
// it was rounded up. This may cause an issue for contents
// which actually really overflow by 1px or so, but that
// should be rare. Not sure how to solve this efficiently.
// See http://blogs.msdn.com/b/ie/archive/2012/02/17/sub-pixel-rendering-and-the-css-object-model.aspx
&& contentBcr.width >= $content[0].scrollWidth - 1
)
};
result.fits = fits.height && fits.width;
}
// old versions of IE get the width wrong for some reason and it causes
// the text to be broken to a new line, so we round it up. If the width
// is the width of the screen though, we can assume it is accurate.
if ( env.IE
&& env.IE <= 11
&& result.size.width !== env.window.document.documentElement.clientWidth
) {
result.size.width = Math.ceil(result.size.width) + 1;
}
return result;
}
};
// quick & dirty compare function, not bijective nor multidimensional
function areEqual(a,b) {
var same = true;
$.each(a, function(i, _) {
if (b[i] === undefined || a[i] !== b[i]) {
same = false;
return false;
}
});
return same;
}
/**
* A fast function to check if an element is still in the DOM. It
* tries to use an id as ids are indexed by the browser, or falls
* back to jQuery's `contains` method. May fail if two elements
* have the same id, but so be it
*
* @param {object} $obj A jQuery-wrapped HTML element
* @return {boolean}
*/
function bodyContains($obj) {
var id = $obj.attr('id'),
el = id ? env.window.document.getElementById(id) : null;
// must also check that the element with the id is the one we want
return el ? el === $obj[0] : $.contains(env.window.document.body, $obj[0]);
}
// detect IE versions for dirty fixes
var uA = navigator.userAgent.toLowerCase();
if (uA.indexOf('msie') != -1) env.IE = parseInt(uA.split('msie')[1]);
else if (uA.toLowerCase().indexOf('trident') !== -1 && uA.indexOf(' rv:11') !== -1) env.IE = 11;
else if (uA.toLowerCase().indexOf('edge/') != -1) env.IE = parseInt(uA.toLowerCase().split('edge/')[1]);
// detecting support for CSS transitions
function transitionSupport() {
// env.window is not defined yet when this is called
if (!win) return false;
var b = win.document.body || win.document.documentElement,
s = b.style,
p = 'transition',
v = ['Moz', 'Webkit', 'Khtml', 'O', 'ms'];
if (typeof s[p] == 'string') { return true; }
p = p.charAt(0).toUpperCase() + p.substr(1);
for (var i=0; i<v.length; i++) {
if (typeof s[v[i] + p] == 'string') { return true; }
}
return false;
}
// we'll return jQuery for plugins not to have to declare it as a dependency,
// but it's done by a build task since it should be included only once at the
// end when we concatenate the main file with a plugin
// sideTip is Tooltipster's default plugin.
// This file will be UMDified by a build task.
var pluginName = 'tooltipster.sideTip';
$.tooltipster._plugin({
name: pluginName,
instance: {
/**
* Defaults are provided as a function for an easy override by inheritance
*
* @return {object} An object with the defaults options
* @private
*/
__defaults: function() {
return {
// if the tooltip should display an arrow that points to the origin
arrow: true,
// the distance in pixels between the tooltip and the origin
distance: 6,
// allows to easily change the position of the tooltip
functionPosition: null,
maxWidth: null,
// used to accomodate the arrow of tooltip if there is one.
// First to make sure that the arrow target is not too close
// to the edge of the tooltip, so the arrow does not overflow
// the tooltip. Secondly when we reposition the tooltip to
// make sure that it's positioned in such a way that the arrow is
// still pointing at the target (and not a few pixels beyond it).
// It should be equal to or greater than half the width of
// the arrow (by width we mean the size of the side which touches
// the side of the tooltip).
minIntersection: 16,
minWidth: 0,
// deprecated in 4.0.0. Listed for _optionsExtract to pick it up
position: null,
side: 'top',
// set to false to position the tooltip relatively to the document rather
// than the window when we open it
viewportAware: true
};
},
/**
* Run once: at instantiation of the plugin
*
* @param {object} instance The tooltipster object that instantiated this plugin
* @private
*/
__init: function(instance) {
var self = this;
// list of instance variables
self.__instance = instance;
self.__namespace = 'tooltipster-sideTip-'+ Math.round(Math.random()*1000000);
self.__previousState = 'closed';
self.__options;
// initial formatting
self.__optionsFormat();
self.__instance._on('state.'+ self.__namespace, function(event) {
if (event.state == 'closed') {
self.__close();
}
else if (event.state == 'appearing' && self.__previousState == 'closed') {
self.__create();
}
self.__previousState = event.state;
});
// reformat every time the options are changed
self.__instance._on('options.'+ self.__namespace, function() {
self.__optionsFormat();
});
self.__instance._on('reposition.'+ self.__namespace, function(e) {
self.__reposition(e.event, e.helper);
});
},
/**
* Called when the tooltip has closed
*
* @private
*/
__close: function() {
// detach our content object first, so the next jQuery's remove()
// call does not unbind its event handlers
if (this.__instance.content() instanceof $) {
this.__instance.content().detach();
}
// remove the tooltip from the DOM
this.__instance._$tooltip.remove();
this.__instance._$tooltip = null;
},
/**
* Creates the HTML element of the tooltip.
*
* @private
*/
__create: function() {
// note: we wrap with a .tooltipster-box div to be able to set a margin on it
// (.tooltipster-base must not have one)
var $html = $(
'<div class="tooltipster-base tooltipster-sidetip">' +
'<div class="tooltipster-box">' +
'<div class="tooltipster-content"></div>' +
'</div>' +
'<div class="tooltipster-arrow">' +
'<div class="tooltipster-arrow-uncropped">' +
'<div class="tooltipster-arrow-border"></div>' +
'<div class="tooltipster-arrow-background"></div>' +
'</div>' +
'</div>' +
'</div>'
);
// hide arrow if asked
if (!this.__options.arrow) {
$html
.find('.tooltipster-box')
.css('margin', 0)
.end()
.find('.tooltipster-arrow')
.hide();
}
// apply min/max width if asked
if (this.__options.minWidth) {
$html.css('min-width', this.__options.minWidth + 'px');
}
if (this.__options.maxWidth) {
$html.css('max-width', this.__options.maxWidth + 'px');
}
this.__instance._$tooltip = $html;
// tell the instance that the tooltip element has been created
this.__instance._trigger('created');
},
/**
* Used when the plugin is to be unplugged
*
* @private
*/
__destroy: function() {
this.__instance._off('.'+ self.__namespace);
},
/**
* (Re)compute this.__options from the options declared to the instance
*
* @private
*/
__optionsFormat: function() {
var self = this;
// get the options
self.__options = self.__instance._optionsExtract(pluginName, self.__defaults());
// for backward compatibility, deprecated in v4.0.0
if (self.__options.position) {
self.__options.side = self.__options.position;
}
// options formatting
// format distance as a four-cell array if it ain't one yet and then make
// it an object with top/bottom/left/right properties
if (typeof self.__options.distance != 'object') {
self.__options.distance = [self.__options.distance];
}
if (self.__options.distance.length < 4) {
if (self.__options.distance[1] === undefined) self.__options.distance[1] = self.__options.distance[0];
if (self.__options.distance[2] === undefined) self.__options.distance[2] = self.__options.distance[0];
if (self.__options.distance[3] === undefined) self.__options.distance[3] = self.__options.distance[1];
self.__options.distance = {
top: self.__options.distance[0],
right: self.__options.distance[1],
bottom: self.__options.distance[2],
left: self.__options.distance[3]
};
}
// let's transform:
// 'top' into ['top', 'bottom', 'right', 'left']
// 'right' into ['right', 'left', 'top', 'bottom']
// 'bottom' into ['bottom', 'top', 'right', 'left']
// 'left' into ['left', 'right', 'top', 'bottom']
if (typeof self.__options.side == 'string') {
var opposites = {
'top': 'bottom',
'right': 'left',
'bottom': 'top',
'left': 'right'
};
self.__options.side = [self.__options.side, opposites[self.__options.side]];
if (self.__options.side[0] == 'left' || self.__options.side[0] == 'right') {
self.__options.side.push('top', 'bottom');
}
else {
self.__options.side.push('right', 'left');
}
}
// misc
// disable the arrow in IE6 unless the arrow option was explicitly set to true
if ( $.tooltipster._env.IE === 6
&& self.__options.arrow !== true
) {
self.__options.arrow = false;
}
},
/**
* This method must compute and set the positioning properties of the
* tooltip (left, top, width, height, etc.). It must also make sure the
* tooltip is eventually appended to its parent (since the element may be
* detached from the DOM at the moment the method is called).
*
* We'll evaluate positioning scenarios to find which side can contain the
* tooltip in the best way. We'll consider things relatively to the window
* (unless the user asks not to), then to the document (if need be, or if the
* user explicitly requires the tests to run on the document). For each
* scenario, measures are taken, allowing us to know how well the tooltip
* is going to fit. After that, a sorting function will let us know what
* the best scenario is (we also allow the user to choose his favorite
* scenario by using an event).
*
* @param {object} helper An object that contains variables that plugin
* creators may find useful (see below)
* @param {object} helper.geo An object with many layout properties
* about objects of interest (window, document, origin). This should help
* plugin users compute the optimal position of the tooltip
* @private
*/
__reposition: function(event, helper) {
var self = this,
finalResult,
// to know where to put the tooltip, we need to know on which point
// of the x or y axis we should center it. That coordinate is the target
targets = self.__targetFind(helper),
testResults = [];
// make sure the tooltip is detached while we make tests on a clone
self.__instance._$tooltip.detach();
// we could actually provide the original element to the Ruler and
// not a clone, but it just feels right to keep it out of the
// machinery.
var $clone = self.__instance._$tooltip.clone(),
// start position tests session
ruler = $.tooltipster._getRuler($clone),
satisfied = false,
animation = self.__instance.option('animation');
// an animation class could contain properties that distort the size
if (animation) {
$clone.removeClass('tooltipster-'+ animation);
}
// start evaluating scenarios
$.each(['window', 'document'], function(i, container) {
var takeTest = null;
// let the user decide to keep on testing or not
self.__instance._trigger({
container: container,
helper: helper,
satisfied: satisfied,
takeTest: function(bool) {
takeTest = bool;
},
results: testResults,
type: 'positionTest'
});
if ( takeTest == true
|| ( takeTest != false
&& satisfied == false
// skip the window scenarios if asked. If they are reintegrated by
// the callback of the positionTest event, they will have to be
// excluded using the callback of positionTested
&& (container != 'window' || self.__options.viewportAware)
)
) {
// for each allowed side
for (var i=0; i < self.__options.side.length; i++) {
var distance = {
horizontal: 0,
vertical: 0
},
side = self.__options.side[i];
if (side == 'top' || side == 'bottom') {
distance.vertical = self.__options.distance[side];
}
else {
distance.horizontal = self.__options.distance[side];
}
// this may have an effect on the size of the tooltip if there are css
// rules for the arrow or something else
self.__sideChange($clone, side);
$.each(['natural', 'constrained'], function(i, mode) {
takeTest = null;
// emit an event on the instance
self.__instance._trigger({
container: container,
event: event,
helper: helper,
mode: mode,
results: testResults,
satisfied: satisfied,
side: side,
takeTest: function(bool) {
takeTest = bool;
},
type: 'positionTest'
});
if ( takeTest == true
|| ( takeTest != false
&& satisfied == false
)
) {
var testResult = {
container: container,
// we let the distance as an object here, it can make things a little easier
// during the user's calculations at positionTest/positionTested
distance: distance,
// whether the tooltip can fit in the size of the viewport (does not mean
// that we'll be able to make it initially entirely visible, see 'whole')
fits: null,
mode: mode,
outerSize: null,
side: side,
size: null,
target: targets[side],
// check if the origin has enough surface on screen for the tooltip to
// aim at it without overflowing the viewport (this is due to the thickness
// of the arrow represented by the minIntersection length).
// If not, the tooltip will have to be partly or entirely off screen in
// order to stay docked to the origin. This value will stay null when the
// container is the document, as it is not relevant
whole: null
};
// get the size of the tooltip with or without size constraints
var rulerConfigured = (mode == 'natural') ?
ruler.free() :
ruler.constrain(
helper.geo.available[container][side].width - distance.horizontal,
helper.geo.available[container][side].height - distance.vertical
),
rulerResults = rulerConfigured.measure();
testResult.size = rulerResults.size;
testResult.outerSize = {
height: rulerResults.size.height + distance.vertical,
width: rulerResults.size.width + distance.horizontal
};
if (mode == 'natural') {
if( helper.geo.available[container][side].width >= testResult.outerSize.width
&& helper.geo.available[container][side].height >= testResult.outerSize.height
) {
testResult.fits = true;
}
else {
testResult.fits = false;
}
}
else {
testResult.fits = rulerResults.fits;
}
if (container == 'window') {
if (!testResult.fits) {
testResult.whole = false;
}
else {
if (side == 'top' || side == 'bottom') {
testResult.whole = (
helper.geo.origin.windowOffset.right >= self.__options.minIntersection
&& helper.geo.window.size.width - helper.geo.origin.windowOffset.left >= self.__options.minIntersection
);
}
else {
testResult.whole = (
helper.geo.origin.windowOffset.bottom >= self.__options.minIntersection
&& helper.geo.window.size.height - helper.geo.origin.windowOffset.top >= self.__options.minIntersection
);
}
}
}
testResults.push(testResult);
// we don't need to compute more positions if we have one fully on screen
if (testResult.whole) {
satisfied = true;
}
else {
// don't run the constrained test unless the natural width was greater
// than the available width, otherwise it's pointless as we know it
// wouldn't fit either
if ( testResult.mode == 'natural'
&& ( testResult.fits
|| testResult.size.width <= helper.geo.available[container][side].width
)
) {
return false;
}
}
}
});
}
}
});
// the user may eliminate the unwanted scenarios from testResults, but he's
// not supposed to alter them at this point. functionPosition and the
// position event serve that purpose.
self.__instance._trigger({
edit: function(r) {
testResults = r;
},
event: event,
helper: helper,
results: testResults,
type: 'positionTested'
});
/**
* Sort the scenarios to find the favorite one.
*
* The favorite scenario is when we can fully display the tooltip on screen,
* even if it means that the middle of the tooltip is no longer centered on
* the middle of the origin (when the origin is near the edge of the screen
* or even partly off screen). We want the tooltip on the preferred side,
* even if it means that we have to use a constrained size rather than a
* natural one (as long as it fits). When the origin is off screen at the top
* the tooltip will be positioned at the bottom (if allowed), if the origin
* is off screen on the right, it will be positioned on the left, etc.
* If there are no scenarios where the tooltip can fit on screen, or if the
* user does not want the tooltip to fit on screen (viewportAware == false),
* we fall back to the scenarios relative to the document.
*
* When the tooltip is bigger than the viewport in either dimension, we stop
* looking at the window scenarios and consider the document scenarios only,
* with the same logic to find on which side it would fit best.
*
* If the tooltip cannot fit the document on any side, we force it at the
* bottom, so at least the user can scroll to see it.
*/
testResults.sort(function(a, b) {
// best if it's whole (the tooltip fits and adapts to the viewport)
if (a.whole && !b.whole) {
return -1;
}
else if (!a.whole && b.whole) {
return 1;
}
else if (a.whole && b.whole) {
var ai = self.__options.side.indexOf(a.side),
bi = self.__options.side.indexOf(b.side);
// use the user's sides fallback array
if (ai < bi) {
return -1;
}
else if (ai > bi) {
return 1;
}
else {
// will be used if the user forced the tests to continue
return a.mode == 'natural' ? -1 : 1;
}
}
else {
// better if it fits
if (a.fits && !b.fits) {
return -1;
}
else if (!a.fits && b.fits) {
return 1;
}
else if (a.fits && b.fits) {
var ai = self.__options.side.indexOf(a.side),
bi = self.__options.side.indexOf(b.side);
// use the user's sides fallback array
if (ai < bi) {
return -1;
}
else if (ai > bi) {
return 1;
}
else {
// will be used if the user forced the tests to continue
return a.mode == 'natural' ? -1 : 1;
}
}
else {
// if everything failed, this will give a preference to the case where
// the tooltip overflows the document at the bottom
if ( a.container == 'document'
&& a.side == 'bottom'
&& a.mode == 'natural'
) {
return -1;
}
else {
return 1;
}
}
}
});
finalResult = testResults[0];
// now let's find the coordinates of the tooltip relatively to the window
finalResult.coord = {};
switch (finalResult.side) {
case 'left':
case 'right':
finalResult.coord.top = Math.floor(finalResult.target - finalResult.size.height / 2);
break;
case 'bottom':
case 'top':
finalResult.coord.left = Math.floor(finalResult.target - finalResult.size.width / 2);
break;
}
switch (finalResult.side) {
case 'left':
finalResult.coord.left = helper.geo.origin.windowOffset.left - finalResult.outerSize.width;
break;
case 'right':
finalResult.coord.left = helper.geo.origin.windowOffset.right + finalResult.distance.horizontal;
break;
case 'top':
finalResult.coord.top = helper.geo.origin.windowOffset.top - finalResult.outerSize.height;
break;
case 'bottom':
finalResult.coord.top = helper.geo.origin.windowOffset.bottom + finalResult.distance.vertical;
break;
}
// if the tooltip can potentially be contained within the viewport dimensions
// and that we are asked to make it fit on screen
if (finalResult.container == 'window') {
// if the tooltip overflows the viewport, we'll move it accordingly (then it will
// not be centered on the middle of the origin anymore). We only move horizontally
// for top and bottom tooltips and vice versa.
if (finalResult.side == 'top' || finalResult.side == 'bottom') {
// if there is an overflow on the left
if (finalResult.coord.left < 0) {
// prevent the overflow unless the origin itself gets off screen (minus the
// margin needed to keep the arrow pointing at the target)
if (helper.geo.origin.windowOffset.right - this.__options.minIntersection >= 0) {
finalResult.coord.left = 0;
}
else {
finalResult.coord.left = helper.geo.origin.windowOffset.right - this.__options.minIntersection - 1;
}
}
// or an overflow on the right
else if (finalResult.coord.left > helper.geo.window.size.width - finalResult.size.width) {
if (helper.geo.origin.windowOffset.left + this.__options.minIntersection <= helper.geo.window.size.width) {
finalResult.coord.left = helper.geo.window.size.width - finalResult.size.width;
}
else {
finalResult.coord.left = helper.geo.origin.windowOffset.left + this.__options.minIntersection + 1 - finalResult.size.width;
}
}
}
else {
// overflow at the top
if (finalResult.coord.top < 0) {
if (helper.geo.origin.windowOffset.bottom - this.__options.minIntersection >= 0) {
finalResult.coord.top = 0;
}
else {
finalResult.coord.top = helper.geo.origin.windowOffset.bottom - this.__options.minIntersection - 1;
}
}
// or at the bottom
else if (finalResult.coord.top > helper.geo.window.size.height - finalResult.size.height) {
if (helper.geo.origin.windowOffset.top + this.__options.minIntersection <= helper.geo.window.size.height) {
finalResult.coord.top = helper.geo.window.size.height - finalResult.size.height;
}
else {
finalResult.coord.top = helper.geo.origin.windowOffset.top + this.__options.minIntersection + 1 - finalResult.size.height;
}
}
}
}
else {
// there might be overflow here too but it's easier to handle. If there has
// to be an overflow, we'll make sure it's on the right side of the screen
// (because the browser will extend the document size if there is an overflow
// on the right, but not on the left). The sort function above has already
// made sure that a bottom document overflow is preferred to a top overflow,
// so we don't have to care about it.
// if there is an overflow on the right
if (finalResult.coord.left > helper.geo.window.size.width - finalResult.size.width) {
// this may actually create on overflow on the left but we'll fix it in a sec
finalResult.coord.left = helper.geo.window.size.width - finalResult.size.width;
}
// if there is an overflow on the left
if (finalResult.coord.left < 0) {
// don't care if it overflows the right after that, we made our best
finalResult.coord.left = 0;
}
}
// submit the positioning proposal to the user function which may choose to change
// the side, size and/or the coordinates
// first, set the rules that corresponds to the proposed side: it may change
// the size of the tooltip, and the custom functionPosition may want to detect the
// size of something before making a decision. So let's make things easier for the
// implementor
self.__sideChange($clone, finalResult.side);
// add some variables to the helper
helper.tooltipClone = $clone[0];
helper.tooltipParent = self.__instance.option('parent').parent[0];
// move informative values to the helper
helper.mode = finalResult.mode;
helper.whole = finalResult.whole;
// add some variables to the helper for the functionPosition callback (these
// will also be added to the event fired by self.__instance._trigger but that's
// ok, we're just being consistent)
helper.origin = self.__instance._$origin[0];
helper.tooltip = self.__instance._$tooltip[0];
// leave only the actionable values in there for functionPosition
delete finalResult.container;
delete finalResult.fits;
delete finalResult.mode;
delete finalResult.outerSize;
delete finalResult.whole;
// keep only the distance on the relevant side, for clarity
finalResult.distance = finalResult.distance.horizontal || finalResult.distance.vertical;
// beginners may not be comfortable with the concept of editing the object
// passed by reference, so we provide an edit function and pass a clone
var finalResultClone = $.extend(true, {}, finalResult);
// emit an event on the instance
self.__instance._trigger({
edit: function(result) {
finalResult = result;
},
event: event,
helper: helper,
position: finalResultClone,
type: 'position'
});
if (self.__options.functionPosition) {
var result = self.__options.functionPosition.call(self, self.__instance, helper, finalResultClone);
if (result) finalResult = result;
}
// end the positioning tests session (the user might have had a
// use for it during the position event, now it's over)
ruler.destroy();
// compute the position of the target relatively to the tooltip root
// element so we can place the arrow and make the needed adjustments
var arrowCoord,
maxVal;
if (finalResult.side == 'top' || finalResult.side == 'bottom') {
arrowCoord = {
prop: 'left',
val: finalResult.target - finalResult.coord.left
};
maxVal = finalResult.size.width - this.__options.minIntersection;
}
else {
arrowCoord = {
prop: 'top',
val: finalResult.target - finalResult.coord.top
};
maxVal = finalResult.size.height - this.__options.minIntersection;
}
// cannot lie beyond the boundaries of the tooltip, minus the
// arrow margin
if (arrowCoord.val < this.__options.minIntersection) {
arrowCoord.val = this.__options.minIntersection;
}
else if (arrowCoord.val > maxVal) {
arrowCoord.val = maxVal;
}
var originParentOffset;
// let's convert the window-relative coordinates into coordinates relative to the
// future positioned parent that the tooltip will be appended to
if (helper.geo.origin.fixedLineage) {
// same as windowOffset when the position is fixed
originParentOffset = helper.geo.origin.windowOffset;
}
else {
// this assumes that the parent of the tooltip is located at
// (0, 0) in the document, typically like when the parent is
// <body>.
// If we ever allow other types of parent, .tooltipster-ruler
// will have to be appended to the parent to inherit css style
// values that affect the display of the text and such.
originParentOffset = {
left: helper.geo.origin.windowOffset.left + helper.geo.window.scroll.left,
top: helper.geo.origin.windowOffset.top + helper.geo.window.scroll.top
};
}
finalResult.coord = {
left: originParentOffset.left + (finalResult.coord.left - helper.geo.origin.windowOffset.left),
top: originParentOffset.top + (finalResult.coord.top - helper.geo.origin.windowOffset.top)
};
// set position values on the original tooltip element
self.__sideChange(self.__instance._$tooltip, finalResult.side);
if (helper.geo.origin.fixedLineage) {
self.__instance._$tooltip
.css('position', 'fixed');
}
else {
// CSS default
self.__instance._$tooltip
.css('position', '');
}
self.__instance._$tooltip
.css({
left: finalResult.coord.left,
top: finalResult.coord.top,
// we need to set a size even if the tooltip is in its natural size
// because when the tooltip is positioned beyond the width of the body
// (which is by default the width of the window; it will happen when
// you scroll the window horizontally to get to the origin), its text
// content will otherwise break lines at each word to keep up with the
// body overflow strategy.
height: finalResult.size.height,
width: finalResult.size.width
})
.find('.tooltipster-arrow')
.css({
'left': '',
'top': ''
})
.css(arrowCoord.prop, arrowCoord.val);
// append the tooltip HTML element to its parent
self.__instance._$tooltip.appendTo(self.__instance.option('parent'));
self.__instance._trigger({
type: 'repositioned',
event: event,
position: finalResult
});
},
/**
* Make whatever modifications are needed when the side is changed. This has
* been made an independant method for easy inheritance in custom plugins based
* on this default plugin.
*
* @param {object} $obj
* @param {string} side
* @private
*/
__sideChange: function($obj, side) {
$obj
.removeClass('tooltipster-bottom')
.removeClass('tooltipster-left')
.removeClass('tooltipster-right')
.removeClass('tooltipster-top')
.addClass('tooltipster-'+ side);
},
/**
* Returns the target that the tooltip should aim at for a given side.
* The calculated value is a distance from the edge of the window
* (left edge for top/bottom sides, top edge for left/right side). The
* tooltip will be centered on that position and the arrow will be
* positioned there (as much as possible).
*
* @param {object} helper
* @return {integer}
* @private
*/
__targetFind: function(helper) {
var target = {},
rects = this.__instance._$origin[0].getClientRects();
// these lines fix a Chrome bug (issue #491)
if (rects.length > 1) {
var opacity = this.__instance._$origin.css('opacity');
if(opacity == 1) {
this.__instance._$origin.css('opacity', 0.99);
rects = this.__instance._$origin[0].getClientRects();
this.__instance._$origin.css('opacity', 1);
}
}
// by default, the target will be the middle of the origin
if (rects.length < 2) {
target.top = Math.floor(helper.geo.origin.windowOffset.left + (helper.geo.origin.size.width / 2));
target.bottom = target.top;
target.left = Math.floor(helper.geo.origin.windowOffset.top + (helper.geo.origin.size.height / 2));
target.right = target.left;
}
// if multiple client rects exist, the element may be text split
// up into multiple lines and the middle of the origin may not be
// best option anymore. We need to choose the best target client rect
else {
// top: the first
var targetRect = rects[0];
target.top = Math.floor(targetRect.left + (targetRect.right - targetRect.left) / 2);
// right: the middle line, rounded down in case there is an even
// number of lines (looks more centered => check out the
// demo with 4 split lines)
if (rects.length > 2) {
targetRect = rects[Math.ceil(rects.length / 2) - 1];
}
else {
targetRect = rects[0];
}
target.right = Math.floor(targetRect.top + (targetRect.bottom - targetRect.top) / 2);
// bottom: the last
targetRect = rects[rects.length - 1];
target.bottom = Math.floor(targetRect.left + (targetRect.right - targetRect.left) / 2);
// left: the middle line, rounded up
if (rects.length > 2) {
targetRect = rects[Math.ceil((rects.length + 1) / 2) - 1];
}
else {
targetRect = rects[rects.length - 1];
}
target.left = Math.floor(targetRect.top + (targetRect.bottom - targetRect.top) / 2);
}
return target;
}
}
});
/* a build task will add "return $;" here */
return $;
}));
|
import domUtils from './domUtils';
const utils = {
getContainerDimensions(containerNode) {
let width, height, scroll;
if (containerNode.tagName === 'BODY') {
width = window.innerWidth;
height = window.innerHeight;
scroll =
domUtils.ownerDocument(containerNode).documentElement.scrollTop ||
containerNode.scrollTop;
} else {
width = containerNode.offsetWidth;
height = containerNode.offsetHeight;
scroll = containerNode.scrollTop;
}
return {width, height, scroll};
},
getPosition(target, container) {
const offset = container.tagName === 'BODY' ?
domUtils.getOffset(target) : domUtils.getPosition(target, container);
return {
...offset, // eslint-disable-line object-shorthand
height: target.offsetHeight,
width: target.offsetWidth
};
},
calcOverlayPosition(placement, overlayNode, target, container, padding) {
const childOffset = utils.getPosition(target, container);
const overlayHeight = overlayNode.offsetHeight;
const overlayWidth = overlayNode.offsetWidth;
let positionLeft, positionTop, arrowOffsetLeft, arrowOffsetTop;
if (placement === 'left' || placement === 'right') {
positionTop = childOffset.top + (childOffset.height - overlayHeight) / 2;
if (placement === 'left') {
positionLeft = childOffset.left - overlayWidth;
} else {
positionLeft = childOffset.left + childOffset.width;
}
const topDelta = getTopDelta(positionTop, overlayHeight, container, padding);
positionTop += topDelta;
arrowOffsetTop = 50 * (1 - 2 * topDelta / overlayHeight) + '%';
arrowOffsetLeft = null;
} else if (placement === 'top' || placement === 'bottom') {
positionLeft = childOffset.left + (childOffset.width - overlayWidth) / 2;
if (placement === 'top') {
positionTop = childOffset.top - overlayHeight;
} else {
positionTop = childOffset.top + childOffset.height;
}
const leftDelta = getLeftDelta(positionLeft, overlayWidth, container, padding);
positionLeft += leftDelta;
arrowOffsetLeft = 50 * (1 - 2 * leftDelta / overlayWidth) + '%';
arrowOffsetTop = null;
} else {
throw new Error(
`calcOverlayPosition(): No such placement of "${placement }" found.`
);
}
return { positionLeft, positionTop, arrowOffsetLeft, arrowOffsetTop };
}
};
function getTopDelta(top, overlayHeight, container, padding) {
const containerDimensions = utils.getContainerDimensions(container);
const containerScroll = containerDimensions.scroll;
const containerHeight = containerDimensions.height;
const topEdgeOffset = top - padding - containerScroll;
const bottomEdgeOffset = top + padding - containerScroll + overlayHeight;
if (topEdgeOffset < 0) {
return -topEdgeOffset;
} else if (bottomEdgeOffset > containerHeight) {
return containerHeight - bottomEdgeOffset;
} else {
return 0;
}
}
function getLeftDelta(left, overlayWidth, container, padding) {
const containerDimensions = utils.getContainerDimensions(container);
const containerWidth = containerDimensions.width;
const leftEdgeOffset = left - padding;
const rightEdgeOffset = left + padding + overlayWidth;
if (leftEdgeOffset < 0) {
return -leftEdgeOffset;
} else if (rightEdgeOffset > containerWidth) {
return containerWidth - rightEdgeOffset;
} else {
return 0;
}
}
export default utils;
|
/*jshint node:true*/
module.exports = {
};
|
/* eslint-env mocha, browser*/
/* global proclaim, it */
describe('console', function () {
it('warn()', function () {
proclaim.doesNotThrow(function () {
console.warn();
});
});
});
|
/*! `csharp` grammar compiled for Highlight.js 11.3.1 */
(()=>{var e=(()=>{"use strict";return e=>{const n={
keyword:["abstract","as","base","break","case","catch","class","const","continue","do","else","event","explicit","extern","finally","fixed","for","foreach","goto","if","implicit","in","interface","internal","is","lock","namespace","new","operator","out","override","params","private","protected","public","readonly","record","ref","return","sealed","sizeof","stackalloc","static","struct","switch","this","throw","try","typeof","unchecked","unsafe","using","virtual","void","volatile","while"].concat(["add","alias","and","ascending","async","await","by","descending","equals","from","get","global","group","init","into","join","let","nameof","not","notnull","on","or","orderby","partial","remove","select","set","unmanaged","value|0","var","when","where","with","yield"]),
built_in:["bool","byte","char","decimal","delegate","double","dynamic","enum","float","int","long","nint","nuint","object","sbyte","short","string","ulong","uint","ushort"],
literal:["default","false","null","true"]},a=e.inherit(e.TITLE_MODE,{
begin:"[a-zA-Z](\\.?\\w)*"}),i={className:"number",variants:[{
begin:"\\b(0b[01']+)"},{
begin:"(-?)\\b([\\d']+(\\.[\\d']*)?|\\.[\\d']+)(u|U|l|L|ul|UL|f|F|b|B)"},{
begin:"(-?)(\\b0[xX][a-fA-F0-9']+|(\\b[\\d']+(\\.[\\d']*)?|\\.[\\d']+)([eE][-+]?[\\d']+)?)"
}],relevance:0},s={className:"string",begin:'@"',end:'"',contains:[{begin:'""'}]
},t=e.inherit(s,{illegal:/\n/}),r={className:"subst",begin:/\{/,end:/\}/,
keywords:n},l=e.inherit(r,{illegal:/\n/}),c={className:"string",begin:/\$"/,
end:'"',illegal:/\n/,contains:[{begin:/\{\{/},{begin:/\}\}/
},e.BACKSLASH_ESCAPE,l]},o={className:"string",begin:/\$@"/,end:'"',contains:[{
begin:/\{\{/},{begin:/\}\}/},{begin:'""'},r]},d=e.inherit(o,{illegal:/\n/,
contains:[{begin:/\{\{/},{begin:/\}\}/},{begin:'""'},l]})
;r.contains=[o,c,s,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,i,e.C_BLOCK_COMMENT_MODE],
l.contains=[d,c,t,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,i,e.inherit(e.C_BLOCK_COMMENT_MODE,{
illegal:/\n/})];const g={variants:[o,c,s,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]
},E={begin:"<",end:">",contains:[{beginKeywords:"in out"},a]
},_=e.IDENT_RE+"(<"+e.IDENT_RE+"(\\s*,\\s*"+e.IDENT_RE+")*>)?(\\[\\])?",b={
begin:"@"+e.IDENT_RE,relevance:0};return{name:"C#",aliases:["cs","c#"],
keywords:n,illegal:/::/,contains:[e.COMMENT("///","$",{returnBegin:!0,
contains:[{className:"doctag",variants:[{begin:"///",relevance:0},{
begin:"\x3c!--|--\x3e"},{begin:"</?",end:">"}]}]
}),e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{className:"meta",begin:"#",
end:"$",keywords:{
keyword:"if else elif endif define undef warning error line region endregion pragma checksum"
}},g,i,{beginKeywords:"class interface",relevance:0,end:/[{;=]/,
illegal:/[^\s:,]/,contains:[{beginKeywords:"where class"
},a,E,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{beginKeywords:"namespace",
relevance:0,end:/[{;=]/,illegal:/[^\s:]/,
contains:[a,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{
beginKeywords:"record",relevance:0,end:/[{;=]/,illegal:/[^\s:]/,
contains:[a,E,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{className:"meta",
begin:"^\\s*\\[(?=[\\w])",excludeBegin:!0,end:"\\]",excludeEnd:!0,contains:[{
className:"string",begin:/"/,end:/"/}]},{
beginKeywords:"new return throw await else",relevance:0},{className:"function",
begin:"("+_+"\\s+)+"+e.IDENT_RE+"\\s*(<[^=]+>\\s*)?\\(",returnBegin:!0,
end:/\s*[{;=]/,excludeEnd:!0,keywords:n,contains:[{
beginKeywords:"public private protected static internal protected abstract async extern override unsafe virtual new sealed partial",
relevance:0},{begin:e.IDENT_RE+"\\s*(<[^=]+>\\s*)?\\(",returnBegin:!0,
contains:[e.TITLE_MODE,E],relevance:0},{match:/\(\)/},{className:"params",
begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:n,relevance:0,
contains:[g,i,e.C_BLOCK_COMMENT_MODE]
},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},b]}}})()
;hljs.registerLanguage("csharp",e)})(); |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @fileOverview Defines the {@link CKEDITOR.lang} object, for the
* Thai language.
*/
/**#@+
@type String
@example
*/
/**
* Constains the dictionary of language entries.
* @namespace
*/
CKEDITOR.lang['th'] =
{
/**
* The language reading direction. Possible values are "rtl" for
* Right-To-Left languages (like Arabic) and "ltr" for Left-To-Right
* languages (like English).
* @default 'ltr'
*/
dir : 'ltr',
/*
* Screenreader titles. Please note that screenreaders are not always capable
* of reading non-English words. So be careful while translating it.
*/
editorTitle : 'Rich text editor, %1', // MISSING
// Toolbar buttons without dialogs.
source : 'ดูรหัส HTML',
newPage : 'สร้างหน้าเอกสารใหม่',
save : 'บันทึก',
preview : 'ดูหน้าเอกสารตัวอย่าง',
cut : 'ตัด',
copy : 'สำเนา',
paste : 'วาง',
print : 'สั่งพิมพ์',
underline : 'ตัวขีดเส้นใต้',
bold : 'ตัวหนา',
italic : 'ตัวเอียง',
selectAll : 'เลือกทั้งหมด',
removeFormat : 'ล้างรูปแบบ',
strike : 'ตัวขีดเส้นทับ',
subscript : 'ตัวห้อย',
superscript : 'ตัวยก',
horizontalrule : 'แทรกเส้นคั่นบรรทัด',
pagebreak : 'แทรกตัวแบ่งหน้า Page Break',
unlink : 'ลบ ลิงค์',
undo : 'ยกเลิกคำสั่ง',
redo : 'ทำซ้ำคำสั่ง',
// Common messages and labels.
common :
{
browseServer : 'เปิดหน้าต่างจัดการไฟล์อัพโหลด',
url : 'ที่อยู่อ้างอิง URL',
protocol : 'โปรโตคอล',
upload : 'อัพโหลดไฟล์',
uploadSubmit : 'อัพโหลดไฟล์ไปเก็บไว้ที่เครื่องแม่ข่าย (เซิร์ฟเวอร์)',
image : 'รูปภาพ',
flash : 'ไฟล์ Flash',
form : 'แบบฟอร์ม',
checkbox : 'เช็คบ๊อก',
radio : 'เรดิโอบัตตอน',
textField : 'เท็กซ์ฟิลด์',
textarea : 'เท็กซ์แอเรีย',
hiddenField : 'ฮิดเดนฟิลด์',
button : 'ปุ่ม',
select : 'แถบตัวเลือก',
imageButton : 'ปุ่มแบบรูปภาพ',
notSet : '<ไม่ระบุ>',
id : 'ไอดี',
name : 'ชื่อ',
langDir : 'การเขียน-อ่านภาษา',
langDirLtr : 'จากซ้ายไปขวา (LTR)',
langDirRtl : 'จากขวามาซ้าย (RTL)',
langCode : 'รหัสภาษา',
longDescr : 'คำอธิบายประกอบ URL',
cssClass : 'คลาสของไฟล์กำหนดลักษณะการแสดงผล',
advisoryTitle : 'คำเกริ่นนำ',
cssStyle : 'ลักษณะการแสดงผล',
ok : 'ตกลง',
cancel : 'ยกเลิก',
generalTab : 'General', // MISSING
advancedTab : 'ขั้นสูง',
validateNumberFailed : 'This value is not a number.', // MISSING
confirmNewPage : 'Any unsaved changes to this content will be lost. Are you sure you want to load new page?', // MISSING
confirmCancel : 'Some of the options have been changed. Are you sure to close the dialog?', // MISSING
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, unavailable</span>' // MISSING
},
// Special char dialog.
specialChar :
{
toolbar : 'แทรกตัวอักษรพิเศษ',
title : 'แทรกตัวอักษรพิเศษ'
},
// Link dialog.
link :
{
toolbar : 'แทรก/แก้ไข ลิงค์',
menu : 'แก้ไข ลิงค์',
title : 'ลิงค์เชื่อมโยงเว็บ อีเมล์ รูปภาพ หรือไฟล์อื่นๆ',
info : 'รายละเอียด',
target : 'การเปิดหน้าลิงค์',
upload : 'อัพโหลดไฟล์',
advanced : 'ขั้นสูง',
type : 'ประเภทของลิงค์',
toAnchor : 'จุดเชื่อมโยง (Anchor)',
toEmail : 'ส่งอีเมล์ (E-Mail)',
target : 'การเปิดหน้าลิงค์',
targetNotSet : '<ไม่ระบุ>',
targetFrame : '<เปิดในเฟรม>',
targetPopup : '<เปิดหน้าจอเล็ก (Pop-up)>',
targetNew : 'เปิดหน้าจอใหม่ (_blank)',
targetTop : 'เปิดในหน้าบนสุด (_top)',
targetSelf : 'เปิดในหน้าปัจจุบัน (_self)',
targetParent : 'เปิดในหน้าหลัก (_parent)',
targetFrameName : 'ชื่อทาร์เก็ตเฟรม',
targetPopupName : 'ระบุชื่อหน้าจอเล็ก (Pop-up)',
popupFeatures : 'คุณสมบัติของหน้าจอเล็ก (Pop-up)',
popupResizable : 'Resizable', // MISSING
popupStatusBar : 'แสดงแถบสถานะ',
popupLocationBar : 'แสดงที่อยู่ของไฟล์',
popupToolbar : 'แสดงแถบเครื่องมือ',
popupMenuBar : 'แสดงแถบเมนู',
popupFullScreen : 'แสดงเต็มหน้าจอ (IE5.5++ เท่านั้น)',
popupScrollBars : 'แสดงแถบเลื่อน',
popupDependent : 'แสดงเต็มหน้าจอ (Netscape)',
popupWidth : 'กว้าง',
popupLeft : 'พิกัดซ้าย (Left Position)',
popupHeight : 'สูง',
popupTop : 'พิกัดบน (Top Position)',
id : 'Id', // MISSING
langDir : 'การเขียน-อ่านภาษา',
langDirNotSet : '<ไม่ระบุ>',
langDirLTR : 'จากซ้ายไปขวา (LTR)',
langDirRTL : 'จากขวามาซ้าย (RTL)',
acccessKey : 'แอคเซส คีย์',
name : 'ชื่อ',
langCode : 'การเขียน-อ่านภาษา',
tabIndex : 'ลำดับของ แท็บ',
advisoryTitle : 'คำเกริ่นนำ',
advisoryContentType : 'ชนิดของคำเกริ่นนำ',
cssClasses : 'คลาสของไฟล์กำหนดลักษณะการแสดงผล',
charset : 'ลิงค์เชื่อมโยงไปยังชุดตัวอักษร',
styles : 'ลักษณะการแสดงผล',
selectAnchor : 'ระบุข้อมูลของจุดเชื่อมโยง (Anchor)',
anchorName : 'ชื่อ',
anchorId : 'ไอดี',
emailAddress : 'อีเมล์ (E-Mail)',
emailSubject : 'หัวเรื่อง',
emailBody : 'ข้อความ',
noAnchors : '(ยังไม่มีจุดเชื่อมโยงภายในหน้าเอกสารนี้)',
noUrl : 'กรุณาระบุที่อยู่อ้างอิงออนไลน์ (URL)',
noEmail : 'กรุณาระบุอีเมล์ (E-mail)'
},
// Anchor dialog
anchor :
{
toolbar : 'แทรก/แก้ไข Anchor',
menu : 'รายละเอียด Anchor',
title : 'รายละเอียด Anchor',
name : 'ชื่อ Anchor',
errorName : 'กรุณาระบุชื่อของ Anchor'
},
// Find And Replace Dialog
findAndReplace :
{
title : 'Find and Replace', // MISSING
find : 'ค้นหา',
replace : 'ค้นหาและแทนที่',
findWhat : 'ค้นหาคำว่า:',
replaceWith : 'แทนที่ด้วย:',
notFoundMsg : 'ไม่พบคำที่ค้นหา.',
matchCase : 'ตัวโหญ่-เล็ก ต้องตรงกัน',
matchWord : 'ต้องตรงกันทุกคำ',
matchCyclic : 'Match cyclic', // MISSING
replaceAll : 'แทนที่ทั้งหมดที่พบ',
replaceSuccessMsg : '%1 occurrence(s) replaced.' // MISSING
},
// Table Dialog
table :
{
toolbar : 'ตาราง',
title : 'คุณสมบัติของ ตาราง',
menu : 'คุณสมบัติของ ตาราง',
deleteTable : 'ลบตาราง',
rows : 'แถว',
columns : 'สดมน์',
border : 'ขนาดเส้นขอบ',
align : 'การจัดตำแหน่ง',
alignNotSet : '<ไม่ระบุ>',
alignLeft : 'ชิดซ้าย',
alignCenter : 'กึ่งกลาง',
alignRight : 'ชิดขวา',
width : 'กว้าง',
widthPx : 'จุดสี',
widthPc : 'เปอร์เซ็น',
height : 'สูง',
cellSpace : 'ระยะแนวนอนน',
cellPad : 'ระยะแนวตั้ง',
caption : 'หัวเรื่องของตาราง',
summary : 'สรุปความ',
headers : 'Headers', // MISSING
headersNone : 'None', // MISSING
headersColumn : 'First column', // MISSING
headersRow : 'First Row', // MISSING
headersBoth : 'Both', // MISSING
invalidRows : 'Number of rows must be a number greater than 0.', // MISSING
invalidCols : 'Number of columns must be a number greater than 0.', // MISSING
invalidBorder : 'Border size must be a number.', // MISSING
invalidWidth : 'Table width must be a number.', // MISSING
invalidHeight : 'Table height must be a number.', // MISSING
invalidCellSpacing : 'Cell spacing must be a number.', // MISSING
invalidCellPadding : 'Cell padding must be a number.', // MISSING
cell :
{
menu : 'ช่องตาราง',
insertBefore : 'Insert Cell Before', // MISSING
insertAfter : 'Insert Cell After', // MISSING
deleteCell : 'ลบช่อง',
merge : 'ผสานช่อง',
mergeRight : 'Merge Right', // MISSING
mergeDown : 'Merge Down', // MISSING
splitHorizontal : 'Split Cell Horizontally', // MISSING
splitVertical : 'Split Cell Vertically', // MISSING
title : 'Cell Properties', // MISSING
cellType : 'Cell Type', // MISSING
rowSpan : 'Rows Span', // MISSING
colSpan : 'Columns Span', // MISSING
wordWrap : 'Word Wrap', // MISSING
hAlign : 'Horizontal Alignment', // MISSING
vAlign : 'Vertical Alignment', // MISSING
alignTop : 'Top', // MISSING
alignMiddle : 'Middle', // MISSING
alignBottom : 'Bottom', // MISSING
alignBaseline : 'Baseline', // MISSING
bgColor : 'Background Color', // MISSING
borderColor : 'Border Color', // MISSING
data : 'Data', // MISSING
header : 'Header', // MISSING
yes : 'Yes', // MISSING
no : 'No', // MISSING
invalidWidth : 'Cell width must be a number.', // MISSING
invalidHeight : 'Cell height must be a number.', // MISSING
invalidRowSpan : 'Rows span must be a whole number.', // MISSING
invalidColSpan : 'Columns span must be a whole number.', // MISSING
chooseColor : 'Choose' // MISSING
},
row :
{
menu : 'แถว',
insertBefore : 'Insert Row Before', // MISSING
insertAfter : 'Insert Row After', // MISSING
deleteRow : 'ลบแถว'
},
column :
{
menu : 'คอลัมน์',
insertBefore : 'Insert Column Before', // MISSING
insertAfter : 'Insert Column After', // MISSING
deleteColumn : 'ลบสดมน์'
}
},
// Button Dialog.
button :
{
title : 'รายละเอียดของ ปุ่ม',
text : 'ข้อความ (ค่าตัวแปร)',
type : 'ข้อความ',
typeBtn : 'Button',
typeSbm : 'Submit',
typeRst : 'Reset'
},
// Checkbox and Radio Button Dialogs.
checkboxAndRadio :
{
checkboxTitle : 'คุณสมบัติของ เช็คบ๊อก',
radioTitle : 'คุณสมบัติของ เรดิโอบัตตอน',
value : 'ค่าตัวแปร',
selected : 'เลือกเป็นค่าเริ่มต้น'
},
// Form Dialog.
form :
{
title : 'คุณสมบัติของ แบบฟอร์ม',
menu : 'คุณสมบัติของ แบบฟอร์ม',
action : 'แอคชั่น',
method : 'เมธอด',
encoding : 'Encoding', // MISSING
target : 'การเปิดหน้าลิงค์',
targetNotSet : '<ไม่ระบุ>',
targetNew : 'เปิดหน้าจอใหม่ (_blank)',
targetTop : 'เปิดในหน้าบนสุด (_top)',
targetSelf : 'เปิดในหน้าปัจจุบัน (_self)',
targetParent : 'เปิดในหน้าหลัก (_parent)'
},
// Select Field Dialog.
select :
{
title : 'คุณสมบัติของ แถบตัวเลือก',
selectInfo : 'อินโฟ',
opAvail : 'รายการตัวเลือก',
value : 'ค่าตัวแปร',
size : 'ขนาด',
lines : 'บรรทัด',
chkMulti : 'เลือกหลายค่าได้',
opText : 'ข้อความ',
opValue : 'ค่าตัวแปร',
btnAdd : 'เพิ่ม',
btnModify : 'แก้ไข',
btnUp : 'บน',
btnDown : 'ล่าง',
btnSetValue : 'เลือกเป็นค่าเริ่มต้น',
btnDelete : 'ลบ'
},
// Textarea Dialog.
textarea :
{
title : 'คุณสมบัติของ เท็กแอเรีย',
cols : 'สดมภ์',
rows : 'แถว'
},
// Text Field Dialog.
textfield :
{
title : 'คุณสมบัติของ เท็กซ์ฟิลด์',
name : 'ชื่อ',
value : 'ค่าตัวแปร',
charWidth : 'ความกว้าง',
maxChars : 'จำนวนตัวอักษรสูงสุด',
type : 'ชนิด',
typeText : 'ข้อความ',
typePass : 'รหัสผ่าน'
},
// Hidden Field Dialog.
hidden :
{
title : 'คุณสมบัติของ ฮิดเดนฟิลด์',
name : 'ชื่อ',
value : 'ค่าตัวแปร'
},
// Image Dialog.
image :
{
title : 'คุณสมบัติของ รูปภาพ',
titleButton : 'คุณสมบัติของ ปุ่มแบบรูปภาพ',
menu : 'คุณสมบัติของ รูปภาพ',
infoTab : 'ข้อมูลของรูปภาพ',
btnUpload : 'อัพโหลดไฟล์ไปเก็บไว้ที่เครื่องแม่ข่าย (เซิร์ฟเวอร์)',
url : 'ที่อยู่อ้างอิง URL',
upload : 'อัพโหลดไฟล์',
alt : 'คำประกอบรูปภาพ',
width : 'ความกว้าง',
height : 'ความสูง',
lockRatio : 'กำหนดอัตราส่วน กว้าง-สูง แบบคงที่',
resetSize : 'กำหนดรูปเท่าขนาดจริง',
border : 'ขนาดขอบรูป',
hSpace : 'ระยะแนวนอน',
vSpace : 'ระยะแนวตั้ง',
align : 'การจัดวาง',
alignLeft : 'ชิดซ้าย',
alignRight : 'ชิดขวา',
preview : 'หน้าเอกสารตัวอย่าง',
alertUrl : 'กรุณาระบุที่อยู่อ้างอิงออนไลน์ของไฟล์รูปภาพ (URL)',
linkTab : 'ลิ้งค์',
button2Img : 'Do you want to transform the selected image button on a simple image?', // MISSING
img2Button : 'Do you want to transform the selected image on a image button?', // MISSING
urlMissing : 'Image source URL is missing.' // MISSING
},
// Flash Dialog
flash :
{
properties : 'คุณสมบัติของไฟล์ Flash',
propertiesTab : 'Properties', // MISSING
title : 'คุณสมบัติของไฟล์ Flash',
chkPlay : 'เล่นอัตโนมัติ Auto Play',
chkLoop : 'เล่นวนรอบ Loop',
chkMenu : 'ให้ใช้งานเมนูของ Flash',
chkFull : 'Allow Fullscreen', // MISSING
scale : 'อัตราส่วน Scale',
scaleAll : 'แสดงให้เห็นทั้งหมด Show all',
scaleNoBorder : 'ไม่แสดงเส้นขอบ No Border',
scaleFit : 'แสดงให้พอดีกับพื้นที่ Exact Fit',
access : 'Script Access', // MISSING
accessAlways : 'Always', // MISSING
accessSameDomain : 'Same domain', // MISSING
accessNever : 'Never', // MISSING
align : 'การจัดวาง',
alignLeft : 'ชิดซ้าย',
alignAbsBottom: 'ชิดด้านล่างสุด',
alignAbsMiddle: 'กึ่งกลาง',
alignBaseline : 'ชิดบรรทัด',
alignBottom : 'ชิดด้านล่าง',
alignMiddle : 'กึ่งกลางแนวตั้ง',
alignRight : 'ชิดขวา',
alignTextTop : 'ใต้ตัวอักษร',
alignTop : 'บนสุด',
quality : 'Quality', // MISSING
qualityBest : 'Best', // MISSING
qualityHigh : 'High', // MISSING
qualityAutoHigh : 'Auto High', // MISSING
qualityMedium : 'Medium', // MISSING
qualityAutoLow : 'Auto Low', // MISSING
qualityLow : 'Low', // MISSING
windowModeWindow : 'Window', // MISSING
windowModeOpaque : 'Opaque', // MISSING
windowModeTransparent : 'Transparent', // MISSING
windowMode : 'Window mode', // MISSING
flashvars : 'Variables for Flash', // MISSING
bgcolor : 'สีพื้นหลัง',
width : 'ความกว้าง',
height : 'ความสูง',
hSpace : 'ระยะแนวนอน',
vSpace : 'ระยะแนวตั้ง',
validateSrc : 'กรุณาระบุที่อยู่อ้างอิงออนไลน์ (URL)',
validateWidth : 'Width must be a number.', // MISSING
validateHeight : 'Height must be a number.', // MISSING
validateHSpace : 'HSpace must be a number.', // MISSING
validateVSpace : 'VSpace must be a number.' // MISSING
},
// Speller Pages Dialog
spellCheck :
{
toolbar : 'ตรวจการสะกดคำ',
title : 'Spell Check', // MISSING
notAvailable : 'Sorry, but service is unavailable now.', // MISSING
errorLoading : 'Error loading application service host: %s.', // MISSING
notInDic : 'ไม่พบในดิกชันนารี',
changeTo : 'แก้ไขเป็น',
btnIgnore : 'ยกเว้น',
btnIgnoreAll : 'ยกเว้นทั้งหมด',
btnReplace : 'แทนที่',
btnReplaceAll : 'แทนที่ทั้งหมด',
btnUndo : 'ยกเลิก',
noSuggestions : '- ไม่มีคำแนะนำใดๆ -',
progress : 'กำลังตรวจสอบคำสะกด...',
noMispell : 'ตรวจสอบคำสะกดเสร็จสิ้น: ไม่พบคำสะกดผิด',
noChanges : 'ตรวจสอบคำสะกดเสร็จสิ้น: ไม่มีการแก้คำใดๆ',
oneChange : 'ตรวจสอบคำสะกดเสร็จสิ้น: แก้ไข1คำ',
manyChanges : 'ตรวจสอบคำสะกดเสร็จสิ้น:: แก้ไข %1 คำ',
ieSpellDownload : 'ไม่ได้ติดตั้งระบบตรวจสอบคำสะกด. ต้องการติดตั้งไหมครับ?'
},
smiley :
{
toolbar : 'รูปสื่ออารมณ์',
title : 'แทรกสัญลักษณ์สื่ออารมณ์'
},
elementsPath :
{
eleTitle : '%1 element' // MISSING
},
numberedlist : 'ลำดับรายการแบบตัวเลข',
bulletedlist : 'ลำดับรายการแบบสัญลักษณ์',
indent : 'เพิ่มระยะย่อหน้า',
outdent : 'ลดระยะย่อหน้า',
justify :
{
left : 'จัดชิดซ้าย',
center : 'จัดกึ่งกลาง',
right : 'จัดชิดขวา',
block : 'จัดพอดีหน้ากระดาษ'
},
blockquote : 'Blockquote', // MISSING
clipboard :
{
title : 'วาง',
cutError : 'ไม่สามารถตัดข้อความที่เลือกไว้ได้เนื่องจากการกำหนดค่าระดับความปลอดภัย. กรุณาใช้ปุ่มลัดเพื่อวางข้อความแทน (กดปุ่ม Ctrl และตัว X พร้อมกัน).',
copyError : 'ไม่สามารถสำเนาข้อความที่เลือกไว้ได้เนื่องจากการกำหนดค่าระดับความปลอดภัย. กรุณาใช้ปุ่มลัดเพื่อวางข้อความแทน (กดปุ่ม Ctrl และตัว C พร้อมกัน).',
pasteMsg : 'กรุณาใช้คีย์บอร์ดเท่านั้น โดยกดปุ๋ม (<strong>Ctrl และ V</strong>)พร้อมๆกัน และกด <strong>OK</strong>.',
securityMsg : 'Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.' // MISSING
},
pastefromword :
{
confirmCleanup : 'The text you want to paste seems to be copied from Word. Do you want to clean it before pasting?', // MISSING
toolbar : 'วางสำเนาจากตัวอักษรเวิร์ด',
title : 'วางสำเนาจากตัวอักษรเวิร์ด',
error : 'It was not possible to clean up the pasted data due to an internal error' // MISSING
},
pasteText :
{
button : 'วางแบบตัวอักษรธรรมดา',
title : 'วางแบบตัวอักษรธรรมดา'
},
templates :
{
button : 'เทมเพลต',
title : 'เทมเพลตของส่วนเนื้อหาเว็บไซต์',
insertOption: 'แทนที่เนื้อหาเว็บไซต์ที่เลือก',
selectPromptMsg: 'กรุณาเลือก เทมเพลต เพื่อนำไปแก้ไขในอีดิตเตอร์<br />(เนื้อหาส่วนนี้จะหายไป):',
emptyListMsg : '(ยังไม่มีการกำหนดเทมเพลต)'
},
showBlocks : 'Show Blocks', // MISSING
stylesCombo :
{
label : 'ลักษณะ',
voiceLabel : 'Styles', // MISSING
panelVoiceLabel : 'Select a style', // MISSING
panelTitle1 : 'Block Styles', // MISSING
panelTitle2 : 'Inline Styles', // MISSING
panelTitle3 : 'Object Styles' // MISSING
},
format :
{
label : 'รูปแบบ',
voiceLabel : 'Format', // MISSING
panelTitle : 'รูปแบบ',
panelVoiceLabel : 'Select a paragraph format', // MISSING
tag_p : 'Normal',
tag_pre : 'Formatted',
tag_address : 'Address',
tag_h1 : 'Heading 1',
tag_h2 : 'Heading 2',
tag_h3 : 'Heading 3',
tag_h4 : 'Heading 4',
tag_h5 : 'Heading 5',
tag_h6 : 'Heading 6',
tag_div : 'Paragraph (DIV)'
},
div :
{
title : 'Create Div Container', // MISSING
toolbar : 'Create Div Container', // MISSING
cssClassInputLabel : 'Stylesheet Classes', // MISSING
styleSelectLabel : 'Style', // MISSING
IdInputLabel : 'Id', // MISSING
languageCodeInputLabel : ' Language Code', // MISSING
inlineStyleInputLabel : 'Inline Style', // MISSING
advisoryTitleInputLabel : 'Advisory Title', // MISSING
langDirLabel : 'Language Direction', // MISSING
langDirLTRLabel : 'Left to Right (LTR)', // MISSING
langDirRTLLabel : 'Right to Left (RTL)', // MISSING
edit : 'Edit Div', // MISSING
remove : 'Remove Div' // MISSING
},
font :
{
label : 'แบบอักษร',
voiceLabel : 'Font', // MISSING
panelTitle : 'แบบอักษร',
panelVoiceLabel : 'Select a font' // MISSING
},
fontSize :
{
label : 'ขนาด',
voiceLabel : 'Font Size', // MISSING
panelTitle : 'ขนาด',
panelVoiceLabel : 'Select a font size' // MISSING
},
colorButton :
{
textColorTitle : 'สีตัวอักษร',
bgColorTitle : 'สีพื้นหลัง',
auto : 'สีอัตโนมัติ',
more : 'เลือกสีอื่นๆ...'
},
colors :
{
'000' : 'Black', // MISSING
'800000' : 'Maroon', // MISSING
'8B4513' : 'Saddle Brown', // MISSING
'2F4F4F' : 'Dark Slate Gray', // MISSING
'008080' : 'Teal', // MISSING
'000080' : 'Navy', // MISSING
'4B0082' : 'Indigo', // MISSING
'696969' : 'Dim Gray', // MISSING
'B22222' : 'Fire Brick', // MISSING
'A52A2A' : 'Brown', // MISSING
'DAA520' : 'Golden Rod', // MISSING
'006400' : 'Dark Green', // MISSING
'40E0D0' : 'Turquoise', // MISSING
'0000CD' : 'Medium Blue', // MISSING
'800080' : 'Purple', // MISSING
'808080' : 'Gray', // MISSING
'F00' : 'Red', // MISSING
'FF8C00' : 'Dark Orange', // MISSING
'FFD700' : 'Gold', // MISSING
'008000' : 'Green', // MISSING
'0FF' : 'Cyan', // MISSING
'00F' : 'Blue', // MISSING
'EE82EE' : 'Violet', // MISSING
'A9A9A9' : 'Dark Gray', // MISSING
'FFA07A' : 'Light Salmon', // MISSING
'FFA500' : 'Orange', // MISSING
'FFFF00' : 'Yellow', // MISSING
'00FF00' : 'Lime', // MISSING
'AFEEEE' : 'Pale Turquoise', // MISSING
'ADD8E6' : 'Light Blue', // MISSING
'DDA0DD' : 'Plum', // MISSING
'D3D3D3' : 'Light Grey', // MISSING
'FFF0F5' : 'Lavender Blush', // MISSING
'FAEBD7' : 'Antique White', // MISSING
'FFFFE0' : 'Light Yellow', // MISSING
'F0FFF0' : 'Honeydew', // MISSING
'F0FFFF' : 'Azure', // MISSING
'F0F8FF' : 'Alice Blue', // MISSING
'E6E6FA' : 'Lavender', // MISSING
'FFF' : 'White' // MISSING
},
scayt :
{
title : 'Spell Check As You Type', // MISSING
enable : 'Enable SCAYT', // MISSING
disable : 'Disable SCAYT', // MISSING
about : 'About SCAYT', // MISSING
toggle : 'Toggle SCAYT', // MISSING
options : 'Options', // MISSING
langs : 'Languages', // MISSING
moreSuggestions : 'More suggestions', // MISSING
ignore : 'Ignore', // MISSING
ignoreAll : 'Ignore All', // MISSING
addWord : 'Add Word', // MISSING
emptyDic : 'Dictionary name should not be empty.', // MISSING
optionsTab : 'Options', // MISSING
languagesTab : 'Languages', // MISSING
dictionariesTab : 'Dictionaries', // MISSING
aboutTab : 'About' // MISSING
},
about :
{
title : 'About CKEditor', // MISSING
dlgTitle : 'About CKEditor', // MISSING
moreInfo : 'For licensing information please visit our web site:', // MISSING
copy : 'Copyright © $1. All rights reserved.' // MISSING
},
maximize : 'Maximize', // MISSING
minimize : 'Minimize', // MISSING
fakeobjects :
{
anchor : 'Anchor', // MISSING
flash : 'Flash Animation', // MISSING
div : 'Page Break', // MISSING
unknown : 'Unknown Object' // MISSING
},
resize : 'Drag to resize', // MISSING
colordialog :
{
title : 'Select color', // MISSING
highlight : 'Highlight', // MISSING
selected : 'Selected', // MISSING
clear : 'Clear' // MISSING
},
toolbarCollapse : 'Collapse Toolbar', // MISSING
toolbarExpand : 'Expand Toolbar' // MISSING
};
|
import Ember from 'ember';
export default Ember.Route.extend({
fastboot: Ember.inject.service(),
shoebox: Ember.computed.readOnly('fastboot.shoebox'),
model() {
let fastboot = this.get('fastboot');
let shoebox = this.get('shoebox');
if (fastboot.get('isFastBoot')) {
shoebox.put('key1', { foo: 'bar' });
shoebox.put('key2', { zip: 'zap' });
}
}
});
|
/*global require */
// This file is used to configure RequireJS. By convention it's the first
// file loaded by require after it has started. It contains a list of key
// value pairs to javascript files and their relative paths in the project.
// It is also responsible for invoking app.js, also by convention.
//
// This file is consumed by a grunt task which invokes r.js which uses dependency
// resolution to only include the files required and also concatenate all
// the JS files into a single main.js which
// avoids round trips and speeds up loading.
//
'use strict';
require.config({
// This contains specific dependency graphs for various components.
shim: {
bootstrap: {
deps: ['jquery'],
exports: 'jquery'
},
gauge: {
deps: ['jquery'],
exports: 'Gauge'
},
raphael: {
exports: 'Raphael'
},
'bootstrap-switch': {
deps: ['bootstrap']
},
'noty': {
deps: ['jquery'],
exports: 'noty'
},
'notylayoutTop': {
deps: ['noty']
},
'notylayoutRight': {
deps: ['noty']
},
'notyGrowltheme': {
deps: ['notylayoutTopRight']
},
'notytheme': {
deps: ['notylayoutTop']
},
'popover': {
deps: ['modal']
},
'l20n': {
exports: 'L20n'
}
},
// General paths to components.
paths: {
kinetic: 'vendor/kinetic-v4.7.3',
application: 'application',
jquery: '../bower_components/jquery/jquery',
noty: '../bower_components/noty/js/noty/jquery.noty',
notylayoutTop: '../bower_components/noty/js/noty/layouts/top',
notylayoutTopRight: 'helpers/noty-topRight',
notyGrowltheme: 'helpers/noty-theme',
notytheme: '../bower_components/noty/js/noty/themes/default',
backbone: '../bower_components/backbone-amd/backbone',
underscore: '../bower_components/underscore-amd/underscore',
bootstrap: 'vendor/bootstrap',
popover: '../bower_components/sass-bootstrap/js/popover',
modal: '../bower_components/sass-bootstrap/js/modal',
gauge: 'vendor/gauge',
bean: '../bower_components/bean/bean',
'backbone.babysitter': '../bower_components/backbone.babysitter/lib/amd/backbone.babysitter',
'backbone.wreqr': '../bower_components/backbone.wreqr/lib/amd/backbone.wreqr',
raphael: 'vendor/raphael',
humanize: 'vendor/humanize',
'bootstrap-switch': '../bower_components/bootstrap-switch/static/js/bootstrap-switch',
statemachine: '../bower_components/javascript-state-machine/state-machine',
marionette: '../bower_components/backbone.marionette/lib/core/amd/backbone.marionette',
gitcommit: 'git',
dygraphs: 'vendor/dygraph-combined',
react: '../bower_components/react/react-with-addons',
loglevel: '../bower_components/loglevel/dist/loglevel',
l20n: 'vendor/l20n.min',
l20nCtx: 'l20nCtxPlugin',
jsuri: '../bower_components/jsuri/Uri',
idbwrapper: '../bower_components/idbwrapper/idbstore',
q: '../bower_components/q/q',
moment: '../bower_components/momentjs/moment',
'Backbone.Modal': 'vendor/backbone.modal'
}
});
// App.js invocation is done here.
require(['./app'], function() {});
|
/**
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
*/
THREE.GeometryUtils = {
merge: function ( geometry1, object2 /* mesh | geometry */ ) {
var matrix, matrixRotation,
vertexOffset = geometry1.vertices.length,
uvPosition = geometry1.faceVertexUvs[ 0 ].length,
geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
vertices1 = geometry1.vertices,
vertices2 = geometry2.vertices,
faces1 = geometry1.faces,
faces2 = geometry2.faces,
uvs1 = geometry1.faceVertexUvs[ 0 ],
uvs2 = geometry2.faceVertexUvs[ 0 ];
var geo1MaterialsMap = {};
for ( var i = 0; i < geometry1.materials.length; i ++ ) {
var id = geometry1.materials[ i ].id;
geo1MaterialsMap[ id ] = i;
}
if ( object2 instanceof THREE.Mesh ) {
object2.matrixAutoUpdate && object2.updateMatrix();
matrix = object2.matrix;
matrixRotation = new THREE.Matrix4();
matrixRotation.extractRotation( matrix, object2.scale );
}
// vertices
for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
var vertex = vertices2[ i ];
var vertexCopy = new THREE.Vertex( vertex.position.clone() );
if ( matrix ) matrix.multiplyVector3( vertexCopy.position );
vertices1.push( vertexCopy );
}
// faces
for ( i = 0, il = faces2.length; i < il; i ++ ) {
var face = faces2[ i ], faceCopy, normal, color,
faceVertexNormals = face.vertexNormals,
faceVertexColors = face.vertexColors;
if ( face instanceof THREE.Face3 ) {
faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
} else if ( face instanceof THREE.Face4 ) {
faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
}
faceCopy.normal.copy( face.normal );
if ( matrixRotation ) matrixRotation.multiplyVector3( faceCopy.normal );
for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
normal = faceVertexNormals[ j ].clone();
if ( matrixRotation ) matrixRotation.multiplyVector3( normal );
faceCopy.vertexNormals.push( normal );
}
faceCopy.color.copy( face.color );
for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
color = faceVertexColors[ j ];
faceCopy.vertexColors.push( color.clone() );
}
if ( face.materialIndex !== undefined ) {
var material2 = geometry2.materials[ face.materialIndex ];
var materialId2 = material2.id;
var materialIndex = geo1MaterialsMap[ materialId2 ];
if ( materialIndex === undefined ) {
materialIndex = geometry1.materials.length;
geometry1.materials.push( material2 );
}
faceCopy.materialIndex = materialIndex;
}
faceCopy.centroid.copy( face.centroid );
if ( matrix ) matrix.multiplyVector3( faceCopy.centroid );
faces1.push( faceCopy );
}
// uvs
for ( i = 0, il = uvs2.length; i < il; i ++ ) {
var uv = uvs2[ i ], uvCopy = [];
for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
}
uvs1.push( uvCopy );
}
},
clone: function ( geometry ) {
var cloneGeo = new THREE.Geometry();
var i, il;
var vertices = geometry.vertices,
faces = geometry.faces,
uvs = geometry.faceVertexUvs[ 0 ];
// materials
if ( geometry.materials ) {
cloneGeo.materials = geometry.materials.slice();
}
// vertices
for ( i = 0, il = vertices.length; i < il; i ++ ) {
var vertex = vertices[ i ];
var vertexCopy = new THREE.Vertex( vertex.position.clone() );
cloneGeo.vertices.push( vertexCopy );
}
// faces
for ( i = 0, il = faces.length; i < il; i ++ ) {
var face = faces[ i ], faceCopy, normal, color,
faceVertexNormals = face.vertexNormals,
faceVertexColors = face.vertexColors;
if ( face instanceof THREE.Face3 ) {
faceCopy = new THREE.Face3( face.a, face.b, face.c );
} else if ( face instanceof THREE.Face4 ) {
faceCopy = new THREE.Face4( face.a, face.b, face.c, face.d );
}
faceCopy.normal.copy( face.normal );
for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
normal = faceVertexNormals[ j ];
faceCopy.vertexNormals.push( normal.clone() );
}
faceCopy.color.copy( face.color );
for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
color = faceVertexColors[ j ];
faceCopy.vertexColors.push( color.clone() );
}
faceCopy.materialIndex = face.materialIndex;
faceCopy.centroid.copy( face.centroid );
cloneGeo.faces.push( faceCopy );
}
// uvs
for ( i = 0, il = uvs.length; i < il; i ++ ) {
var uv = uvs[ i ], uvCopy = [];
for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
}
cloneGeo.faceVertexUvs[ 0 ].push( uvCopy );
}
return cloneGeo;
},
// Get random point in triangle (via barycentric coordinates)
// (uniform distribution)
// http://www.cgafaq.info/wiki/Random_Point_In_Triangle
randomPointInTriangle: function( vectorA, vectorB, vectorC ) {
var a, b, c,
point = new THREE.Vector3(),
tmp = THREE.GeometryUtils.__v1;
a = THREE.GeometryUtils.random();
b = THREE.GeometryUtils.random();
if ( ( a + b ) > 1 ) {
a = 1 - a;
b = 1 - b;
}
c = 1 - a - b;
point.copy( vectorA );
point.multiplyScalar( a );
tmp.copy( vectorB );
tmp.multiplyScalar( b );
point.addSelf( tmp );
tmp.copy( vectorC );
tmp.multiplyScalar( c );
point.addSelf( tmp );
return point;
},
// Get random point in face (triangle / quad)
// (uniform distribution)
randomPointInFace: function( face, geometry, useCachedAreas ) {
var vA, vB, vC, vD;
if ( face instanceof THREE.Face3 ) {
vA = geometry.vertices[ face.a ].position;
vB = geometry.vertices[ face.b ].position;
vC = geometry.vertices[ face.c ].position;
return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
} else if ( face instanceof THREE.Face4 ) {
vA = geometry.vertices[ face.a ].position;
vB = geometry.vertices[ face.b ].position;
vC = geometry.vertices[ face.c ].position;
vD = geometry.vertices[ face.d ].position;
var area1, area2;
if ( useCachedAreas ) {
if ( face._area1 && face._area2 ) {
area1 = face._area1;
area2 = face._area2;
} else {
area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
face._area1 = area1;
face._area2 = area2;
}
} else {
area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
}
var r = THREE.GeometryUtils.random() * ( area1 + area2 );
if ( r < area1 ) {
return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
} else {
return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
}
}
},
// Get uniformly distributed random points in mesh
// - create array with cumulative sums of face areas
// - pick random number from 0 to total area
// - find corresponding place in area array by binary search
// - get random point in face
randomPointsInGeometry: function( geometry, n ) {
var face, i,
faces = geometry.faces,
vertices = geometry.vertices,
il = faces.length,
totalArea = 0,
cumulativeAreas = [],
vA, vB, vC, vD;
// precompute face areas
for ( i = 0; i < il; i ++ ) {
face = faces[ i ];
if ( face instanceof THREE.Face3 ) {
vA = vertices[ face.a ].position;
vB = vertices[ face.b ].position;
vC = vertices[ face.c ].position;
face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
} else if ( face instanceof THREE.Face4 ) {
vA = vertices[ face.a ].position;
vB = vertices[ face.b ].position;
vC = vertices[ face.c ].position;
vD = vertices[ face.d ].position;
face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
face._area = face._area1 + face._area2;
}
totalArea += face._area;
cumulativeAreas[ i ] = totalArea;
}
// binary search cumulative areas array
function binarySearchIndices( value ) {
function binarySearch( start, end ) {
// return closest larger index
// if exact number is not found
if ( end < start )
return start;
var mid = start + Math.floor( ( end - start ) / 2 );
if ( cumulativeAreas[ mid ] > value ) {
return binarySearch( start, mid - 1 );
} else if ( cumulativeAreas[ mid ] < value ) {
return binarySearch( mid + 1, end );
} else {
return mid;
}
}
var result = binarySearch( 0, cumulativeAreas.length - 1 )
return result;
}
// pick random face weighted by face area
var r, index,
result = [];
var stats = {};
for ( i = 0; i < n; i ++ ) {
r = THREE.GeometryUtils.random() * totalArea;
index = binarySearchIndices( r );
result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
if ( ! stats[ index ] ) {
stats[ index ] = 1;
} else {
stats[ index ] += 1;
}
}
return result;
},
// Get triangle area (by Heron's formula)
// http://en.wikipedia.org/wiki/Heron%27s_formula
triangleArea: function( vectorA, vectorB, vectorC ) {
var s, a, b, c,
tmp = THREE.GeometryUtils.__v1;
tmp.sub( vectorA, vectorB );
a = tmp.length();
tmp.sub( vectorA, vectorC );
b = tmp.length();
tmp.sub( vectorB, vectorC );
c = tmp.length();
s = 0.5 * ( a + b + c );
return Math.sqrt( s * ( s - a ) * ( s - b ) * ( s - c ) );
},
center: function( geometry ) {
geometry.computeBoundingBox();
var matrix = new THREE.Matrix4();
var dx = -0.5 * ( geometry.boundingBox.x[ 1 ] + geometry.boundingBox.x[ 0 ] );
var dy = -0.5 * ( geometry.boundingBox.y[ 1 ] + geometry.boundingBox.y[ 0 ] );
var dz = -0.5 * ( geometry.boundingBox.z[ 1 ] + geometry.boundingBox.z[ 0 ] );
matrix.setTranslation( dx, dy, dz );
geometry.applyMatrix( matrix );
geometry.computeBoundingBox();
}
};
THREE.GeometryUtils.random = THREE.Math.random16;
THREE.GeometryUtils.__v1 = new THREE.Vector3();
|
var moment = require("../../index");
exports["Europe/Kaliningrad"] = {
"1916" : function (t) {
t.equal(moment("1916-04-30T21:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "22:59:59", "1916-04-30T21:59:59+00:00 should be 22:59:59 CET");
t.equal(moment("1916-04-30T22:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "00:00:00", "1916-04-30T22:00:00+00:00 should be 00:00:00 CEST");
t.equal(moment("1916-09-30T22:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "00:59:59", "1916-09-30T22:59:59+00:00 should be 00:59:59 CEST");
t.equal(moment("1916-09-30T23:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "00:00:00", "1916-09-30T23:00:00+00:00 should be 00:00:00 CET");
t.equal(moment("1916-04-30T21:59:59+00:00").tz("Europe/Kaliningrad").zone(), -60, "1916-04-30T21:59:59+00:00 should be -60 minutes offset in CET");
t.equal(moment("1916-04-30T22:00:00+00:00").tz("Europe/Kaliningrad").zone(), -120, "1916-04-30T22:00:00+00:00 should be -120 minutes offset in CEST");
t.equal(moment("1916-09-30T22:59:59+00:00").tz("Europe/Kaliningrad").zone(), -120, "1916-09-30T22:59:59+00:00 should be -120 minutes offset in CEST");
t.equal(moment("1916-09-30T23:00:00+00:00").tz("Europe/Kaliningrad").zone(), -60, "1916-09-30T23:00:00+00:00 should be -60 minutes offset in CET");
t.done();
},
"1917" : function (t) {
t.equal(moment("1917-04-16T00:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "01:59:59", "1917-04-16T00:59:59+00:00 should be 01:59:59 CET");
t.equal(moment("1917-04-16T01:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "03:00:00", "1917-04-16T01:00:00+00:00 should be 03:00:00 CEST");
t.equal(moment("1917-09-17T00:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:59:59", "1917-09-17T00:59:59+00:00 should be 02:59:59 CEST");
t.equal(moment("1917-09-17T01:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:00:00", "1917-09-17T01:00:00+00:00 should be 02:00:00 CET");
t.equal(moment("1917-04-16T00:59:59+00:00").tz("Europe/Kaliningrad").zone(), -60, "1917-04-16T00:59:59+00:00 should be -60 minutes offset in CET");
t.equal(moment("1917-04-16T01:00:00+00:00").tz("Europe/Kaliningrad").zone(), -120, "1917-04-16T01:00:00+00:00 should be -120 minutes offset in CEST");
t.equal(moment("1917-09-17T00:59:59+00:00").tz("Europe/Kaliningrad").zone(), -120, "1917-09-17T00:59:59+00:00 should be -120 minutes offset in CEST");
t.equal(moment("1917-09-17T01:00:00+00:00").tz("Europe/Kaliningrad").zone(), -60, "1917-09-17T01:00:00+00:00 should be -60 minutes offset in CET");
t.done();
},
"1918" : function (t) {
t.equal(moment("1918-04-15T00:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "01:59:59", "1918-04-15T00:59:59+00:00 should be 01:59:59 CET");
t.equal(moment("1918-04-15T01:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "03:00:00", "1918-04-15T01:00:00+00:00 should be 03:00:00 CEST");
t.equal(moment("1918-09-16T00:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:59:59", "1918-09-16T00:59:59+00:00 should be 02:59:59 CEST");
t.equal(moment("1918-09-16T01:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:00:00", "1918-09-16T01:00:00+00:00 should be 02:00:00 CET");
t.equal(moment("1918-04-15T00:59:59+00:00").tz("Europe/Kaliningrad").zone(), -60, "1918-04-15T00:59:59+00:00 should be -60 minutes offset in CET");
t.equal(moment("1918-04-15T01:00:00+00:00").tz("Europe/Kaliningrad").zone(), -120, "1918-04-15T01:00:00+00:00 should be -120 minutes offset in CEST");
t.equal(moment("1918-09-16T00:59:59+00:00").tz("Europe/Kaliningrad").zone(), -120, "1918-09-16T00:59:59+00:00 should be -120 minutes offset in CEST");
t.equal(moment("1918-09-16T01:00:00+00:00").tz("Europe/Kaliningrad").zone(), -60, "1918-09-16T01:00:00+00:00 should be -60 minutes offset in CET");
t.done();
},
"1940" : function (t) {
t.equal(moment("1940-04-01T00:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "01:59:59", "1940-04-01T00:59:59+00:00 should be 01:59:59 CET");
t.equal(moment("1940-04-01T01:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "03:00:00", "1940-04-01T01:00:00+00:00 should be 03:00:00 CEST");
t.equal(moment("1940-04-01T00:59:59+00:00").tz("Europe/Kaliningrad").zone(), -60, "1940-04-01T00:59:59+00:00 should be -60 minutes offset in CET");
t.equal(moment("1940-04-01T01:00:00+00:00").tz("Europe/Kaliningrad").zone(), -120, "1940-04-01T01:00:00+00:00 should be -120 minutes offset in CEST");
t.done();
},
"1942" : function (t) {
t.equal(moment("1942-11-02T00:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:59:59", "1942-11-02T00:59:59+00:00 should be 02:59:59 CEST");
t.equal(moment("1942-11-02T01:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:00:00", "1942-11-02T01:00:00+00:00 should be 02:00:00 CET");
t.equal(moment("1942-11-02T00:59:59+00:00").tz("Europe/Kaliningrad").zone(), -120, "1942-11-02T00:59:59+00:00 should be -120 minutes offset in CEST");
t.equal(moment("1942-11-02T01:00:00+00:00").tz("Europe/Kaliningrad").zone(), -60, "1942-11-02T01:00:00+00:00 should be -60 minutes offset in CET");
t.done();
},
"1943" : function (t) {
t.equal(moment("1943-03-29T00:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "01:59:59", "1943-03-29T00:59:59+00:00 should be 01:59:59 CET");
t.equal(moment("1943-03-29T01:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "03:00:00", "1943-03-29T01:00:00+00:00 should be 03:00:00 CEST");
t.equal(moment("1943-10-04T00:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:59:59", "1943-10-04T00:59:59+00:00 should be 02:59:59 CEST");
t.equal(moment("1943-10-04T01:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:00:00", "1943-10-04T01:00:00+00:00 should be 02:00:00 CET");
t.equal(moment("1943-03-29T00:59:59+00:00").tz("Europe/Kaliningrad").zone(), -60, "1943-03-29T00:59:59+00:00 should be -60 minutes offset in CET");
t.equal(moment("1943-03-29T01:00:00+00:00").tz("Europe/Kaliningrad").zone(), -120, "1943-03-29T01:00:00+00:00 should be -120 minutes offset in CEST");
t.equal(moment("1943-10-04T00:59:59+00:00").tz("Europe/Kaliningrad").zone(), -120, "1943-10-04T00:59:59+00:00 should be -120 minutes offset in CEST");
t.equal(moment("1943-10-04T01:00:00+00:00").tz("Europe/Kaliningrad").zone(), -60, "1943-10-04T01:00:00+00:00 should be -60 minutes offset in CET");
t.done();
},
"1944" : function (t) {
t.equal(moment("1944-04-03T00:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "01:59:59", "1944-04-03T00:59:59+00:00 should be 01:59:59 CET");
t.equal(moment("1944-04-03T01:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "03:00:00", "1944-04-03T01:00:00+00:00 should be 03:00:00 CEST");
t.equal(moment("1944-10-02T00:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:59:59", "1944-10-02T00:59:59+00:00 should be 02:59:59 CEST");
t.equal(moment("1944-10-02T01:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:00:00", "1944-10-02T01:00:00+00:00 should be 02:00:00 CET");
t.equal(moment("1944-12-31T22:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "23:59:59", "1944-12-31T22:59:59+00:00 should be 23:59:59 CET");
t.equal(moment("1944-12-31T23:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "01:00:00", "1944-12-31T23:00:00+00:00 should be 01:00:00 CET");
t.equal(moment("1944-04-03T00:59:59+00:00").tz("Europe/Kaliningrad").zone(), -60, "1944-04-03T00:59:59+00:00 should be -60 minutes offset in CET");
t.equal(moment("1944-04-03T01:00:00+00:00").tz("Europe/Kaliningrad").zone(), -120, "1944-04-03T01:00:00+00:00 should be -120 minutes offset in CEST");
t.equal(moment("1944-10-02T00:59:59+00:00").tz("Europe/Kaliningrad").zone(), -120, "1944-10-02T00:59:59+00:00 should be -120 minutes offset in CEST");
t.equal(moment("1944-10-02T01:00:00+00:00").tz("Europe/Kaliningrad").zone(), -60, "1944-10-02T01:00:00+00:00 should be -60 minutes offset in CET");
t.equal(moment("1944-12-31T22:59:59+00:00").tz("Europe/Kaliningrad").zone(), -60, "1944-12-31T22:59:59+00:00 should be -60 minutes offset in CET");
t.equal(moment("1944-12-31T23:00:00+00:00").tz("Europe/Kaliningrad").zone(), -120, "1944-12-31T23:00:00+00:00 should be -120 minutes offset in CET");
t.done();
},
"1945" : function (t) {
t.equal(moment("1945-04-28T21:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "23:59:59", "1945-04-28T21:59:59+00:00 should be 23:59:59 CET");
t.equal(moment("1945-04-28T22:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "01:00:00", "1945-04-28T22:00:00+00:00 should be 01:00:00 CEST");
t.equal(moment("1945-10-31T20:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "23:59:59", "1945-10-31T20:59:59+00:00 should be 23:59:59 CEST");
t.equal(moment("1945-10-31T21:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "23:00:00", "1945-10-31T21:00:00+00:00 should be 23:00:00 CET");
t.equal(moment("1945-12-31T21:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "23:59:59", "1945-12-31T21:59:59+00:00 should be 23:59:59 CET");
t.equal(moment("1945-12-31T22:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "01:00:00", "1945-12-31T22:00:00+00:00 should be 01:00:00 MSK");
t.equal(moment("1945-04-28T21:59:59+00:00").tz("Europe/Kaliningrad").zone(), -120, "1945-04-28T21:59:59+00:00 should be -120 minutes offset in CET");
t.equal(moment("1945-04-28T22:00:00+00:00").tz("Europe/Kaliningrad").zone(), -180, "1945-04-28T22:00:00+00:00 should be -180 minutes offset in CEST");
t.equal(moment("1945-10-31T20:59:59+00:00").tz("Europe/Kaliningrad").zone(), -180, "1945-10-31T20:59:59+00:00 should be -180 minutes offset in CEST");
t.equal(moment("1945-10-31T21:00:00+00:00").tz("Europe/Kaliningrad").zone(), -120, "1945-10-31T21:00:00+00:00 should be -120 minutes offset in CET");
t.equal(moment("1945-12-31T21:59:59+00:00").tz("Europe/Kaliningrad").zone(), -120, "1945-12-31T21:59:59+00:00 should be -120 minutes offset in CET");
t.equal(moment("1945-12-31T22:00:00+00:00").tz("Europe/Kaliningrad").zone(), -180, "1945-12-31T22:00:00+00:00 should be -180 minutes offset in MSK");
t.done();
},
"1981" : function (t) {
t.equal(moment("1981-03-31T20:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "23:59:59", "1981-03-31T20:59:59+00:00 should be 23:59:59 MSK");
t.equal(moment("1981-03-31T21:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "01:00:00", "1981-03-31T21:00:00+00:00 should be 01:00:00 MSD");
t.equal(moment("1981-09-30T19:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "23:59:59", "1981-09-30T19:59:59+00:00 should be 23:59:59 MSD");
t.equal(moment("1981-09-30T20:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "23:00:00", "1981-09-30T20:00:00+00:00 should be 23:00:00 MSK");
t.equal(moment("1981-03-31T20:59:59+00:00").tz("Europe/Kaliningrad").zone(), -180, "1981-03-31T20:59:59+00:00 should be -180 minutes offset in MSK");
t.equal(moment("1981-03-31T21:00:00+00:00").tz("Europe/Kaliningrad").zone(), -240, "1981-03-31T21:00:00+00:00 should be -240 minutes offset in MSD");
t.equal(moment("1981-09-30T19:59:59+00:00").tz("Europe/Kaliningrad").zone(), -240, "1981-09-30T19:59:59+00:00 should be -240 minutes offset in MSD");
t.equal(moment("1981-09-30T20:00:00+00:00").tz("Europe/Kaliningrad").zone(), -180, "1981-09-30T20:00:00+00:00 should be -180 minutes offset in MSK");
t.done();
},
"1982" : function (t) {
t.equal(moment("1982-03-31T20:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "23:59:59", "1982-03-31T20:59:59+00:00 should be 23:59:59 MSK");
t.equal(moment("1982-03-31T21:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "01:00:00", "1982-03-31T21:00:00+00:00 should be 01:00:00 MSD");
t.equal(moment("1982-09-30T19:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "23:59:59", "1982-09-30T19:59:59+00:00 should be 23:59:59 MSD");
t.equal(moment("1982-09-30T20:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "23:00:00", "1982-09-30T20:00:00+00:00 should be 23:00:00 MSK");
t.equal(moment("1982-03-31T20:59:59+00:00").tz("Europe/Kaliningrad").zone(), -180, "1982-03-31T20:59:59+00:00 should be -180 minutes offset in MSK");
t.equal(moment("1982-03-31T21:00:00+00:00").tz("Europe/Kaliningrad").zone(), -240, "1982-03-31T21:00:00+00:00 should be -240 minutes offset in MSD");
t.equal(moment("1982-09-30T19:59:59+00:00").tz("Europe/Kaliningrad").zone(), -240, "1982-09-30T19:59:59+00:00 should be -240 minutes offset in MSD");
t.equal(moment("1982-09-30T20:00:00+00:00").tz("Europe/Kaliningrad").zone(), -180, "1982-09-30T20:00:00+00:00 should be -180 minutes offset in MSK");
t.done();
},
"1983" : function (t) {
t.equal(moment("1983-03-31T20:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "23:59:59", "1983-03-31T20:59:59+00:00 should be 23:59:59 MSK");
t.equal(moment("1983-03-31T21:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "01:00:00", "1983-03-31T21:00:00+00:00 should be 01:00:00 MSD");
t.equal(moment("1983-09-30T19:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "23:59:59", "1983-09-30T19:59:59+00:00 should be 23:59:59 MSD");
t.equal(moment("1983-09-30T20:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "23:00:00", "1983-09-30T20:00:00+00:00 should be 23:00:00 MSK");
t.equal(moment("1983-03-31T20:59:59+00:00").tz("Europe/Kaliningrad").zone(), -180, "1983-03-31T20:59:59+00:00 should be -180 minutes offset in MSK");
t.equal(moment("1983-03-31T21:00:00+00:00").tz("Europe/Kaliningrad").zone(), -240, "1983-03-31T21:00:00+00:00 should be -240 minutes offset in MSD");
t.equal(moment("1983-09-30T19:59:59+00:00").tz("Europe/Kaliningrad").zone(), -240, "1983-09-30T19:59:59+00:00 should be -240 minutes offset in MSD");
t.equal(moment("1983-09-30T20:00:00+00:00").tz("Europe/Kaliningrad").zone(), -180, "1983-09-30T20:00:00+00:00 should be -180 minutes offset in MSK");
t.done();
},
"1984" : function (t) {
t.equal(moment("1984-03-31T20:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "23:59:59", "1984-03-31T20:59:59+00:00 should be 23:59:59 MSK");
t.equal(moment("1984-03-31T21:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "01:00:00", "1984-03-31T21:00:00+00:00 should be 01:00:00 MSD");
t.equal(moment("1984-09-29T22:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:59:59", "1984-09-29T22:59:59+00:00 should be 02:59:59 MSD");
t.equal(moment("1984-09-29T23:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:00:00", "1984-09-29T23:00:00+00:00 should be 02:00:00 MSK");
t.equal(moment("1984-03-31T20:59:59+00:00").tz("Europe/Kaliningrad").zone(), -180, "1984-03-31T20:59:59+00:00 should be -180 minutes offset in MSK");
t.equal(moment("1984-03-31T21:00:00+00:00").tz("Europe/Kaliningrad").zone(), -240, "1984-03-31T21:00:00+00:00 should be -240 minutes offset in MSD");
t.equal(moment("1984-09-29T22:59:59+00:00").tz("Europe/Kaliningrad").zone(), -240, "1984-09-29T22:59:59+00:00 should be -240 minutes offset in MSD");
t.equal(moment("1984-09-29T23:00:00+00:00").tz("Europe/Kaliningrad").zone(), -180, "1984-09-29T23:00:00+00:00 should be -180 minutes offset in MSK");
t.done();
},
"1985" : function (t) {
t.equal(moment("1985-03-30T22:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "01:59:59", "1985-03-30T22:59:59+00:00 should be 01:59:59 MSK");
t.equal(moment("1985-03-30T23:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "03:00:00", "1985-03-30T23:00:00+00:00 should be 03:00:00 MSD");
t.equal(moment("1985-09-28T22:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:59:59", "1985-09-28T22:59:59+00:00 should be 02:59:59 MSD");
t.equal(moment("1985-09-28T23:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:00:00", "1985-09-28T23:00:00+00:00 should be 02:00:00 MSK");
t.equal(moment("1985-03-30T22:59:59+00:00").tz("Europe/Kaliningrad").zone(), -180, "1985-03-30T22:59:59+00:00 should be -180 minutes offset in MSK");
t.equal(moment("1985-03-30T23:00:00+00:00").tz("Europe/Kaliningrad").zone(), -240, "1985-03-30T23:00:00+00:00 should be -240 minutes offset in MSD");
t.equal(moment("1985-09-28T22:59:59+00:00").tz("Europe/Kaliningrad").zone(), -240, "1985-09-28T22:59:59+00:00 should be -240 minutes offset in MSD");
t.equal(moment("1985-09-28T23:00:00+00:00").tz("Europe/Kaliningrad").zone(), -180, "1985-09-28T23:00:00+00:00 should be -180 minutes offset in MSK");
t.done();
},
"1986" : function (t) {
t.equal(moment("1986-03-29T22:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "01:59:59", "1986-03-29T22:59:59+00:00 should be 01:59:59 MSK");
t.equal(moment("1986-03-29T23:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "03:00:00", "1986-03-29T23:00:00+00:00 should be 03:00:00 MSD");
t.equal(moment("1986-09-27T22:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:59:59", "1986-09-27T22:59:59+00:00 should be 02:59:59 MSD");
t.equal(moment("1986-09-27T23:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:00:00", "1986-09-27T23:00:00+00:00 should be 02:00:00 MSK");
t.equal(moment("1986-03-29T22:59:59+00:00").tz("Europe/Kaliningrad").zone(), -180, "1986-03-29T22:59:59+00:00 should be -180 minutes offset in MSK");
t.equal(moment("1986-03-29T23:00:00+00:00").tz("Europe/Kaliningrad").zone(), -240, "1986-03-29T23:00:00+00:00 should be -240 minutes offset in MSD");
t.equal(moment("1986-09-27T22:59:59+00:00").tz("Europe/Kaliningrad").zone(), -240, "1986-09-27T22:59:59+00:00 should be -240 minutes offset in MSD");
t.equal(moment("1986-09-27T23:00:00+00:00").tz("Europe/Kaliningrad").zone(), -180, "1986-09-27T23:00:00+00:00 should be -180 minutes offset in MSK");
t.done();
},
"1987" : function (t) {
t.equal(moment("1987-03-28T22:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "01:59:59", "1987-03-28T22:59:59+00:00 should be 01:59:59 MSK");
t.equal(moment("1987-03-28T23:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "03:00:00", "1987-03-28T23:00:00+00:00 should be 03:00:00 MSD");
t.equal(moment("1987-09-26T22:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:59:59", "1987-09-26T22:59:59+00:00 should be 02:59:59 MSD");
t.equal(moment("1987-09-26T23:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:00:00", "1987-09-26T23:00:00+00:00 should be 02:00:00 MSK");
t.equal(moment("1987-03-28T22:59:59+00:00").tz("Europe/Kaliningrad").zone(), -180, "1987-03-28T22:59:59+00:00 should be -180 minutes offset in MSK");
t.equal(moment("1987-03-28T23:00:00+00:00").tz("Europe/Kaliningrad").zone(), -240, "1987-03-28T23:00:00+00:00 should be -240 minutes offset in MSD");
t.equal(moment("1987-09-26T22:59:59+00:00").tz("Europe/Kaliningrad").zone(), -240, "1987-09-26T22:59:59+00:00 should be -240 minutes offset in MSD");
t.equal(moment("1987-09-26T23:00:00+00:00").tz("Europe/Kaliningrad").zone(), -180, "1987-09-26T23:00:00+00:00 should be -180 minutes offset in MSK");
t.done();
},
"1988" : function (t) {
t.equal(moment("1988-03-26T22:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "01:59:59", "1988-03-26T22:59:59+00:00 should be 01:59:59 MSK");
t.equal(moment("1988-03-26T23:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "03:00:00", "1988-03-26T23:00:00+00:00 should be 03:00:00 MSD");
t.equal(moment("1988-09-24T22:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:59:59", "1988-09-24T22:59:59+00:00 should be 02:59:59 MSD");
t.equal(moment("1988-09-24T23:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:00:00", "1988-09-24T23:00:00+00:00 should be 02:00:00 MSK");
t.equal(moment("1988-03-26T22:59:59+00:00").tz("Europe/Kaliningrad").zone(), -180, "1988-03-26T22:59:59+00:00 should be -180 minutes offset in MSK");
t.equal(moment("1988-03-26T23:00:00+00:00").tz("Europe/Kaliningrad").zone(), -240, "1988-03-26T23:00:00+00:00 should be -240 minutes offset in MSD");
t.equal(moment("1988-09-24T22:59:59+00:00").tz("Europe/Kaliningrad").zone(), -240, "1988-09-24T22:59:59+00:00 should be -240 minutes offset in MSD");
t.equal(moment("1988-09-24T23:00:00+00:00").tz("Europe/Kaliningrad").zone(), -180, "1988-09-24T23:00:00+00:00 should be -180 minutes offset in MSK");
t.done();
},
"1989" : function (t) {
t.equal(moment("1989-03-25T22:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "01:59:59", "1989-03-25T22:59:59+00:00 should be 01:59:59 MSK");
t.equal(moment("1989-03-25T23:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "03:00:00", "1989-03-25T23:00:00+00:00 should be 03:00:00 MSD");
t.equal(moment("1989-09-23T22:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:59:59", "1989-09-23T22:59:59+00:00 should be 02:59:59 MSD");
t.equal(moment("1989-09-23T23:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:00:00", "1989-09-23T23:00:00+00:00 should be 02:00:00 MSK");
t.equal(moment("1989-03-25T22:59:59+00:00").tz("Europe/Kaliningrad").zone(), -180, "1989-03-25T22:59:59+00:00 should be -180 minutes offset in MSK");
t.equal(moment("1989-03-25T23:00:00+00:00").tz("Europe/Kaliningrad").zone(), -240, "1989-03-25T23:00:00+00:00 should be -240 minutes offset in MSD");
t.equal(moment("1989-09-23T22:59:59+00:00").tz("Europe/Kaliningrad").zone(), -240, "1989-09-23T22:59:59+00:00 should be -240 minutes offset in MSD");
t.equal(moment("1989-09-23T23:00:00+00:00").tz("Europe/Kaliningrad").zone(), -180, "1989-09-23T23:00:00+00:00 should be -180 minutes offset in MSK");
t.done();
},
"1990" : function (t) {
t.equal(moment("1990-03-24T22:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "01:59:59", "1990-03-24T22:59:59+00:00 should be 01:59:59 MSK");
t.equal(moment("1990-03-24T23:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "03:00:00", "1990-03-24T23:00:00+00:00 should be 03:00:00 MSD");
t.equal(moment("1990-09-29T22:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:59:59", "1990-09-29T22:59:59+00:00 should be 02:59:59 MSD");
t.equal(moment("1990-09-29T23:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:00:00", "1990-09-29T23:00:00+00:00 should be 02:00:00 MSK");
t.equal(moment("1990-03-24T22:59:59+00:00").tz("Europe/Kaliningrad").zone(), -180, "1990-03-24T22:59:59+00:00 should be -180 minutes offset in MSK");
t.equal(moment("1990-03-24T23:00:00+00:00").tz("Europe/Kaliningrad").zone(), -240, "1990-03-24T23:00:00+00:00 should be -240 minutes offset in MSD");
t.equal(moment("1990-09-29T22:59:59+00:00").tz("Europe/Kaliningrad").zone(), -240, "1990-09-29T22:59:59+00:00 should be -240 minutes offset in MSD");
t.equal(moment("1990-09-29T23:00:00+00:00").tz("Europe/Kaliningrad").zone(), -180, "1990-09-29T23:00:00+00:00 should be -180 minutes offset in MSK");
t.done();
},
"1991" : function (t) {
t.equal(moment("1991-03-30T22:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "01:59:59", "1991-03-30T22:59:59+00:00 should be 01:59:59 MSK");
t.equal(moment("1991-03-30T23:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:00:00", "1991-03-30T23:00:00+00:00 should be 02:00:00 EEST");
t.equal(moment("1991-09-28T23:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:59:59", "1991-09-28T23:59:59+00:00 should be 02:59:59 EEST");
t.equal(moment("1991-09-29T00:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:00:00", "1991-09-29T00:00:00+00:00 should be 02:00:00 EET");
t.equal(moment("1991-03-30T22:59:59+00:00").tz("Europe/Kaliningrad").zone(), -180, "1991-03-30T22:59:59+00:00 should be -180 minutes offset in MSK");
t.equal(moment("1991-03-30T23:00:00+00:00").tz("Europe/Kaliningrad").zone(), -180, "1991-03-30T23:00:00+00:00 should be -180 minutes offset in EEST");
t.equal(moment("1991-09-28T23:59:59+00:00").tz("Europe/Kaliningrad").zone(), -180, "1991-09-28T23:59:59+00:00 should be -180 minutes offset in EEST");
t.equal(moment("1991-09-29T00:00:00+00:00").tz("Europe/Kaliningrad").zone(), -120, "1991-09-29T00:00:00+00:00 should be -120 minutes offset in EET");
t.done();
},
"1992" : function (t) {
t.equal(moment("1992-03-28T20:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "22:59:59", "1992-03-28T20:59:59+00:00 should be 22:59:59 EET");
t.equal(moment("1992-03-28T21:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "00:00:00", "1992-03-28T21:00:00+00:00 should be 00:00:00 EEST");
t.equal(moment("1992-09-26T19:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "22:59:59", "1992-09-26T19:59:59+00:00 should be 22:59:59 EEST");
t.equal(moment("1992-09-26T20:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "22:00:00", "1992-09-26T20:00:00+00:00 should be 22:00:00 EET");
t.equal(moment("1992-03-28T20:59:59+00:00").tz("Europe/Kaliningrad").zone(), -120, "1992-03-28T20:59:59+00:00 should be -120 minutes offset in EET");
t.equal(moment("1992-03-28T21:00:00+00:00").tz("Europe/Kaliningrad").zone(), -180, "1992-03-28T21:00:00+00:00 should be -180 minutes offset in EEST");
t.equal(moment("1992-09-26T19:59:59+00:00").tz("Europe/Kaliningrad").zone(), -180, "1992-09-26T19:59:59+00:00 should be -180 minutes offset in EEST");
t.equal(moment("1992-09-26T20:00:00+00:00").tz("Europe/Kaliningrad").zone(), -120, "1992-09-26T20:00:00+00:00 should be -120 minutes offset in EET");
t.done();
},
"1993" : function (t) {
t.equal(moment("1993-03-27T23:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "01:59:59", "1993-03-27T23:59:59+00:00 should be 01:59:59 EET");
t.equal(moment("1993-03-28T00:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "03:00:00", "1993-03-28T00:00:00+00:00 should be 03:00:00 EEST");
t.equal(moment("1993-09-25T23:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:59:59", "1993-09-25T23:59:59+00:00 should be 02:59:59 EEST");
t.equal(moment("1993-09-26T00:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:00:00", "1993-09-26T00:00:00+00:00 should be 02:00:00 EET");
t.equal(moment("1993-03-27T23:59:59+00:00").tz("Europe/Kaliningrad").zone(), -120, "1993-03-27T23:59:59+00:00 should be -120 minutes offset in EET");
t.equal(moment("1993-03-28T00:00:00+00:00").tz("Europe/Kaliningrad").zone(), -180, "1993-03-28T00:00:00+00:00 should be -180 minutes offset in EEST");
t.equal(moment("1993-09-25T23:59:59+00:00").tz("Europe/Kaliningrad").zone(), -180, "1993-09-25T23:59:59+00:00 should be -180 minutes offset in EEST");
t.equal(moment("1993-09-26T00:00:00+00:00").tz("Europe/Kaliningrad").zone(), -120, "1993-09-26T00:00:00+00:00 should be -120 minutes offset in EET");
t.done();
},
"1994" : function (t) {
t.equal(moment("1994-03-26T23:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "01:59:59", "1994-03-26T23:59:59+00:00 should be 01:59:59 EET");
t.equal(moment("1994-03-27T00:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "03:00:00", "1994-03-27T00:00:00+00:00 should be 03:00:00 EEST");
t.equal(moment("1994-09-24T23:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:59:59", "1994-09-24T23:59:59+00:00 should be 02:59:59 EEST");
t.equal(moment("1994-09-25T00:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:00:00", "1994-09-25T00:00:00+00:00 should be 02:00:00 EET");
t.equal(moment("1994-03-26T23:59:59+00:00").tz("Europe/Kaliningrad").zone(), -120, "1994-03-26T23:59:59+00:00 should be -120 minutes offset in EET");
t.equal(moment("1994-03-27T00:00:00+00:00").tz("Europe/Kaliningrad").zone(), -180, "1994-03-27T00:00:00+00:00 should be -180 minutes offset in EEST");
t.equal(moment("1994-09-24T23:59:59+00:00").tz("Europe/Kaliningrad").zone(), -180, "1994-09-24T23:59:59+00:00 should be -180 minutes offset in EEST");
t.equal(moment("1994-09-25T00:00:00+00:00").tz("Europe/Kaliningrad").zone(), -120, "1994-09-25T00:00:00+00:00 should be -120 minutes offset in EET");
t.done();
},
"1995" : function (t) {
t.equal(moment("1995-03-25T23:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "01:59:59", "1995-03-25T23:59:59+00:00 should be 01:59:59 EET");
t.equal(moment("1995-03-26T00:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "03:00:00", "1995-03-26T00:00:00+00:00 should be 03:00:00 EEST");
t.equal(moment("1995-09-23T23:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:59:59", "1995-09-23T23:59:59+00:00 should be 02:59:59 EEST");
t.equal(moment("1995-09-24T00:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:00:00", "1995-09-24T00:00:00+00:00 should be 02:00:00 EET");
t.equal(moment("1995-03-25T23:59:59+00:00").tz("Europe/Kaliningrad").zone(), -120, "1995-03-25T23:59:59+00:00 should be -120 minutes offset in EET");
t.equal(moment("1995-03-26T00:00:00+00:00").tz("Europe/Kaliningrad").zone(), -180, "1995-03-26T00:00:00+00:00 should be -180 minutes offset in EEST");
t.equal(moment("1995-09-23T23:59:59+00:00").tz("Europe/Kaliningrad").zone(), -180, "1995-09-23T23:59:59+00:00 should be -180 minutes offset in EEST");
t.equal(moment("1995-09-24T00:00:00+00:00").tz("Europe/Kaliningrad").zone(), -120, "1995-09-24T00:00:00+00:00 should be -120 minutes offset in EET");
t.done();
},
"1996" : function (t) {
t.equal(moment("1996-03-30T23:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "01:59:59", "1996-03-30T23:59:59+00:00 should be 01:59:59 EET");
t.equal(moment("1996-03-31T00:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "03:00:00", "1996-03-31T00:00:00+00:00 should be 03:00:00 EEST");
t.equal(moment("1996-10-26T23:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:59:59", "1996-10-26T23:59:59+00:00 should be 02:59:59 EEST");
t.equal(moment("1996-10-27T00:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:00:00", "1996-10-27T00:00:00+00:00 should be 02:00:00 EET");
t.equal(moment("1996-03-30T23:59:59+00:00").tz("Europe/Kaliningrad").zone(), -120, "1996-03-30T23:59:59+00:00 should be -120 minutes offset in EET");
t.equal(moment("1996-03-31T00:00:00+00:00").tz("Europe/Kaliningrad").zone(), -180, "1996-03-31T00:00:00+00:00 should be -180 minutes offset in EEST");
t.equal(moment("1996-10-26T23:59:59+00:00").tz("Europe/Kaliningrad").zone(), -180, "1996-10-26T23:59:59+00:00 should be -180 minutes offset in EEST");
t.equal(moment("1996-10-27T00:00:00+00:00").tz("Europe/Kaliningrad").zone(), -120, "1996-10-27T00:00:00+00:00 should be -120 minutes offset in EET");
t.done();
},
"1997" : function (t) {
t.equal(moment("1997-03-29T23:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "01:59:59", "1997-03-29T23:59:59+00:00 should be 01:59:59 EET");
t.equal(moment("1997-03-30T00:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "03:00:00", "1997-03-30T00:00:00+00:00 should be 03:00:00 EEST");
t.equal(moment("1997-10-25T23:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:59:59", "1997-10-25T23:59:59+00:00 should be 02:59:59 EEST");
t.equal(moment("1997-10-26T00:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:00:00", "1997-10-26T00:00:00+00:00 should be 02:00:00 EET");
t.equal(moment("1997-03-29T23:59:59+00:00").tz("Europe/Kaliningrad").zone(), -120, "1997-03-29T23:59:59+00:00 should be -120 minutes offset in EET");
t.equal(moment("1997-03-30T00:00:00+00:00").tz("Europe/Kaliningrad").zone(), -180, "1997-03-30T00:00:00+00:00 should be -180 minutes offset in EEST");
t.equal(moment("1997-10-25T23:59:59+00:00").tz("Europe/Kaliningrad").zone(), -180, "1997-10-25T23:59:59+00:00 should be -180 minutes offset in EEST");
t.equal(moment("1997-10-26T00:00:00+00:00").tz("Europe/Kaliningrad").zone(), -120, "1997-10-26T00:00:00+00:00 should be -120 minutes offset in EET");
t.done();
},
"1998" : function (t) {
t.equal(moment("1998-03-28T23:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "01:59:59", "1998-03-28T23:59:59+00:00 should be 01:59:59 EET");
t.equal(moment("1998-03-29T00:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "03:00:00", "1998-03-29T00:00:00+00:00 should be 03:00:00 EEST");
t.equal(moment("1998-10-24T23:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:59:59", "1998-10-24T23:59:59+00:00 should be 02:59:59 EEST");
t.equal(moment("1998-10-25T00:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:00:00", "1998-10-25T00:00:00+00:00 should be 02:00:00 EET");
t.equal(moment("1998-03-28T23:59:59+00:00").tz("Europe/Kaliningrad").zone(), -120, "1998-03-28T23:59:59+00:00 should be -120 minutes offset in EET");
t.equal(moment("1998-03-29T00:00:00+00:00").tz("Europe/Kaliningrad").zone(), -180, "1998-03-29T00:00:00+00:00 should be -180 minutes offset in EEST");
t.equal(moment("1998-10-24T23:59:59+00:00").tz("Europe/Kaliningrad").zone(), -180, "1998-10-24T23:59:59+00:00 should be -180 minutes offset in EEST");
t.equal(moment("1998-10-25T00:00:00+00:00").tz("Europe/Kaliningrad").zone(), -120, "1998-10-25T00:00:00+00:00 should be -120 minutes offset in EET");
t.done();
},
"1999" : function (t) {
t.equal(moment("1999-03-27T23:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "01:59:59", "1999-03-27T23:59:59+00:00 should be 01:59:59 EET");
t.equal(moment("1999-03-28T00:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "03:00:00", "1999-03-28T00:00:00+00:00 should be 03:00:00 EEST");
t.equal(moment("1999-10-30T23:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:59:59", "1999-10-30T23:59:59+00:00 should be 02:59:59 EEST");
t.equal(moment("1999-10-31T00:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:00:00", "1999-10-31T00:00:00+00:00 should be 02:00:00 EET");
t.equal(moment("1999-03-27T23:59:59+00:00").tz("Europe/Kaliningrad").zone(), -120, "1999-03-27T23:59:59+00:00 should be -120 minutes offset in EET");
t.equal(moment("1999-03-28T00:00:00+00:00").tz("Europe/Kaliningrad").zone(), -180, "1999-03-28T00:00:00+00:00 should be -180 minutes offset in EEST");
t.equal(moment("1999-10-30T23:59:59+00:00").tz("Europe/Kaliningrad").zone(), -180, "1999-10-30T23:59:59+00:00 should be -180 minutes offset in EEST");
t.equal(moment("1999-10-31T00:00:00+00:00").tz("Europe/Kaliningrad").zone(), -120, "1999-10-31T00:00:00+00:00 should be -120 minutes offset in EET");
t.done();
},
"2000" : function (t) {
t.equal(moment("2000-03-25T23:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "01:59:59", "2000-03-25T23:59:59+00:00 should be 01:59:59 EET");
t.equal(moment("2000-03-26T00:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "03:00:00", "2000-03-26T00:00:00+00:00 should be 03:00:00 EEST");
t.equal(moment("2000-10-28T23:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:59:59", "2000-10-28T23:59:59+00:00 should be 02:59:59 EEST");
t.equal(moment("2000-10-29T00:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:00:00", "2000-10-29T00:00:00+00:00 should be 02:00:00 EET");
t.equal(moment("2000-03-25T23:59:59+00:00").tz("Europe/Kaliningrad").zone(), -120, "2000-03-25T23:59:59+00:00 should be -120 minutes offset in EET");
t.equal(moment("2000-03-26T00:00:00+00:00").tz("Europe/Kaliningrad").zone(), -180, "2000-03-26T00:00:00+00:00 should be -180 minutes offset in EEST");
t.equal(moment("2000-10-28T23:59:59+00:00").tz("Europe/Kaliningrad").zone(), -180, "2000-10-28T23:59:59+00:00 should be -180 minutes offset in EEST");
t.equal(moment("2000-10-29T00:00:00+00:00").tz("Europe/Kaliningrad").zone(), -120, "2000-10-29T00:00:00+00:00 should be -120 minutes offset in EET");
t.done();
},
"2001" : function (t) {
t.equal(moment("2001-03-24T23:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "01:59:59", "2001-03-24T23:59:59+00:00 should be 01:59:59 EET");
t.equal(moment("2001-03-25T00:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "03:00:00", "2001-03-25T00:00:00+00:00 should be 03:00:00 EEST");
t.equal(moment("2001-10-27T23:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:59:59", "2001-10-27T23:59:59+00:00 should be 02:59:59 EEST");
t.equal(moment("2001-10-28T00:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:00:00", "2001-10-28T00:00:00+00:00 should be 02:00:00 EET");
t.equal(moment("2001-03-24T23:59:59+00:00").tz("Europe/Kaliningrad").zone(), -120, "2001-03-24T23:59:59+00:00 should be -120 minutes offset in EET");
t.equal(moment("2001-03-25T00:00:00+00:00").tz("Europe/Kaliningrad").zone(), -180, "2001-03-25T00:00:00+00:00 should be -180 minutes offset in EEST");
t.equal(moment("2001-10-27T23:59:59+00:00").tz("Europe/Kaliningrad").zone(), -180, "2001-10-27T23:59:59+00:00 should be -180 minutes offset in EEST");
t.equal(moment("2001-10-28T00:00:00+00:00").tz("Europe/Kaliningrad").zone(), -120, "2001-10-28T00:00:00+00:00 should be -120 minutes offset in EET");
t.done();
},
"2002" : function (t) {
t.equal(moment("2002-03-30T23:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "01:59:59", "2002-03-30T23:59:59+00:00 should be 01:59:59 EET");
t.equal(moment("2002-03-31T00:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "03:00:00", "2002-03-31T00:00:00+00:00 should be 03:00:00 EEST");
t.equal(moment("2002-10-26T23:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:59:59", "2002-10-26T23:59:59+00:00 should be 02:59:59 EEST");
t.equal(moment("2002-10-27T00:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:00:00", "2002-10-27T00:00:00+00:00 should be 02:00:00 EET");
t.equal(moment("2002-03-30T23:59:59+00:00").tz("Europe/Kaliningrad").zone(), -120, "2002-03-30T23:59:59+00:00 should be -120 minutes offset in EET");
t.equal(moment("2002-03-31T00:00:00+00:00").tz("Europe/Kaliningrad").zone(), -180, "2002-03-31T00:00:00+00:00 should be -180 minutes offset in EEST");
t.equal(moment("2002-10-26T23:59:59+00:00").tz("Europe/Kaliningrad").zone(), -180, "2002-10-26T23:59:59+00:00 should be -180 minutes offset in EEST");
t.equal(moment("2002-10-27T00:00:00+00:00").tz("Europe/Kaliningrad").zone(), -120, "2002-10-27T00:00:00+00:00 should be -120 minutes offset in EET");
t.done();
},
"2003" : function (t) {
t.equal(moment("2003-03-29T23:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "01:59:59", "2003-03-29T23:59:59+00:00 should be 01:59:59 EET");
t.equal(moment("2003-03-30T00:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "03:00:00", "2003-03-30T00:00:00+00:00 should be 03:00:00 EEST");
t.equal(moment("2003-10-25T23:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:59:59", "2003-10-25T23:59:59+00:00 should be 02:59:59 EEST");
t.equal(moment("2003-10-26T00:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:00:00", "2003-10-26T00:00:00+00:00 should be 02:00:00 EET");
t.equal(moment("2003-03-29T23:59:59+00:00").tz("Europe/Kaliningrad").zone(), -120, "2003-03-29T23:59:59+00:00 should be -120 minutes offset in EET");
t.equal(moment("2003-03-30T00:00:00+00:00").tz("Europe/Kaliningrad").zone(), -180, "2003-03-30T00:00:00+00:00 should be -180 minutes offset in EEST");
t.equal(moment("2003-10-25T23:59:59+00:00").tz("Europe/Kaliningrad").zone(), -180, "2003-10-25T23:59:59+00:00 should be -180 minutes offset in EEST");
t.equal(moment("2003-10-26T00:00:00+00:00").tz("Europe/Kaliningrad").zone(), -120, "2003-10-26T00:00:00+00:00 should be -120 minutes offset in EET");
t.done();
},
"2004" : function (t) {
t.equal(moment("2004-03-27T23:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "01:59:59", "2004-03-27T23:59:59+00:00 should be 01:59:59 EET");
t.equal(moment("2004-03-28T00:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "03:00:00", "2004-03-28T00:00:00+00:00 should be 03:00:00 EEST");
t.equal(moment("2004-10-30T23:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:59:59", "2004-10-30T23:59:59+00:00 should be 02:59:59 EEST");
t.equal(moment("2004-10-31T00:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:00:00", "2004-10-31T00:00:00+00:00 should be 02:00:00 EET");
t.equal(moment("2004-03-27T23:59:59+00:00").tz("Europe/Kaliningrad").zone(), -120, "2004-03-27T23:59:59+00:00 should be -120 minutes offset in EET");
t.equal(moment("2004-03-28T00:00:00+00:00").tz("Europe/Kaliningrad").zone(), -180, "2004-03-28T00:00:00+00:00 should be -180 minutes offset in EEST");
t.equal(moment("2004-10-30T23:59:59+00:00").tz("Europe/Kaliningrad").zone(), -180, "2004-10-30T23:59:59+00:00 should be -180 minutes offset in EEST");
t.equal(moment("2004-10-31T00:00:00+00:00").tz("Europe/Kaliningrad").zone(), -120, "2004-10-31T00:00:00+00:00 should be -120 minutes offset in EET");
t.done();
},
"2005" : function (t) {
t.equal(moment("2005-03-26T23:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "01:59:59", "2005-03-26T23:59:59+00:00 should be 01:59:59 EET");
t.equal(moment("2005-03-27T00:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "03:00:00", "2005-03-27T00:00:00+00:00 should be 03:00:00 EEST");
t.equal(moment("2005-10-29T23:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:59:59", "2005-10-29T23:59:59+00:00 should be 02:59:59 EEST");
t.equal(moment("2005-10-30T00:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:00:00", "2005-10-30T00:00:00+00:00 should be 02:00:00 EET");
t.equal(moment("2005-03-26T23:59:59+00:00").tz("Europe/Kaliningrad").zone(), -120, "2005-03-26T23:59:59+00:00 should be -120 minutes offset in EET");
t.equal(moment("2005-03-27T00:00:00+00:00").tz("Europe/Kaliningrad").zone(), -180, "2005-03-27T00:00:00+00:00 should be -180 minutes offset in EEST");
t.equal(moment("2005-10-29T23:59:59+00:00").tz("Europe/Kaliningrad").zone(), -180, "2005-10-29T23:59:59+00:00 should be -180 minutes offset in EEST");
t.equal(moment("2005-10-30T00:00:00+00:00").tz("Europe/Kaliningrad").zone(), -120, "2005-10-30T00:00:00+00:00 should be -120 minutes offset in EET");
t.done();
},
"2006" : function (t) {
t.equal(moment("2006-03-25T23:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "01:59:59", "2006-03-25T23:59:59+00:00 should be 01:59:59 EET");
t.equal(moment("2006-03-26T00:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "03:00:00", "2006-03-26T00:00:00+00:00 should be 03:00:00 EEST");
t.equal(moment("2006-10-28T23:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:59:59", "2006-10-28T23:59:59+00:00 should be 02:59:59 EEST");
t.equal(moment("2006-10-29T00:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:00:00", "2006-10-29T00:00:00+00:00 should be 02:00:00 EET");
t.equal(moment("2006-03-25T23:59:59+00:00").tz("Europe/Kaliningrad").zone(), -120, "2006-03-25T23:59:59+00:00 should be -120 minutes offset in EET");
t.equal(moment("2006-03-26T00:00:00+00:00").tz("Europe/Kaliningrad").zone(), -180, "2006-03-26T00:00:00+00:00 should be -180 minutes offset in EEST");
t.equal(moment("2006-10-28T23:59:59+00:00").tz("Europe/Kaliningrad").zone(), -180, "2006-10-28T23:59:59+00:00 should be -180 minutes offset in EEST");
t.equal(moment("2006-10-29T00:00:00+00:00").tz("Europe/Kaliningrad").zone(), -120, "2006-10-29T00:00:00+00:00 should be -120 minutes offset in EET");
t.done();
},
"2007" : function (t) {
t.equal(moment("2007-03-24T23:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "01:59:59", "2007-03-24T23:59:59+00:00 should be 01:59:59 EET");
t.equal(moment("2007-03-25T00:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "03:00:00", "2007-03-25T00:00:00+00:00 should be 03:00:00 EEST");
t.equal(moment("2007-10-27T23:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:59:59", "2007-10-27T23:59:59+00:00 should be 02:59:59 EEST");
t.equal(moment("2007-10-28T00:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:00:00", "2007-10-28T00:00:00+00:00 should be 02:00:00 EET");
t.equal(moment("2007-03-24T23:59:59+00:00").tz("Europe/Kaliningrad").zone(), -120, "2007-03-24T23:59:59+00:00 should be -120 minutes offset in EET");
t.equal(moment("2007-03-25T00:00:00+00:00").tz("Europe/Kaliningrad").zone(), -180, "2007-03-25T00:00:00+00:00 should be -180 minutes offset in EEST");
t.equal(moment("2007-10-27T23:59:59+00:00").tz("Europe/Kaliningrad").zone(), -180, "2007-10-27T23:59:59+00:00 should be -180 minutes offset in EEST");
t.equal(moment("2007-10-28T00:00:00+00:00").tz("Europe/Kaliningrad").zone(), -120, "2007-10-28T00:00:00+00:00 should be -120 minutes offset in EET");
t.done();
},
"2008" : function (t) {
t.equal(moment("2008-03-29T23:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "01:59:59", "2008-03-29T23:59:59+00:00 should be 01:59:59 EET");
t.equal(moment("2008-03-30T00:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "03:00:00", "2008-03-30T00:00:00+00:00 should be 03:00:00 EEST");
t.equal(moment("2008-10-25T23:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:59:59", "2008-10-25T23:59:59+00:00 should be 02:59:59 EEST");
t.equal(moment("2008-10-26T00:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:00:00", "2008-10-26T00:00:00+00:00 should be 02:00:00 EET");
t.equal(moment("2008-03-29T23:59:59+00:00").tz("Europe/Kaliningrad").zone(), -120, "2008-03-29T23:59:59+00:00 should be -120 minutes offset in EET");
t.equal(moment("2008-03-30T00:00:00+00:00").tz("Europe/Kaliningrad").zone(), -180, "2008-03-30T00:00:00+00:00 should be -180 minutes offset in EEST");
t.equal(moment("2008-10-25T23:59:59+00:00").tz("Europe/Kaliningrad").zone(), -180, "2008-10-25T23:59:59+00:00 should be -180 minutes offset in EEST");
t.equal(moment("2008-10-26T00:00:00+00:00").tz("Europe/Kaliningrad").zone(), -120, "2008-10-26T00:00:00+00:00 should be -120 minutes offset in EET");
t.done();
},
"2009" : function (t) {
t.equal(moment("2009-03-28T23:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "01:59:59", "2009-03-28T23:59:59+00:00 should be 01:59:59 EET");
t.equal(moment("2009-03-29T00:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "03:00:00", "2009-03-29T00:00:00+00:00 should be 03:00:00 EEST");
t.equal(moment("2009-10-24T23:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:59:59", "2009-10-24T23:59:59+00:00 should be 02:59:59 EEST");
t.equal(moment("2009-10-25T00:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:00:00", "2009-10-25T00:00:00+00:00 should be 02:00:00 EET");
t.equal(moment("2009-03-28T23:59:59+00:00").tz("Europe/Kaliningrad").zone(), -120, "2009-03-28T23:59:59+00:00 should be -120 minutes offset in EET");
t.equal(moment("2009-03-29T00:00:00+00:00").tz("Europe/Kaliningrad").zone(), -180, "2009-03-29T00:00:00+00:00 should be -180 minutes offset in EEST");
t.equal(moment("2009-10-24T23:59:59+00:00").tz("Europe/Kaliningrad").zone(), -180, "2009-10-24T23:59:59+00:00 should be -180 minutes offset in EEST");
t.equal(moment("2009-10-25T00:00:00+00:00").tz("Europe/Kaliningrad").zone(), -120, "2009-10-25T00:00:00+00:00 should be -120 minutes offset in EET");
t.done();
},
"2010" : function (t) {
t.equal(moment("2010-03-27T23:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "01:59:59", "2010-03-27T23:59:59+00:00 should be 01:59:59 EET");
t.equal(moment("2010-03-28T00:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "03:00:00", "2010-03-28T00:00:00+00:00 should be 03:00:00 EEST");
t.equal(moment("2010-10-30T23:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:59:59", "2010-10-30T23:59:59+00:00 should be 02:59:59 EEST");
t.equal(moment("2010-10-31T00:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "02:00:00", "2010-10-31T00:00:00+00:00 should be 02:00:00 EET");
t.equal(moment("2010-03-27T23:59:59+00:00").tz("Europe/Kaliningrad").zone(), -120, "2010-03-27T23:59:59+00:00 should be -120 minutes offset in EET");
t.equal(moment("2010-03-28T00:00:00+00:00").tz("Europe/Kaliningrad").zone(), -180, "2010-03-28T00:00:00+00:00 should be -180 minutes offset in EEST");
t.equal(moment("2010-10-30T23:59:59+00:00").tz("Europe/Kaliningrad").zone(), -180, "2010-10-30T23:59:59+00:00 should be -180 minutes offset in EEST");
t.equal(moment("2010-10-31T00:00:00+00:00").tz("Europe/Kaliningrad").zone(), -120, "2010-10-31T00:00:00+00:00 should be -120 minutes offset in EET");
t.done();
},
"2011" : function (t) {
t.equal(moment("2011-03-26T23:59:59+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "01:59:59", "2011-03-26T23:59:59+00:00 should be 01:59:59 EET");
t.equal(moment("2011-03-27T00:00:00+00:00").tz("Europe/Kaliningrad").format("HH:mm:ss"), "03:00:00", "2011-03-27T00:00:00+00:00 should be 03:00:00 FET");
t.equal(moment("2011-03-26T23:59:59+00:00").tz("Europe/Kaliningrad").zone(), -120, "2011-03-26T23:59:59+00:00 should be -120 minutes offset in EET");
t.equal(moment("2011-03-27T00:00:00+00:00").tz("Europe/Kaliningrad").zone(), -180, "2011-03-27T00:00:00+00:00 should be -180 minutes offset in FET");
t.done();
}
}; |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
//@ts-check
'use strict';
//#region global bootstrapping
// increase number of stack frames(from 10, https://github.com/v8/v8/wiki/Stack-Trace-API)
Error.stackTraceLimit = 100;
// Workaround for Electron not installing a handler to ignore SIGPIPE
// (https://github.com/electron/electron/issues/13254)
// @ts-ignore
process.on('SIGPIPE', () => {
console.error(new Error('Unexpected SIGPIPE'));
});
//#endregion
//#region Add support for using node_modules.asar
/**
* @param {string=} nodeModulesPath
*/
exports.enableASARSupport = function (nodeModulesPath) {
// @ts-ignore
const Module = require('module');
const path = require('path');
let NODE_MODULES_PATH = nodeModulesPath;
if (!NODE_MODULES_PATH) {
NODE_MODULES_PATH = path.join(__dirname, '../node_modules');
}
const NODE_MODULES_ASAR_PATH = NODE_MODULES_PATH + '.asar';
// @ts-ignore
const originalResolveLookupPaths = Module._resolveLookupPaths;
// @ts-ignore
Module._resolveLookupPaths = function (request, parent, newReturn) {
const result = originalResolveLookupPaths(request, parent, newReturn);
const paths = newReturn ? result : result[1];
for (let i = 0, len = paths.length; i < len; i++) {
if (paths[i] === NODE_MODULES_PATH) {
paths.splice(i, 0, NODE_MODULES_ASAR_PATH);
break;
}
}
return result;
};
};
//#endregion
//#region URI helpers
/**
* @param {string} _path
* @returns {string}
*/
exports.uriFromPath = function (_path) {
const path = require('path');
let pathName = path.resolve(_path).replace(/\\/g, '/');
if (pathName.length > 0 && pathName.charAt(0) !== '/') {
pathName = '/' + pathName;
}
return encodeURI('file://' + pathName).replace(/#/g, '%23');
};
//#endregion
//#region FS helpers
/**
* @param {string} file
* @returns {Promise<string>}
*/
exports.readFile = function (file) {
const fs = require('fs');
return new Promise(function (resolve, reject) {
fs.readFile(file, 'utf8', function (err, data) {
if (err) {
reject(err);
return;
}
resolve(data);
});
});
};
/**
* @param {string} file
* @param {string} content
* @returns {Promise<void>}
*/
exports.writeFile = function (file, content) {
const fs = require('fs');
return new Promise(function (resolve, reject) {
fs.writeFile(file, content, 'utf8', function (err) {
if (err) {
reject(err);
return;
}
resolve();
});
});
};
//#endregion
//#region NLS helpers
/**
* @returns {{locale?: string, availableLanguages: {[lang: string]: string;}, pseudo?: boolean }}
*/
exports.setupNLS = function () {
const path = require('path');
// Get the nls configuration into the process.env as early as possible.
let nlsConfig = { availableLanguages: {} };
if (process.env['VSCODE_NLS_CONFIG']) {
try {
nlsConfig = JSON.parse(process.env['VSCODE_NLS_CONFIG']);
} catch (e) {
// Ignore
}
}
if (nlsConfig._resolvedLanguagePackCoreLocation) {
const bundles = Object.create(null);
nlsConfig.loadBundle = function (bundle, language, cb) {
let result = bundles[bundle];
if (result) {
cb(undefined, result);
return;
}
const bundleFile = path.join(nlsConfig._resolvedLanguagePackCoreLocation, bundle.replace(/\//g, '!') + '.nls.json');
exports.readFile(bundleFile).then(function (content) {
let json = JSON.parse(content);
bundles[bundle] = json;
cb(undefined, json);
}).catch((error) => {
try {
if (nlsConfig._corruptedFile) {
exports.writeFile(nlsConfig._corruptedFile, 'corrupted').catch(function (error) { console.error(error); });
}
} finally {
cb(error, undefined);
}
});
};
}
return nlsConfig;
};
//#endregion
//#region Portable helpers
/**
* @returns {{ portableDataPath: string, isPortable: boolean }}
*/
exports.configurePortable = function () {
// @ts-ignore
const product = require('../product.json');
const path = require('path');
const fs = require('fs');
const appRoot = path.dirname(__dirname);
function getApplicationPath() {
if (process.env['VSCODE_DEV']) {
return appRoot;
}
if (process.platform === 'darwin') {
return path.dirname(path.dirname(path.dirname(appRoot)));
}
return path.dirname(path.dirname(appRoot));
}
function getPortableDataPath() {
if (process.env['VSCODE_PORTABLE']) {
return process.env['VSCODE_PORTABLE'];
}
if (process.platform === 'win32' || process.platform === 'linux') {
return path.join(getApplicationPath(), 'data');
}
const portableDataName = product.portable || `${product.applicationName}-portable-data`;
return path.join(path.dirname(getApplicationPath()), portableDataName);
}
const portableDataPath = getPortableDataPath();
const isPortable = !('target' in product) && fs.existsSync(portableDataPath);
const portableTempPath = path.join(portableDataPath, 'tmp');
const isTempPortable = isPortable && fs.existsSync(portableTempPath);
if (isPortable) {
process.env['VSCODE_PORTABLE'] = portableDataPath;
} else {
delete process.env['VSCODE_PORTABLE'];
}
if (isTempPortable) {
process.env[process.platform === 'win32' ? 'TEMP' : 'TMPDIR'] = portableTempPath;
}
return {
portableDataPath,
isPortable
};
};
//#endregion
//#region ApplicationInsights
/**
* Prevents appinsights from monkey patching modules.
* This should be called before importing the applicationinsights module
*/
exports.avoidMonkeyPatchFromAppInsights = function () {
// @ts-ignore
process.env['APPLICATION_INSIGHTS_NO_DIAGNOSTIC_CHANNEL'] = true; // Skip monkey patching of 3rd party modules by appinsights
global['diagnosticsSource'] = {}; // Prevents diagnostic channel (which patches "require") from initializing entirely
};
//#endregion |
Prism.languages.julia={comment:{pattern:/(^|[^\\])(?:#=(?:[^#=]|=(?!#)|#(?!=)|#=(?:[^#=]|=(?!#)|#(?!=))*=#)*=#|#.*)/,lookbehind:!0},regex:{pattern:/r"(?:\\.|[^"\\\r\n])*"[imsx]{0,4}/,greedy:!0},string:{pattern:/"""[\s\S]+?"""|(?:\b\w+)?"(?:\\.|[^"\\\r\n])*"|(^|[^\w'])'(?:\\[^\r\n][^'\r\n]*|[^\\\r\n])'|`(?:[^\\`\r\n]|\\.)*`/,lookbehind:!0,greedy:!0},keyword:/\b(?:abstract|baremodule|begin|bitstype|break|catch|ccall|const|continue|do|else|elseif|end|export|finally|for|function|global|if|immutable|import|importall|in|let|local|macro|module|print|println|quote|return|struct|try|type|typealias|using|while)\b/,boolean:/\b(?:true|false)\b/,number:/(?:\b(?=\d)|\B(?=\.))(?:0[box])?(?:[\da-f]+(?:_[\da-f]+)*(?:\.(?:\d+(?:_\d+)*)?)?|\.\d+(?:_\d+)*)(?:[efp][+-]?\d+(?:_\d+)*)?j?/i,operator:/&&|\|\||[-+*^%÷⊻&$\\]=?|\/[\/=]?|!=?=?|\|[=>]?|<(?:<=?|[=:|])?|>(?:=|>>?=?)?|==?=?|[~≠≤≥'√∛]/,punctuation:/::?|[{}[\]();,.?]/,constant:/\b(?:(?:NaN|Inf)(?:16|32|64)?|im|pi)\b|[πℯ]/}; |
/* */
var $export = require('./_export'),
$entries = require('./_object-to-array')(true);
$export($export.S, 'Object', {entries: function entries(it) {
return $entries(it);
}});
|
/**
@license
* @pnp/pnpjs v1.2.2 - pnp - rollup library of core functionality (mimics sp-pnp-js)
* MIT (https://github.com/pnp/pnpjs/blob/master/LICENSE)
* Copyright (c) 2018 Microsoft
* docs: https://pnp.github.io/pnpjs/
* source: https:github.com/pnp/pnpjs
* bugs: https://github.com/pnp/pnpjs/issues
*/
import { RuntimeConfig, PnPClientStorage, dateAdd, combine, getCtxCallback, getRandomString, getGUID, isFunc, objectDefinedNotNull, isArray, extend, isUrlAbsolute, stringIsNullOrEmpty, getAttrValueFromString, sanitizeGuid } from '@pnp/common';
export * from '@pnp/common';
import { Logger } from '@pnp/logging';
export * from '@pnp/logging';
import { Settings } from '@pnp/config-store';
export * from '@pnp/config-store';
import { graph } from '@pnp/graph';
export * from '@pnp/graph';
import { sp } from '@pnp/sp-addinhelpers';
export * from '@pnp/sp';
export * from '@pnp/odata';
function setup(config) {
RuntimeConfig.extend(config);
}
/**
* Utility methods
*/
var util = {
combine: combine,
dateAdd: dateAdd,
extend: extend,
getAttrValueFromString: getAttrValueFromString,
getCtxCallback: getCtxCallback,
getGUID: getGUID,
getRandomString: getRandomString,
isArray: isArray,
isFunc: isFunc,
isUrlAbsolute: isUrlAbsolute,
objectDefinedNotNull: objectDefinedNotNull,
sanitizeGuid: sanitizeGuid,
stringIsNullOrEmpty: stringIsNullOrEmpty,
};
/**
* Provides access to the SharePoint REST interface
*/
var sp$1 = sp;
/**
* Provides access to the Microsoft Graph REST interface
*/
var graph$1 = graph;
/**
* Provides access to local and session storage
*/
var storage = new PnPClientStorage();
/**
* Global configuration instance to which providers can be added
*/
var config = new Settings();
/**
* Global logging instance to which subscribers can be registered and messages written
*/
var log = Logger;
/**
* Allows for the configuration of the library
*/
var setup$1 = setup;
// /**
// * Expose a subset of classes from the library for public consumption
// */
// creating this class instead of directly assigning to default fixes issue #116
var Def = {
/**
* Global configuration instance to which providers can be added
*/
config: config,
/**
* Provides access to the Microsoft Graph REST interface
*/
graph: graph$1,
/**
* Global logging instance to which subscribers can be registered and messages written
*/
log: log,
/**
* Provides access to local and session storage
*/
setup: setup$1,
/**
* Provides access to the REST interface
*/
sp: sp$1,
/**
* Provides access to local and session storage
*/
storage: storage,
/**
* Utility methods
*/
util: util,
};
export default Def;
export { util, sp$1 as sp, graph$1 as graph, storage, config, log, setup$1 as setup };
//# sourceMappingURL=pnpjs.es5.js.map
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: The length property of the toString method is 0
es5id: 15.3.4.2_A11
description: Checking Function.prototype.toString.length
---*/
//CHECK#1
if (!(Function.prototype.toString.hasOwnProperty("length"))) {
$ERROR('#1: The Function.prototype.toString has the length property');
}
//CHECK#2
if (Function.prototype.toString.length !== 0) {
$ERROR('#2: The length property of the toString method is 0');
}
|
var test = "hi";
if (test == 'hello') {
}
|
/**
* @author supereggbert / http://www.paulbrunt.co.uk/
* @author mrdoob / http://mrdoob.com/
* @author alteredq / http://alteredqualia.com/
* @author szimek / https://github.com/szimek/
*/
THREE.WebGLRenderer = function ( parameters ) {
console.log( 'THREE.WebGLRenderer', THREE.REVISION );
parameters = parameters || {};
var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
_precision = parameters.precision !== undefined ? parameters.precision : 'highp',
_alpha = parameters.alpha !== undefined ? parameters.alpha : false,
_premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
_antialias = parameters.antialias !== undefined ? parameters.antialias : false,
_stencil = parameters.stencil !== undefined ? parameters.stencil : true,
_preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
_clearColor = new THREE.Color( 0x000000 ),
_clearAlpha = 0;
// public properties
this.domElement = _canvas;
this.context = null;
this.devicePixelRatio = parameters.devicePixelRatio !== undefined
? parameters.devicePixelRatio
: self.devicePixelRatio !== undefined
? self.devicePixelRatio
: 1;
// clearing
this.autoClear = true;
this.autoClearColor = true;
this.autoClearDepth = true;
this.autoClearStencil = true;
// scene graph
this.sortObjects = true;
this.autoUpdateObjects = true;
// physically based shading
this.gammaInput = false;
this.gammaOutput = false;
this.physicallyBasedShading = false;
// shadow map
this.shadowMapEnabled = false;
this.shadowMapAutoUpdate = true;
this.shadowMapType = THREE.PCFShadowMap;
this.shadowMapCullFace = THREE.CullFaceFront;
this.shadowMapDebug = false;
this.shadowMapCascade = false;
// morphs
this.maxMorphTargets = 8;
this.maxMorphNormals = 4;
// flags
this.autoScaleCubemaps = true;
// custom render plugins
this.renderPluginsPre = [];
this.renderPluginsPost = [];
// info
this.info = {
memory: {
programs: 0,
geometries: 0,
textures: 0
},
render: {
calls: 0,
vertices: 0,
faces: 0,
points: 0
}
};
// internal properties
var _this = this,
_programs = [],
_programs_counter = 0,
// internal state cache
_currentProgram = null,
_currentFramebuffer = null,
_currentMaterialId = -1,
_currentGeometryGroupHash = null,
_currentCamera = null,
_geometryGroupCounter = 0,
_usedTextureUnits = 0,
// GL state cache
_oldDoubleSided = -1,
_oldFlipSided = -1,
_oldBlending = -1,
_oldBlendEquation = -1,
_oldBlendSrc = -1,
_oldBlendDst = -1,
_oldDepthTest = -1,
_oldDepthWrite = -1,
_oldPolygonOffset = null,
_oldPolygonOffsetFactor = null,
_oldPolygonOffsetUnits = null,
_oldLineWidth = null,
_viewportX = 0,
_viewportY = 0,
_viewportWidth = _canvas.width,
_viewportHeight = _canvas.height,
_currentWidth = 0,
_currentHeight = 0,
_enabledAttributes = {},
// frustum
_frustum = new THREE.Frustum(),
// camera matrices cache
_projScreenMatrix = new THREE.Matrix4(),
_projScreenMatrixPS = new THREE.Matrix4(),
_vector3 = new THREE.Vector3(),
// light arrays cache
_direction = new THREE.Vector3(),
_lightsNeedUpdate = true,
_lights = {
ambient: [ 0, 0, 0 ],
directional: { length: 0, colors: new Array(), positions: new Array() },
point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
};
// initialize
var _gl;
var _glExtensionTextureFloat;
var _glExtensionTextureFloatLinear;
var _glExtensionStandardDerivatives;
var _glExtensionTextureFilterAnisotropic;
var _glExtensionCompressedTextureS3TC;
initGL();
setDefaultGLState();
this.context = _gl;
// GPU capabilities
var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
var _supportsVertexTextures = ( _maxVertexTextures > 0 );
var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
//
var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
// clamp precision to maximum available
var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
if ( _precision === "highp" && ! highpAvailable ) {
if ( mediumpAvailable ) {
_precision = "mediump";
console.warn( "WebGLRenderer: highp not supported, using mediump" );
} else {
_precision = "lowp";
console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
}
}
if ( _precision === "mediump" && ! mediumpAvailable ) {
_precision = "lowp";
console.warn( "WebGLRenderer: mediump not supported, using lowp" );
}
// API
this.getContext = function () {
return _gl;
};
this.supportsVertexTextures = function () {
return _supportsVertexTextures;
};
this.supportsFloatTextures = function () {
return _glExtensionTextureFloat;
};
this.supportsStandardDerivatives = function () {
return _glExtensionStandardDerivatives;
};
this.supportsCompressedTextureS3TC = function () {
return _glExtensionCompressedTextureS3TC;
};
this.getMaxAnisotropy = function () {
return _maxAnisotropy;
};
this.getPrecision = function () {
return _precision;
};
this.setSize = function ( width, height, updateStyle ) {
_canvas.width = width * this.devicePixelRatio;
_canvas.height = height * this.devicePixelRatio;
if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
_canvas.style.width = width + 'px';
_canvas.style.height = height + 'px';
}
this.setViewport( 0, 0, _canvas.width, _canvas.height );
};
this.setViewport = function ( x, y, width, height ) {
_viewportX = x !== undefined ? x : 0;
_viewportY = y !== undefined ? y : 0;
_viewportWidth = width !== undefined ? width : _canvas.width;
_viewportHeight = height !== undefined ? height : _canvas.height;
_gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
};
this.setScissor = function ( x, y, width, height ) {
_gl.scissor( x, y, width, height );
};
this.enableScissorTest = function ( enable ) {
enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
};
// Clearing
this.setClearColor = function ( color, alpha ) {
_clearColor.set( color );
_clearAlpha = alpha !== undefined ? alpha : 1;
_gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
};
this.setClearColorHex = function ( hex, alpha ) {
console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
this.setClearColor( hex, alpha );
};
this.getClearColor = function () {
return _clearColor;
};
this.getClearAlpha = function () {
return _clearAlpha;
};
this.clear = function ( color, depth, stencil ) {
var bits = 0;
if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
_gl.clear( bits );
};
this.clearTarget = function ( renderTarget, color, depth, stencil ) {
this.setRenderTarget( renderTarget );
this.clear( color, depth, stencil );
};
// Plugins
this.addPostPlugin = function ( plugin ) {
plugin.init( this );
this.renderPluginsPost.push( plugin );
};
this.addPrePlugin = function ( plugin ) {
plugin.init( this );
this.renderPluginsPre.push( plugin );
};
// Rendering
this.updateShadowMap = function ( scene, camera ) {
_currentProgram = null;
_oldBlending = -1;
_oldDepthTest = -1;
_oldDepthWrite = -1;
_currentGeometryGroupHash = -1;
_currentMaterialId = -1;
_lightsNeedUpdate = true;
_oldDoubleSided = -1;
_oldFlipSided = -1;
this.shadowMapPlugin.update( scene, camera );
};
// Internal functions
// Buffer allocation
function createParticleBuffers ( geometry ) {
geometry.__webglVertexBuffer = _gl.createBuffer();
geometry.__webglColorBuffer = _gl.createBuffer();
_this.info.memory.geometries ++;
};
function createLineBuffers ( geometry ) {
geometry.__webglVertexBuffer = _gl.createBuffer();
geometry.__webglColorBuffer = _gl.createBuffer();
geometry.__webglLineDistanceBuffer = _gl.createBuffer();
_this.info.memory.geometries ++;
};
function createMeshBuffers ( geometryGroup ) {
geometryGroup.__webglVertexBuffer = _gl.createBuffer();
geometryGroup.__webglNormalBuffer = _gl.createBuffer();
geometryGroup.__webglTangentBuffer = _gl.createBuffer();
geometryGroup.__webglColorBuffer = _gl.createBuffer();
geometryGroup.__webglUVBuffer = _gl.createBuffer();
geometryGroup.__webglUV2Buffer = _gl.createBuffer();
geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
geometryGroup.__webglFaceBuffer = _gl.createBuffer();
geometryGroup.__webglLineBuffer = _gl.createBuffer();
var m, ml;
if ( geometryGroup.numMorphTargets ) {
geometryGroup.__webglMorphTargetsBuffers = [];
for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
}
}
if ( geometryGroup.numMorphNormals ) {
geometryGroup.__webglMorphNormalsBuffers = [];
for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
}
}
_this.info.memory.geometries ++;
};
// Events
var onGeometryDispose = function ( event ) {
var geometry = event.target;
geometry.removeEventListener( 'dispose', onGeometryDispose );
deallocateGeometry( geometry );
};
var onTextureDispose = function ( event ) {
var texture = event.target;
texture.removeEventListener( 'dispose', onTextureDispose );
deallocateTexture( texture );
_this.info.memory.textures --;
};
var onRenderTargetDispose = function ( event ) {
var renderTarget = event.target;
renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
deallocateRenderTarget( renderTarget );
_this.info.memory.textures --;
};
var onMaterialDispose = function ( event ) {
var material = event.target;
material.removeEventListener( 'dispose', onMaterialDispose );
deallocateMaterial( material );
};
// Buffer deallocation
var deleteBuffers = function ( geometry ) {
if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
// custom attributes
if ( geometry.__webglCustomAttributesList !== undefined ) {
for ( var id in geometry.__webglCustomAttributesList ) {
_gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
}
}
_this.info.memory.geometries --;
};
var deallocateGeometry = function ( geometry ) {
geometry.__webglInit = undefined;
if ( geometry instanceof THREE.BufferGeometry ) {
var attributes = geometry.attributes;
for ( var key in attributes ) {
if ( attributes[ key ].buffer !== undefined ) {
_gl.deleteBuffer( attributes[ key ].buffer );
}
}
_this.info.memory.geometries --;
} else {
if ( geometry.geometryGroups !== undefined ) {
for ( var g in geometry.geometryGroups ) {
var geometryGroup = geometry.geometryGroups[ g ];
if ( geometryGroup.numMorphTargets !== undefined ) {
for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
_gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
}
}
if ( geometryGroup.numMorphNormals !== undefined ) {
for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
_gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
}
}
deleteBuffers( geometryGroup );
}
} else {
deleteBuffers( geometry );
}
}
};
var deallocateTexture = function ( texture ) {
if ( texture.image && texture.image.__webglTextureCube ) {
// cube texture
_gl.deleteTexture( texture.image.__webglTextureCube );
} else {
// 2D texture
if ( ! texture.__webglInit ) return;
texture.__webglInit = false;
_gl.deleteTexture( texture.__webglTexture );
}
};
var deallocateRenderTarget = function ( renderTarget ) {
if ( !renderTarget || ! renderTarget.__webglTexture ) return;
_gl.deleteTexture( renderTarget.__webglTexture );
if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
for ( var i = 0; i < 6; i ++ ) {
_gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
_gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
}
} else {
_gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
_gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
}
};
var deallocateMaterial = function ( material ) {
var program = material.program;
if ( program === undefined ) return;
material.program = undefined;
// only deallocate GL program if this was the last use of shared program
// assumed there is only single copy of any program in the _programs list
// (that's how it's constructed)
var i, il, programInfo;
var deleteProgram = false;
for ( i = 0, il = _programs.length; i < il; i ++ ) {
programInfo = _programs[ i ];
if ( programInfo.program === program ) {
programInfo.usedTimes --;
if ( programInfo.usedTimes === 0 ) {
deleteProgram = true;
}
break;
}
}
if ( deleteProgram === true ) {
// avoid using array.splice, this is costlier than creating new array from scratch
var newPrograms = [];
for ( i = 0, il = _programs.length; i < il; i ++ ) {
programInfo = _programs[ i ];
if ( programInfo.program !== program ) {
newPrograms.push( programInfo );
}
}
_programs = newPrograms;
_gl.deleteProgram( program );
_this.info.memory.programs --;
}
};
// Buffer initialization
function initCustomAttributes ( geometry, object ) {
var nvertices = geometry.vertices.length;
var material = object.material;
if ( material.attributes ) {
if ( geometry.__webglCustomAttributesList === undefined ) {
geometry.__webglCustomAttributesList = [];
}
for ( var a in material.attributes ) {
var attribute = material.attributes[ a ];
if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
attribute.__webglInitialized = true;
var size = 1; // "f" and "i"
if ( attribute.type === "v2" ) size = 2;
else if ( attribute.type === "v3" ) size = 3;
else if ( attribute.type === "v4" ) size = 4;
else if ( attribute.type === "c" ) size = 3;
attribute.size = size;
attribute.array = new Float32Array( nvertices * size );
attribute.buffer = _gl.createBuffer();
attribute.buffer.belongsToAttribute = a;
attribute.needsUpdate = true;
}
geometry.__webglCustomAttributesList.push( attribute );
}
}
};
function initParticleBuffers ( geometry, object ) {
var nvertices = geometry.vertices.length;
geometry.__vertexArray = new Float32Array( nvertices * 3 );
geometry.__colorArray = new Float32Array( nvertices * 3 );
geometry.__sortArray = [];
geometry.__webglParticleCount = nvertices;
initCustomAttributes ( geometry, object );
};
function initLineBuffers ( geometry, object ) {
var nvertices = geometry.vertices.length;
geometry.__vertexArray = new Float32Array( nvertices * 3 );
geometry.__colorArray = new Float32Array( nvertices * 3 );
geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
geometry.__webglLineCount = nvertices;
initCustomAttributes ( geometry, object );
};
function initMeshBuffers ( geometryGroup, object ) {
var geometry = object.geometry,
faces3 = geometryGroup.faces3,
nvertices = faces3.length * 3,
ntris = faces3.length * 1,
nlines = faces3.length * 3,
material = getBufferMaterial( object, geometryGroup ),
uvType = bufferGuessUVType( material ),
normalType = bufferGuessNormalType( material ),
vertexColorType = bufferGuessVertexColorType( material );
// console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
if ( normalType ) {
geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
}
if ( geometry.hasTangents ) {
geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
}
if ( vertexColorType ) {
geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
}
if ( uvType ) {
if ( geometry.faceVertexUvs.length > 0 ) {
geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
}
if ( geometry.faceVertexUvs.length > 1 ) {
geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
}
}
if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
}
geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
var m, ml;
if ( geometryGroup.numMorphTargets ) {
geometryGroup.__morphTargetsArrays = [];
for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
}
}
if ( geometryGroup.numMorphNormals ) {
geometryGroup.__morphNormalsArrays = [];
for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
}
}
geometryGroup.__webglFaceCount = ntris * 3;
geometryGroup.__webglLineCount = nlines * 2;
// custom attributes
if ( material.attributes ) {
if ( geometryGroup.__webglCustomAttributesList === undefined ) {
geometryGroup.__webglCustomAttributesList = [];
}
for ( var a in material.attributes ) {
// Do a shallow copy of the attribute object so different geometryGroup chunks use different
// attribute buffers which are correctly indexed in the setMeshBuffers function
var originalAttribute = material.attributes[ a ];
var attribute = {};
for ( var property in originalAttribute ) {
attribute[ property ] = originalAttribute[ property ];
}
if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
attribute.__webglInitialized = true;
var size = 1; // "f" and "i"
if( attribute.type === "v2" ) size = 2;
else if( attribute.type === "v3" ) size = 3;
else if( attribute.type === "v4" ) size = 4;
else if( attribute.type === "c" ) size = 3;
attribute.size = size;
attribute.array = new Float32Array( nvertices * size );
attribute.buffer = _gl.createBuffer();
attribute.buffer.belongsToAttribute = a;
originalAttribute.needsUpdate = true;
attribute.__original = originalAttribute;
}
geometryGroup.__webglCustomAttributesList.push( attribute );
}
}
geometryGroup.__inittedArrays = true;
};
function getBufferMaterial( object, geometryGroup ) {
return object.material instanceof THREE.MeshFaceMaterial
? object.material.materials[ geometryGroup.materialIndex ]
: object.material;
};
function materialNeedsSmoothNormals ( material ) {
return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
};
function bufferGuessNormalType ( material ) {
// only MeshBasicMaterial and MeshDepthMaterial don't need normals
if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
return false;
}
if ( materialNeedsSmoothNormals( material ) ) {
return THREE.SmoothShading;
} else {
return THREE.FlatShading;
}
};
function bufferGuessVertexColorType( material ) {
if ( material.vertexColors ) {
return material.vertexColors;
}
return false;
};
function bufferGuessUVType( material ) {
// material must use some texture to require uvs
if ( material.map ||
material.lightMap ||
material.bumpMap ||
material.normalMap ||
material.specularMap ||
material instanceof THREE.ShaderMaterial ) {
return true;
}
return false;
};
//
function initDirectBuffers( geometry ) {
var a, attribute, type;
for ( a in geometry.attributes ) {
if ( a === "index" ) {
type = _gl.ELEMENT_ARRAY_BUFFER;
} else {
type = _gl.ARRAY_BUFFER;
}
attribute = geometry.attributes[ a ];
if ( attribute.numItems === undefined ) {
attribute.numItems = attribute.array.length;
}
attribute.buffer = _gl.createBuffer();
_gl.bindBuffer( type, attribute.buffer );
_gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
}
};
// Buffer setting
function setParticleBuffers ( geometry, hint, object ) {
var v, c, vertex, offset, index, color,
vertices = geometry.vertices,
vl = vertices.length,
colors = geometry.colors,
cl = colors.length,
vertexArray = geometry.__vertexArray,
colorArray = geometry.__colorArray,
sortArray = geometry.__sortArray,
dirtyVertices = geometry.verticesNeedUpdate,
dirtyElements = geometry.elementsNeedUpdate,
dirtyColors = geometry.colorsNeedUpdate,
customAttributes = geometry.__webglCustomAttributesList,
i, il,
a, ca, cal, value,
customAttribute;
if ( object.sortParticles ) {
_projScreenMatrixPS.copy( _projScreenMatrix );
_projScreenMatrixPS.multiply( object.matrixWorld );
for ( v = 0; v < vl; v ++ ) {
vertex = vertices[ v ];
_vector3.copy( vertex );
_vector3.applyProjection( _projScreenMatrixPS );
sortArray[ v ] = [ _vector3.z, v ];
}
sortArray.sort( numericalSort );
for ( v = 0; v < vl; v ++ ) {
vertex = vertices[ sortArray[v][1] ];
offset = v * 3;
vertexArray[ offset ] = vertex.x;
vertexArray[ offset + 1 ] = vertex.y;
vertexArray[ offset + 2 ] = vertex.z;
}
for ( c = 0; c < cl; c ++ ) {
offset = c * 3;
color = colors[ sortArray[c][1] ];
colorArray[ offset ] = color.r;
colorArray[ offset + 1 ] = color.g;
colorArray[ offset + 2 ] = color.b;
}
if ( customAttributes ) {
for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
customAttribute = customAttributes[ i ];
if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
offset = 0;
cal = customAttribute.value.length;
if ( customAttribute.size === 1 ) {
for ( ca = 0; ca < cal; ca ++ ) {
index = sortArray[ ca ][ 1 ];
customAttribute.array[ ca ] = customAttribute.value[ index ];
}
} else if ( customAttribute.size === 2 ) {
for ( ca = 0; ca < cal; ca ++ ) {
index = sortArray[ ca ][ 1 ];
value = customAttribute.value[ index ];
customAttribute.array[ offset ] = value.x;
customAttribute.array[ offset + 1 ] = value.y;
offset += 2;
}
} else if ( customAttribute.size === 3 ) {
if ( customAttribute.type === "c" ) {
for ( ca = 0; ca < cal; ca ++ ) {
index = sortArray[ ca ][ 1 ];
value = customAttribute.value[ index ];
customAttribute.array[ offset ] = value.r;
customAttribute.array[ offset + 1 ] = value.g;
customAttribute.array[ offset + 2 ] = value.b;
offset += 3;
}
} else {
for ( ca = 0; ca < cal; ca ++ ) {
index = sortArray[ ca ][ 1 ];
value = customAttribute.value[ index ];
customAttribute.array[ offset ] = value.x;
customAttribute.array[ offset + 1 ] = value.y;
customAttribute.array[ offset + 2 ] = value.z;
offset += 3;
}
}
} else if ( customAttribute.size === 4 ) {
for ( ca = 0; ca < cal; ca ++ ) {
index = sortArray[ ca ][ 1 ];
value = customAttribute.value[ index ];
customAttribute.array[ offset ] = value.x;
customAttribute.array[ offset + 1 ] = value.y;
customAttribute.array[ offset + 2 ] = value.z;
customAttribute.array[ offset + 3 ] = value.w;
offset += 4;
}
}
}
}
} else {
if ( dirtyVertices ) {
for ( v = 0; v < vl; v ++ ) {
vertex = vertices[ v ];
offset = v * 3;
vertexArray[ offset ] = vertex.x;
vertexArray[ offset + 1 ] = vertex.y;
vertexArray[ offset + 2 ] = vertex.z;
}
}
if ( dirtyColors ) {
for ( c = 0; c < cl; c ++ ) {
color = colors[ c ];
offset = c * 3;
colorArray[ offset ] = color.r;
colorArray[ offset + 1 ] = color.g;
colorArray[ offset + 2 ] = color.b;
}
}
if ( customAttributes ) {
for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
customAttribute = customAttributes[ i ];
if ( customAttribute.needsUpdate &&
( customAttribute.boundTo === undefined ||
customAttribute.boundTo === "vertices") ) {
cal = customAttribute.value.length;
offset = 0;
if ( customAttribute.size === 1 ) {
for ( ca = 0; ca < cal; ca ++ ) {
customAttribute.array[ ca ] = customAttribute.value[ ca ];
}
} else if ( customAttribute.size === 2 ) {
for ( ca = 0; ca < cal; ca ++ ) {
value = customAttribute.value[ ca ];
customAttribute.array[ offset ] = value.x;
customAttribute.array[ offset + 1 ] = value.y;
offset += 2;
}
} else if ( customAttribute.size === 3 ) {
if ( customAttribute.type === "c" ) {
for ( ca = 0; ca < cal; ca ++ ) {
value = customAttribute.value[ ca ];
customAttribute.array[ offset ] = value.r;
customAttribute.array[ offset + 1 ] = value.g;
customAttribute.array[ offset + 2 ] = value.b;
offset += 3;
}
} else {
for ( ca = 0; ca < cal; ca ++ ) {
value = customAttribute.value[ ca ];
customAttribute.array[ offset ] = value.x;
customAttribute.array[ offset + 1 ] = value.y;
customAttribute.array[ offset + 2 ] = value.z;
offset += 3;
}
}
} else if ( customAttribute.size === 4 ) {
for ( ca = 0; ca < cal; ca ++ ) {
value = customAttribute.value[ ca ];
customAttribute.array[ offset ] = value.x;
customAttribute.array[ offset + 1 ] = value.y;
customAttribute.array[ offset + 2 ] = value.z;
customAttribute.array[ offset + 3 ] = value.w;
offset += 4;
}
}
}
}
}
}
if ( dirtyVertices || object.sortParticles ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
}
if ( dirtyColors || object.sortParticles ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
}
if ( customAttributes ) {
for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
customAttribute = customAttributes[ i ];
if ( customAttribute.needsUpdate || object.sortParticles ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
_gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
}
}
}
};
function setLineBuffers ( geometry, hint ) {
var v, c, d, vertex, offset, color,
vertices = geometry.vertices,
colors = geometry.colors,
lineDistances = geometry.lineDistances,
vl = vertices.length,
cl = colors.length,
dl = lineDistances.length,
vertexArray = geometry.__vertexArray,
colorArray = geometry.__colorArray,
lineDistanceArray = geometry.__lineDistanceArray,
dirtyVertices = geometry.verticesNeedUpdate,
dirtyColors = geometry.colorsNeedUpdate,
dirtyLineDistances = geometry.lineDistancesNeedUpdate,
customAttributes = geometry.__webglCustomAttributesList,
i, il,
a, ca, cal, value,
customAttribute;
if ( dirtyVertices ) {
for ( v = 0; v < vl; v ++ ) {
vertex = vertices[ v ];
offset = v * 3;
vertexArray[ offset ] = vertex.x;
vertexArray[ offset + 1 ] = vertex.y;
vertexArray[ offset + 2 ] = vertex.z;
}
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
}
if ( dirtyColors ) {
for ( c = 0; c < cl; c ++ ) {
color = colors[ c ];
offset = c * 3;
colorArray[ offset ] = color.r;
colorArray[ offset + 1 ] = color.g;
colorArray[ offset + 2 ] = color.b;
}
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
}
if ( dirtyLineDistances ) {
for ( d = 0; d < dl; d ++ ) {
lineDistanceArray[ d ] = lineDistances[ d ];
}
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
}
if ( customAttributes ) {
for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
customAttribute = customAttributes[ i ];
if ( customAttribute.needsUpdate &&
( customAttribute.boundTo === undefined ||
customAttribute.boundTo === "vertices" ) ) {
offset = 0;
cal = customAttribute.value.length;
if ( customAttribute.size === 1 ) {
for ( ca = 0; ca < cal; ca ++ ) {
customAttribute.array[ ca ] = customAttribute.value[ ca ];
}
} else if ( customAttribute.size === 2 ) {
for ( ca = 0; ca < cal; ca ++ ) {
value = customAttribute.value[ ca ];
customAttribute.array[ offset ] = value.x;
customAttribute.array[ offset + 1 ] = value.y;
offset += 2;
}
} else if ( customAttribute.size === 3 ) {
if ( customAttribute.type === "c" ) {
for ( ca = 0; ca < cal; ca ++ ) {
value = customAttribute.value[ ca ];
customAttribute.array[ offset ] = value.r;
customAttribute.array[ offset + 1 ] = value.g;
customAttribute.array[ offset + 2 ] = value.b;
offset += 3;
}
} else {
for ( ca = 0; ca < cal; ca ++ ) {
value = customAttribute.value[ ca ];
customAttribute.array[ offset ] = value.x;
customAttribute.array[ offset + 1 ] = value.y;
customAttribute.array[ offset + 2 ] = value.z;
offset += 3;
}
}
} else if ( customAttribute.size === 4 ) {
for ( ca = 0; ca < cal; ca ++ ) {
value = customAttribute.value[ ca ];
customAttribute.array[ offset ] = value.x;
customAttribute.array[ offset + 1 ] = value.y;
customAttribute.array[ offset + 2 ] = value.z;
customAttribute.array[ offset + 3 ] = value.w;
offset += 4;
}
}
_gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
_gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
}
}
}
};
function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
if ( ! geometryGroup.__inittedArrays ) {
return;
}
var normalType = bufferGuessNormalType( material ),
vertexColorType = bufferGuessVertexColorType( material ),
uvType = bufferGuessUVType( material ),
needsSmoothNormals = ( normalType === THREE.SmoothShading );
var f, fl, fi, face,
vertexNormals, faceNormal, normal,
vertexColors, faceColor,
vertexTangents,
uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
c1, c2, c3, c4,
sw1, sw2, sw3, sw4,
si1, si2, si3, si4,
sa1, sa2, sa3, sa4,
sb1, sb2, sb3, sb4,
m, ml, i, il,
vn, uvi, uv2i,
vk, vkl, vka,
nka, chf, faceVertexNormals,
a,
vertexIndex = 0,
offset = 0,
offset_uv = 0,
offset_uv2 = 0,
offset_face = 0,
offset_normal = 0,
offset_tangent = 0,
offset_line = 0,
offset_color = 0,
offset_skin = 0,
offset_morphTarget = 0,
offset_custom = 0,
offset_customSrc = 0,
value,
vertexArray = geometryGroup.__vertexArray,
uvArray = geometryGroup.__uvArray,
uv2Array = geometryGroup.__uv2Array,
normalArray = geometryGroup.__normalArray,
tangentArray = geometryGroup.__tangentArray,
colorArray = geometryGroup.__colorArray,
skinIndexArray = geometryGroup.__skinIndexArray,
skinWeightArray = geometryGroup.__skinWeightArray,
morphTargetsArrays = geometryGroup.__morphTargetsArrays,
morphNormalsArrays = geometryGroup.__morphNormalsArrays,
customAttributes = geometryGroup.__webglCustomAttributesList,
customAttribute,
faceArray = geometryGroup.__faceArray,
lineArray = geometryGroup.__lineArray,
geometry = object.geometry, // this is shared for all chunks
dirtyVertices = geometry.verticesNeedUpdate,
dirtyElements = geometry.elementsNeedUpdate,
dirtyUvs = geometry.uvsNeedUpdate,
dirtyNormals = geometry.normalsNeedUpdate,
dirtyTangents = geometry.tangentsNeedUpdate,
dirtyColors = geometry.colorsNeedUpdate,
dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
vertices = geometry.vertices,
chunk_faces3 = geometryGroup.faces3,
obj_faces = geometry.faces,
obj_uvs = geometry.faceVertexUvs[ 0 ],
obj_uvs2 = geometry.faceVertexUvs[ 1 ],
obj_colors = geometry.colors,
obj_skinIndices = geometry.skinIndices,
obj_skinWeights = geometry.skinWeights,
morphTargets = geometry.morphTargets,
morphNormals = geometry.morphNormals;
if ( dirtyVertices ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
face = obj_faces[ chunk_faces3[ f ] ];
v1 = vertices[ face.a ];
v2 = vertices[ face.b ];
v3 = vertices[ face.c ];
vertexArray[ offset ] = v1.x;
vertexArray[ offset + 1 ] = v1.y;
vertexArray[ offset + 2 ] = v1.z;
vertexArray[ offset + 3 ] = v2.x;
vertexArray[ offset + 4 ] = v2.y;
vertexArray[ offset + 5 ] = v2.z;
vertexArray[ offset + 6 ] = v3.x;
vertexArray[ offset + 7 ] = v3.y;
vertexArray[ offset + 8 ] = v3.z;
offset += 9;
}
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
}
if ( dirtyMorphTargets ) {
for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
offset_morphTarget = 0;
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
chf = chunk_faces3[ f ];
face = obj_faces[ chf ];
// morph positions
v1 = morphTargets[ vk ].vertices[ face.a ];
v2 = morphTargets[ vk ].vertices[ face.b ];
v3 = morphTargets[ vk ].vertices[ face.c ];
vka = morphTargetsArrays[ vk ];
vka[ offset_morphTarget ] = v1.x;
vka[ offset_morphTarget + 1 ] = v1.y;
vka[ offset_morphTarget + 2 ] = v1.z;
vka[ offset_morphTarget + 3 ] = v2.x;
vka[ offset_morphTarget + 4 ] = v2.y;
vka[ offset_morphTarget + 5 ] = v2.z;
vka[ offset_morphTarget + 6 ] = v3.x;
vka[ offset_morphTarget + 7 ] = v3.y;
vka[ offset_morphTarget + 8 ] = v3.z;
// morph normals
if ( material.morphNormals ) {
if ( needsSmoothNormals ) {
faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
n1 = faceVertexNormals.a;
n2 = faceVertexNormals.b;
n3 = faceVertexNormals.c;
} else {
n1 = morphNormals[ vk ].faceNormals[ chf ];
n2 = n1;
n3 = n1;
}
nka = morphNormalsArrays[ vk ];
nka[ offset_morphTarget ] = n1.x;
nka[ offset_morphTarget + 1 ] = n1.y;
nka[ offset_morphTarget + 2 ] = n1.z;
nka[ offset_morphTarget + 3 ] = n2.x;
nka[ offset_morphTarget + 4 ] = n2.y;
nka[ offset_morphTarget + 5 ] = n2.z;
nka[ offset_morphTarget + 6 ] = n3.x;
nka[ offset_morphTarget + 7 ] = n3.y;
nka[ offset_morphTarget + 8 ] = n3.z;
}
//
offset_morphTarget += 9;
}
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
_gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
if ( material.morphNormals ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
_gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
}
}
}
if ( obj_skinWeights.length ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
face = obj_faces[ chunk_faces3[ f ] ];
// weights
sw1 = obj_skinWeights[ face.a ];
sw2 = obj_skinWeights[ face.b ];
sw3 = obj_skinWeights[ face.c ];
skinWeightArray[ offset_skin ] = sw1.x;
skinWeightArray[ offset_skin + 1 ] = sw1.y;
skinWeightArray[ offset_skin + 2 ] = sw1.z;
skinWeightArray[ offset_skin + 3 ] = sw1.w;
skinWeightArray[ offset_skin + 4 ] = sw2.x;
skinWeightArray[ offset_skin + 5 ] = sw2.y;
skinWeightArray[ offset_skin + 6 ] = sw2.z;
skinWeightArray[ offset_skin + 7 ] = sw2.w;
skinWeightArray[ offset_skin + 8 ] = sw3.x;
skinWeightArray[ offset_skin + 9 ] = sw3.y;
skinWeightArray[ offset_skin + 10 ] = sw3.z;
skinWeightArray[ offset_skin + 11 ] = sw3.w;
// indices
si1 = obj_skinIndices[ face.a ];
si2 = obj_skinIndices[ face.b ];
si3 = obj_skinIndices[ face.c ];
skinIndexArray[ offset_skin ] = si1.x;
skinIndexArray[ offset_skin + 1 ] = si1.y;
skinIndexArray[ offset_skin + 2 ] = si1.z;
skinIndexArray[ offset_skin + 3 ] = si1.w;
skinIndexArray[ offset_skin + 4 ] = si2.x;
skinIndexArray[ offset_skin + 5 ] = si2.y;
skinIndexArray[ offset_skin + 6 ] = si2.z;
skinIndexArray[ offset_skin + 7 ] = si2.w;
skinIndexArray[ offset_skin + 8 ] = si3.x;
skinIndexArray[ offset_skin + 9 ] = si3.y;
skinIndexArray[ offset_skin + 10 ] = si3.z;
skinIndexArray[ offset_skin + 11 ] = si3.w;
offset_skin += 12;
}
if ( offset_skin > 0 ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
}
}
if ( dirtyColors && vertexColorType ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
face = obj_faces[ chunk_faces3[ f ] ];
vertexColors = face.vertexColors;
faceColor = face.color;
if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
c1 = vertexColors[ 0 ];
c2 = vertexColors[ 1 ];
c3 = vertexColors[ 2 ];
} else {
c1 = faceColor;
c2 = faceColor;
c3 = faceColor;
}
colorArray[ offset_color ] = c1.r;
colorArray[ offset_color + 1 ] = c1.g;
colorArray[ offset_color + 2 ] = c1.b;
colorArray[ offset_color + 3 ] = c2.r;
colorArray[ offset_color + 4 ] = c2.g;
colorArray[ offset_color + 5 ] = c2.b;
colorArray[ offset_color + 6 ] = c3.r;
colorArray[ offset_color + 7 ] = c3.g;
colorArray[ offset_color + 8 ] = c3.b;
offset_color += 9;
}
if ( offset_color > 0 ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
}
}
if ( dirtyTangents && geometry.hasTangents ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
face = obj_faces[ chunk_faces3[ f ] ];
vertexTangents = face.vertexTangents;
t1 = vertexTangents[ 0 ];
t2 = vertexTangents[ 1 ];
t3 = vertexTangents[ 2 ];
tangentArray[ offset_tangent ] = t1.x;
tangentArray[ offset_tangent + 1 ] = t1.y;
tangentArray[ offset_tangent + 2 ] = t1.z;
tangentArray[ offset_tangent + 3 ] = t1.w;
tangentArray[ offset_tangent + 4 ] = t2.x;
tangentArray[ offset_tangent + 5 ] = t2.y;
tangentArray[ offset_tangent + 6 ] = t2.z;
tangentArray[ offset_tangent + 7 ] = t2.w;
tangentArray[ offset_tangent + 8 ] = t3.x;
tangentArray[ offset_tangent + 9 ] = t3.y;
tangentArray[ offset_tangent + 10 ] = t3.z;
tangentArray[ offset_tangent + 11 ] = t3.w;
offset_tangent += 12;
}
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
}
if ( dirtyNormals && normalType ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
face = obj_faces[ chunk_faces3[ f ] ];
vertexNormals = face.vertexNormals;
faceNormal = face.normal;
if ( vertexNormals.length === 3 && needsSmoothNormals ) {
for ( i = 0; i < 3; i ++ ) {
vn = vertexNormals[ i ];
normalArray[ offset_normal ] = vn.x;
normalArray[ offset_normal + 1 ] = vn.y;
normalArray[ offset_normal + 2 ] = vn.z;
offset_normal += 3;
}
} else {
for ( i = 0; i < 3; i ++ ) {
normalArray[ offset_normal ] = faceNormal.x;
normalArray[ offset_normal + 1 ] = faceNormal.y;
normalArray[ offset_normal + 2 ] = faceNormal.z;
offset_normal += 3;
}
}
}
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
}
if ( dirtyUvs && obj_uvs && uvType ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
fi = chunk_faces3[ f ];
uv = obj_uvs[ fi ];
if ( uv === undefined ) continue;
for ( i = 0; i < 3; i ++ ) {
uvi = uv[ i ];
uvArray[ offset_uv ] = uvi.x;
uvArray[ offset_uv + 1 ] = uvi.y;
offset_uv += 2;
}
}
if ( offset_uv > 0 ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
}
}
if ( dirtyUvs && obj_uvs2 && uvType ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
fi = chunk_faces3[ f ];
uv2 = obj_uvs2[ fi ];
if ( uv2 === undefined ) continue;
for ( i = 0; i < 3; i ++ ) {
uv2i = uv2[ i ];
uv2Array[ offset_uv2 ] = uv2i.x;
uv2Array[ offset_uv2 + 1 ] = uv2i.y;
offset_uv2 += 2;
}
}
if ( offset_uv2 > 0 ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
_gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
}
}
if ( dirtyElements ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
faceArray[ offset_face ] = vertexIndex;
faceArray[ offset_face + 1 ] = vertexIndex + 1;
faceArray[ offset_face + 2 ] = vertexIndex + 2;
offset_face += 3;
lineArray[ offset_line ] = vertexIndex;
lineArray[ offset_line + 1 ] = vertexIndex + 1;
lineArray[ offset_line + 2 ] = vertexIndex;
lineArray[ offset_line + 3 ] = vertexIndex + 2;
lineArray[ offset_line + 4 ] = vertexIndex + 1;
lineArray[ offset_line + 5 ] = vertexIndex + 2;
offset_line += 6;
vertexIndex += 3;
}
_gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
_gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
_gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
_gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
}
if ( customAttributes ) {
for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
customAttribute = customAttributes[ i ];
if ( ! customAttribute.__original.needsUpdate ) continue;
offset_custom = 0;
offset_customSrc = 0;
if ( customAttribute.size === 1 ) {
if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
face = obj_faces[ chunk_faces3[ f ] ];
customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
offset_custom += 3;
}
} else if ( customAttribute.boundTo === "faces" ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
value = customAttribute.value[ chunk_faces3[ f ] ];
customAttribute.array[ offset_custom ] = value;
customAttribute.array[ offset_custom + 1 ] = value;
customAttribute.array[ offset_custom + 2 ] = value;
offset_custom += 3;
}
}
} else if ( customAttribute.size === 2 ) {
if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
face = obj_faces[ chunk_faces3[ f ] ];
v1 = customAttribute.value[ face.a ];
v2 = customAttribute.value[ face.b ];
v3 = customAttribute.value[ face.c ];
customAttribute.array[ offset_custom ] = v1.x;
customAttribute.array[ offset_custom + 1 ] = v1.y;
customAttribute.array[ offset_custom + 2 ] = v2.x;
customAttribute.array[ offset_custom + 3 ] = v2.y;
customAttribute.array[ offset_custom + 4 ] = v3.x;
customAttribute.array[ offset_custom + 5 ] = v3.y;
offset_custom += 6;
}
} else if ( customAttribute.boundTo === "faces" ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
value = customAttribute.value[ chunk_faces3[ f ] ];
v1 = value;
v2 = value;
v3 = value;
customAttribute.array[ offset_custom ] = v1.x;
customAttribute.array[ offset_custom + 1 ] = v1.y;
customAttribute.array[ offset_custom + 2 ] = v2.x;
customAttribute.array[ offset_custom + 3 ] = v2.y;
customAttribute.array[ offset_custom + 4 ] = v3.x;
customAttribute.array[ offset_custom + 5 ] = v3.y;
offset_custom += 6;
}
}
} else if ( customAttribute.size === 3 ) {
var pp;
if ( customAttribute.type === "c" ) {
pp = [ "r", "g", "b" ];
} else {
pp = [ "x", "y", "z" ];
}
if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
face = obj_faces[ chunk_faces3[ f ] ];
v1 = customAttribute.value[ face.a ];
v2 = customAttribute.value[ face.b ];
v3 = customAttribute.value[ face.c ];
customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
offset_custom += 9;
}
} else if ( customAttribute.boundTo === "faces" ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
value = customAttribute.value[ chunk_faces3[ f ] ];
v1 = value;
v2 = value;
v3 = value;
customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
offset_custom += 9;
}
} else if ( customAttribute.boundTo === "faceVertices" ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
value = customAttribute.value[ chunk_faces3[ f ] ];
v1 = value[ 0 ];
v2 = value[ 1 ];
v3 = value[ 2 ];
customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
offset_custom += 9;
}
}
} else if ( customAttribute.size === 4 ) {
if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
face = obj_faces[ chunk_faces3[ f ] ];
v1 = customAttribute.value[ face.a ];
v2 = customAttribute.value[ face.b ];
v3 = customAttribute.value[ face.c ];
customAttribute.array[ offset_custom ] = v1.x;
customAttribute.array[ offset_custom + 1 ] = v1.y;
customAttribute.array[ offset_custom + 2 ] = v1.z;
customAttribute.array[ offset_custom + 3 ] = v1.w;
customAttribute.array[ offset_custom + 4 ] = v2.x;
customAttribute.array[ offset_custom + 5 ] = v2.y;
customAttribute.array[ offset_custom + 6 ] = v2.z;
customAttribute.array[ offset_custom + 7 ] = v2.w;
customAttribute.array[ offset_custom + 8 ] = v3.x;
customAttribute.array[ offset_custom + 9 ] = v3.y;
customAttribute.array[ offset_custom + 10 ] = v3.z;
customAttribute.array[ offset_custom + 11 ] = v3.w;
offset_custom += 12;
}
} else if ( customAttribute.boundTo === "faces" ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
value = customAttribute.value[ chunk_faces3[ f ] ];
v1 = value;
v2 = value;
v3 = value;
customAttribute.array[ offset_custom ] = v1.x;
customAttribute.array[ offset_custom + 1 ] = v1.y;
customAttribute.array[ offset_custom + 2 ] = v1.z;
customAttribute.array[ offset_custom + 3 ] = v1.w;
customAttribute.array[ offset_custom + 4 ] = v2.x;
customAttribute.array[ offset_custom + 5 ] = v2.y;
customAttribute.array[ offset_custom + 6 ] = v2.z;
customAttribute.array[ offset_custom + 7 ] = v2.w;
customAttribute.array[ offset_custom + 8 ] = v3.x;
customAttribute.array[ offset_custom + 9 ] = v3.y;
customAttribute.array[ offset_custom + 10 ] = v3.z;
customAttribute.array[ offset_custom + 11 ] = v3.w;
offset_custom += 12;
}
} else if ( customAttribute.boundTo === "faceVertices" ) {
for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
value = customAttribute.value[ chunk_faces3[ f ] ];
v1 = value[ 0 ];
v2 = value[ 1 ];
v3 = value[ 2 ];
customAttribute.array[ offset_custom ] = v1.x;
customAttribute.array[ offset_custom + 1 ] = v1.y;
customAttribute.array[ offset_custom + 2 ] = v1.z;
customAttribute.array[ offset_custom + 3 ] = v1.w;
customAttribute.array[ offset_custom + 4 ] = v2.x;
customAttribute.array[ offset_custom + 5 ] = v2.y;
customAttribute.array[ offset_custom + 6 ] = v2.z;
customAttribute.array[ offset_custom + 7 ] = v2.w;
customAttribute.array[ offset_custom + 8 ] = v3.x;
customAttribute.array[ offset_custom + 9 ] = v3.y;
customAttribute.array[ offset_custom + 10 ] = v3.z;
customAttribute.array[ offset_custom + 11 ] = v3.w;
offset_custom += 12;
}
}
}
_gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
_gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
}
}
if ( dispose ) {
delete geometryGroup.__inittedArrays;
delete geometryGroup.__colorArray;
delete geometryGroup.__normalArray;
delete geometryGroup.__tangentArray;
delete geometryGroup.__uvArray;
delete geometryGroup.__uv2Array;
delete geometryGroup.__faceArray;
delete geometryGroup.__vertexArray;
delete geometryGroup.__lineArray;
delete geometryGroup.__skinIndexArray;
delete geometryGroup.__skinWeightArray;
}
};
function setDirectBuffers ( geometry, hint, dispose ) {
var attributes = geometry.attributes;
var attributeName, attributeItem;
for ( attributeName in attributes ) {
attributeItem = attributes[ attributeName ];
if ( attributeItem.needsUpdate ) {
if ( attributeName === 'index' ) {
_gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.buffer );
_gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.array, hint );
} else {
_gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
_gl.bufferData( _gl.ARRAY_BUFFER, attributeItem.array, hint );
}
attributeItem.needsUpdate = false;
}
if ( dispose && ! attributeItem.dynamic ) {
attributeItem.array = null;
}
}
};
// Buffer rendering
this.renderBufferImmediate = function ( object, program, material ) {
if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
if ( object.hasPositions ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
_gl.enableVertexAttribArray( program.attributes.position );
_gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
}
if ( object.hasNormals ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
if ( material.shading === THREE.FlatShading ) {
var nx, ny, nz,
nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
normalArray,
i, il = object.count * 3;
for( i = 0; i < il; i += 9 ) {
normalArray = object.normalArray;
nax = normalArray[ i ];
nay = normalArray[ i + 1 ];
naz = normalArray[ i + 2 ];
nbx = normalArray[ i + 3 ];
nby = normalArray[ i + 4 ];
nbz = normalArray[ i + 5 ];
ncx = normalArray[ i + 6 ];
ncy = normalArray[ i + 7 ];
ncz = normalArray[ i + 8 ];
nx = ( nax + nbx + ncx ) / 3;
ny = ( nay + nby + ncy ) / 3;
nz = ( naz + nbz + ncz ) / 3;
normalArray[ i ] = nx;
normalArray[ i + 1 ] = ny;
normalArray[ i + 2 ] = nz;
normalArray[ i + 3 ] = nx;
normalArray[ i + 4 ] = ny;
normalArray[ i + 5 ] = nz;
normalArray[ i + 6 ] = nx;
normalArray[ i + 7 ] = ny;
normalArray[ i + 8 ] = nz;
}
}
_gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
_gl.enableVertexAttribArray( program.attributes.normal );
_gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
}
if ( object.hasUvs && material.map ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
_gl.enableVertexAttribArray( program.attributes.uv );
_gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
}
if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
_gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
_gl.enableVertexAttribArray( program.attributes.color );
_gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
}
_gl.drawArrays( _gl.TRIANGLES, 0, object.count );
object.count = 0;
};
this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
if ( material.visible === false ) return;
var linewidth, a, attribute;
var attributeItem, attributeName, attributePointer, attributeSize;
var program = setProgram( camera, lights, fog, material, object );
var programAttributes = program.attributes;
var geometryAttributes = geometry.attributes;
var updateBuffers = false,
wireframeBit = material.wireframe ? 1 : 0,
geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
if ( geometryHash !== _currentGeometryGroupHash ) {
_currentGeometryGroupHash = geometryHash;
updateBuffers = true;
}
if ( updateBuffers ) {
disableAttributes();
}
// render mesh
if ( object instanceof THREE.Mesh ) {
var index = geometryAttributes[ "index" ];
// indexed triangles
if ( index ) {
var offsets = geometry.offsets;
// if there is more than 1 chunk
// must set attribute pointers to use new offsets for each chunk
// even if geometry and materials didn't change
if ( offsets.length > 1 ) updateBuffers = true;
for ( var i = 0, il = offsets.length; i < il; i ++ ) {
var startIndex = offsets[ i ].index;
if ( updateBuffers ) {
for ( attributeName in programAttributes ) {
attributePointer = programAttributes[ attributeName ];
attributeItem = geometryAttributes[ attributeName ];
if ( attributePointer >= 0 ) {
if ( attributeItem ) {
attributeSize = attributeItem.itemSize;
_gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
enableAttribute( attributePointer );
_gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
} else if ( material.defaultAttributeValues ) {
if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
_gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
} else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
_gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
}
}
}
}
// indices
_gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
}
// render indexed triangles
_gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
_this.info.render.calls ++;
_this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
_this.info.render.faces += offsets[ i ].count / 3;
}
// non-indexed triangles
} else {
if ( updateBuffers ) {
for ( attributeName in programAttributes ) {
if ( attributeName === 'index') continue;
attributePointer = programAttributes[ attributeName ];
attributeItem = geometryAttributes[ attributeName ];
if ( attributePointer >= 0 ) {
if ( attributeItem ) {
attributeSize = attributeItem.itemSize;
_gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
enableAttribute( attributePointer );
_gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
} else if ( material.defaultAttributeValues && material.defaultAttributeValues[ attributeName ] ) {
if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
_gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
} else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
_gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
}
}
}
}
}
var position = geometry.attributes[ "position" ];
// render non-indexed triangles
_gl.drawArrays( _gl.TRIANGLES, 0, position.numItems / 3 );
_this.info.render.calls ++;
_this.info.render.vertices += position.numItems / 3;
_this.info.render.faces += position.numItems / 3 / 3;
}
// render particles
} else if ( object instanceof THREE.ParticleSystem ) {
if ( updateBuffers ) {
for ( attributeName in programAttributes ) {
attributePointer = programAttributes[ attributeName ];
attributeItem = geometryAttributes[ attributeName ];
if ( attributePointer >= 0 ) {
if ( attributeItem ) {
attributeSize = attributeItem.itemSize;
_gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
enableAttribute( attributePointer );
_gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
} else if ( material.defaultAttributeValues && material.defaultAttributeValues[ attributeName ] ) {
if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
_gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
} else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
_gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
}
}
}
}
var position = geometryAttributes[ "position" ];
// render particles
_gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );
_this.info.render.calls ++;
_this.info.render.points += position.numItems / 3;
}
} else if ( object instanceof THREE.Line ) {
if ( updateBuffers ) {
for ( attributeName in programAttributes ) {
attributePointer = programAttributes[ attributeName ];
attributeItem = geometryAttributes[ attributeName ];
if ( attributePointer >= 0 ) {
if ( attributeItem ) {
attributeSize = attributeItem.itemSize;
_gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
enableAttribute( attributePointer );
_gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
} else if ( material.defaultAttributeValues && material.defaultAttributeValues[ attributeName ] ) {
if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
_gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
} else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
_gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
}
}
}
}
// render lines
var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
setLineWidth( material.linewidth );
var position = geometryAttributes[ "position" ];
_gl.drawArrays( primitives, 0, position.numItems / 3 );
_this.info.render.calls ++;
_this.info.render.points += position.numItems;
}
}
};
this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
if ( material.visible === false ) return;
var linewidth, a, attribute, i, il;
var program = setProgram( camera, lights, fog, material, object );
var attributes = program.attributes;
var updateBuffers = false,
wireframeBit = material.wireframe ? 1 : 0,
geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
if ( geometryGroupHash !== _currentGeometryGroupHash ) {
_currentGeometryGroupHash = geometryGroupHash;
updateBuffers = true;
}
if ( updateBuffers ) {
disableAttributes();
}
// vertices
if ( !material.morphTargets && attributes.position >= 0 ) {
if ( updateBuffers ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
enableAttribute( attributes.position );
_gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
}
} else {
if ( object.morphTargetBase ) {
setupMorphTargets( material, geometryGroup, object );
}
}
if ( updateBuffers ) {
// custom attributes
// Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
if ( geometryGroup.__webglCustomAttributesList ) {
for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
attribute = geometryGroup.__webglCustomAttributesList[ i ];
if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
_gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
}
}
}
// colors
if ( attributes.color >= 0 ) {
if ( object.geometry.colors.length > 0 || object.geometry.faces.length > 0 ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
enableAttribute( attributes.color );
_gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
} else if ( material.defaultAttributeValues ) {
_gl.vertexAttrib3fv( attributes.color, material.defaultAttributeValues.color );
}
}
// normals
if ( attributes.normal >= 0 ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
enableAttribute( attributes.normal );
_gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
}
// tangents
if ( attributes.tangent >= 0 ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
enableAttribute( attributes.tangent );
_gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
}
// uvs
if ( attributes.uv >= 0 ) {
if ( object.geometry.faceVertexUvs[0] ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
enableAttribute( attributes.uv );
_gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
} else if ( material.defaultAttributeValues ) {
_gl.vertexAttrib2fv( attributes.uv, material.defaultAttributeValues.uv );
}
}
if ( attributes.uv2 >= 0 ) {
if ( object.geometry.faceVertexUvs[1] ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
enableAttribute( attributes.uv2 );
_gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
} else if ( material.defaultAttributeValues ) {
_gl.vertexAttrib2fv( attributes.uv2, material.defaultAttributeValues.uv2 );
}
}
if ( material.skinning &&
attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
enableAttribute( attributes.skinIndex );
_gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
enableAttribute( attributes.skinWeight );
_gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
}
// line distances
if ( attributes.lineDistance >= 0 ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
enableAttribute( attributes.lineDistance );
_gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
}
}
// render mesh
if ( object instanceof THREE.Mesh ) {
// wireframe
if ( material.wireframe ) {
setLineWidth( material.wireframeLinewidth );
if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
_gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
// triangles
} else {
if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
_gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
}
_this.info.render.calls ++;
_this.info.render.vertices += geometryGroup.__webglFaceCount;
_this.info.render.faces += geometryGroup.__webglFaceCount / 3;
// render lines
} else if ( object instanceof THREE.Line ) {
var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
setLineWidth( material.linewidth );
_gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
_this.info.render.calls ++;
// render particles
} else if ( object instanceof THREE.ParticleSystem ) {
_gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
_this.info.render.calls ++;
_this.info.render.points += geometryGroup.__webglParticleCount;
}
};
function enableAttribute( attribute ) {
if ( ! _enabledAttributes[ attribute ] ) {
_gl.enableVertexAttribArray( attribute );
_enabledAttributes[ attribute ] = true;
}
};
function disableAttributes() {
for ( var attribute in _enabledAttributes ) {
if ( _enabledAttributes[ attribute ] ) {
_gl.disableVertexAttribArray( attribute );
_enabledAttributes[ attribute ] = false;
}
}
};
function setupMorphTargets ( material, geometryGroup, object ) {
// set base
var attributes = material.program.attributes;
if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
enableAttribute( attributes.position );
_gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
} else if ( attributes.position >= 0 ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
enableAttribute( attributes.position );
_gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
}
if ( object.morphTargetForcedOrder.length ) {
// set forced order
var m = 0;
var order = object.morphTargetForcedOrder;
var influences = object.morphTargetInfluences;
while ( m < material.numSupportedMorphTargets && m < order.length ) {
if ( attributes[ "morphTarget" + m ] >= 0 ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
enableAttribute( attributes[ "morphTarget" + m ] );
_gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
}
if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
enableAttribute( attributes[ "morphNormal" + m ] );
_gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
}
object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
m ++;
}
} else {
// find the most influencing
var influence, activeInfluenceIndices = [];
var influences = object.morphTargetInfluences;
var i, il = influences.length;
for ( i = 0; i < il; i ++ ) {
influence = influences[ i ];
if ( influence > 0 ) {
activeInfluenceIndices.push( [ influence, i ] );
}
}
if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
activeInfluenceIndices.sort( numericalSort );
activeInfluenceIndices.length = material.numSupportedMorphTargets;
} else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
activeInfluenceIndices.sort( numericalSort );
} else if ( activeInfluenceIndices.length === 0 ) {
activeInfluenceIndices.push( [ 0, 0 ] );
};
var influenceIndex, m = 0;
while ( m < material.numSupportedMorphTargets ) {
if ( activeInfluenceIndices[ m ] ) {
influenceIndex = activeInfluenceIndices[ m ][ 1 ];
if ( attributes[ "morphTarget" + m ] >= 0 ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
enableAttribute( attributes[ "morphTarget" + m ] );
_gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
}
if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
_gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
enableAttribute( attributes[ "morphNormal" + m ] );
_gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
}
object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
} else {
/*
_gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
if ( material.morphNormals ) {
_gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
}
*/
object.__webglMorphTargetInfluences[ m ] = 0;
}
m ++;
}
}
// load updated influences uniform
if ( material.program.uniforms.morphTargetInfluences !== null ) {
_gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
}
};
// Sorting
function painterSortStable ( a, b ) {
if ( a.z !== b.z ) {
return b.z - a.z;
} else {
return a.id - b.id;
}
};
function numericalSort ( a, b ) {
return b[ 0 ] - a[ 0 ];
};
// Rendering
this.render = function ( scene, camera, renderTarget, forceClear ) {
if ( camera instanceof THREE.Camera === false ) {
console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
return;
}
var i, il,
webglObject, object,
renderList,
lights = scene.__lights,
fog = scene.fog;
// reset caching for this frame
_currentMaterialId = -1;
_lightsNeedUpdate = true;
// update scene graph
if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
// update camera matrices and frustum
if ( camera.parent === undefined ) camera.updateMatrixWorld();
camera.matrixWorldInverse.getInverse( camera.matrixWorld );
_projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
_frustum.setFromMatrix( _projScreenMatrix );
// update WebGL objects
if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
// custom render plugins (pre pass)
renderPlugins( this.renderPluginsPre, scene, camera );
//
_this.info.render.calls = 0;
_this.info.render.vertices = 0;
_this.info.render.faces = 0;
_this.info.render.points = 0;
this.setRenderTarget( renderTarget );
if ( this.autoClear || forceClear ) {
this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
}
// set matrices for regular objects (frustum culled)
renderList = scene.__webglObjects;
for ( i = 0, il = renderList.length; i < il; i ++ ) {
webglObject = renderList[ i ];
object = webglObject.object;
webglObject.id = i;
webglObject.render = false;
if ( object.visible ) {
if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
setupMatrices( object, camera );
unrollBufferMaterial( webglObject );
webglObject.render = true;
if ( this.sortObjects === true ) {
if ( object.renderDepth !== null ) {
webglObject.z = object.renderDepth;
} else {
_vector3.getPositionFromMatrix( object.matrixWorld );
_vector3.applyProjection( _projScreenMatrix );
webglObject.z = _vector3.z;
}
}
}
}
}
if ( this.sortObjects ) {
renderList.sort( painterSortStable );
}
// set matrices for immediate objects
renderList = scene.__webglObjectsImmediate;
for ( i = 0, il = renderList.length; i < il; i ++ ) {
webglObject = renderList[ i ];
object = webglObject.object;
if ( object.visible ) {
setupMatrices( object, camera );
unrollImmediateBufferMaterial( webglObject );
}
}
if ( scene.overrideMaterial ) {
var material = scene.overrideMaterial;
this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
this.setDepthTest( material.depthTest );
this.setDepthWrite( material.depthWrite );
setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
} else {
var material = null;
// opaque pass (front-to-back order)
this.setBlending( THREE.NoBlending );
renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
// transparent pass (back-to-front order)
renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
}
// custom render plugins (post pass)
renderPlugins( this.renderPluginsPost, scene, camera );
// Generate mipmap if we're using any kind of mipmap filtering
if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
updateRenderTargetMipmap( renderTarget );
}
// Ensure depth buffer writing is enabled so it can be cleared on next render
this.setDepthTest( true );
this.setDepthWrite( true );
// _gl.finish();
};
function renderPlugins( plugins, scene, camera ) {
if ( ! plugins.length ) return;
for ( var i = 0, il = plugins.length; i < il; i ++ ) {
// reset state for plugin (to start from clean slate)
_currentProgram = null;
_currentCamera = null;
_oldBlending = -1;
_oldDepthTest = -1;
_oldDepthWrite = -1;
_oldDoubleSided = -1;
_oldFlipSided = -1;
_currentGeometryGroupHash = -1;
_currentMaterialId = -1;
_lightsNeedUpdate = true;
plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
// reset state after plugin (anything could have changed)
_currentProgram = null;
_currentCamera = null;
_oldBlending = -1;
_oldDepthTest = -1;
_oldDepthWrite = -1;
_oldDoubleSided = -1;
_oldFlipSided = -1;
_currentGeometryGroupHash = -1;
_currentMaterialId = -1;
_lightsNeedUpdate = true;
}
};
function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
var webglObject, object, buffer, material, start, end, delta;
if ( reverse ) {
start = renderList.length - 1;
end = -1;
delta = -1;
} else {
start = 0;
end = renderList.length;
delta = 1;
}
for ( var i = start; i !== end; i += delta ) {
webglObject = renderList[ i ];
if ( webglObject.render ) {
object = webglObject.object;
buffer = webglObject.buffer;
if ( overrideMaterial ) {
material = overrideMaterial;
} else {
material = webglObject[ materialType ];
if ( ! material ) continue;
if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
_this.setDepthTest( material.depthTest );
_this.setDepthWrite( material.depthWrite );
setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
}
_this.setMaterialFaces( material );
if ( buffer instanceof THREE.BufferGeometry ) {
_this.renderBufferDirect( camera, lights, fog, material, buffer, object );
} else {
_this.renderBuffer( camera, lights, fog, material, buffer, object );
}
}
}
};
function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
var webglObject, object, material, program;
for ( var i = 0, il = renderList.length; i < il; i ++ ) {
webglObject = renderList[ i ];
object = webglObject.object;
if ( object.visible ) {
if ( overrideMaterial ) {
material = overrideMaterial;
} else {
material = webglObject[ materialType ];
if ( ! material ) continue;
if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
_this.setDepthTest( material.depthTest );
_this.setDepthWrite( material.depthWrite );
setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
}
_this.renderImmediateObject( camera, lights, fog, material, object );
}
}
};
this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
var program = setProgram( camera, lights, fog, material, object );
_currentGeometryGroupHash = -1;
_this.setMaterialFaces( material );
if ( object.immediateRenderCallback ) {
object.immediateRenderCallback( program, _gl, _frustum );
} else {
object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
}
};
function unrollImmediateBufferMaterial ( globject ) {
var object = globject.object,
material = object.material;
if ( material.transparent ) {
globject.transparent = material;
globject.opaque = null;
} else {
globject.opaque = material;
globject.transparent = null;
}
};
function unrollBufferMaterial ( globject ) {
var object = globject.object,
buffer = globject.buffer,
material, materialIndex, meshMaterial;
meshMaterial = object.material;
if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
materialIndex = buffer.materialIndex;
material = meshMaterial.materials[ materialIndex ];
if ( material.transparent ) {
globject.transparent = material;
globject.opaque = null;
} else {
globject.opaque = material;
globject.transparent = null;
}
} else {
material = meshMaterial;
if ( material ) {
if ( material.transparent ) {
globject.transparent = material;
globject.opaque = null;
} else {
globject.opaque = material;
globject.transparent = null;
}
}
}
};
// Geometry splitting
function sortFacesByMaterial ( geometry, material ) {
var f, fl, face, materialIndex, vertices,
groupHash, hash_map = {};
var numMorphTargets = geometry.morphTargets.length;
var numMorphNormals = geometry.morphNormals.length;
var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
geometry.geometryGroups = {};
for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
face = geometry.faces[ f ];
materialIndex = usesFaceMaterial ? face.materialIndex : 0;
if ( hash_map[ materialIndex ] === undefined ) {
hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
}
groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
if ( geometry.geometryGroups[ groupHash ] === undefined ) {
geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
}
vertices = 3;
if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
hash_map[ materialIndex ].counter += 1;
groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
if ( geometry.geometryGroups[ groupHash ] === undefined ) {
geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
}
}
geometry.geometryGroups[ groupHash ].faces3.push( f );
geometry.geometryGroups[ groupHash ].vertices += vertices;
}
geometry.geometryGroupsList = [];
for ( var g in geometry.geometryGroups ) {
geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
}
};
// Objects refresh
this.initWebGLObjects = function ( scene ) {
if ( !scene.__webglObjects ) {
scene.__webglObjects = [];
scene.__webglObjectsImmediate = [];
scene.__webglSprites = [];
scene.__webglFlares = [];
}
while ( scene.__objectsAdded.length ) {
addObject( scene.__objectsAdded[ 0 ], scene );
scene.__objectsAdded.splice( 0, 1 );
}
while ( scene.__objectsRemoved.length ) {
removeObject( scene.__objectsRemoved[ 0 ], scene );
scene.__objectsRemoved.splice( 0, 1 );
}
// update must be called after objects adding / removal
for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
var object = scene.__webglObjects[ o ].object;
// TODO: Remove this hack (WebGLRenderer refactoring)
if ( object.__webglInit === undefined ) {
if ( object.__webglActive !== undefined ) {
removeObject( object, scene );
}
addObject( object, scene );
}
updateObject( object );
}
};
// Objects adding
function addObject( object, scene ) {
var g, geometry, material, geometryGroup;
if ( object.__webglInit === undefined ) {
object.__webglInit = true;
object._modelViewMatrix = new THREE.Matrix4();
object._normalMatrix = new THREE.Matrix3();
if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) {
object.geometry.__webglInit = true;
object.geometry.addEventListener( 'dispose', onGeometryDispose );
}
geometry = object.geometry;
if ( geometry === undefined ) {
// fail silently for now
} else if ( geometry instanceof THREE.BufferGeometry ) {
initDirectBuffers( geometry );
} else if ( object instanceof THREE.Mesh ) {
material = object.material;
if ( geometry.geometryGroups === undefined ) {
sortFacesByMaterial( geometry, material );
}
// create separate VBOs per geometry chunk
for ( g in geometry.geometryGroups ) {
geometryGroup = geometry.geometryGroups[ g ];
// initialise VBO on the first access
if ( ! geometryGroup.__webglVertexBuffer ) {
createMeshBuffers( geometryGroup );
initMeshBuffers( geometryGroup, object );
geometry.verticesNeedUpdate = true;
geometry.morphTargetsNeedUpdate = true;
geometry.elementsNeedUpdate = true;
geometry.uvsNeedUpdate = true;
geometry.normalsNeedUpdate = true;
geometry.tangentsNeedUpdate = true;
geometry.colorsNeedUpdate = true;
}
}
} else if ( object instanceof THREE.Line ) {
if ( ! geometry.__webglVertexBuffer ) {
createLineBuffers( geometry );
initLineBuffers( geometry, object );
geometry.verticesNeedUpdate = true;
geometry.colorsNeedUpdate = true;
geometry.lineDistancesNeedUpdate = true;
}
} else if ( object instanceof THREE.ParticleSystem ) {
if ( ! geometry.__webglVertexBuffer ) {
createParticleBuffers( geometry );
initParticleBuffers( geometry, object );
geometry.verticesNeedUpdate = true;
geometry.colorsNeedUpdate = true;
}
}
}
if ( object.__webglActive === undefined ) {
if ( object instanceof THREE.Mesh ) {
geometry = object.geometry;
if ( geometry instanceof THREE.BufferGeometry ) {
addBuffer( scene.__webglObjects, geometry, object );
} else if ( geometry instanceof THREE.Geometry ) {
for ( g in geometry.geometryGroups ) {
geometryGroup = geometry.geometryGroups[ g ];
addBuffer( scene.__webglObjects, geometryGroup, object );
}
}
} else if ( object instanceof THREE.Line ||
object instanceof THREE.ParticleSystem ) {
geometry = object.geometry;
addBuffer( scene.__webglObjects, geometry, object );
} else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
addBufferImmediate( scene.__webglObjectsImmediate, object );
} else if ( object instanceof THREE.Sprite ) {
scene.__webglSprites.push( object );
} else if ( object instanceof THREE.LensFlare ) {
scene.__webglFlares.push( object );
}
object.__webglActive = true;
}
};
function addBuffer( objlist, buffer, object ) {
objlist.push(
{
id: null,
buffer: buffer,
object: object,
opaque: null,
transparent: null,
z: 0
}
);
};
function addBufferImmediate( objlist, object ) {
objlist.push(
{
id: null,
object: object,
opaque: null,
transparent: null,
z: 0
}
);
};
// Objects updates
function updateObject( object ) {
var geometry = object.geometry,
geometryGroup, customAttributesDirty, material;
if ( geometry instanceof THREE.BufferGeometry ) {
setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
} else if ( object instanceof THREE.Mesh ) {
// check all geometry groups
for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
geometryGroup = geometry.geometryGroupsList[ i ];
material = getBufferMaterial( object, geometryGroup );
if ( geometry.buffersNeedUpdate ) {
initMeshBuffers( geometryGroup, object );
}
customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
}
}
geometry.verticesNeedUpdate = false;
geometry.morphTargetsNeedUpdate = false;
geometry.elementsNeedUpdate = false;
geometry.uvsNeedUpdate = false;
geometry.normalsNeedUpdate = false;
geometry.colorsNeedUpdate = false;
geometry.tangentsNeedUpdate = false;
geometry.buffersNeedUpdate = false;
material.attributes && clearCustomAttributes( material );
} else if ( object instanceof THREE.Line ) {
material = getBufferMaterial( object, geometry );
customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
}
geometry.verticesNeedUpdate = false;
geometry.colorsNeedUpdate = false;
geometry.lineDistancesNeedUpdate = false;
material.attributes && clearCustomAttributes( material );
} else if ( object instanceof THREE.ParticleSystem ) {
material = getBufferMaterial( object, geometry );
customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
}
geometry.verticesNeedUpdate = false;
geometry.colorsNeedUpdate = false;
material.attributes && clearCustomAttributes( material );
}
};
// Objects updates - custom attributes check
function areCustomAttributesDirty( material ) {
for ( var a in material.attributes ) {
if ( material.attributes[ a ].needsUpdate ) return true;
}
return false;
};
function clearCustomAttributes( material ) {
for ( var a in material.attributes ) {
material.attributes[ a ].needsUpdate = false;
}
};
// Objects removal
function removeObject( object, scene ) {
if ( object instanceof THREE.Mesh ||
object instanceof THREE.ParticleSystem ||
object instanceof THREE.Line ) {
removeInstances( scene.__webglObjects, object );
} else if ( object instanceof THREE.Sprite ) {
removeInstancesDirect( scene.__webglSprites, object );
} else if ( object instanceof THREE.LensFlare ) {
removeInstancesDirect( scene.__webglFlares, object );
} else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
removeInstances( scene.__webglObjectsImmediate, object );
}
delete object.__webglActive;
};
function removeInstances( objlist, object ) {
for ( var o = objlist.length - 1; o >= 0; o -- ) {
if ( objlist[ o ].object === object ) {
objlist.splice( o, 1 );
}
}
};
function removeInstancesDirect( objlist, object ) {
for ( var o = objlist.length - 1; o >= 0; o -- ) {
if ( objlist[ o ] === object ) {
objlist.splice( o, 1 );
}
}
};
// Materials
this.initMaterial = function ( material, lights, fog, object ) {
material.addEventListener( 'dispose', onMaterialDispose );
var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
if ( material instanceof THREE.MeshDepthMaterial ) {
shaderID = 'depth';
} else if ( material instanceof THREE.MeshNormalMaterial ) {
shaderID = 'normal';
} else if ( material instanceof THREE.MeshBasicMaterial ) {
shaderID = 'basic';
} else if ( material instanceof THREE.MeshLambertMaterial ) {
shaderID = 'lambert';
} else if ( material instanceof THREE.MeshPhongMaterial ) {
shaderID = 'phong';
} else if ( material instanceof THREE.LineBasicMaterial ) {
shaderID = 'basic';
} else if ( material instanceof THREE.LineDashedMaterial ) {
shaderID = 'dashed';
} else if ( material instanceof THREE.ParticleSystemMaterial ) {
shaderID = 'particle_basic';
}
if ( shaderID ) {
setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
}
// heuristics to create shader parameters according to lights in the scene
// (not to blow over maxLights budget)
maxLightCount = allocateLights( lights );
maxShadows = allocateShadows( lights );
maxBones = allocateBones( object );
parameters = {
map: !!material.map,
envMap: !!material.envMap,
lightMap: !!material.lightMap,
bumpMap: !!material.bumpMap,
normalMap: !!material.normalMap,
specularMap: !!material.specularMap,
vertexColors: material.vertexColors,
fog: fog,
useFog: material.fog,
fogExp: fog instanceof THREE.FogExp2,
sizeAttenuation: material.sizeAttenuation,
skinning: material.skinning,
maxBones: maxBones,
useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
morphTargets: material.morphTargets,
morphNormals: material.morphNormals,
maxMorphTargets: this.maxMorphTargets,
maxMorphNormals: this.maxMorphNormals,
maxDirLights: maxLightCount.directional,
maxPointLights: maxLightCount.point,
maxSpotLights: maxLightCount.spot,
maxHemiLights: maxLightCount.hemi,
maxShadows: maxShadows,
shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
shadowMapType: this.shadowMapType,
shadowMapDebug: this.shadowMapDebug,
shadowMapCascade: this.shadowMapCascade,
alphaTest: material.alphaTest,
metal: material.metal,
perPixel: material.perPixel,
wrapAround: material.wrapAround,
doubleSided: material.side === THREE.DoubleSide,
flipSided: material.side === THREE.BackSide
};
material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters, material.index0AttributeName );
var attributes = material.program.attributes;
if ( material.morphTargets ) {
material.numSupportedMorphTargets = 0;
var id, base = "morphTarget";
for ( i = 0; i < this.maxMorphTargets; i ++ ) {
id = base + i;
if ( attributes[ id ] >= 0 ) {
material.numSupportedMorphTargets ++;
}
}
}
if ( material.morphNormals ) {
material.numSupportedMorphNormals = 0;
var id, base = "morphNormal";
for ( i = 0; i < this.maxMorphNormals; i ++ ) {
id = base + i;
if ( attributes[ id ] >= 0 ) {
material.numSupportedMorphNormals ++;
}
}
}
material.uniformsList = [];
for ( u in material.uniforms ) {
material.uniformsList.push( [ material.uniforms[ u ], u ] );
}
};
function setMaterialShaders( material, shaders ) {
material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
material.vertexShader = shaders.vertexShader;
material.fragmentShader = shaders.fragmentShader;
};
function setProgram( camera, lights, fog, material, object ) {
_usedTextureUnits = 0;
if ( material.needsUpdate ) {
if ( material.program ) deallocateMaterial( material );
_this.initMaterial( material, lights, fog, object );
material.needsUpdate = false;
}
if ( material.morphTargets ) {
if ( ! object.__webglMorphTargetInfluences ) {
object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
}
}
var refreshMaterial = false;
var program = material.program,
p_uniforms = program.uniforms,
m_uniforms = material.uniforms;
if ( program !== _currentProgram ) {
_gl.useProgram( program );
_currentProgram = program;
refreshMaterial = true;
}
if ( material.id !== _currentMaterialId ) {
_currentMaterialId = material.id;
refreshMaterial = true;
}
if ( refreshMaterial || camera !== _currentCamera ) {
_gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
if ( camera !== _currentCamera ) _currentCamera = camera;
}
// skinning uniforms must be set even if material didn't change
// auto-setting of texture unit for bone texture must go before other textures
// not sure why, but otherwise weird things happen
if ( material.skinning ) {
if ( _supportsBoneTextures && object.useVertexTexture ) {
if ( p_uniforms.boneTexture !== null ) {
var textureUnit = getTextureUnit();
_gl.uniform1i( p_uniforms.boneTexture, textureUnit );
_this.setTexture( object.boneTexture, textureUnit );
}
if ( p_uniforms.boneTextureWidth !== null ) {
_gl.uniform1i( p_uniforms.boneTextureWidth, object.boneTextureWidth );
}
if ( p_uniforms.boneTextureHeight !== null ) {
_gl.uniform1i( p_uniforms.boneTextureHeight, object.boneTextureHeight );
}
} else {
if ( p_uniforms.boneGlobalMatrices !== null ) {
_gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
}
}
}
if ( refreshMaterial ) {
// refresh uniforms common to several materials
if ( fog && material.fog ) {
refreshUniformsFog( m_uniforms, fog );
}
if ( material instanceof THREE.MeshPhongMaterial ||
material instanceof THREE.MeshLambertMaterial ||
material.lights ) {
if ( _lightsNeedUpdate ) {
setupLights( program, lights );
_lightsNeedUpdate = false;
}
refreshUniformsLights( m_uniforms, _lights );
}
if ( material instanceof THREE.MeshBasicMaterial ||
material instanceof THREE.MeshLambertMaterial ||
material instanceof THREE.MeshPhongMaterial ) {
refreshUniformsCommon( m_uniforms, material );
}
// refresh single material specific uniforms
if ( material instanceof THREE.LineBasicMaterial ) {
refreshUniformsLine( m_uniforms, material );
} else if ( material instanceof THREE.LineDashedMaterial ) {
refreshUniformsLine( m_uniforms, material );
refreshUniformsDash( m_uniforms, material );
} else if ( material instanceof THREE.ParticleSystemMaterial ) {
refreshUniformsParticle( m_uniforms, material );
} else if ( material instanceof THREE.MeshPhongMaterial ) {
refreshUniformsPhong( m_uniforms, material );
} else if ( material instanceof THREE.MeshLambertMaterial ) {
refreshUniformsLambert( m_uniforms, material );
} else if ( material instanceof THREE.MeshDepthMaterial ) {
m_uniforms.mNear.value = camera.near;
m_uniforms.mFar.value = camera.far;
m_uniforms.opacity.value = material.opacity;
} else if ( material instanceof THREE.MeshNormalMaterial ) {
m_uniforms.opacity.value = material.opacity;
}
if ( object.receiveShadow && ! material._shadowPass ) {
refreshUniformsShadow( m_uniforms, lights );
}
// load common uniforms
loadUniformsGeneric( program, material.uniformsList );
// load material specific uniforms
// (shader material also gets them for the sake of genericity)
if ( material instanceof THREE.ShaderMaterial ||
material instanceof THREE.MeshPhongMaterial ||
material.envMap ) {
if ( p_uniforms.cameraPosition !== null ) {
_vector3.getPositionFromMatrix( camera.matrixWorld );
_gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
}
}
if ( material instanceof THREE.MeshPhongMaterial ||
material instanceof THREE.MeshLambertMaterial ||
material instanceof THREE.ShaderMaterial ||
material.skinning ) {
if ( p_uniforms.viewMatrix !== null ) {
_gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
}
}
}
loadUniformsMatrices( p_uniforms, object );
if ( p_uniforms.modelMatrix !== null ) {
_gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
}
return program;
};
// Uniforms (refresh uniforms objects)
function refreshUniformsCommon ( uniforms, material ) {
uniforms.opacity.value = material.opacity;
if ( _this.gammaInput ) {
uniforms.diffuse.value.copyGammaToLinear( material.color );
} else {
uniforms.diffuse.value = material.color;
}
uniforms.map.value = material.map;
uniforms.lightMap.value = material.lightMap;
uniforms.specularMap.value = material.specularMap;
if ( material.bumpMap ) {
uniforms.bumpMap.value = material.bumpMap;
uniforms.bumpScale.value = material.bumpScale;
}
if ( material.normalMap ) {
uniforms.normalMap.value = material.normalMap;
uniforms.normalScale.value.copy( material.normalScale );
}
// uv repeat and offset setting priorities
// 1. color map
// 2. specular map
// 3. normal map
// 4. bump map
var uvScaleMap;
if ( material.map ) {
uvScaleMap = material.map;
} else if ( material.specularMap ) {
uvScaleMap = material.specularMap;
} else if ( material.normalMap ) {
uvScaleMap = material.normalMap;
} else if ( material.bumpMap ) {
uvScaleMap = material.bumpMap;
}
if ( uvScaleMap !== undefined ) {
var offset = uvScaleMap.offset;
var repeat = uvScaleMap.repeat;
uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
}
uniforms.envMap.value = material.envMap;
uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
if ( _this.gammaInput ) {
//uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
uniforms.reflectivity.value = material.reflectivity;
} else {
uniforms.reflectivity.value = material.reflectivity;
}
uniforms.refractionRatio.value = material.refractionRatio;
uniforms.combine.value = material.combine;
uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
};
function refreshUniformsLine ( uniforms, material ) {
uniforms.diffuse.value = material.color;
uniforms.opacity.value = material.opacity;
};
function refreshUniformsDash ( uniforms, material ) {
uniforms.dashSize.value = material.dashSize;
uniforms.totalSize.value = material.dashSize + material.gapSize;
uniforms.scale.value = material.scale;
};
function refreshUniformsParticle ( uniforms, material ) {
uniforms.psColor.value = material.color;
uniforms.opacity.value = material.opacity;
uniforms.size.value = material.size;
uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
uniforms.map.value = material.map;
};
function refreshUniformsFog ( uniforms, fog ) {
uniforms.fogColor.value = fog.color;
if ( fog instanceof THREE.Fog ) {
uniforms.fogNear.value = fog.near;
uniforms.fogFar.value = fog.far;
} else if ( fog instanceof THREE.FogExp2 ) {
uniforms.fogDensity.value = fog.density;
}
};
function refreshUniformsPhong ( uniforms, material ) {
uniforms.shininess.value = material.shininess;
if ( _this.gammaInput ) {
uniforms.ambient.value.copyGammaToLinear( material.ambient );
uniforms.emissive.value.copyGammaToLinear( material.emissive );
uniforms.specular.value.copyGammaToLinear( material.specular );
} else {
uniforms.ambient.value = material.ambient;
uniforms.emissive.value = material.emissive;
uniforms.specular.value = material.specular;
}
if ( material.wrapAround ) {
uniforms.wrapRGB.value.copy( material.wrapRGB );
}
};
function refreshUniformsLambert ( uniforms, material ) {
if ( _this.gammaInput ) {
uniforms.ambient.value.copyGammaToLinear( material.ambient );
uniforms.emissive.value.copyGammaToLinear( material.emissive );
} else {
uniforms.ambient.value = material.ambient;
uniforms.emissive.value = material.emissive;
}
if ( material.wrapAround ) {
uniforms.wrapRGB.value.copy( material.wrapRGB );
}
};
function refreshUniformsLights ( uniforms, lights ) {
uniforms.ambientLightColor.value = lights.ambient;
uniforms.directionalLightColor.value = lights.directional.colors;
uniforms.directionalLightDirection.value = lights.directional.positions;
uniforms.pointLightColor.value = lights.point.colors;
uniforms.pointLightPosition.value = lights.point.positions;
uniforms.pointLightDistance.value = lights.point.distances;
uniforms.spotLightColor.value = lights.spot.colors;
uniforms.spotLightPosition.value = lights.spot.positions;
uniforms.spotLightDistance.value = lights.spot.distances;
uniforms.spotLightDirection.value = lights.spot.directions;
uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
uniforms.spotLightExponent.value = lights.spot.exponents;
uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
uniforms.hemisphereLightDirection.value = lights.hemi.positions;
};
function refreshUniformsShadow ( uniforms, lights ) {
if ( uniforms.shadowMatrix ) {
var j = 0;
for ( var i = 0, il = lights.length; i < il; i ++ ) {
var light = lights[ i ];
if ( ! light.castShadow ) continue;
if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
uniforms.shadowMap.value[ j ] = light.shadowMap;
uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
uniforms.shadowBias.value[ j ] = light.shadowBias;
j ++;
}
}
}
};
// Uniforms (load to GPU)
function loadUniformsMatrices ( uniforms, object ) {
_gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
if ( uniforms.normalMatrix ) {
_gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
}
};
function getTextureUnit() {
var textureUnit = _usedTextureUnits;
if ( textureUnit >= _maxTextures ) {
console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
}
_usedTextureUnits += 1;
return textureUnit;
};
function loadUniformsGeneric ( program, uniforms ) {
var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
location = program.uniforms[ uniforms[ j ][ 1 ] ];
if ( !location ) continue;
uniform = uniforms[ j ][ 0 ];
type = uniform.type;
value = uniform.value;
if ( type === "i" ) { // single integer
_gl.uniform1i( location, value );
} else if ( type === "f" ) { // single float
_gl.uniform1f( location, value );
} else if ( type === "v2" ) { // single THREE.Vector2
_gl.uniform2f( location, value.x, value.y );
} else if ( type === "v3" ) { // single THREE.Vector3
_gl.uniform3f( location, value.x, value.y, value.z );
} else if ( type === "v4" ) { // single THREE.Vector4
_gl.uniform4f( location, value.x, value.y, value.z, value.w );
} else if ( type === "c" ) { // single THREE.Color
_gl.uniform3f( location, value.r, value.g, value.b );
} else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
_gl.uniform1iv( location, value );
} else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
_gl.uniform3iv( location, value );
} else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
_gl.uniform1fv( location, value );
} else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
_gl.uniform3fv( location, value );
} else if ( type === "v2v" ) { // array of THREE.Vector2
if ( uniform._array === undefined ) {
uniform._array = new Float32Array( 2 * value.length );
}
for ( i = 0, il = value.length; i < il; i ++ ) {
offset = i * 2;
uniform._array[ offset ] = value[ i ].x;
uniform._array[ offset + 1 ] = value[ i ].y;
}
_gl.uniform2fv( location, uniform._array );
} else if ( type === "v3v" ) { // array of THREE.Vector3
if ( uniform._array === undefined ) {
uniform._array = new Float32Array( 3 * value.length );
}
for ( i = 0, il = value.length; i < il; i ++ ) {
offset = i * 3;
uniform._array[ offset ] = value[ i ].x;
uniform._array[ offset + 1 ] = value[ i ].y;
uniform._array[ offset + 2 ] = value[ i ].z;
}
_gl.uniform3fv( location, uniform._array );
} else if ( type === "v4v" ) { // array of THREE.Vector4
if ( uniform._array === undefined ) {
uniform._array = new Float32Array( 4 * value.length );
}
for ( i = 0, il = value.length; i < il; i ++ ) {
offset = i * 4;
uniform._array[ offset ] = value[ i ].x;
uniform._array[ offset + 1 ] = value[ i ].y;
uniform._array[ offset + 2 ] = value[ i ].z;
uniform._array[ offset + 3 ] = value[ i ].w;
}
_gl.uniform4fv( location, uniform._array );
} else if ( type === "m4") { // single THREE.Matrix4
if ( uniform._array === undefined ) {
uniform._array = new Float32Array( 16 );
}
value.flattenToArray( uniform._array );
_gl.uniformMatrix4fv( location, false, uniform._array );
} else if ( type === "m4v" ) { // array of THREE.Matrix4
if ( uniform._array === undefined ) {
uniform._array = new Float32Array( 16 * value.length );
}
for ( i = 0, il = value.length; i < il; i ++ ) {
value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
}
_gl.uniformMatrix4fv( location, false, uniform._array );
} else if ( type === "t" ) { // single THREE.Texture (2d or cube)
texture = value;
textureUnit = getTextureUnit();
_gl.uniform1i( location, textureUnit );
if ( !texture ) continue;
if ( texture.image instanceof Array && texture.image.length === 6 ) {
setCubeTexture( texture, textureUnit );
} else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
setCubeTextureDynamic( texture, textureUnit );
} else {
_this.setTexture( texture, textureUnit );
}
} else if ( type === "tv" ) { // array of THREE.Texture (2d)
if ( uniform._array === undefined ) {
uniform._array = [];
}
for( i = 0, il = uniform.value.length; i < il; i ++ ) {
uniform._array[ i ] = getTextureUnit();
}
_gl.uniform1iv( location, uniform._array );
for( i = 0, il = uniform.value.length; i < il; i ++ ) {
texture = uniform.value[ i ];
textureUnit = uniform._array[ i ];
if ( !texture ) continue;
_this.setTexture( texture, textureUnit );
}
} else {
console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
}
}
};
function setupMatrices ( object, camera ) {
object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
};
//
function setColorGamma( array, offset, color, intensitySq ) {
array[ offset ] = color.r * color.r * intensitySq;
array[ offset + 1 ] = color.g * color.g * intensitySq;
array[ offset + 2 ] = color.b * color.b * intensitySq;
};
function setColorLinear( array, offset, color, intensity ) {
array[ offset ] = color.r * intensity;
array[ offset + 1 ] = color.g * intensity;
array[ offset + 2 ] = color.b * intensity;
};
function setupLights ( program, lights ) {
var l, ll, light, n,
r = 0, g = 0, b = 0,
color, skyColor, groundColor,
intensity, intensitySq,
position,
distance,
zlights = _lights,
dirColors = zlights.directional.colors,
dirPositions = zlights.directional.positions,
pointColors = zlights.point.colors,
pointPositions = zlights.point.positions,
pointDistances = zlights.point.distances,
spotColors = zlights.spot.colors,
spotPositions = zlights.spot.positions,
spotDistances = zlights.spot.distances,
spotDirections = zlights.spot.directions,
spotAnglesCos = zlights.spot.anglesCos,
spotExponents = zlights.spot.exponents,
hemiSkyColors = zlights.hemi.skyColors,
hemiGroundColors = zlights.hemi.groundColors,
hemiPositions = zlights.hemi.positions,
dirLength = 0,
pointLength = 0,
spotLength = 0,
hemiLength = 0,
dirCount = 0,
pointCount = 0,
spotCount = 0,
hemiCount = 0,
dirOffset = 0,
pointOffset = 0,
spotOffset = 0,
hemiOffset = 0;
for ( l = 0, ll = lights.length; l < ll; l ++ ) {
light = lights[ l ];
if ( light.onlyShadow ) continue;
color = light.color;
intensity = light.intensity;
distance = light.distance;
if ( light instanceof THREE.AmbientLight ) {
if ( ! light.visible ) continue;
if ( _this.gammaInput ) {
r += color.r * color.r;
g += color.g * color.g;
b += color.b * color.b;
} else {
r += color.r;
g += color.g;
b += color.b;
}
} else if ( light instanceof THREE.DirectionalLight ) {
dirCount += 1;
if ( ! light.visible ) continue;
_direction.getPositionFromMatrix( light.matrixWorld );
_vector3.getPositionFromMatrix( light.target.matrixWorld );
_direction.sub( _vector3 );
_direction.normalize();
// skip lights with undefined direction
// these create troubles in OpenGL (making pixel black)
if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
dirOffset = dirLength * 3;
dirPositions[ dirOffset ] = _direction.x;
dirPositions[ dirOffset + 1 ] = _direction.y;
dirPositions[ dirOffset + 2 ] = _direction.z;
if ( _this.gammaInput ) {
setColorGamma( dirColors, dirOffset, color, intensity * intensity );
} else {
setColorLinear( dirColors, dirOffset, color, intensity );
}
dirLength += 1;
} else if ( light instanceof THREE.PointLight ) {
pointCount += 1;
if ( ! light.visible ) continue;
pointOffset = pointLength * 3;
if ( _this.gammaInput ) {
setColorGamma( pointColors, pointOffset, color, intensity * intensity );
} else {
setColorLinear( pointColors, pointOffset, color, intensity );
}
_vector3.getPositionFromMatrix( light.matrixWorld );
pointPositions[ pointOffset ] = _vector3.x;
pointPositions[ pointOffset + 1 ] = _vector3.y;
pointPositions[ pointOffset + 2 ] = _vector3.z;
pointDistances[ pointLength ] = distance;
pointLength += 1;
} else if ( light instanceof THREE.SpotLight ) {
spotCount += 1;
if ( ! light.visible ) continue;
spotOffset = spotLength * 3;
if ( _this.gammaInput ) {
setColorGamma( spotColors, spotOffset, color, intensity * intensity );
} else {
setColorLinear( spotColors, spotOffset, color, intensity );
}
_vector3.getPositionFromMatrix( light.matrixWorld );
spotPositions[ spotOffset ] = _vector3.x;
spotPositions[ spotOffset + 1 ] = _vector3.y;
spotPositions[ spotOffset + 2 ] = _vector3.z;
spotDistances[ spotLength ] = distance;
_direction.copy( _vector3 );
_vector3.getPositionFromMatrix( light.target.matrixWorld );
_direction.sub( _vector3 );
_direction.normalize();
spotDirections[ spotOffset ] = _direction.x;
spotDirections[ spotOffset + 1 ] = _direction.y;
spotDirections[ spotOffset + 2 ] = _direction.z;
spotAnglesCos[ spotLength ] = Math.cos( light.angle );
spotExponents[ spotLength ] = light.exponent;
spotLength += 1;
} else if ( light instanceof THREE.HemisphereLight ) {
hemiCount += 1;
if ( ! light.visible ) continue;
_direction.getPositionFromMatrix( light.matrixWorld );
_direction.normalize();
// skip lights with undefined direction
// these create troubles in OpenGL (making pixel black)
if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
hemiOffset = hemiLength * 3;
hemiPositions[ hemiOffset ] = _direction.x;
hemiPositions[ hemiOffset + 1 ] = _direction.y;
hemiPositions[ hemiOffset + 2 ] = _direction.z;
skyColor = light.color;
groundColor = light.groundColor;
if ( _this.gammaInput ) {
intensitySq = intensity * intensity;
setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
} else {
setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
}
hemiLength += 1;
}
}
// null eventual remains from removed lights
// (this is to avoid if in shader)
for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
zlights.directional.length = dirLength;
zlights.point.length = pointLength;
zlights.spot.length = spotLength;
zlights.hemi.length = hemiLength;
zlights.ambient[ 0 ] = r;
zlights.ambient[ 1 ] = g;
zlights.ambient[ 2 ] = b;
};
// GL state setting
this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
if ( cullFace === THREE.CullFaceNone ) {
_gl.disable( _gl.CULL_FACE );
} else {
if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
_gl.frontFace( _gl.CW );
} else {
_gl.frontFace( _gl.CCW );
}
if ( cullFace === THREE.CullFaceBack ) {
_gl.cullFace( _gl.BACK );
} else if ( cullFace === THREE.CullFaceFront ) {
_gl.cullFace( _gl.FRONT );
} else {
_gl.cullFace( _gl.FRONT_AND_BACK );
}
_gl.enable( _gl.CULL_FACE );
}
};
this.setMaterialFaces = function ( material ) {
var doubleSided = material.side === THREE.DoubleSide;
var flipSided = material.side === THREE.BackSide;
if ( _oldDoubleSided !== doubleSided ) {
if ( doubleSided ) {
_gl.disable( _gl.CULL_FACE );
} else {
_gl.enable( _gl.CULL_FACE );
}
_oldDoubleSided = doubleSided;
}
if ( _oldFlipSided !== flipSided ) {
if ( flipSided ) {
_gl.frontFace( _gl.CW );
} else {
_gl.frontFace( _gl.CCW );
}
_oldFlipSided = flipSided;
}
};
this.setDepthTest = function ( depthTest ) {
if ( _oldDepthTest !== depthTest ) {
if ( depthTest ) {
_gl.enable( _gl.DEPTH_TEST );
} else {
_gl.disable( _gl.DEPTH_TEST );
}
_oldDepthTest = depthTest;
}
};
this.setDepthWrite = function ( depthWrite ) {
if ( _oldDepthWrite !== depthWrite ) {
_gl.depthMask( depthWrite );
_oldDepthWrite = depthWrite;
}
};
function setLineWidth ( width ) {
if ( width !== _oldLineWidth ) {
_gl.lineWidth( width );
_oldLineWidth = width;
}
};
function setPolygonOffset ( polygonoffset, factor, units ) {
if ( _oldPolygonOffset !== polygonoffset ) {
if ( polygonoffset ) {
_gl.enable( _gl.POLYGON_OFFSET_FILL );
} else {
_gl.disable( _gl.POLYGON_OFFSET_FILL );
}
_oldPolygonOffset = polygonoffset;
}
if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
_gl.polygonOffset( factor, units );
_oldPolygonOffsetFactor = factor;
_oldPolygonOffsetUnits = units;
}
};
this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
if ( blending !== _oldBlending ) {
if ( blending === THREE.NoBlending ) {
_gl.disable( _gl.BLEND );
} else if ( blending === THREE.AdditiveBlending ) {
_gl.enable( _gl.BLEND );
_gl.blendEquation( _gl.FUNC_ADD );
_gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
} else if ( blending === THREE.SubtractiveBlending ) {
// TODO: Find blendFuncSeparate() combination
_gl.enable( _gl.BLEND );
_gl.blendEquation( _gl.FUNC_ADD );
_gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
} else if ( blending === THREE.MultiplyBlending ) {
// TODO: Find blendFuncSeparate() combination
_gl.enable( _gl.BLEND );
_gl.blendEquation( _gl.FUNC_ADD );
_gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
} else if ( blending === THREE.CustomBlending ) {
_gl.enable( _gl.BLEND );
} else {
_gl.enable( _gl.BLEND );
_gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
_gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
}
_oldBlending = blending;
}
if ( blending === THREE.CustomBlending ) {
if ( blendEquation !== _oldBlendEquation ) {
_gl.blendEquation( paramThreeToGL( blendEquation ) );
_oldBlendEquation = blendEquation;
}
if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
_gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
_oldBlendSrc = blendSrc;
_oldBlendDst = blendDst;
}
} else {
_oldBlendEquation = null;
_oldBlendSrc = null;
_oldBlendDst = null;
}
};
// Defines
function generateDefines ( defines ) {
var value, chunk, chunks = [];
for ( var d in defines ) {
value = defines[ d ];
if ( value === false ) continue;
chunk = "#define " + d + " " + value;
chunks.push( chunk );
}
return chunks.join( "\n" );
};
// Shaders
function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters, index0AttributeName ) {
var p, pl, d, program, code;
var chunks = [];
// Generate code
if ( shaderID ) {
chunks.push( shaderID );
} else {
chunks.push( fragmentShader );
chunks.push( vertexShader );
}
for ( d in defines ) {
chunks.push( d );
chunks.push( defines[ d ] );
}
for ( p in parameters ) {
chunks.push( p );
chunks.push( parameters[ p ] );
}
code = chunks.join();
// Check if code has been already compiled
for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
var programInfo = _programs[ p ];
if ( programInfo.code === code ) {
// console.log( "Code already compiled." /*: \n\n" + code*/ );
programInfo.usedTimes ++;
return programInfo.program;
}
}
var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
} else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
}
// console.log( "building new program " );
//
var customDefines = generateDefines( defines );
//
program = _gl.createProgram();
var prefix_vertex = [
"precision " + _precision + " float;",
"precision " + _precision + " int;",
customDefines,
_supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
_this.gammaInput ? "#define GAMMA_INPUT" : "",
_this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
_this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
"#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
"#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
"#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
"#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
"#define MAX_SHADOWS " + parameters.maxShadows,
"#define MAX_BONES " + parameters.maxBones,
parameters.map ? "#define USE_MAP" : "",
parameters.envMap ? "#define USE_ENVMAP" : "",
parameters.lightMap ? "#define USE_LIGHTMAP" : "",
parameters.bumpMap ? "#define USE_BUMPMAP" : "",
parameters.normalMap ? "#define USE_NORMALMAP" : "",
parameters.specularMap ? "#define USE_SPECULARMAP" : "",
parameters.vertexColors ? "#define USE_COLOR" : "",
parameters.skinning ? "#define USE_SKINNING" : "",
parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
parameters.wrapAround ? "#define WRAP_AROUND" : "",
parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
parameters.flipSided ? "#define FLIP_SIDED" : "",
parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
"uniform mat4 modelMatrix;",
"uniform mat4 modelViewMatrix;",
"uniform mat4 projectionMatrix;",
"uniform mat4 viewMatrix;",
"uniform mat3 normalMatrix;",
"uniform vec3 cameraPosition;",
"attribute vec3 position;",
"attribute vec3 normal;",
"attribute vec2 uv;",
"attribute vec2 uv2;",
"#ifdef USE_COLOR",
"attribute vec3 color;",
"#endif",
"#ifdef USE_MORPHTARGETS",
"attribute vec3 morphTarget0;",
"attribute vec3 morphTarget1;",
"attribute vec3 morphTarget2;",
"attribute vec3 morphTarget3;",
"#ifdef USE_MORPHNORMALS",
"attribute vec3 morphNormal0;",
"attribute vec3 morphNormal1;",
"attribute vec3 morphNormal2;",
"attribute vec3 morphNormal3;",
"#else",
"attribute vec3 morphTarget4;",
"attribute vec3 morphTarget5;",
"attribute vec3 morphTarget6;",
"attribute vec3 morphTarget7;",
"#endif",
"#endif",
"#ifdef USE_SKINNING",
"attribute vec4 skinIndex;",
"attribute vec4 skinWeight;",
"#endif",
""
].join("\n");
var prefix_fragment = [
"precision " + _precision + " float;",
"precision " + _precision + " int;",
( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
customDefines,
"#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
"#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
"#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
"#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
"#define MAX_SHADOWS " + parameters.maxShadows,
parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
_this.gammaInput ? "#define GAMMA_INPUT" : "",
_this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
_this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
parameters.map ? "#define USE_MAP" : "",
parameters.envMap ? "#define USE_ENVMAP" : "",
parameters.lightMap ? "#define USE_LIGHTMAP" : "",
parameters.bumpMap ? "#define USE_BUMPMAP" : "",
parameters.normalMap ? "#define USE_NORMALMAP" : "",
parameters.specularMap ? "#define USE_SPECULARMAP" : "",
parameters.vertexColors ? "#define USE_COLOR" : "",
parameters.metal ? "#define METAL" : "",
parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
parameters.wrapAround ? "#define WRAP_AROUND" : "",
parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
parameters.flipSided ? "#define FLIP_SIDED" : "",
parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
"uniform mat4 viewMatrix;",
"uniform vec3 cameraPosition;",
""
].join("\n");
var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
_gl.attachShader( program, glVertexShader );
_gl.attachShader( program, glFragmentShader );
//Force a particular attribute to index 0.
// because potentially expensive emulation is done by browser if attribute 0 is disabled.
//And, color, for example is often automatically bound to index 0 so disabling it
if ( index0AttributeName ) {
_gl.bindAttribLocation( program, 0, index0AttributeName );
}
_gl.linkProgram( program );
if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
console.error( "Program Info Log: " + _gl.getProgramInfoLog( program ) );
}
// clean up
_gl.deleteShader( glFragmentShader );
_gl.deleteShader( glVertexShader );
// console.log( prefix_fragment + fragmentShader );
// console.log( prefix_vertex + vertexShader );
program.uniforms = {};
program.attributes = {};
var identifiers, u, a, i;
// cache uniform locations
identifiers = [
'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
'morphTargetInfluences'
];
if ( parameters.useVertexTexture ) {
identifiers.push( 'boneTexture' );
identifiers.push( 'boneTextureWidth' );
identifiers.push( 'boneTextureHeight' );
} else {
identifiers.push( 'boneGlobalMatrices' );
}
for ( u in uniforms ) {
identifiers.push( u );
}
cacheUniformLocations( program, identifiers );
// cache attributes locations
identifiers = [
"position", "normal", "uv", "uv2", "tangent", "color",
"skinIndex", "skinWeight", "lineDistance"
];
for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
identifiers.push( "morphTarget" + i );
}
for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
identifiers.push( "morphNormal" + i );
}
for ( a in attributes ) {
identifiers.push( a );
}
cacheAttributeLocations( program, identifiers );
program.id = _programs_counter ++;
_programs.push( { program: program, code: code, usedTimes: 1 } );
_this.info.memory.programs = _programs.length;
return program;
};
// Shader parameters cache
function cacheUniformLocations ( program, identifiers ) {
var i, l, id;
for( i = 0, l = identifiers.length; i < l; i ++ ) {
id = identifiers[ i ];
program.uniforms[ id ] = _gl.getUniformLocation( program, id );
}
};
function cacheAttributeLocations ( program, identifiers ) {
var i, l, id;
for( i = 0, l = identifiers.length; i < l; i ++ ) {
id = identifiers[ i ];
program.attributes[ id ] = _gl.getAttribLocation( program, id );
}
};
function addLineNumbers ( string ) {
var chunks = string.split( "\n" );
for ( var i = 0, il = chunks.length; i < il; i ++ ) {
// Chrome reports shader errors on lines
// starting counting from 1
chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
}
return chunks.join( "\n" );
};
function getShader ( type, string ) {
var shader;
if ( type === "fragment" ) {
shader = _gl.createShader( _gl.FRAGMENT_SHADER );
} else if ( type === "vertex" ) {
shader = _gl.createShader( _gl.VERTEX_SHADER );
}
_gl.shaderSource( shader, string );
_gl.compileShader( shader );
if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
console.error( _gl.getShaderInfoLog( shader ) );
console.error( addLineNumbers( string ) );
return null;
}
return shader;
};
// Textures
function isPowerOfTwo ( value ) {
return ( value & ( value - 1 ) ) === 0;
};
function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
if ( isImagePowerOfTwo ) {
_gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
_gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
_gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
_gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
} else {
_gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
_gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
_gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
_gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
}
if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
_gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
texture.__oldAnisotropy = texture.anisotropy;
}
}
};
this.setTexture = function ( texture, slot ) {
if ( texture.needsUpdate ) {
if ( ! texture.__webglInit ) {
texture.__webglInit = true;
texture.addEventListener( 'dispose', onTextureDispose );
texture.__webglTexture = _gl.createTexture();
_this.info.memory.textures ++;
}
_gl.activeTexture( _gl.TEXTURE0 + slot );
_gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
_gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
_gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
_gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
var image = texture.image,
isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
glFormat = paramThreeToGL( texture.format ),
glType = paramThreeToGL( texture.type );
setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
var mipmap, mipmaps = texture.mipmaps;
if ( texture instanceof THREE.DataTexture ) {
// use manually created mipmaps if available
// if there are no manual mipmaps
// set 0 level mipmap and then use GL to generate other mipmap levels
if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
mipmap = mipmaps[ i ];
_gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
}
texture.generateMipmaps = false;
} else {
_gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
}
} else if ( texture instanceof THREE.CompressedTexture ) {
for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
mipmap = mipmaps[ i ];
if ( texture.format!==THREE.RGBAFormat ) {
_gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
} else {
_gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
}
}
} else { // regular Texture (image, video, canvas)
// use manually created mipmaps if available
// if there are no manual mipmaps
// set 0 level mipmap and then use GL to generate other mipmap levels
if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
mipmap = mipmaps[ i ];
_gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
}
texture.generateMipmaps = false;
} else {
_gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
}
}
if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
texture.needsUpdate = false;
if ( texture.onUpdate ) texture.onUpdate();
} else {
_gl.activeTexture( _gl.TEXTURE0 + slot );
_gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
}
};
function clampToMaxSize ( image, maxSize ) {
if ( image.width <= maxSize && image.height <= maxSize ) {
return image;
}
// Warning: Scaling through the canvas will only work with images that use
// premultiplied alpha.
var maxDimension = Math.max( image.width, image.height );
var newWidth = Math.floor( image.width * maxSize / maxDimension );
var newHeight = Math.floor( image.height * maxSize / maxDimension );
var canvas = document.createElement( 'canvas' );
canvas.width = newWidth;
canvas.height = newHeight;
var ctx = canvas.getContext( "2d" );
ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
return canvas;
}
function setCubeTexture ( texture, slot ) {
if ( texture.image.length === 6 ) {
if ( texture.needsUpdate ) {
if ( ! texture.image.__webglTextureCube ) {
texture.addEventListener( 'dispose', onTextureDispose );
texture.image.__webglTextureCube = _gl.createTexture();
_this.info.memory.textures ++;
}
_gl.activeTexture( _gl.TEXTURE0 + slot );
_gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
_gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
var isCompressed = texture instanceof THREE.CompressedTexture;
var cubeImage = [];
for ( var i = 0; i < 6; i ++ ) {
if ( _this.autoScaleCubemaps && ! isCompressed ) {
cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
} else {
cubeImage[ i ] = texture.image[ i ];
}
}
var image = cubeImage[ 0 ],
isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
glFormat = paramThreeToGL( texture.format ),
glType = paramThreeToGL( texture.type );
setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
for ( var i = 0; i < 6; i ++ ) {
if( !isCompressed ) {
_gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
} else {
var mipmap, mipmaps = cubeImage[ i ].mipmaps;
for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
mipmap = mipmaps[ j ];
if ( texture.format!==THREE.RGBAFormat ) {
_gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
} else {
_gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
}
}
}
}
if ( texture.generateMipmaps && isImagePowerOfTwo ) {
_gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
}
texture.needsUpdate = false;
if ( texture.onUpdate ) texture.onUpdate();
} else {
_gl.activeTexture( _gl.TEXTURE0 + slot );
_gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
}
}
};
function setCubeTextureDynamic ( texture, slot ) {
_gl.activeTexture( _gl.TEXTURE0 + slot );
_gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
};
// Render targets
function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
_gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
_gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
};
function setupRenderBuffer ( renderbuffer, renderTarget ) {
_gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
_gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
_gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
/* For some reason this is not working. Defaulting to RGBA4.
} else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
_gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
_gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
*/
} else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
_gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
_gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
} else {
_gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
}
};
this.setRenderTarget = function ( renderTarget ) {
var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
renderTarget.__webglTexture = _gl.createTexture();
_this.info.memory.textures ++;
// Setup texture, create render and frame buffers
var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
glFormat = paramThreeToGL( renderTarget.format ),
glType = paramThreeToGL( renderTarget.type );
if ( isCube ) {
renderTarget.__webglFramebuffer = [];
renderTarget.__webglRenderbuffer = [];
_gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
for ( var i = 0; i < 6; i ++ ) {
renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
_gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
}
if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
} else {
renderTarget.__webglFramebuffer = _gl.createFramebuffer();
if ( renderTarget.shareDepthFrom ) {
renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
} else {
renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
}
_gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
_gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
if ( renderTarget.shareDepthFrom ) {
if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
_gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
} else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
_gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
}
} else {
setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
}
if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
}
// Release everything
if ( isCube ) {
_gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
} else {
_gl.bindTexture( _gl.TEXTURE_2D, null );
}
_gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
_gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
}
var framebuffer, width, height, vx, vy;
if ( renderTarget ) {
if ( isCube ) {
framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
} else {
framebuffer = renderTarget.__webglFramebuffer;
}
width = renderTarget.width;
height = renderTarget.height;
vx = 0;
vy = 0;
} else {
framebuffer = null;
width = _viewportWidth;
height = _viewportHeight;
vx = _viewportX;
vy = _viewportY;
}
if ( framebuffer !== _currentFramebuffer ) {
_gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
_gl.viewport( vx, vy, width, height );
_currentFramebuffer = framebuffer;
}
_currentWidth = width;
_currentHeight = height;
};
function updateRenderTargetMipmap ( renderTarget ) {
if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
_gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
_gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
_gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
} else {
_gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
_gl.generateMipmap( _gl.TEXTURE_2D );
_gl.bindTexture( _gl.TEXTURE_2D, null );
}
};
// Fallback filters for non-power-of-2 textures
function filterFallback ( f ) {
if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
return _gl.NEAREST;
}
return _gl.LINEAR;
};
// Map three.js constants to WebGL constants
function paramThreeToGL ( p ) {
if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
if ( p === THREE.NearestFilter ) return _gl.NEAREST;
if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
if ( p === THREE.LinearFilter ) return _gl.LINEAR;
if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
if ( p === THREE.ByteType ) return _gl.BYTE;
if ( p === THREE.ShortType ) return _gl.SHORT;
if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
if ( p === THREE.IntType ) return _gl.INT;
if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
if ( p === THREE.FloatType ) return _gl.FLOAT;
if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
if ( p === THREE.RGBFormat ) return _gl.RGB;
if ( p === THREE.RGBAFormat ) return _gl.RGBA;
if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
if ( p === THREE.ZeroFactor ) return _gl.ZERO;
if ( p === THREE.OneFactor ) return _gl.ONE;
if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
if ( _glExtensionCompressedTextureS3TC !== undefined ) {
if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
}
return 0;
};
// Allocations
function allocateBones ( object ) {
if ( _supportsBoneTextures && object && object.useVertexTexture ) {
return 1024;
} else {
// default for when object is not specified
// ( for example when prebuilding shader
// to be used with multiple objects )
//
// - leave some extra space for other uniforms
// - limit here is ANGLE's 254 max uniform vectors
// (up to 54 should be safe)
var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
var maxBones = nVertexMatrices;
if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
maxBones = Math.min( object.bones.length, maxBones );
if ( maxBones < object.bones.length ) {
console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
}
}
return maxBones;
}
};
function allocateLights( lights ) {
var dirLights = 0;
var pointLights = 0;
var spotLights = 0;
var hemiLights = 0;
for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
var light = lights[ l ];
if ( light.onlyShadow ) continue;
if ( light instanceof THREE.DirectionalLight ) dirLights ++;
if ( light instanceof THREE.PointLight ) pointLights ++;
if ( light instanceof THREE.SpotLight ) spotLights ++;
if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
}
return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
};
function allocateShadows( lights ) {
var maxShadows = 0;
for ( var l = 0, ll = lights.length; l < ll; l++ ) {
var light = lights[ l ];
if ( ! light.castShadow ) continue;
if ( light instanceof THREE.SpotLight ) maxShadows ++;
if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
}
return maxShadows;
};
// Initialization
function initGL() {
try {
var attributes = {
alpha: _alpha,
premultipliedAlpha: _premultipliedAlpha,
antialias: _antialias,
stencil: _stencil,
preserveDrawingBuffer: _preserveDrawingBuffer
};
_gl = _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
if ( _gl === null ) {
throw 'Error creating WebGL context.';
}
} catch ( error ) {
console.error( error );
}
_glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
_glExtensionTextureFloatLinear = _gl.getExtension( 'OES_texture_float_linear' );
_glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
_glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
_glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
if ( ! _glExtensionTextureFloat ) {
console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
}
if ( ! _glExtensionStandardDerivatives ) {
console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
}
if ( ! _glExtensionTextureFilterAnisotropic ) {
console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
}
if ( ! _glExtensionCompressedTextureS3TC ) {
console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
}
if ( _gl.getShaderPrecisionFormat === undefined ) {
_gl.getShaderPrecisionFormat = function() {
return {
"rangeMin" : 1,
"rangeMax" : 1,
"precision" : 1
};
}
}
};
function setDefaultGLState () {
_gl.clearColor( 0, 0, 0, 1 );
_gl.clearDepth( 1 );
_gl.clearStencil( 0 );
_gl.enable( _gl.DEPTH_TEST );
_gl.depthFunc( _gl.LEQUAL );
_gl.frontFace( _gl.CCW );
_gl.cullFace( _gl.BACK );
_gl.enable( _gl.CULL_FACE );
_gl.enable( _gl.BLEND );
_gl.blendEquation( _gl.FUNC_ADD );
_gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
_gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
_gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
};
// default plugins (order is important)
this.shadowMapPlugin = new THREE.ShadowMapPlugin();
this.addPrePlugin( this.shadowMapPlugin );
this.addPostPlugin( new THREE.SpritePlugin() );
this.addPostPlugin( new THREE.LensFlarePlugin() );
};
|
import Ember from 'ember';
import { moduleForComponent, test } from 'ember-qunit';
moduleForComponent( 'sl-grid-row', 'Unit | Component | sl grid row', {
unit: true
});
test( 'Active row class is supported', function( assert ) {
const row = {};
this.subject({ row });
assert.equal(
this.$().hasClass( 'active' ),
false,
'Component with non-active row does not have "active" class'
);
Ember.run( () => {
Ember.set( row, 'active', true );
});
assert.equal(
this.$().hasClass( 'active' ),
true,
'Component with active row has "active" class'
);
});
test( 'Click event triggers rowClick action with row record', function( assert ) {
const row = { testValue: true };
this.subject({
row,
rowClick: 'test',
targetObject: {
test( passedRow ) {
assert.equal(
passedRow,
row,
'Row record passed from rowClick is expected value'
);
}
}
});
this.$().trigger( 'click' );
});
|
'use strict';
exports.__esModule = true;
exports['default'] = {
optional: ' (opcional)',
required: '',
add: 'Añadir',
remove: 'Eliminar',
up: 'Arriba',
down: 'Abajo'
};
module.exports = exports['default']; |
import Telescope from 'meteor/nova:lib';
import {Inject} from 'meteor/meteorhacks:inject-initial';
import Events from "meteor/nova:events";
Meteor.startup(function () {
Events.log({
name: "firstRun",
unique: true, // will only get logged a single time
important: true
});
});
if (Telescope.settings.get('mailUrl')) {
process.env.MAIL_URL = Telescope.settings.get('mailUrl');
}
Meteor.startup(function() {
if (typeof SyncedCron !== "undefined") {
SyncedCron.start();
}
});
Inject.obj('serverTimezoneOffset', {offset: new Date().getTimezoneOffset()}); |
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var common = require('../common');
var assert = require('assert');
var spawn = require('child_process').spawn;
var args = ['--harmony', '--use-strict', '-i'];
var child = spawn(process.execPath, args);
var input = 'function x(){const y=1;y=2}\n';
var expectOut = /^> SyntaxError: Assignment to constant variable.\n/;
child.stderr.setEncoding('utf8');
child.stderr.on('data', function(c) {
throw new Error('child.stderr be silent');
});
child.stdout.setEncoding('utf8');
var out = '';
child.stdout.on('data', function(c) {
out += c;
});
child.stdout.on('end', function() {
assert(expectOut.test(out));
console.log('ok');
});
child.stdin.end(input);
|
export default function Attribute$updateIEStyleAttribute () {
var node, value;
node = this.node;
value = this.value;
if ( value === undefined ) {
value = '';
}
node.style.setAttribute( 'cssText', value );
}
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: Operator x = y PutValue(x, y)
es5id: 11.13.1_A3.1
description: Checking Expression and Variable statements
---*/
//CHECK#1
var x = 1;
if (x !== 1) {
$ERROR('#1: var x = 1; x === 1. Actual: ' + (x));
}
//CHECK#2
x = 1;
if (x !== 1) {
$ERROR('#2: x = 1; x === 1. Actual: ' + (x));
}
|
define([
'aeris/util',
'aeris/helpers/validator/pathvalidator',
'aeris/helpers/validator/errors/pathvalidationerror'
], function(_, PathValidator, PathValidationError) {
describe('A PathValidator', function() {
var pathValidator = new PathValidator();
describe('isValid', function() {
it('should require an array', function() {
var notAnArray = {};
pathValidator.setPath(notAnArray);
expect(pathValidator.isValid()).toEqual(false);
});
it('should accept an empty array', function() {
pathValidator.setPath([]);
expect(pathValidator.isValid()).toEqual(true);
});
it('should require an array of latLons', function() {
var invalidPathValues = [
['foo', 'bar'],
[12, 34, 56],
[[12, 34, 56]],
[['foo', 'bar']]
];
_.each(invalidPathValues, function(path) {
pathValidator.setPath(path);
expect(pathValidator.isValid()).toEqual(false);
});
});
});
describe('getLastError', function() {
it('should return a PathValidationError', function() {
pathValidator.setPath('foo');
pathValidator.isValid();
expect(pathValidator.getLastError()).toBeInstanceOf(PathValidationError);
});
});
});
});
|
var common = require("./common")
, odbc = require("../")
, db = new odbc.Database();
db.open(common.connectionString, function(err){
if (err) {
console.log(err);
process.exit(1);
}
dropTable();
createTable();
});
function createTable() {
db.query("create table bench_insert (str varchar(50))", function (err) {
if (err) {
console.log(err);
return finish();
}
return insertData();
});
}
function dropTable() {
try {
db.querySync("drop table bench_insert")
}catch(e){
// console.log(e);
// do nothing if the table doesn't exist
}
}
function insertData() {
var count = 0
, iterations = 100
, time = new Date().getTime();
for (var x = 0; x < iterations; x++) {
db.query("insert into bench_insert (str) values ('testing')", cb);
}
function cb (err) {
if (err) {
console.log(err);
return finish();
}
if (++count == iterations) {
var elapsed = (new Date().getTime() - time)/1000;
process.stdout.write("(" + iterations + " records inserted in " + elapsed + " seconds, " + (iterations/elapsed).toFixed(4) + " records/sec)");
return dropTable();
}
}
}
function finish() {
db.close(function () {
console.log("connection closed");
});
}
|
/**
* Copyright 2015 Google Inc. All Rights Reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file or at
* https://github.com/firebase/superstatic/blob/master/LICENSE
*/
'use strict';
var glob = require('glob');
var tryRequire = require('try-require');
var join = require('join-path');
var npmPaths = require('./npm-paths');
module.exports = function globalResolve(name) {
var servicePath;
npmPaths()
.forEach(function(root) {
if (!servicePath) {
var filepath = glob.sync(join(root, name))[0];
servicePath = tryRequire(filepath);
}
});
return servicePath;
};
|
module.exports={title:"Tidal",slug:"tidal",svg:'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Tidal icon</title><path d="M12.012 3.992L8.008 7.996 4.004 3.992 0 7.996 4.004 12l4.004-4.004L12.012 12l-4.004 4.004 4.004 4.004 4.004-4.004L12.012 12l4.004-4.004-4.004-4.004zM16.042 7.996l3.979-3.979L24 7.996l-3.979 3.979z"/></svg>',get path(){return this.svg.match(/<path\s+d="([^"]*)/)[1]},source:"https://tidal.com",hex:"000000",license:void 0}; |
define([ 'jquery', 'transition' ], function ( jQuery ) {
/* ========================================================================
* Bootstrap: modal.js v3.3.5
* http://getbootstrap.com/javascript/#modals
* ========================================================================
* Copyright 2011-2015 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// MODAL CLASS DEFINITION
// ======================
var Modal = function (element, options) {
this.options = options
this.$body = $(document.body)
this.$element = $(element)
this.$dialog = this.$element.find('.modal-dialog')
this.$backdrop = null
this.isShown = null
this.originalBodyPad = null
this.scrollbarWidth = 0
this.ignoreBackdropClick = false
if (this.options.remote) {
this.$element
.find('.modal-content')
.load(this.options.remote, $.proxy(function () {
this.$element.trigger('loaded.bs.modal')
}, this))
}
}
Modal.VERSION = '3.3.5'
Modal.TRANSITION_DURATION = 300
Modal.BACKDROP_TRANSITION_DURATION = 150
Modal.DEFAULTS = {
backdrop: true,
keyboard: true,
show: true
}
Modal.prototype.toggle = function (_relatedTarget) {
return this.isShown ? this.hide() : this.show(_relatedTarget)
}
Modal.prototype.show = function (_relatedTarget) {
var that = this
var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget })
this.$element.trigger(e)
if (this.isShown || e.isDefaultPrevented()) return
this.isShown = true
this.checkScrollbar()
this.setScrollbar()
this.$body.addClass('modal-open')
this.escape()
this.resize()
this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this))
this.$dialog.on('mousedown.dismiss.bs.modal', function () {
that.$element.one('mouseup.dismiss.bs.modal', function (e) {
if ($(e.target).is(that.$element)) that.ignoreBackdropClick = true
})
})
this.backdrop(function () {
var transition = $.support.transition && that.$element.hasClass('fade')
if (!that.$element.parent().length) {
that.$element.appendTo(that.$body) // don't move modals dom position
}
that.$element
.show()
.scrollTop(0)
that.adjustDialog()
if (transition) {
that.$element[0].offsetWidth // force reflow
}
that.$element.addClass('in')
that.enforceFocus()
var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget })
transition ?
that.$dialog // wait for modal to slide in
.one('bsTransitionEnd', function () {
that.$element.trigger('focus').trigger(e)
})
.emulateTransitionEnd(Modal.TRANSITION_DURATION) :
that.$element.trigger('focus').trigger(e)
})
}
Modal.prototype.hide = function (e) {
if (e) e.preventDefault()
e = $.Event('hide.bs.modal')
this.$element.trigger(e)
if (!this.isShown || e.isDefaultPrevented()) return
this.isShown = false
this.escape()
this.resize()
$(document).off('focusin.bs.modal')
this.$element
.removeClass('in')
.off('click.dismiss.bs.modal')
.off('mouseup.dismiss.bs.modal')
this.$dialog.off('mousedown.dismiss.bs.modal')
$.support.transition && this.$element.hasClass('fade') ?
this.$element
.one('bsTransitionEnd', $.proxy(this.hideModal, this))
.emulateTransitionEnd(Modal.TRANSITION_DURATION) :
this.hideModal()
}
Modal.prototype.enforceFocus = function () {
$(document)
.off('focusin.bs.modal') // guard against infinite focus loop
.on('focusin.bs.modal', $.proxy(function (e) {
if (this.$element[0] !== e.target && !this.$element.has(e.target).length) {
this.$element.trigger('focus')
}
}, this))
}
Modal.prototype.escape = function () {
if (this.isShown && this.options.keyboard) {
this.$element.on('keydown.dismiss.bs.modal', $.proxy(function (e) {
e.which == 27 && this.hide()
}, this))
} else if (!this.isShown) {
this.$element.off('keydown.dismiss.bs.modal')
}
}
Modal.prototype.resize = function () {
if (this.isShown) {
$(window).on('resize.bs.modal', $.proxy(this.handleUpdate, this))
} else {
$(window).off('resize.bs.modal')
}
}
Modal.prototype.hideModal = function () {
var that = this
this.$element.hide()
this.backdrop(function () {
that.$body.removeClass('modal-open')
that.resetAdjustments()
that.resetScrollbar()
that.$element.trigger('hidden.bs.modal')
})
}
Modal.prototype.removeBackdrop = function () {
this.$backdrop && this.$backdrop.remove()
this.$backdrop = null
}
Modal.prototype.backdrop = function (callback) {
var that = this
var animate = this.$element.hasClass('fade') ? 'fade' : ''
if (this.isShown && this.options.backdrop) {
var doAnimate = $.support.transition && animate
this.$backdrop = $(document.createElement('div'))
.addClass('modal-backdrop ' + animate)
.appendTo(this.$body)
this.$element.on('click.dismiss.bs.modal', $.proxy(function (e) {
if (this.ignoreBackdropClick) {
this.ignoreBackdropClick = false
return
}
if (e.target !== e.currentTarget) return
this.options.backdrop == 'static'
? this.$element[0].focus()
: this.hide()
}, this))
if (doAnimate) this.$backdrop[0].offsetWidth // force reflow
this.$backdrop.addClass('in')
if (!callback) return
doAnimate ?
this.$backdrop
.one('bsTransitionEnd', callback)
.emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
callback()
} else if (!this.isShown && this.$backdrop) {
this.$backdrop.removeClass('in')
var callbackRemove = function () {
that.removeBackdrop()
callback && callback()
}
$.support.transition && this.$element.hasClass('fade') ?
this.$backdrop
.one('bsTransitionEnd', callbackRemove)
.emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
callbackRemove()
} else if (callback) {
callback()
}
}
// these following methods are used to handle overflowing modals
Modal.prototype.handleUpdate = function () {
this.adjustDialog()
}
Modal.prototype.adjustDialog = function () {
var modalIsOverflowing = this.$element[0].scrollHeight > document.documentElement.clientHeight
this.$element.css({
paddingLeft: !this.bodyIsOverflowing && modalIsOverflowing ? this.scrollbarWidth : '',
paddingRight: this.bodyIsOverflowing && !modalIsOverflowing ? this.scrollbarWidth : ''
})
}
Modal.prototype.resetAdjustments = function () {
this.$element.css({
paddingLeft: '',
paddingRight: ''
})
}
Modal.prototype.checkScrollbar = function () {
var fullWindowWidth = window.innerWidth
if (!fullWindowWidth) { // workaround for missing window.innerWidth in IE8
var documentElementRect = document.documentElement.getBoundingClientRect()
fullWindowWidth = documentElementRect.right - Math.abs(documentElementRect.left)
}
this.bodyIsOverflowing = document.body.clientWidth < fullWindowWidth
this.scrollbarWidth = this.measureScrollbar()
}
Modal.prototype.setScrollbar = function () {
var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10)
this.originalBodyPad = document.body.style.paddingRight || ''
if (this.bodyIsOverflowing) this.$body.css('padding-right', bodyPad + this.scrollbarWidth)
}
Modal.prototype.resetScrollbar = function () {
this.$body.css('padding-right', this.originalBodyPad)
}
Modal.prototype.measureScrollbar = function () { // thx walsh
var scrollDiv = document.createElement('div')
scrollDiv.className = 'modal-scrollbar-measure'
this.$body.append(scrollDiv)
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth
this.$body[0].removeChild(scrollDiv)
return scrollbarWidth
}
// MODAL PLUGIN DEFINITION
// =======================
function Plugin(option, _relatedTarget) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.modal')
var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data) $this.data('bs.modal', (data = new Modal(this, options)))
if (typeof option == 'string') data[option](_relatedTarget)
else if (options.show) data.show(_relatedTarget)
})
}
var old = $.fn.modal
$.fn.modal = Plugin
$.fn.modal.Constructor = Modal
// MODAL NO CONFLICT
// =================
$.fn.modal.noConflict = function () {
$.fn.modal = old
return this
}
// MODAL DATA-API
// ==============
$(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) {
var $this = $(this)
var href = $this.attr('href')
var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7
var option = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())
if ($this.is('a')) e.preventDefault()
$target.one('show.bs.modal', function (showEvent) {
if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown
$target.one('hidden.bs.modal', function () {
$this.is(':visible') && $this.trigger('focus')
})
})
Plugin.call($target, option, this)
})
}(jQuery);
}); |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'bidi', 'fo', {
ltr: 'Tekstkós frá vinstru til høgru',
rtl: 'Tekstkós frá høgru til vinstru'
});
|
'use strict';
var glob = require('glob');
var Mocha = require('mocha');
var RSVP = require('rsvp');
var fs = require('fs-extra');
var mochaOnlyDetector = require('mocha-only-detector');
if (process.env.EOLNEWLINE) {
require('os').EOL = '\n';
}
fs.removeSync('.node_modules-tmp');
fs.removeSync('.bower_components-tmp');
var root = 'tests/{unit,acceptance}';
var _checkOnlyInTests = RSVP.denodeify(mochaOnlyDetector.checkFolder.bind(null, root + '/**/*{-test,-slow}.js'));
var optionOrFile = process.argv[2];
var mocha = new Mocha({
timeout: 5000,
reporter: process.env.MOCHA_REPORTER || 'spec',
retries: 2
});
var testFiles = glob.sync(root + '/**/*-test.js');
var lintPosition = testFiles.indexOf('tests/unit/lint-test.js');
var lint = testFiles.splice(lintPosition, 1);
var docsLintPosition = testFiles.indexOf('tests/unit/docs-lint-test.js');
var docsLint = testFiles.splice(docsLintPosition, 1);
testFiles = lint.concat(docsLint).concat(testFiles);
if (optionOrFile === 'all') {
addFiles(mocha, testFiles);
addFiles(mocha, '/**/*-slow.js');
} else if (optionOrFile === 'slow') {
addFiles(mocha, '/**/*-slow.js');
} else if (optionOrFile === 'lint') {
addFiles(mocha, lint);
addFiles(mocha, docsLint);
} else if (process.argv.length > 2) {
addFiles(mocha, process.argv.slice(2));
} else {
addFiles(mocha, testFiles);
}
function addFiles(mocha, files) {
files = (typeof files === 'string') ? glob.sync(root + files) : files;
files.forEach(mocha.addFile.bind(mocha));
}
function checkOnlyInTests() {
console.log('Verifing `.only` in tests');
return _checkOnlyInTests().then(function() {
console.log('No `.only` found');
});
}
function runMocha() {
console.time('Mocha Tests Running Time');
mocha.run(function(failures) {
process.on('exit', function() {
console.timeEnd('Mocha Tests Running Time');
process.exit(failures);
});
});
}
function ciVerificationStep() {
if (process.env.CI === 'true') {
return checkOnlyInTests();
} else {
return RSVP.resolve();
}
}
ciVerificationStep()
.then(function() {
runMocha();
})
.catch(function(error) {
console.error(error);
console.error(error.stack);
process.exit(1);
});
|
/*
* RTLCSS 2.0.5 https://github.com/MohammadYounes/rtlcss
* Framework for transforming Cascading Style Sheets (CSS) from Left-To-Right (LTR) to Right-To-Left (RTL).
* Copyright 2016 Mohammad Younes.
* Licensed under MIT <http://opensource.org/licenses/mit-license.php>
* */
'use strict'
var postcss = require('postcss')
// var directiveParser = require('./directive-parser.js')
var state = require('./state.js')
var config = require('./config.js')
var util = require('./util.js')
module.exports = postcss.plugin('rtlcss', function (options, plugins) {
var configuration = config.configure(options, plugins)
var context = {
// provides access to postcss
'postcss': postcss,
// provides access to the current configuration
'config': configuration,
// provides access to utilities object
'util': util.configure(configuration)
}
return function (css, result) {
var flipped = 0
var toBeRenamed = {}
css.walk(function (node) {
var prevent = false
state.walk(function (current) {
// check if current directive is expecting this node
if (!current.metadata.blacklist && current.directive.expect[node.type]) {
// perform action and prevent further processing if result equals true
if (current.directive.begin(node, current.metadata, context)) {
prevent = true
}
// if should end? end it.
if (current.metadata.end && current.directive.end(node, current.metadata, context)) {
state.pop(current)
}
}
})
if (prevent === false) {
switch (node.type) {
case 'atrule':
// @rules requires url flipping only
if (context.config.processUrls === true || context.config.processUrls.atrule === true) {
var params = context.util.applyStringMap(node.params, true)
node.params = params
}
break
case 'comment':
state.parse(node, result, function (current) {
var push = true
if (current.directive === null) {
current.preserve = !context.config.clean
context.util.each(context.config.plugins, function (plugin) {
var blacklist = context.config.blacklist[plugin.name]
if (blacklist && blacklist[current.metadata.name] === true) {
current.metadata.blacklist = true
if (current.metadata.end) {
push = false
}
if (current.metadata.begin) {
result.warn('directive "' + plugin.name + '.' + current.metadata.name + '" is blacklisted.', {node: current.source})
}
// break each
return false
}
current.directive = plugin.directives.control[current.metadata.name]
if (current.directive) {
// break each
return false
}
})
}
if (current.directive) {
if (!current.metadata.begin && current.metadata.end) {
if (current.directive.end(node, current.metadata, context)) {
state.pop(current)
}
push = false
} else if (current.directive.expect.self && current.directive.begin(node, current.metadata, context)) {
if (current.metadata.end && current.directive.end(node, current.metadata, context)) {
push = false
}
}
} else if (!current.metadata.blacklist) {
push = false
result.warn('unsupported directive "' + current.metadata.name + '".', {node: current.source})
}
return push
})
break
case 'decl':
// if broken by a matching value directive .. break
if (!context.util.each(context.config.plugins,
function (plugin) {
return context.util.each(plugin.directives.value, function (directive) {
if (node.raws.value && node.raws.value.raw) {
var expr = context.util.regexDirective(directive.name)
if (expr.test(node.raws.value.raw)) {
expr.lastIndex = 0
if (directive.action(node, expr, context)) {
if (context.config.clean) {
node.value = node.raws.value.raw = context.util.trimDirective(node.raws.value.raw)
}
flipped++
// break
return false
}
}
}
})
})) break
// loop over all plugins/property processors
context.util.each(context.config.plugins, function (plugin) {
return context.util.each(plugin.processors, function (directive) {
if (node.prop.match(directive.expr)) {
var raw = node.raws.value && node.raws.value.raw ? node.raws.value.raw : node.value
var state = context.util.saveComments(raw)
var pair = directive.action(node.prop, state.value, context)
state.value = pair.value
pair.value = context.util.restoreComments(state)
if (pair.prop !== node.prop || pair.value !== raw) {
flipped++
node.prop = pair.prop
node.value = pair.value
}
// match found, break
return false
}
})
})
// if last decl, apply auto rename
// decl. may be found inside @rules
if (context.config.autoRename && !flipped && node.parent.type === 'rule' && context.util.isLastOfType(node)) {
var renamed = context.util.applyStringMap(node.parent.selector)
if (context.config.autoRenameStrict === true) {
var pair = toBeRenamed[renamed]
if (pair) {
pair.selector = node.parent.selector
node.parent.selector = renamed
} else {
toBeRenamed[node.parent.selector] = node.parent
}
} else {
node.parent.selector = renamed
}
}
break
case 'rule':
// new rule, reset flipped decl count to zero
flipped = 0
break
}
}
})
state.walk(function (item) {
result.warn('unclosed directive "' + item.metadata.name + '".', {node: item.source})
})
Object.keys(toBeRenamed).forEach(function (key) {
result.warn('renaming skipped due to lack of a matching pair.', {node: toBeRenamed[key]})
})
}
})
/**
* Creates a new RTLCSS instance, process the input and return its result.
* @param {String} css A string containing input CSS.
* @param {Object} options An object containing RTLCSS settings.
* @param {Object|Array} plugins An array containing a list of RTLCSS plugins or a single RTLCSS plugin.
* @returns {String} A string contining the RTLed css.
*/
module.exports.process = function (css, options, plugins) {
return postcss([this(options, plugins)]).process(css).css
}
/**
* Creates a new instance of RTLCSS using the passed configuration object
* @param {Object} config An object containing RTLCSS options and plugins.
* @returns {Object} A new RTLCSS instance.
*/
module.exports.configure = function (config) {
config = config || {}
return postcss([this(config.options, config.plugins)])
}
|
import Ember from 'ember';
import config from './config/environment';
var Router = Ember.Router.extend({
location: config.locationType
});
Router.map(function() {
/* Interactive Documentation */
this.route('installation');
this.route("helpers-documentation", { path: 'helpers'}, function(){
this.route('liquid-outlet', function(){
this.route('other');
});
this.route('liquid-bind');
this.route('liquid-bind-block', function(){
this.route('page', { path: '/:id' });
});
this.route('liquid-if');
this.route('liquid-spacer');
});
this.route('transition-map', function(){
this.route('route-constraints');
this.route('value-constraints');
this.route('dom-constraints');
this.route('initial-constraints');
this.route('choosing-transitions');
this.route('debugging-constraints');
});
this.route('transitions', function(){
this.route('predefined');
this.route('explode');
this.route('defining');
this.route('primitives', function(){
this.route('two');
this.route('three');
});
});
this.route("modal-documentation", { path: 'modals'}, function(){
this.route('modal');
this.route('component');
this.route('animation');
// BEGIN-SNIPPET hello-modal-map
this.modal('hello-modal', {
withParams: ['salutation', 'person'],
otherParams: {
modalMessage: "message"
},
actions: {
changeSalutation: "changeSalutation"
}
});
// END-SNIPPET
});
this.modal('warning-popup', {
withParams: 'warn'
});
/* Test Scenarios */
this.route('scenarios', function() {
this.route('inline');
this.route('inline-serial');
this.route('empty-if');
this.route('growable-with');
this.route('growable-flexboxes');
this.route('nested-outlets', function(){
this.route('middle', function(){
this.route('inner');
this.route('inner2');
});
this.route('middle2');
});
this.route('table-row');
this.route('remapped-modal');
this.modal('hello-modal', {
withParams: {
testSalutation : 'salutation',
testPerson : 'person'
}
});
this.route('spacer');
this.route('versions');
this.route('hero');
this.route('model-dependent-rule', function() {
this.route('page', { path: '/:id' });
this.route('other', { path: '/other/:id' });
});
this.route('interrupted-move', function() {
this.route('two');
this.route('three');
});
this.route('in-test-outlet');
});
});
export default Router;
|
//>>excludeStart('excludeAfterBuild', pragmas.excludeAfterBuild)
define(['hbs/handlebars', "hbs/underscore"], function ( Handlebars, _ ) {
function replaceLocaleStrings ( ast, mapping, options ) {
options = options || {};
mapping = mapping || {};
// Base set of things
if ( ast && ast.type === "program" && ast.statements ) {
_(ast.statements).forEach(function(statement, i){
var newString = "<!-- i18n error -->";
// If it's a translation node
if ( statement.type === "mustache" && statement.id && statement.id.original === "$" ) {
if ( statement.params.length && statement.params[0].string ) {
var key = statement.params[0].string;
newString = mapping[ key ] || (options.originalKeyFallback ? key : newString);
}
ast.statements[i] = new Handlebars.AST.ContentNode(newString);
}
// If we need to recurse
else if ( statement.program ) {
statement.program = replaceLocaleStrings( statement.program, mapping, options );
}
});
// Also cover the else blocks
if (ast.inverse) {
replaceLocaleStrings(ast.inverse, mapping, options);
}
}
return ast;
}
return function precompile (string, mapping, options) {
var ast, environment;
options = options || {};
if (!('data' in options)) {
options.data = true;
}
if (options.compat) {
options.useDepths = true;
}
ast = Handlebars.parse(string);
// avoid replacing locale if mapping is `false`
if (mapping !== false) {
ast = replaceLocaleStrings(ast, mapping, options);
}
environment = new Handlebars.Compiler().compile(ast, options);
return new Handlebars.JavaScriptCompiler().compile(environment, options);
};
});
//>>excludeEnd('excludeAfterBuild')
|
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v17.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
var column_1 = require("./entities/column");
var context_1 = require("./context/context");
var gridOptionsWrapper_1 = require("./gridOptionsWrapper");
var columnApi_1 = require("./columnController/columnApi");
var columnController_1 = require("./columnController/columnController");
var eventService_1 = require("./eventService");
var events_1 = require("./events");
var context_2 = require("./context/context");
var utils_1 = require("./utils");
var gridApi_1 = require("./gridApi");
var SortController = (function () {
function SortController() {
}
SortController_1 = SortController;
SortController.prototype.progressSort = function (column, multiSort, source) {
if (source === void 0) { source = "api"; }
var nextDirection = this.getNextSortDirection(column);
this.setSortForColumn(column, nextDirection, multiSort, source);
};
SortController.prototype.setSortForColumn = function (column, sort, multiSort, source) {
if (source === void 0) { source = "api"; }
// auto correct - if sort not legal value, then set it to 'no sort' (which is null)
if (sort !== column_1.Column.SORT_ASC && sort !== column_1.Column.SORT_DESC) {
sort = null;
}
// update sort on current col
column.setSort(sort, source);
// sortedAt used for knowing order of cols when multi-col sort
if (column.getSort()) {
var sortedAt = Number(new Date().valueOf());
column.setSortedAt(sortedAt);
}
else {
column.setSortedAt(null);
}
var doingMultiSort = multiSort && !this.gridOptionsWrapper.isSuppressMultiSort();
// clear sort on all columns except this one, and update the icons
if (!doingMultiSort) {
this.clearSortBarThisColumn(column, source);
}
this.dispatchSortChangedEvents();
};
// gets called by API, so if data changes, use can call this, which will end up
// working out the sort order again of the rows.
SortController.prototype.onSortChanged = function () {
this.dispatchSortChangedEvents();
};
SortController.prototype.dispatchSortChangedEvents = function () {
var event = {
type: events_1.Events.EVENT_SORT_CHANGED,
api: this.gridApi,
columnApi: this.columnApi
};
this.eventService.dispatchEvent(event);
};
SortController.prototype.clearSortBarThisColumn = function (columnToSkip, source) {
this.columnController.getPrimaryAndSecondaryAndAutoColumns().forEach(function (columnToClear) {
// Do not clear if either holding shift, or if column in question was clicked
if (!(columnToClear === columnToSkip)) {
columnToClear.setSort(null, source);
}
});
};
SortController.prototype.getNextSortDirection = function (column) {
var sortingOrder;
if (column.getColDef().sortingOrder) {
sortingOrder = column.getColDef().sortingOrder;
}
else if (this.gridOptionsWrapper.getSortingOrder()) {
sortingOrder = this.gridOptionsWrapper.getSortingOrder();
}
else {
sortingOrder = SortController_1.DEFAULT_SORTING_ORDER;
}
if (!Array.isArray(sortingOrder) || sortingOrder.length <= 0) {
console.warn('ag-grid: sortingOrder must be an array with at least one element, currently it\'s ' + sortingOrder);
return;
}
var currentIndex = sortingOrder.indexOf(column.getSort());
var notInArray = currentIndex < 0;
var lastItemInArray = currentIndex == sortingOrder.length - 1;
var result;
if (notInArray || lastItemInArray) {
result = sortingOrder[0];
}
else {
result = sortingOrder[currentIndex + 1];
}
// verify the sort type exists, as the user could provide the sortingOrder, need to make sure it's valid
if (SortController_1.DEFAULT_SORTING_ORDER.indexOf(result) < 0) {
console.warn('ag-grid: invalid sort type ' + result);
return null;
}
return result;
};
// used by the public api, for saving the sort model
SortController.prototype.getSortModel = function () {
var columnsWithSorting = this.getColumnsWithSortingOrdered();
return utils_1.Utils.map(columnsWithSorting, function (column) {
return {
colId: column.getColId(),
sort: column.getSort()
};
});
};
SortController.prototype.setSortModel = function (sortModel, source) {
var _this = this;
if (source === void 0) { source = "api"; }
if (!this.gridOptionsWrapper.isEnableSorting()) {
console.warn('ag-grid: You are setting the sort model on a grid that does not have sorting enabled');
return;
}
// first up, clear any previous sort
var sortModelProvided = sortModel && sortModel.length > 0;
var allColumnsIncludingAuto = this.columnController.getPrimaryAndSecondaryAndAutoColumns();
allColumnsIncludingAuto.forEach(function (column) {
var sortForCol = null;
var sortedAt = -1;
if (sortModelProvided && !column.getColDef().suppressSorting) {
for (var j = 0; j < sortModel.length; j++) {
var sortModelEntry = sortModel[j];
if (typeof sortModelEntry.colId === 'string'
&& typeof column.getColId() === 'string'
&& _this.compareColIds(sortModelEntry, column)) {
sortForCol = sortModelEntry.sort;
sortedAt = j;
}
}
}
if (sortForCol) {
column.setSort(sortForCol, source);
column.setSortedAt(sortedAt);
}
else {
column.setSort(null, source);
column.setSortedAt(null);
}
});
this.dispatchSortChangedEvents();
};
SortController.prototype.compareColIds = function (sortModelEntry, column) {
return sortModelEntry.colId === column.getColId();
};
SortController.prototype.getColumnsWithSortingOrdered = function () {
// pull out all the columns that have sorting set
var allColumnsIncludingAuto = this.columnController.getPrimaryAndSecondaryAndAutoColumns();
var columnsWithSorting = utils_1.Utils.filter(allColumnsIncludingAuto, function (column) { return !!column.getSort(); });
// put the columns in order of which one got sorted first
columnsWithSorting.sort(function (a, b) { return a.sortedAt - b.sortedAt; });
return columnsWithSorting;
};
// used by row controller, when doing the sorting
SortController.prototype.getSortForRowController = function () {
var columnsWithSorting = this.getColumnsWithSortingOrdered();
return utils_1.Utils.map(columnsWithSorting, function (column) {
var ascending = column.getSort() === column_1.Column.SORT_ASC;
return {
inverter: ascending ? 1 : -1,
column: column
};
});
};
SortController.DEFAULT_SORTING_ORDER = [column_1.Column.SORT_ASC, column_1.Column.SORT_DESC, null];
__decorate([
context_1.Autowired('gridOptionsWrapper'),
__metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper)
], SortController.prototype, "gridOptionsWrapper", void 0);
__decorate([
context_1.Autowired('columnController'),
__metadata("design:type", columnController_1.ColumnController)
], SortController.prototype, "columnController", void 0);
__decorate([
context_1.Autowired('eventService'),
__metadata("design:type", eventService_1.EventService)
], SortController.prototype, "eventService", void 0);
__decorate([
context_1.Autowired('columnApi'),
__metadata("design:type", columnApi_1.ColumnApi)
], SortController.prototype, "columnApi", void 0);
__decorate([
context_1.Autowired('gridApi'),
__metadata("design:type", gridApi_1.GridApi)
], SortController.prototype, "gridApi", void 0);
SortController = SortController_1 = __decorate([
context_2.Bean('sortController')
], SortController);
return SortController;
var SortController_1;
}());
exports.SortController = SortController;
|
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v17.1.1
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var utils_1 = require("../utils");
var TabbedLayout = (function () {
function TabbedLayout(params) {
var _this = this;
this.items = [];
this.params = params;
this.eGui = document.createElement('div');
this.eGui.innerHTML = TabbedLayout.TEMPLATE;
this.eHeader = this.eGui.querySelector('#tabHeader');
this.eBody = this.eGui.querySelector('#tabBody');
utils_1.Utils.addCssClass(this.eGui, params.cssClass);
if (params.items) {
params.items.forEach(function (item) { return _this.addItem(item); });
}
}
TabbedLayout.prototype.setAfterAttachedParams = function (params) {
this.afterAttachedParams = params;
};
TabbedLayout.prototype.getMinWidth = function () {
var eDummyContainer = document.createElement('span');
// position fixed, so it isn't restricted to the boundaries of the parent
eDummyContainer.style.position = 'fixed';
// we put the dummy into the body container, so it will inherit all the
// css styles that the real cells are inheriting
this.eGui.appendChild(eDummyContainer);
var minWidth = 0;
this.items.forEach(function (itemWrapper) {
utils_1.Utils.removeAllChildren(eDummyContainer);
var eClone = itemWrapper.tabbedItem.bodyPromise.resolveNow(null, function (body) { return body.cloneNode(true); });
if (eClone == null) {
return;
}
eDummyContainer.appendChild(eClone);
if (minWidth < eDummyContainer.offsetWidth) {
minWidth = eDummyContainer.offsetWidth;
}
});
this.eGui.removeChild(eDummyContainer);
return minWidth;
};
TabbedLayout.prototype.showFirstItem = function () {
if (this.items.length > 0) {
this.showItemWrapper(this.items[0]);
}
};
TabbedLayout.prototype.addItem = function (item) {
var eHeaderButton = document.createElement('span');
eHeaderButton.appendChild(item.title);
utils_1.Utils.addCssClass(eHeaderButton, 'ag-tab');
this.eHeader.appendChild(eHeaderButton);
var wrapper = {
tabbedItem: item,
eHeaderButton: eHeaderButton
};
this.items.push(wrapper);
eHeaderButton.addEventListener('click', this.showItemWrapper.bind(this, wrapper));
};
TabbedLayout.prototype.showItem = function (tabbedItem) {
var itemWrapper = utils_1.Utils.find(this.items, function (itemWrapper) {
return itemWrapper.tabbedItem === tabbedItem;
});
if (itemWrapper) {
this.showItemWrapper(itemWrapper);
}
};
TabbedLayout.prototype.showItemWrapper = function (wrapper) {
var _this = this;
if (this.params.onItemClicked) {
this.params.onItemClicked({ item: wrapper.tabbedItem });
}
if (this.activeItem === wrapper) {
utils_1.Utils.callIfPresent(this.params.onActiveItemClicked);
return;
}
utils_1.Utils.removeAllChildren(this.eBody);
wrapper.tabbedItem.bodyPromise.then(function (body) {
_this.eBody.appendChild(body);
});
if (this.activeItem) {
utils_1.Utils.removeCssClass(this.activeItem.eHeaderButton, 'ag-tab-selected');
}
utils_1.Utils.addCssClass(wrapper.eHeaderButton, 'ag-tab-selected');
this.activeItem = wrapper;
if (wrapper.tabbedItem.afterAttachedCallback) {
wrapper.tabbedItem.afterAttachedCallback(this.afterAttachedParams);
}
};
TabbedLayout.prototype.getGui = function () {
return this.eGui;
};
TabbedLayout.TEMPLATE = '<div>' +
'<div id="tabHeader" class="ag-tab-header"></div>' +
'<div id="tabBody" class="ag-tab-body"></div>' +
'</div>';
return TabbedLayout;
}());
exports.TabbedLayout = TabbedLayout;
|
var dep8;
|
/* @flow */
function foo(text: string | number): string {
switch (typeof text) {
case 'string':
return text;
case 'number':
return text; // error, should return string
default:
return 'wat';
}
}
function bar(text: string | number): string {
switch (typeof text) {
case 'string':
return text[0];
default:
return (text++) + '';
}
}
function baz1(text: string | number): string {
switch (typeof text) {
case 'number':
case 'string':
return text[0]; // error, [0] on number
default:
return 'wat';
}
}
function baz2(text: string | number): string {
switch (typeof text) {
case 'string':
case 'number':
return text[0]; // error, [0] on number
default:
return 'wat';
}
}
function corge(text: string | number | Array<string>): string {
switch (typeof text) {
case 'object':
return text[0];
case 'string':
case 'number':
// using ++ since it isn't valid on arrays or strings.
// should only error for string since Array was filtered out.
return (text++) + '';
default:
return 'wat';
}
}
|
/*!
* Note: While Microsoft is not the author of this script file, Microsoft
* grants you the right to use this file for the sole purpose of either:
* (i) interacting through your browser with the Microsoft website, subject
* to the website's terms of use; or (ii) using the files as included with a
* Microsoft product subject to the Microsoft Software License Terms for that
* Microsoft product. Microsoft reserves all other rights to the files not
* expressly granted by Microsoft, whether by implication, estoppel or
* otherwise. The notices and licenses below are for informational purposes
* only.
*
* Provided for Informational Purposes Only
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* jQuery JavaScript Library v1.6.2
* http://jquery.com/
*
* Copyright 2011, John Resig
*
* Includes Sizzle.js
* http://sizzlejs.com/
* Copyright 2011, The Dojo Foundation
*
* Date: Thu Jun 30 14:16:56 2011 -0400
*/
(function( window, undefined ) {
// Use the correct document accordingly with window argument (sandbox)
var document = window.document,
navigator = window.navigator,
location = window.location;
var jQuery = (function() {
// Define a local copy of jQuery
var jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// A central reference to the root jQuery(document)
rootjQuery,
// A simple way to check for HTML strings or ID strings
// (both of which we optimize for)
quickExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,
// Check if a string has a non-whitespace character in it
rnotwhite = /\S/,
// Used for trimming whitespace
trimLeft = /^\s+/,
trimRight = /\s+$/,
// Check for digits
rdigit = /\d/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
// Useragent RegExp
rwebkit = /(webkit)[ \/]([\w.]+)/,
ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/,
rmsie = /(msie) ([\w.]+)/,
rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/,
// Matches dashed string for camelizing
rdashAlpha = /-([a-z])/ig,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
},
// Keep a UserAgent string for use with jQuery.browser
userAgent = navigator.userAgent,
// For matching the engine and version of the browser
browserMatch,
// The deferred used on DOM ready
readyList,
// The ready event handler
DOMContentLoaded,
// Save a reference to some core methods
toString = Object.prototype.toString,
hasOwn = Object.prototype.hasOwnProperty,
push = Array.prototype.push,
slice = Array.prototype.slice,
trim = String.prototype.trim,
indexOf = Array.prototype.indexOf,
// [[Class]] -> type pairs
class2type = {};
jQuery.fn = jQuery.prototype = {
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem, ret, doc;
// Handle $(""), $(null), or $(undefined)
if ( !selector ) {
return this;
}
// Handle $(DOMElement)
if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
}
// The body element only exists once, optimize finding it
if ( selector === "body" && !context && document.body ) {
this.context = document;
this[0] = document.body;
this.selector = selector;
this.length = 1;
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
// Are we dealing with HTML string or an ID?
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = quickExpr.exec( selector );
}
// Verify a match, and that no context was specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
doc = (context ? context.ownerDocument || context : document);
// If a single string is passed in and it's a single tag
// just do a createElement and skip the rest
ret = rsingleTag.exec( selector );
if ( ret ) {
if ( jQuery.isPlainObject( context ) ) {
selector = [ document.createElement( ret[1] ) ];
jQuery.fn.attr.call( selector, context, true );
} else {
selector = [ doc.createElement( ret[1] ) ];
}
} else {
ret = jQuery.buildFragment( [ match[1] ], [ doc ] );
selector = (ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment).childNodes;
}
return jQuery.merge( this, selector );
// HANDLE: $("#id")
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return (context || rootjQuery).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if (selector.selector !== undefined) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The current version of jQuery being used
jquery: "1.6.2",
// The default length of a jQuery object is 0
length: 0,
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
toArray: function() {
return slice.call( this, 0 );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems, name, selector ) {
// Build a new jQuery matched element set
var ret = this.constructor();
if ( jQuery.isArray( elems ) ) {
push.apply( ret, elems );
} else {
jQuery.merge( ret, elems );
}
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
if ( name === "find" ) {
ret.selector = this.selector + (this.selector ? " " : "") + selector;
} else if ( name ) {
ret.selector = this.selector + "." + name + "(" + selector + ")";
}
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Attach the listeners
jQuery.bindReady();
// Add the callback
readyList.done( fn );
return this;
},
eq: function( i ) {
return i === -1 ?
this.slice( i ) :
this.slice( i, +i + 1 );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
slice: function() {
return this.pushStack( slice.apply( this, arguments ),
"slice", slice.call(arguments).join(",") );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Either a released hold or an DOMready/load event and not yet ready
if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready, 1 );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger( "ready" ).unbind( "ready" );
}
}
},
bindReady: function() {
if ( readyList ) {
return;
}
readyList = jQuery._Deferred();
// Catch cases where $(document).ready() is called after the
// browser event has already occurred.
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
return setTimeout( jQuery.ready, 1 );
}
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", DOMContentLoaded );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
// If IE and not a frame
// continually check to see if the document is ready
var toplevel = false;
try {
toplevel = window.frameElement == null;
} catch(e) {}
if ( document.documentElement.doScroll && toplevel ) {
doScrollCheck();
}
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
// A crude way of determining if an object is a window
isWindow: function( obj ) {
return obj && typeof obj === "object" && "setInterval" in obj;
},
isNaN: function( obj ) {
return obj == null || !rdigit.test( obj ) || isNaN( obj );
},
type: function( obj ) {
return obj == null ?
String( obj ) :
class2type[ toString.call(obj) ] || "object";
},
isPlainObject: function( obj ) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
// Not own constructor property must be Object
if ( obj.constructor &&
!hasOwn.call(obj, "constructor") &&
!hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
for ( var name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw msg;
},
parseJSON: function( data ) {
if ( typeof data !== "string" || !data ) {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return (new Function( "return " + data ))();
}
jQuery.error( "Invalid JSON: " + data );
},
// Cross-browser xml parsing
// (xml & tmp used internally)
parseXML: function( data , xml , tmp ) {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
tmp = xml.documentElement;
if ( ! tmp || ! tmp.nodeName || tmp.nodeName === "parsererror" ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && rnotwhite.test( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Converts a dashed string to camelCased string;
// Used by both the css and data modules
camelCase: function( string ) {
return string.replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
},
// args is for internal usage only
each: function( object, callback, args ) {
var name, i = 0,
length = object.length,
isObj = length === undefined || jQuery.isFunction( object );
if ( args ) {
if ( isObj ) {
for ( name in object ) {
if ( callback.apply( object[ name ], args ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.apply( object[ i++ ], args ) === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isObj ) {
for ( name in object ) {
if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) {
break;
}
}
}
}
return object;
},
// Use native String.trim function wherever possible
trim: trim ?
function( text ) {
return text == null ?
"" :
trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
text.toString().replace( trimLeft, "" ).replace( trimRight, "" );
},
// results is for internal usage only
makeArray: function( array, results ) {
var ret = results || [];
if ( array != null ) {
// The window, strings (and functions) also have 'length'
// The extra typeof function check is to prevent crashes
// in Safari 2 (See: #3039)
// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
var type = jQuery.type( array );
if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) {
push.call( ret, array );
} else {
jQuery.merge( ret, array );
}
}
return ret;
},
inArray: function( elem, array ) {
if ( indexOf ) {
return indexOf.call( array, elem );
}
for ( var i = 0, length = array.length; i < length; i++ ) {
if ( array[ i ] === elem ) {
return i;
}
}
return -1;
},
merge: function( first, second ) {
var i = first.length,
j = 0;
if ( typeof second.length === "number" ) {
for ( var l = second.length; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var ret = [], retVal;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( var i = 0, length = elems.length; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value, key, ret = [],
i = 0,
length = elems.length,
// jquery objects are treated as arrays
isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( key in elems ) {
value = callback( elems[ key ], key, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return ret.concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
if ( typeof context === "string" ) {
var tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
var args = slice.call( arguments, 2 ),
proxy = function() {
return fn.apply( context, args.concat( slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
return proxy;
},
// Mutifunctional method to get and set values to a collection
// The value/s can optionally be executed if it's a function
access: function( elems, key, value, exec, fn, pass ) {
var length = elems.length;
// Setting many attributes
if ( typeof key === "object" ) {
for ( var k in key ) {
jQuery.access( elems, k, key[k], exec, fn, value );
}
return elems;
}
// Setting one attribute
if ( value !== undefined ) {
// Optionally, function values get executed if exec is true
exec = !pass && exec && jQuery.isFunction(value);
for ( var i = 0; i < length; i++ ) {
fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
}
return elems;
}
// Getting an attribute
return length ? fn( elems[0], key ) : undefined;
},
now: function() {
return (new Date()).getTime();
},
// Use of jQuery.browser is frowned upon.
// More details: http://docs.jquery.com/Utilities/jQuery.browser
uaMatch: function( ua ) {
ua = ua.toLowerCase();
var match = rwebkit.exec( ua ) ||
ropera.exec( ua ) ||
rmsie.exec( ua ) ||
ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) ||
[];
return { browser: match[1] || "", version: match[2] || "0" };
},
sub: function() {
function jQuerySub( selector, context ) {
return new jQuerySub.fn.init( selector, context );
}
jQuery.extend( true, jQuerySub, this );
jQuerySub.superclass = this;
jQuerySub.fn = jQuerySub.prototype = this();
jQuerySub.fn.constructor = jQuerySub;
jQuerySub.sub = this.sub;
jQuerySub.fn.init = function init( selector, context ) {
if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
context = jQuerySub( context );
}
return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
};
jQuerySub.fn.init.prototype = jQuerySub.fn;
var rootjQuerySub = jQuerySub(document);
return jQuerySub;
},
browser: {}
});
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
browserMatch = jQuery.uaMatch( userAgent );
if ( browserMatch.browser ) {
jQuery.browser[ browserMatch.browser ] = true;
jQuery.browser.version = browserMatch.version;
}
// Deprecated, use jQuery.browser.webkit instead
if ( jQuery.browser.webkit ) {
jQuery.browser.safari = true;
}
// IE doesn't match non-breaking spaces with \s
if ( rnotwhite.test( "\xA0" ) ) {
trimLeft = /^[\s\xA0]+/;
trimRight = /[\s\xA0]+$/;
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
// Cleanup functions for the document ready method
if ( document.addEventListener ) {
DOMContentLoaded = function() {
document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
jQuery.ready();
};
} else if ( document.attachEvent ) {
DOMContentLoaded = function() {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", DOMContentLoaded );
jQuery.ready();
}
};
}
// The DOM ready check for Internet Explorer
function doScrollCheck() {
if ( jQuery.isReady ) {
return;
}
try {
// If IE is used, use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
document.documentElement.doScroll("left");
} catch(e) {
setTimeout( doScrollCheck, 1 );
return;
}
// and execute any waiting functions
jQuery.ready();
}
return jQuery;
})();
var // Promise methods
promiseMethods = "done fail isResolved isRejected promise then always pipe".split( " " ),
// Static reference to slice
sliceDeferred = [].slice;
jQuery.extend({
// Create a simple deferred (one callbacks list)
_Deferred: function() {
var // callbacks list
callbacks = [],
// stored [ context , args ]
fired,
// to avoid firing when already doing so
firing,
// flag to know if the deferred has been cancelled
cancelled,
// the deferred itself
deferred = {
// done( f1, f2, ...)
done: function() {
if ( !cancelled ) {
var args = arguments,
i,
length,
elem,
type,
_fired;
if ( fired ) {
_fired = fired;
fired = 0;
}
for ( i = 0, length = args.length; i < length; i++ ) {
elem = args[ i ];
type = jQuery.type( elem );
if ( type === "array" ) {
deferred.done.apply( deferred, elem );
} else if ( type === "function" ) {
callbacks.push( elem );
}
}
if ( _fired ) {
deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] );
}
}
return this;
},
// resolve with given context and args
resolveWith: function( context, args ) {
if ( !cancelled && !fired && !firing ) {
// make sure args are available (#8421)
args = args || [];
firing = 1;
try {
while( callbacks[ 0 ] ) {
callbacks.shift().apply( context, args );
}
}
finally {
fired = [ context, args ];
firing = 0;
}
}
return this;
},
// resolve with this as context and given arguments
resolve: function() {
deferred.resolveWith( this, arguments );
return this;
},
// Has this deferred been resolved?
isResolved: function() {
return !!( firing || fired );
},
// Cancel
cancel: function() {
cancelled = 1;
callbacks = [];
return this;
}
};
return deferred;
},
// Full fledged deferred (two callbacks list)
Deferred: function( func ) {
var deferred = jQuery._Deferred(),
failDeferred = jQuery._Deferred(),
promise;
// Add errorDeferred methods, then and promise
jQuery.extend( deferred, {
then: function( doneCallbacks, failCallbacks ) {
deferred.done( doneCallbacks ).fail( failCallbacks );
return this;
},
always: function() {
return deferred.done.apply( deferred, arguments ).fail.apply( this, arguments );
},
fail: failDeferred.done,
rejectWith: failDeferred.resolveWith,
reject: failDeferred.resolve,
isRejected: failDeferred.isResolved,
pipe: function( fnDone, fnFail ) {
return jQuery.Deferred(function( newDefer ) {
jQuery.each( {
done: [ fnDone, "resolve" ],
fail: [ fnFail, "reject" ]
}, function( handler, data ) {
var fn = data[ 0 ],
action = data[ 1 ],
returned;
if ( jQuery.isFunction( fn ) ) {
deferred[ handler ](function() {
returned = fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise().then( newDefer.resolve, newDefer.reject );
} else {
newDefer[ action ]( returned );
}
});
} else {
deferred[ handler ]( newDefer[ action ] );
}
});
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
if ( obj == null ) {
if ( promise ) {
return promise;
}
promise = obj = {};
}
var i = promiseMethods.length;
while( i-- ) {
obj[ promiseMethods[i] ] = deferred[ promiseMethods[i] ];
}
return obj;
}
});
// Make sure only one callback list will be used
deferred.done( failDeferred.cancel ).fail( deferred.cancel );
// Unexpose cancel
delete deferred.cancel;
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
return deferred;
},
// Deferred helper
when: function( firstParam ) {
var args = arguments,
i = 0,
length = args.length,
count = length,
deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ?
firstParam :
jQuery.Deferred();
function resolveFunc( i ) {
return function( value ) {
args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value;
if ( !( --count ) ) {
// Strange bug in FF4:
// Values changed onto the arguments object sometimes end up as undefined values
// outside the $.when method. Cloning the object into a fresh array solves the issue
deferred.resolveWith( deferred, sliceDeferred.call( args, 0 ) );
}
};
}
if ( length > 1 ) {
for( ; i < length; i++ ) {
if ( args[ i ] && jQuery.isFunction( args[ i ].promise ) ) {
args[ i ].promise().then( resolveFunc(i), deferred.reject );
} else {
--count;
}
}
if ( !count ) {
deferred.resolveWith( deferred, args );
}
} else if ( deferred !== firstParam ) {
deferred.resolveWith( deferred, length ? [ firstParam ] : [] );
}
return deferred.promise();
}
});
jQuery.support = (function() {
var div = document.createElement( "div" ),
documentElement = document.documentElement,
all,
a,
select,
opt,
input,
marginDiv,
support,
fragment,
body,
testElementParent,
testElement,
testElementStyle,
tds,
events,
eventName,
i,
isSupported;
// Preliminary tests
div.setAttribute("className", "t");
div.innerHTML = " <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>";
all = div.getElementsByTagName( "*" );
a = div.getElementsByTagName( "a" )[ 0 ];
// Can't get basic test support
if ( !all || !all.length || !a ) {
return {};
}
// First batch of supports tests
select = document.createElement( "select" );
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName( "input" )[ 0 ];
support = {
// IE strips leading whitespace when .innerHTML is used
leadingWhitespace: ( div.firstChild.nodeType === 3 ),
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
tbody: !div.getElementsByTagName( "tbody" ).length,
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
htmlSerialize: !!div.getElementsByTagName( "link" ).length,
// Get the style information from getAttribute
// (IE uses .cssText instead)
style: /top/.test( a.getAttribute("style") ),
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
hrefNormalized: ( a.getAttribute( "href" ) === "/a" ),
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
opacity: /^0.55$/.test( a.style.opacity ),
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
cssFloat: !!a.style.cssFloat,
// Make sure that if no value is specified for a checkbox
// that it defaults to "on".
// (WebKit defaults to "" instead)
checkOn: ( input.value === "on" ),
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
optSelected: opt.selected,
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
getSetAttribute: div.className !== "t",
// Will be defined later
submitBubbles: true,
changeBubbles: true,
focusinBubbles: false,
deleteExpando: true,
noCloneEvent: true,
inlineBlockNeedsLayout: false,
shrinkWrapBlocks: false,
reliableMarginRight: true
};
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Test to see if it's possible to delete an expando from an element
// Fails in Internet Explorer
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
if ( !div.addEventListener && div.attachEvent && div.fireEvent ) {
div.attachEvent( "onclick", function() {
// Cloning a node shouldn't copy over any
// bound event handlers (IE does this)
support.noCloneEvent = false;
});
div.cloneNode( true ).fireEvent( "onclick" );
}
// Check if a radio maintains it's value
// after being appended to the DOM
input = document.createElement("input");
input.value = "t";
input.setAttribute("type", "radio");
support.radioValue = input.value === "t";
input.setAttribute("checked", "checked");
div.appendChild( input );
fragment = document.createDocumentFragment();
fragment.appendChild( div.firstChild );
// WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
div.innerHTML = "";
// Figure out if the W3C box model works as expected
div.style.width = div.style.paddingLeft = "1px";
body = document.getElementsByTagName( "body" )[ 0 ];
// We use our own, invisible, body unless the body is already present
// in which case we use a div (#9239)
testElement = document.createElement( body ? "div" : "body" );
testElementStyle = {
visibility: "hidden",
width: 0,
height: 0,
border: 0,
margin: 0
};
if ( body ) {
jQuery.extend( testElementStyle, {
position: "absolute",
left: -1000,
top: -1000
});
}
for ( i in testElementStyle ) {
testElement.style[ i ] = testElementStyle[ i ];
}
testElement.appendChild( div );
testElementParent = body || documentElement;
testElementParent.insertBefore( testElement, testElementParent.firstChild );
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
support.appendChecked = input.checked;
support.boxModel = div.offsetWidth === 2;
if ( "zoom" in div.style ) {
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
// (IE < 8 does this)
div.style.display = "inline";
div.style.zoom = 1;
support.inlineBlockNeedsLayout = ( div.offsetWidth === 2 );
// Check if elements with layout shrink-wrap their children
// (IE 6 does this)
div.style.display = "";
div.innerHTML = "<div style='width:4px;'></div>";
support.shrinkWrapBlocks = ( div.offsetWidth !== 2 );
}
div.innerHTML = "<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>";
tds = div.getElementsByTagName( "td" );
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
// (only IE 8 fails this test)
isSupported = ( tds[ 0 ].offsetHeight === 0 );
tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";
// Check if empty table cells still have offsetWidth/Height
// (IE < 8 fail this test)
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
div.innerHTML = "";
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. For more
// info see bug #3333
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
if ( document.defaultView && document.defaultView.getComputedStyle ) {
marginDiv = document.createElement( "div" );
marginDiv.style.width = "0";
marginDiv.style.marginRight = "0";
div.appendChild( marginDiv );
support.reliableMarginRight =
( parseInt( ( document.defaultView.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0;
}
// Remove the body element we added
testElement.innerHTML = "";
testElementParent.removeChild( testElement );
// Technique from Juriy Zaytsev
// http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/
// We only care about the case where non-standard event systems
// are used, namely in IE. Short-circuiting here helps us to
// avoid an eval call (in setAttribute) which can cause CSP
// to go haywire. See: https://developer.mozilla.org/en/Security/CSP
if ( div.attachEvent ) {
for( i in {
submit: 1,
change: 1,
focusin: 1
} ) {
eventName = "on" + i;
isSupported = ( eventName in div );
if ( !isSupported ) {
div.setAttribute( eventName, "return;" );
isSupported = ( typeof div[ eventName ] === "function" );
}
support[ i + "Bubbles" ] = isSupported;
}
}
// Null connected elements to avoid leaks in IE
testElement = fragment = select = opt = body = marginDiv = div = input = null;
return support;
})();
// Keep track of boxModel
jQuery.boxModel = jQuery.support.boxModel;
var rbrace = /^(?:\{.*\}|\[.*\])$/,
rmultiDash = /([a-z])([A-Z])/g;
jQuery.extend({
cache: {},
// Please use with caution
uuid: 0,
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
"applet": true
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var internalKey = jQuery.expando, getByName = typeof name === "string", thisCache,
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ jQuery.expando ] : elem[ jQuery.expando ] && jQuery.expando;
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || (pvt && id && !cache[ id ][ internalKey ])) && getByName && data === undefined ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
elem[ jQuery.expando ] = id = ++jQuery.uuid;
} else {
id = jQuery.expando;
}
}
if ( !cache[ id ] ) {
cache[ id ] = {};
// TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery
// metadata on plain JS objects when the object is serialized using
// JSON.stringify
if ( !isNode ) {
cache[ id ].toJSON = jQuery.noop;
}
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ][ internalKey ] = jQuery.extend(cache[ id ][ internalKey ], name);
} else {
cache[ id ] = jQuery.extend(cache[ id ], name);
}
}
thisCache = cache[ id ];
// Internal jQuery data is stored in a separate object inside the object's data
// cache in order to avoid key collisions between internal data and user-defined
// data
if ( pvt ) {
if ( !thisCache[ internalKey ] ) {
thisCache[ internalKey ] = {};
}
thisCache = thisCache[ internalKey ];
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// TODO: This is a hack for 1.5 ONLY. It will be removed in 1.6. Users should
// not attempt to inspect the internal events object using jQuery.data, as this
// internal data object is undocumented and subject to change.
if ( name === "events" && !thisCache[name] ) {
return thisCache[ internalKey ] && thisCache[ internalKey ].events;
}
return getByName ?
// Check for both converted-to-camel and non-converted data property names
thisCache[ jQuery.camelCase( name ) ] || thisCache[ name ] :
thisCache;
},
removeData: function( elem, name, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var internalKey = jQuery.expando, isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
// See jQuery.data for more information
id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
var thisCache = pvt ? cache[ id ][ internalKey ] : cache[ id ];
if ( thisCache ) {
delete thisCache[ name ];
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( !isEmptyDataObject(thisCache) ) {
return;
}
}
}
// See jQuery.data for more information
if ( pvt ) {
delete cache[ id ][ internalKey ];
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject(cache[ id ]) ) {
return;
}
}
var internalCache = cache[ id ][ internalKey ];
// Browsers that fail expando deletion also refuse to delete expandos on
// the window, but it will allow it on all other JS objects; other browsers
// don't care
if ( jQuery.support.deleteExpando || cache != window ) {
delete cache[ id ];
} else {
cache[ id ] = null;
}
// We destroyed the entire user cache at once because it's faster than
// iterating through each key, but we need to continue to persist internal
// data if it existed
if ( internalCache ) {
cache[ id ] = {};
// TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery
// metadata on plain JS objects when the object is serialized using
// JSON.stringify
if ( !isNode ) {
cache[ id ].toJSON = jQuery.noop;
}
cache[ id ][ internalKey ] = internalCache;
// Otherwise, we need to eliminate the expando on the node to avoid
// false lookups in the cache for entries that no longer exist
} else if ( isNode ) {
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( jQuery.support.deleteExpando ) {
delete elem[ jQuery.expando ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( jQuery.expando );
} else {
elem[ jQuery.expando ] = null;
}
}
},
// For internal use only.
_data: function( elem, name, data ) {
return jQuery.data( elem, name, data, true );
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
if ( elem.nodeName ) {
var match = jQuery.noData[ elem.nodeName.toLowerCase() ];
if ( match ) {
return !(match === true || elem.getAttribute("classid") !== match);
}
}
return true;
}
});
jQuery.fn.extend({
data: function( key, value ) {
var data = null;
if ( typeof key === "undefined" ) {
if ( this.length ) {
data = jQuery.data( this[0] );
if ( this[0].nodeType === 1 ) {
var attr = this[0].attributes, name;
for ( var i = 0, l = attr.length; i < l; i++ ) {
name = attr[i].name;
if ( name.indexOf( "data-" ) === 0 ) {
name = jQuery.camelCase( name.substring(5) );
dataAttr( this[0], name, data[ name ] );
}
}
}
}
return data;
} else if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
var parts = key.split(".");
parts[1] = parts[1] ? "." + parts[1] : "";
if ( value === undefined ) {
data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);
// Try to fetch any internally stored data first
if ( data === undefined && this.length ) {
data = jQuery.data( this[0], key );
data = dataAttr( this[0], key, data );
}
return data === undefined && parts[1] ?
this.data( parts[0] ) :
data;
} else {
return this.each(function() {
var $this = jQuery( this ),
args = [ parts[0], value ];
$this.triggerHandler( "setData" + parts[1] + "!", args );
jQuery.data( this, key, value );
$this.triggerHandler( "changeData" + parts[1] + "!", args );
});
}
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "$1-$2" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
!jQuery.isNaN( data ) ? parseFloat( data ) :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// TODO: This is a hack for 1.5 ONLY to allow objects with a single toJSON
// property to be considered empty objects; this property always exists in
// order to make sure JSON.stringify does not expose internal metadata
function isEmptyDataObject( obj ) {
for ( var name in obj ) {
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
function handleQueueMarkDefer( elem, type, src ) {
var deferDataKey = type + "defer",
queueDataKey = type + "queue",
markDataKey = type + "mark",
defer = jQuery.data( elem, deferDataKey, undefined, true );
if ( defer &&
( src === "queue" || !jQuery.data( elem, queueDataKey, undefined, true ) ) &&
( src === "mark" || !jQuery.data( elem, markDataKey, undefined, true ) ) ) {
// Give room for hard-coded callbacks to fire first
// and eventually mark/queue something else on the element
setTimeout( function() {
if ( !jQuery.data( elem, queueDataKey, undefined, true ) &&
!jQuery.data( elem, markDataKey, undefined, true ) ) {
jQuery.removeData( elem, deferDataKey, true );
defer.resolve();
}
}, 0 );
}
}
jQuery.extend({
_mark: function( elem, type ) {
if ( elem ) {
type = (type || "fx") + "mark";
jQuery.data( elem, type, (jQuery.data(elem,type,undefined,true) || 0) + 1, true );
}
},
_unmark: function( force, elem, type ) {
if ( force !== true ) {
type = elem;
elem = force;
force = false;
}
if ( elem ) {
type = type || "fx";
var key = type + "mark",
count = force ? 0 : ( (jQuery.data( elem, key, undefined, true) || 1 ) - 1 );
if ( count ) {
jQuery.data( elem, key, count, true );
} else {
jQuery.removeData( elem, key, true );
handleQueueMarkDefer( elem, type, "mark" );
}
}
},
queue: function( elem, type, data ) {
if ( elem ) {
type = (type || "fx") + "queue";
var q = jQuery.data( elem, type, undefined, true );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !q || jQuery.isArray(data) ) {
q = jQuery.data( elem, type, jQuery.makeArray(data), true );
} else {
q.push( data );
}
}
return q || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
fn = queue.shift(),
defer;
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift("inprogress");
}
fn.call(elem, function() {
jQuery.dequeue(elem, type);
});
}
if ( !queue.length ) {
jQuery.removeData( elem, type + "queue", true );
handleQueueMarkDefer( elem, type, "queue" );
}
}
});
jQuery.fn.extend({
queue: function( type, data ) {
if ( typeof type !== "string" ) {
data = type;
type = "fx";
}
if ( data === undefined ) {
return jQuery.queue( this[0], type );
}
return this.each(function() {
var queue = jQuery.queue( this, type, data );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
type = type || "fx";
return this.queue( type, function() {
var elem = this;
setTimeout(function() {
jQuery.dequeue( elem, type );
}, time );
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, object ) {
if ( typeof type !== "string" ) {
object = type;
type = undefined;
}
type = type || "fx";
var defer = jQuery.Deferred(),
elements = this,
i = elements.length,
count = 1,
deferDataKey = type + "defer",
queueDataKey = type + "queue",
markDataKey = type + "mark",
tmp;
function resolve() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
}
while( i-- ) {
if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) ||
( jQuery.data( elements[ i ], queueDataKey, undefined, true ) ||
jQuery.data( elements[ i ], markDataKey, undefined, true ) ) &&
jQuery.data( elements[ i ], deferDataKey, jQuery._Deferred(), true ) )) {
count++;
tmp.done( resolve );
}
}
resolve();
return defer.promise();
}
});
var rclass = /[\n\t\r]/g,
rspace = /\s+/,
rreturn = /\r/g,
rtype = /^(?:button|input)$/i,
rfocusable = /^(?:button|input|object|select|textarea)$/i,
rclickable = /^a(?:rea)?$/i,
rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
rinvalidChar = /\:|^on/,
formHook, boolHook;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, name, value, true, jQuery.attr );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return jQuery.access( this, name, value, true, jQuery.prop );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
},
addClass: function( value ) {
var classNames, i, l, elem,
setClass, c, cl;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call(this, j, this.className) );
});
}
if ( value && typeof value === "string" ) {
classNames = value.split( rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 ) {
if ( !elem.className && classNames.length === 1 ) {
elem.className = value;
} else {
setClass = " " + elem.className + " ";
for ( c = 0, cl = classNames.length; c < cl; c++ ) {
if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) {
setClass += classNames[ c ] + " ";
}
}
elem.className = jQuery.trim( setClass );
}
}
}
}
return this;
},
removeClass: function( value ) {
var classNames, i, l, elem, className, c, cl;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call(this, j, this.className) );
});
}
if ( (value && typeof value === "string") || value === undefined ) {
classNames = (value || "").split( rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 && elem.className ) {
if ( value ) {
className = (" " + elem.className + " ").replace( rclass, " " );
for ( c = 0, cl = classNames.length; c < cl; c++ ) {
className = className.replace(" " + classNames[ c ] + " ", " ");
}
elem.className = jQuery.trim( className );
} else {
elem.className = "";
}
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value,
isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
state = stateVal,
classNames = value.split( rspace );
while ( (className = classNames[ i++ ]) ) {
// check each className given, space seperated list
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
} else if ( type === "undefined" || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// toggle whole className
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ";
for ( var i = 0, l = this.length; i < l; i++ ) {
if ( (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) {
return true;
}
}
return false;
},
val: function( value ) {
var hooks, ret,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return undefined;
}
var isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var self = jQuery(this), val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, self.val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.nodeName.toLowerCase() ] || jQuery.valHooks[ this.type ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
// attributes.value is undefined in Blackberry 4.7 but
// uses .value. See #6932
var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text;
}
},
select: {
get: function( elem ) {
var value,
index = elem.selectedIndex,
values = [],
options = elem.options,
one = elem.type === "select-one";
// Nothing was selected
if ( index < 0 ) {
return null;
}
// Loop through all the selected options
for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) {
var option = options[ i ];
// Don't return options that are disabled or in a disabled optgroup
if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) &&
(!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
// Fixes Bug #2551 -- select.val() broken in IE after form.reset()
if ( one && !values.length && options.length ) {
return jQuery( options[ index ] ).val();
}
return values;
},
set: function( elem, value ) {
var values = jQuery.makeArray( value );
jQuery(elem).find("option").each(function() {
this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
});
if ( !values.length ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
attrFn: {
val: true,
css: true,
html: true,
text: true,
data: true,
width: true,
height: true,
offset: true
},
attrFix: {
// Always normalize to ensure hook usage
tabindex: "tabIndex"
},
attr: function( elem, name, value, pass ) {
var nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return undefined;
}
if ( pass && name in jQuery.attrFn ) {
return jQuery( elem )[ name ]( value );
}
// Fallback to prop when attributes are not supported
if ( !("getAttribute" in elem) ) {
return jQuery.prop( elem, name, value );
}
var ret, hooks,
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
// Normalize the name if needed
if ( notxml ) {
name = jQuery.attrFix[ name ] || name;
hooks = jQuery.attrHooks[ name ];
if ( !hooks ) {
// Use boolHook for boolean attributes
if ( rboolean.test( name ) ) {
hooks = boolHook;
// Use formHook for forms and if the name contains certain characters
} else if ( formHook && name !== "className" &&
(jQuery.nodeName( elem, "form" ) || rinvalidChar.test( name )) ) {
hooks = formHook;
}
}
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
return undefined;
} else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, "" + value );
return value;
}
} else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = elem.getAttribute( name );
// Non-existent attributes return null, we normalize to undefined
return ret === null ?
undefined :
ret;
}
},
removeAttr: function( elem, name ) {
var propName;
if ( elem.nodeType === 1 ) {
name = jQuery.attrFix[ name ] || name;
if ( jQuery.support.getSetAttribute ) {
// Use removeAttribute in browsers that support it
elem.removeAttribute( name );
} else {
jQuery.attr( elem, name, "" );
elem.removeAttributeNode( elem.getAttributeNode( name ) );
}
// Set corresponding property to false for boolean attributes
if ( rboolean.test( name ) && (propName = jQuery.propFix[ name ] || name) in elem ) {
elem[ propName ] = false;
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
// We can't allow the type property to be changed (since it causes problems in IE)
if ( rtype.test( elem.nodeName ) && elem.parentNode ) {
jQuery.error( "type property can't be changed" );
} else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to it's default in case type is set after value
// This is for element creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
},
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
var attributeNode = elem.getAttributeNode("tabIndex");
return attributeNode && attributeNode.specified ?
parseInt( attributeNode.value, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
undefined;
}
},
// Use the value property for back compat
// Use the formHook for button elements in IE6/7 (#1954)
value: {
get: function( elem, name ) {
if ( formHook && jQuery.nodeName( elem, "button" ) ) {
return formHook.get( elem, name );
}
return name in elem ?
elem.value :
null;
},
set: function( elem, value, name ) {
if ( formHook && jQuery.nodeName( elem, "button" ) ) {
return formHook.set( elem, value, name );
}
// Does not return so that setAttribute is also used
elem.value = value;
}
}
},
propFix: {
tabindex: "tabIndex",
readonly: "readOnly",
"for": "htmlFor",
"class": "className",
maxlength: "maxLength",
cellspacing: "cellSpacing",
cellpadding: "cellPadding",
rowspan: "rowSpan",
colspan: "colSpan",
usemap: "useMap",
frameborder: "frameBorder",
contenteditable: "contentEditable"
},
prop: function( elem, name, value ) {
var nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return undefined;
}
var ret, hooks,
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
return (elem[ name ] = value);
}
} else {
if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== undefined ) {
return ret;
} else {
return elem[ name ];
}
}
},
propHooks: {}
});
// Hook for boolean attributes
boolHook = {
get: function( elem, name ) {
// Align boolean attributes with corresponding properties
return jQuery.prop( elem, name ) ?
name.toLowerCase() :
undefined;
},
set: function( elem, value, name ) {
var propName;
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
// value is true since we know at this point it's type boolean and not false
// Set boolean attributes to the same name and set the DOM property
propName = jQuery.propFix[ name ] || name;
if ( propName in elem ) {
// Only set the IDL specifically if it already exists on the element
elem[ propName ] = true;
}
elem.setAttribute( name, name.toLowerCase() );
}
return name;
}
};
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !jQuery.support.getSetAttribute ) {
// propFix is more comprehensive and contains all fixes
jQuery.attrFix = jQuery.propFix;
// Use this for any attribute on a form in IE6/7
formHook = jQuery.attrHooks.name = jQuery.attrHooks.title = jQuery.valHooks.button = {
get: function( elem, name ) {
var ret;
ret = elem.getAttributeNode( name );
// Return undefined if nodeValue is empty string
return ret && ret.nodeValue !== "" ?
ret.nodeValue :
undefined;
},
set: function( elem, value, name ) {
// Check form objects in IE (multiple bugs related)
// Only use nodeValue if the attribute node exists on the form
var ret = elem.getAttributeNode( name );
if ( ret ) {
ret.nodeValue = value;
return value;
}
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
});
});
}
// Some attributes require a special call on IE
if ( !jQuery.support.hrefNormalized ) {
jQuery.each([ "href", "src", "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
get: function( elem ) {
var ret = elem.getAttribute( name, 2 );
return ret === null ? undefined : ret;
}
});
});
}
if ( !jQuery.support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Normalize to lowercase since IE uppercases css property names
return elem.style.cssText.toLowerCase() || undefined;
},
set: function( elem, value ) {
return (elem.style.cssText = "" + value);
}
};
}
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
}
});
}
// Radios and checkboxes getter/setter
if ( !jQuery.support.checkOn ) {
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
get: function( elem ) {
// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
}
};
});
}
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return (elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0);
}
}
});
});
var rnamespaces = /\.(.*)$/,
rformElems = /^(?:textarea|input|select)$/i,
rperiod = /\./g,
rspaces = / /g,
rescape = /[^\w\s.|`]/g,
fcleanup = function( nm ) {
return nm.replace(rescape, "\\$&");
};
/*
* A number of helper functions used for managing events.
* Many of the ideas behind this code originated from
* Dean Edwards' addEvent library.
*/
jQuery.event = {
// Bind an event to an element
// Original by Dean Edwards
add: function( elem, types, handler, data ) {
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
if ( handler === false ) {
handler = returnFalse;
} else if ( !handler ) {
// Fixes bug #7229. Fix recommended by jdalton
return;
}
var handleObjIn, handleObj;
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
}
// Make sure that the function being executed has a unique ID
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure
var elemData = jQuery._data( elem );
// If no elemData is found then we must be trying to bind to one of the
// banned noData elements
if ( !elemData ) {
return;
}
var events = elemData.events,
eventHandle = elemData.handle;
if ( !events ) {
elemData.events = events = {};
}
if ( !eventHandle ) {
elemData.handle = eventHandle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.handle.apply( eventHandle.elem, arguments ) :
undefined;
};
}
// Add elem as a property of the handle function
// This is to prevent a memory leak with non-native events in IE.
eventHandle.elem = elem;
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
types = types.split(" ");
var type, i = 0, namespaces;
while ( (type = types[ i++ ]) ) {
handleObj = handleObjIn ?
jQuery.extend({}, handleObjIn) :
{ handler: handler, data: data };
// Namespaced event handlers
if ( type.indexOf(".") > -1 ) {
namespaces = type.split(".");
type = namespaces.shift();
handleObj.namespace = namespaces.slice(0).sort().join(".");
} else {
namespaces = [];
handleObj.namespace = "";
}
handleObj.type = type;
if ( !handleObj.guid ) {
handleObj.guid = handler.guid;
}
// Get the current list of functions bound to this event
var handlers = events[ type ],
special = jQuery.event.special[ type ] || {};
// Init the event handler queue
if ( !handlers ) {
handlers = events[ type ] = [];
// Check for a special event handler
// Only use addEventListener/attachEvent if the special
// events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add the function to the element's handler list
handlers.push( handleObj );
// Keep track of which events have been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
global: {},
// Detach an event or set of events from an element
remove: function( elem, types, handler, pos ) {
// don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
if ( handler === false ) {
handler = returnFalse;
}
var ret, type, fn, j, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType,
elemData = jQuery.hasData( elem ) && jQuery._data( elem ),
events = elemData && elemData.events;
if ( !elemData || !events ) {
return;
}
// types is actually an event object here
if ( types && types.type ) {
handler = types.handler;
types = types.type;
}
// Unbind all events for the element
if ( !types || typeof types === "string" && types.charAt(0) === "." ) {
types = types || "";
for ( type in events ) {
jQuery.event.remove( elem, type + types );
}
return;
}
// Handle multiple events separated by a space
// jQuery(...).unbind("mouseover mouseout", fn);
types = types.split(" ");
while ( (type = types[ i++ ]) ) {
origType = type;
handleObj = null;
all = type.indexOf(".") < 0;
namespaces = [];
if ( !all ) {
// Namespaced event handlers
namespaces = type.split(".");
type = namespaces.shift();
namespace = new RegExp("(^|\\.)" +
jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)");
}
eventType = events[ type ];
if ( !eventType ) {
continue;
}
if ( !handler ) {
for ( j = 0; j < eventType.length; j++ ) {
handleObj = eventType[ j ];
if ( all || namespace.test( handleObj.namespace ) ) {
jQuery.event.remove( elem, origType, handleObj.handler, j );
eventType.splice( j--, 1 );
}
}
continue;
}
special = jQuery.event.special[ type ] || {};
for ( j = pos || 0; j < eventType.length; j++ ) {
handleObj = eventType[ j ];
if ( handler.guid === handleObj.guid ) {
// remove the given handler for the given type
if ( all || namespace.test( handleObj.namespace ) ) {
if ( pos == null ) {
eventType.splice( j--, 1 );
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
if ( pos != null ) {
break;
}
}
}
// remove generic event handler if no more handlers exist
if ( eventType.length === 0 || pos != null && eventType.length === 1 ) {
if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
ret = null;
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
var handle = elemData.handle;
if ( handle ) {
handle.elem = null;
}
delete elemData.events;
delete elemData.handle;
if ( jQuery.isEmptyObject( elemData ) ) {
jQuery.removeData( elem, undefined, true );
}
}
},
// Events that are safe to short-circuit if no handlers are attached.
// Native DOM events should not be added, they may have inline handlers.
customEvent: {
"getData": true,
"setData": true,
"changeData": true
},
trigger: function( event, data, elem, onlyHandlers ) {
// Event object or event type
var type = event.type || event,
namespaces = [],
exclusive;
if ( type.indexOf("!") >= 0 ) {
// Exclusive events trigger only for the exact event (no namespaces)
type = type.slice(0, -1);
exclusive = true;
}
if ( type.indexOf(".") >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) {
// No jQuery handlers for this event type, and it can't have inline handlers
return;
}
// Caller can pass in an Event, Object, or just an event type string
event = typeof event === "object" ?
// jQuery.Event object
event[ jQuery.expando ] ? event :
// Object literal
new jQuery.Event( type, event ) :
// Just the event type (string)
new jQuery.Event( type );
event.type = type;
event.exclusive = exclusive;
event.namespace = namespaces.join(".");
event.namespace_re = new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)");
// triggerHandler() and global events don't bubble or run the default action
if ( onlyHandlers || !elem ) {
event.preventDefault();
event.stopPropagation();
}
// Handle a global trigger
if ( !elem ) {
// TODO: Stop taunting the data cache; remove global events and always attach to document
jQuery.each( jQuery.cache, function() {
// internalKey variable is just used to make it easier to find
// and potentially change this stuff later; currently it just
// points to jQuery.expando
var internalKey = jQuery.expando,
internalCache = this[ internalKey ];
if ( internalCache && internalCache.events && internalCache.events[ type ] ) {
jQuery.event.trigger( event, data, internalCache.handle.elem );
}
});
return;
}
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// Clean up the event in case it is being reused
event.result = undefined;
event.target = elem;
// Clone any incoming data and prepend the event, creating the handler arg list
data = data != null ? jQuery.makeArray( data ) : [];
data.unshift( event );
var cur = elem,
// IE doesn't like method names with a colon (#3533, #8272)
ontype = type.indexOf(":") < 0 ? "on" + type : "";
// Fire event on the current element, then bubble up the DOM tree
do {
var handle = jQuery._data( cur, "handle" );
event.currentTarget = cur;
if ( handle ) {
handle.apply( cur, data );
}
// Trigger an inline bound script
if ( ontype && jQuery.acceptData( cur ) && cur[ ontype ] && cur[ ontype ].apply( cur, data ) === false ) {
event.result = false;
event.preventDefault();
}
// Bubble up to document, then to window
cur = cur.parentNode || cur.ownerDocument || cur === event.target.ownerDocument && window;
} while ( cur && !event.isPropagationStopped() );
// If nobody prevented the default action, do it now
if ( !event.isDefaultPrevented() ) {
var old,
special = jQuery.event.special[ type ] || {};
if ( (!special._default || special._default.call( elem.ownerDocument, event ) === false) &&
!(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction)() check here because IE6/7 fails that test.
// IE<9 dies on focus to hidden element (#1486), may want to revisit a try/catch.
try {
if ( ontype && elem[ type ] ) {
// Don't re-trigger an onFOO event when we call its FOO() method
old = elem[ ontype ];
if ( old ) {
elem[ ontype ] = null;
}
jQuery.event.triggered = type;
elem[ type ]();
}
} catch ( ieError ) {}
if ( old ) {
elem[ ontype ] = old;
}
jQuery.event.triggered = undefined;
}
}
return event.result;
},
handle: function( event ) {
event = jQuery.event.fix( event || window.event );
// Snapshot the handlers list since a called handler may add/remove events.
var handlers = ((jQuery._data( this, "events" ) || {})[ event.type ] || []).slice(0),
run_all = !event.exclusive && !event.namespace,
args = Array.prototype.slice.call( arguments, 0 );
// Use the fix-ed Event rather than the (read-only) native event
args[0] = event;
event.currentTarget = this;
for ( var j = 0, l = handlers.length; j < l; j++ ) {
var handleObj = handlers[ j ];
// Triggered event must 1) be non-exclusive and have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event.
if ( run_all || event.namespace_re.test( handleObj.namespace ) ) {
// Pass in a reference to the handler function itself
// So that we can later remove it
event.handler = handleObj.handler;
event.data = handleObj.data;
event.handleObj = handleObj;
var ret = handleObj.handler.apply( this, args );
if ( ret !== undefined ) {
event.result = ret;
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
}
if ( event.isImmediatePropagationStopped() ) {
break;
}
}
}
return event.result;
},
props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// store a copy of the original event object
// and "clone" to set read-only properties
var originalEvent = event;
event = jQuery.Event( originalEvent );
for ( var i = this.props.length, prop; i; ) {
prop = this.props[ --i ];
event[ prop ] = originalEvent[ prop ];
}
// Fix target property, if necessary
if ( !event.target ) {
// Fixes #1925 where srcElement might not be defined either
event.target = event.srcElement || document;
}
// check if target is a textnode (safari)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && event.fromElement ) {
event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement;
}
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && event.clientX != null ) {
var eventDocument = event.target.ownerDocument || document,
doc = eventDocument.documentElement,
body = eventDocument.body;
event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
}
// Add which for key events
if ( event.which == null && (event.charCode != null || event.keyCode != null) ) {
event.which = event.charCode != null ? event.charCode : event.keyCode;
}
// Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
if ( !event.metaKey && event.ctrlKey ) {
event.metaKey = event.ctrlKey;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && event.button !== undefined ) {
event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
}
return event;
},
// Deprecated, use jQuery.guid instead
guid: 1E8,
// Deprecated, use jQuery.proxy instead
proxy: jQuery.proxy,
special: {
ready: {
// Make sure the ready event is setup
setup: jQuery.bindReady,
teardown: jQuery.noop
},
live: {
add: function( handleObj ) {
jQuery.event.add( this,
liveConvert( handleObj.origType, handleObj.selector ),
jQuery.extend({}, handleObj, {handler: liveHandler, guid: handleObj.handler.guid}) );
},
remove: function( handleObj ) {
jQuery.event.remove( this, liveConvert( handleObj.origType, handleObj.selector ), handleObj );
}
},
beforeunload: {
setup: function( data, namespaces, eventHandle ) {
// We only want to do this special case on windows
if ( jQuery.isWindow( this ) ) {
this.onbeforeunload = eventHandle;
}
},
teardown: function( namespaces, eventHandle ) {
if ( this.onbeforeunload === eventHandle ) {
this.onbeforeunload = null;
}
}
}
}
};
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
if ( elem.detachEvent ) {
elem.detachEvent( "on" + type, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !this.preventDefault ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = (src.defaultPrevented || src.returnValue === false ||
src.getPreventDefault && src.getPreventDefault()) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// timeStamp is buggy for some events on Firefox(#3843)
// So we won't rely on the native value
this.timeStamp = jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
function returnFalse() {
return false;
}
function returnTrue() {
return true;
}
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
preventDefault: function() {
this.isDefaultPrevented = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if preventDefault exists run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// otherwise set the returnValue property of the original event to false (IE)
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
this.isPropagationStopped = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if stopPropagation exists run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// otherwise set the cancelBubble property of the original event to true (IE)
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
},
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse
};
// Checks if an event happened on an element within another element
// Used in jQuery.event.special.mouseenter and mouseleave handlers
var withinElement = function( event ) {
// Check if mouse(over|out) are still within the same parent element
var related = event.relatedTarget,
inside = false,
eventType = event.type;
event.type = event.data;
if ( related !== this ) {
if ( related ) {
inside = jQuery.contains( this, related );
}
if ( !inside ) {
jQuery.event.handle.apply( this, arguments );
event.type = eventType;
}
}
},
// In case of event delegation, we only need to rename the event.type,
// liveHandler will take care of the rest.
delegate = function( event ) {
event.type = event.data;
jQuery.event.handle.apply( this, arguments );
};
// Create mouseenter and mouseleave events
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
setup: function( data ) {
jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig );
},
teardown: function( data ) {
jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement );
}
};
});
// submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function( data, namespaces ) {
if ( !jQuery.nodeName( this, "form" ) ) {
jQuery.event.add(this, "click.specialSubmit", function( e ) {
var elem = e.target,
type = elem.type;
if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) {
trigger( "submit", this, arguments );
}
});
jQuery.event.add(this, "keypress.specialSubmit", function( e ) {
var elem = e.target,
type = elem.type;
if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) {
trigger( "submit", this, arguments );
}
});
} else {
return false;
}
},
teardown: function( namespaces ) {
jQuery.event.remove( this, ".specialSubmit" );
}
};
}
// change delegation, happens here so we have bind.
if ( !jQuery.support.changeBubbles ) {
var changeFilters,
getVal = function( elem ) {
var type = elem.type, val = elem.value;
if ( type === "radio" || type === "checkbox" ) {
val = elem.checked;
} else if ( type === "select-multiple" ) {
val = elem.selectedIndex > -1 ?
jQuery.map( elem.options, function( elem ) {
return elem.selected;
}).join("-") :
"";
} else if ( jQuery.nodeName( elem, "select" ) ) {
val = elem.selectedIndex;
}
return val;
},
testChange = function testChange( e ) {
var elem = e.target, data, val;
if ( !rformElems.test( elem.nodeName ) || elem.readOnly ) {
return;
}
data = jQuery._data( elem, "_change_data" );
val = getVal(elem);
// the current data will be also retrieved by beforeactivate
if ( e.type !== "focusout" || elem.type !== "radio" ) {
jQuery._data( elem, "_change_data", val );
}
if ( data === undefined || val === data ) {
return;
}
if ( data != null || val ) {
e.type = "change";
e.liveFired = undefined;
jQuery.event.trigger( e, arguments[1], elem );
}
};
jQuery.event.special.change = {
filters: {
focusout: testChange,
beforedeactivate: testChange,
click: function( e ) {
var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : "";
if ( type === "radio" || type === "checkbox" || jQuery.nodeName( elem, "select" ) ) {
testChange.call( this, e );
}
},
// Change has to be called before submit
// Keydown will be called before keypress, which is used in submit-event delegation
keydown: function( e ) {
var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : "";
if ( (e.keyCode === 13 && !jQuery.nodeName( elem, "textarea" ) ) ||
(e.keyCode === 32 && (type === "checkbox" || type === "radio")) ||
type === "select-multiple" ) {
testChange.call( this, e );
}
},
// Beforeactivate happens also before the previous element is blurred
// with this event you can't trigger a change event, but you can store
// information
beforeactivate: function( e ) {
var elem = e.target;
jQuery._data( elem, "_change_data", getVal(elem) );
}
},
setup: function( data, namespaces ) {
if ( this.type === "file" ) {
return false;
}
for ( var type in changeFilters ) {
jQuery.event.add( this, type + ".specialChange", changeFilters[type] );
}
return rformElems.test( this.nodeName );
},
teardown: function( namespaces ) {
jQuery.event.remove( this, ".specialChange" );
return rformElems.test( this.nodeName );
}
};
changeFilters = jQuery.event.special.change.filters;
// Handle when the input is .focus()'d
changeFilters.focus = changeFilters.beforeactivate;
}
function trigger( type, elem, args ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
// Don't pass args or remember liveFired; they apply to the donor event.
var event = jQuery.extend( {}, args[ 0 ] );
event.type = type;
event.originalEvent = {};
event.liveFired = undefined;
jQuery.event.handle.call( elem, event );
if ( event.isDefaultPrevented() ) {
args[ 0 ].preventDefault();
}
}
// Create "bubbling" focus and blur events
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0;
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
function handler( donor ) {
// Donor event is always a native one; fix it and switch its type.
// Let focusin/out handler cancel the donor focus/blur event.
var e = jQuery.event.fix( donor );
e.type = fix;
e.originalEvent = {};
jQuery.event.trigger( e, null, e.target );
if ( e.isDefaultPrevented() ) {
donor.preventDefault();
}
}
});
}
jQuery.each(["bind", "one"], function( i, name ) {
jQuery.fn[ name ] = function( type, data, fn ) {
var handler;
// Handle object literals
if ( typeof type === "object" ) {
for ( var key in type ) {
this[ name ](key, data, type[key], fn);
}
return this;
}
if ( arguments.length === 2 || data === false ) {
fn = data;
data = undefined;
}
if ( name === "one" ) {
handler = function( event ) {
jQuery( this ).unbind( event, handler );
return fn.apply( this, arguments );
};
handler.guid = fn.guid || jQuery.guid++;
} else {
handler = fn;
}
if ( type === "unload" && name !== "one" ) {
this.one( type, data, fn );
} else {
for ( var i = 0, l = this.length; i < l; i++ ) {
jQuery.event.add( this[i], type, handler, data );
}
}
return this;
};
});
jQuery.fn.extend({
unbind: function( type, fn ) {
// Handle object literals
if ( typeof type === "object" && !type.preventDefault ) {
for ( var key in type ) {
this.unbind(key, type[key]);
}
} else {
for ( var i = 0, l = this.length; i < l; i++ ) {
jQuery.event.remove( this[i], type, fn );
}
}
return this;
},
delegate: function( selector, types, data, fn ) {
return this.live( types, data, fn, selector );
},
undelegate: function( selector, types, fn ) {
if ( arguments.length === 0 ) {
return this.unbind( "live" );
} else {
return this.die( types, null, fn, selector );
}
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
if ( this[0] ) {
return jQuery.event.trigger( type, data, this[0], true );
}
},
toggle: function( fn ) {
// Save reference to arguments for access in closure
var args = arguments,
guid = fn.guid || jQuery.guid++,
i = 0,
toggler = function( event ) {
// Figure out which function to execute
var lastToggle = ( jQuery.data( this, "lastToggle" + fn.guid ) || 0 ) % i;
jQuery.data( this, "lastToggle" + fn.guid, lastToggle + 1 );
// Make sure that clicks stop
event.preventDefault();
// and execute the function
return args[ lastToggle ].apply( this, arguments ) || false;
};
// link all the functions, so any of them can unbind this click handler
toggler.guid = guid;
while ( i < args.length ) {
args[ i++ ].guid = guid;
}
return this.click( toggler );
},
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
}
});
var liveMap = {
focus: "focusin",
blur: "focusout",
mouseenter: "mouseover",
mouseleave: "mouseout"
};
jQuery.each(["live", "die"], function( i, name ) {
jQuery.fn[ name ] = function( types, data, fn, origSelector /* Internal Use Only */ ) {
var type, i = 0, match, namespaces, preType,
selector = origSelector || this.selector,
context = origSelector ? this : jQuery( this.context );
if ( typeof types === "object" && !types.preventDefault ) {
for ( var key in types ) {
context[ name ]( key, data, types[key], selector );
}
return this;
}
if ( name === "die" && !types &&
origSelector && origSelector.charAt(0) === "." ) {
context.unbind( origSelector );
return this;
}
if ( data === false || jQuery.isFunction( data ) ) {
fn = data || returnFalse;
data = undefined;
}
types = (types || "").split(" ");
while ( (type = types[ i++ ]) != null ) {
match = rnamespaces.exec( type );
namespaces = "";
if ( match ) {
namespaces = match[0];
type = type.replace( rnamespaces, "" );
}
if ( type === "hover" ) {
types.push( "mouseenter" + namespaces, "mouseleave" + namespaces );
continue;
}
preType = type;
if ( liveMap[ type ] ) {
types.push( liveMap[ type ] + namespaces );
type = type + namespaces;
} else {
type = (liveMap[ type ] || type) + namespaces;
}
if ( name === "live" ) {
// bind live handler
for ( var j = 0, l = context.length; j < l; j++ ) {
jQuery.event.add( context[j], "live." + liveConvert( type, selector ),
{ data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } );
}
} else {
// unbind live handler
context.unbind( "live." + liveConvert( type, selector ), fn );
}
}
return this;
};
});
function liveHandler( event ) {
var stop, maxLevel, related, match, handleObj, elem, j, i, l, data, close, namespace, ret,
elems = [],
selectors = [],
events = jQuery._data( this, "events" );
// Make sure we avoid non-left-click bubbling in Firefox (#3861) and disabled elements in IE (#6911)
if ( event.liveFired === this || !events || !events.live || event.target.disabled || event.button && event.type === "click" ) {
return;
}
if ( event.namespace ) {
namespace = new RegExp("(^|\\.)" + event.namespace.split(".").join("\\.(?:.*\\.)?") + "(\\.|$)");
}
event.liveFired = this;
var live = events.live.slice(0);
for ( j = 0; j < live.length; j++ ) {
handleObj = live[j];
if ( handleObj.origType.replace( rnamespaces, "" ) === event.type ) {
selectors.push( handleObj.selector );
} else {
live.splice( j--, 1 );
}
}
match = jQuery( event.target ).closest( selectors, event.currentTarget );
for ( i = 0, l = match.length; i < l; i++ ) {
close = match[i];
for ( j = 0; j < live.length; j++ ) {
handleObj = live[j];
if ( close.selector === handleObj.selector && (!namespace || namespace.test( handleObj.namespace )) && !close.elem.disabled ) {
elem = close.elem;
related = null;
// Those two events require additional checking
if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) {
event.type = handleObj.preType;
related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0];
// Make sure not to accidentally match a child element with the same selector
if ( related && jQuery.contains( elem, related ) ) {
related = elem;
}
}
if ( !related || related !== elem ) {
elems.push({ elem: elem, handleObj: handleObj, level: close.level });
}
}
}
}
for ( i = 0, l = elems.length; i < l; i++ ) {
match = elems[i];
if ( maxLevel && match.level > maxLevel ) {
break;
}
event.currentTarget = match.elem;
event.data = match.handleObj.data;
event.handleObj = match.handleObj;
ret = match.handleObj.origHandler.apply( match.elem, arguments );
if ( ret === false || event.isPropagationStopped() ) {
maxLevel = match.level;
if ( ret === false ) {
stop = false;
}
if ( event.isImmediatePropagationStopped() ) {
break;
}
}
}
return stop;
}
function liveConvert( type, selector ) {
return (type && type !== "*" ? type + "." : "") + selector.replace(rperiod, "`").replace(rspaces, "&");
}
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.bind( name, data, fn ) :
this.trigger( name );
};
if ( jQuery.attrFn ) {
jQuery.attrFn[ name ] = true;
}
});
/*!
* Sizzle CSS Selector Engine
* Copyright 2011, The Dojo Foundation
*/
(function(){
var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
done = 0,
toString = Object.prototype.toString,
hasDuplicate = false,
baseHasDuplicate = true,
rBackslash = /\\/g,
rNonWord = /\W/;
// Here we check if the JavaScript engine is using some sort of
// optimization where it does not always call our comparision
// function. If that is the case, discard the hasDuplicate value.
// Thus far that includes Google Chrome.
[0, 0].sort(function() {
baseHasDuplicate = false;
return 0;
});
var Sizzle = function( selector, context, results, seed ) {
results = results || [];
context = context || document;
var origContext = context;
if ( context.nodeType !== 1 && context.nodeType !== 9 ) {
return [];
}
if ( !selector || typeof selector !== "string" ) {
return results;
}
var m, set, checkSet, extra, ret, cur, pop, i,
prune = true,
contextXML = Sizzle.isXML( context ),
parts = [],
soFar = selector;
// Reset the position of the chunker regexp (start from head)
do {
chunker.exec( "" );
m = chunker.exec( soFar );
if ( m ) {
soFar = m[3];
parts.push( m[1] );
if ( m[2] ) {
extra = m[3];
break;
}
}
} while ( m );
if ( parts.length > 1 && origPOS.exec( selector ) ) {
if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
set = posProcess( parts[0] + parts[1], context );
} else {
set = Expr.relative[ parts[0] ] ?
[ context ] :
Sizzle( parts.shift(), context );
while ( parts.length ) {
selector = parts.shift();
if ( Expr.relative[ selector ] ) {
selector += parts.shift();
}
set = posProcess( selector, set );
}
}
} else {
// Take a shortcut and set the context if the root selector is an ID
// (but not if it'll be faster if the inner selector is an ID)
if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML &&
Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) {
ret = Sizzle.find( parts.shift(), context, contextXML );
context = ret.expr ?
Sizzle.filter( ret.expr, ret.set )[0] :
ret.set[0];
}
if ( context ) {
ret = seed ?
{ expr: parts.pop(), set: makeArray(seed) } :
Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML );
set = ret.expr ?
Sizzle.filter( ret.expr, ret.set ) :
ret.set;
if ( parts.length > 0 ) {
checkSet = makeArray( set );
} else {
prune = false;
}
while ( parts.length ) {
cur = parts.pop();
pop = cur;
if ( !Expr.relative[ cur ] ) {
cur = "";
} else {
pop = parts.pop();
}
if ( pop == null ) {
pop = context;
}
Expr.relative[ cur ]( checkSet, pop, contextXML );
}
} else {
checkSet = parts = [];
}
}
if ( !checkSet ) {
checkSet = set;
}
if ( !checkSet ) {
Sizzle.error( cur || selector );
}
if ( toString.call(checkSet) === "[object Array]" ) {
if ( !prune ) {
results.push.apply( results, checkSet );
} else if ( context && context.nodeType === 1 ) {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) {
results.push( set[i] );
}
}
} else {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
results.push( set[i] );
}
}
}
} else {
makeArray( checkSet, results );
}
if ( extra ) {
Sizzle( extra, origContext, results, seed );
Sizzle.uniqueSort( results );
}
return results;
};
Sizzle.uniqueSort = function( results ) {
if ( sortOrder ) {
hasDuplicate = baseHasDuplicate;
results.sort( sortOrder );
if ( hasDuplicate ) {
for ( var i = 1; i < results.length; i++ ) {
if ( results[i] === results[ i - 1 ] ) {
results.splice( i--, 1 );
}
}
}
}
return results;
};
Sizzle.matches = function( expr, set ) {
return Sizzle( expr, null, null, set );
};
Sizzle.matchesSelector = function( node, expr ) {
return Sizzle( expr, null, null, [node] ).length > 0;
};
Sizzle.find = function( expr, context, isXML ) {
var set;
if ( !expr ) {
return [];
}
for ( var i = 0, l = Expr.order.length; i < l; i++ ) {
var match,
type = Expr.order[i];
if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {
var left = match[1];
match.splice( 1, 1 );
if ( left.substr( left.length - 1 ) !== "\\" ) {
match[1] = (match[1] || "").replace( rBackslash, "" );
set = Expr.find[ type ]( match, context, isXML );
if ( set != null ) {
expr = expr.replace( Expr.match[ type ], "" );
break;
}
}
}
}
if ( !set ) {
set = typeof context.getElementsByTagName !== "undefined" ?
context.getElementsByTagName( "*" ) :
[];
}
return { set: set, expr: expr };
};
Sizzle.filter = function( expr, set, inplace, not ) {
var match, anyFound,
old = expr,
result = [],
curLoop = set,
isXMLFilter = set && set[0] && Sizzle.isXML( set[0] );
while ( expr && set.length ) {
for ( var type in Expr.filter ) {
if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) {
var found, item,
filter = Expr.filter[ type ],
left = match[1];
anyFound = false;
match.splice(1,1);
if ( left.substr( left.length - 1 ) === "\\" ) {
continue;
}
if ( curLoop === result ) {
result = [];
}
if ( Expr.preFilter[ type ] ) {
match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );
if ( !match ) {
anyFound = found = true;
} else if ( match === true ) {
continue;
}
}
if ( match ) {
for ( var i = 0; (item = curLoop[i]) != null; i++ ) {
if ( item ) {
found = filter( item, match, i, curLoop );
var pass = not ^ !!found;
if ( inplace && found != null ) {
if ( pass ) {
anyFound = true;
} else {
curLoop[i] = false;
}
} else if ( pass ) {
result.push( item );
anyFound = true;
}
}
}
}
if ( found !== undefined ) {
if ( !inplace ) {
curLoop = result;
}
expr = expr.replace( Expr.match[ type ], "" );
if ( !anyFound ) {
return [];
}
break;
}
}
}
// Improper expression
if ( expr === old ) {
if ( anyFound == null ) {
Sizzle.error( expr );
} else {
break;
}
}
old = expr;
}
return curLoop;
};
Sizzle.error = function( msg ) {
throw "Syntax error, unrecognized expression: " + msg;
};
var Expr = Sizzle.selectors = {
order: [ "ID", "NAME", "TAG" ],
match: {
ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,
ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,
TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,
CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,
POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,
PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
},
leftMatch: {},
attrMap: {
"class": "className",
"for": "htmlFor"
},
attrHandle: {
href: function( elem ) {
return elem.getAttribute( "href" );
},
type: function( elem ) {
return elem.getAttribute( "type" );
}
},
relative: {
"+": function(checkSet, part){
var isPartStr = typeof part === "string",
isTag = isPartStr && !rNonWord.test( part ),
isPartStrNotTag = isPartStr && !isTag;
if ( isTag ) {
part = part.toLowerCase();
}
for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
if ( (elem = checkSet[i]) ) {
while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}
checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ?
elem || false :
elem === part;
}
}
if ( isPartStrNotTag ) {
Sizzle.filter( part, checkSet, true );
}
},
">": function( checkSet, part ) {
var elem,
isPartStr = typeof part === "string",
i = 0,
l = checkSet.length;
if ( isPartStr && !rNonWord.test( part ) ) {
part = part.toLowerCase();
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
var parent = elem.parentNode;
checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
}
}
} else {
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
checkSet[i] = isPartStr ?
elem.parentNode :
elem.parentNode === part;
}
}
if ( isPartStr ) {
Sizzle.filter( part, checkSet, true );
}
}
},
"": function(checkSet, part, isXML){
var nodeCheck,
doneName = done++,
checkFn = dirCheck;
if ( typeof part === "string" && !rNonWord.test( part ) ) {
part = part.toLowerCase();
nodeCheck = part;
checkFn = dirNodeCheck;
}
checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML );
},
"~": function( checkSet, part, isXML ) {
var nodeCheck,
doneName = done++,
checkFn = dirCheck;
if ( typeof part === "string" && !rNonWord.test( part ) ) {
part = part.toLowerCase();
nodeCheck = part;
checkFn = dirNodeCheck;
}
checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML );
}
},
find: {
ID: function( match, context, isXML ) {
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
},
NAME: function( match, context ) {
if ( typeof context.getElementsByName !== "undefined" ) {
var ret = [],
results = context.getElementsByName( match[1] );
for ( var i = 0, l = results.length; i < l; i++ ) {
if ( results[i].getAttribute("name") === match[1] ) {
ret.push( results[i] );
}
}
return ret.length === 0 ? null : ret;
}
},
TAG: function( match, context ) {
if ( typeof context.getElementsByTagName !== "undefined" ) {
return context.getElementsByTagName( match[1] );
}
}
},
preFilter: {
CLASS: function( match, curLoop, inplace, result, not, isXML ) {
match = " " + match[1].replace( rBackslash, "" ) + " ";
if ( isXML ) {
return match;
}
for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
if ( elem ) {
if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) {
if ( !inplace ) {
result.push( elem );
}
} else if ( inplace ) {
curLoop[i] = false;
}
}
}
return false;
},
ID: function( match ) {
return match[1].replace( rBackslash, "" );
},
TAG: function( match, curLoop ) {
return match[1].replace( rBackslash, "" ).toLowerCase();
},
CHILD: function( match ) {
if ( match[1] === "nth" ) {
if ( !match[2] ) {
Sizzle.error( match[0] );
}
match[2] = match[2].replace(/^\+|\s*/g, '');
// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec(
match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
!/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);
// calculate the numbers (first)n+(last) including if they are negative
match[2] = (test[1] + (test[2] || 1)) - 0;
match[3] = test[3] - 0;
}
else if ( match[2] ) {
Sizzle.error( match[0] );
}
// TODO: Move to normal caching system
match[0] = done++;
return match;
},
ATTR: function( match, curLoop, inplace, result, not, isXML ) {
var name = match[1] = match[1].replace( rBackslash, "" );
if ( !isXML && Expr.attrMap[name] ) {
match[1] = Expr.attrMap[name];
}
// Handle if an un-quoted value was used
match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" );
if ( match[2] === "~=" ) {
match[4] = " " + match[4] + " ";
}
return match;
},
PSEUDO: function( match, curLoop, inplace, result, not ) {
if ( match[1] === "not" ) {
// If we're dealing with a complex expression, or a simple one
if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) {
match[3] = Sizzle(match[3], null, null, curLoop);
} else {
var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
if ( !inplace ) {
result.push.apply( result, ret );
}
return false;
}
} else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
return true;
}
return match;
},
POS: function( match ) {
match.unshift( true );
return match;
}
},
filters: {
enabled: function( elem ) {
return elem.disabled === false && elem.type !== "hidden";
},
disabled: function( elem ) {
return elem.disabled === true;
},
checked: function( elem ) {
return elem.checked === true;
},
selected: function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
parent: function( elem ) {
return !!elem.firstChild;
},
empty: function( elem ) {
return !elem.firstChild;
},
has: function( elem, i, match ) {
return !!Sizzle( match[3], elem ).length;
},
header: function( elem ) {
return (/h\d/i).test( elem.nodeName );
},
text: function( elem ) {
var attr = elem.getAttribute( "type" ), type = elem.type;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null );
},
radio: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type;
},
checkbox: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type;
},
file: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "file" === elem.type;
},
password: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "password" === elem.type;
},
submit: function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && "submit" === elem.type;
},
image: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "image" === elem.type;
},
reset: function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && "reset" === elem.type;
},
button: function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && "button" === elem.type || name === "button";
},
input: function( elem ) {
return (/input|select|textarea|button/i).test( elem.nodeName );
},
focus: function( elem ) {
return elem === elem.ownerDocument.activeElement;
}
},
setFilters: {
first: function( elem, i ) {
return i === 0;
},
last: function( elem, i, match, array ) {
return i === array.length - 1;
},
even: function( elem, i ) {
return i % 2 === 0;
},
odd: function( elem, i ) {
return i % 2 === 1;
},
lt: function( elem, i, match ) {
return i < match[3] - 0;
},
gt: function( elem, i, match ) {
return i > match[3] - 0;
},
nth: function( elem, i, match ) {
return match[3] - 0 === i;
},
eq: function( elem, i, match ) {
return match[3] - 0 === i;
}
},
filter: {
PSEUDO: function( elem, match, i, array ) {
var name = match[1],
filter = Expr.filters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
} else if ( name === "contains" ) {
return (elem.textContent || elem.innerText || Sizzle.getText([ elem ]) || "").indexOf(match[3]) >= 0;
} else if ( name === "not" ) {
var not = match[3];
for ( var j = 0, l = not.length; j < l; j++ ) {
if ( not[j] === elem ) {
return false;
}
}
return true;
} else {
Sizzle.error( name );
}
},
CHILD: function( elem, match ) {
var type = match[1],
node = elem;
switch ( type ) {
case "only":
case "first":
while ( (node = node.previousSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
if ( type === "first" ) {
return true;
}
node = elem;
case "last":
while ( (node = node.nextSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
return true;
case "nth":
var first = match[2],
last = match[3];
if ( first === 1 && last === 0 ) {
return true;
}
var doneName = match[0],
parent = elem.parentNode;
if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) {
var count = 0;
for ( node = parent.firstChild; node; node = node.nextSibling ) {
if ( node.nodeType === 1 ) {
node.nodeIndex = ++count;
}
}
parent.sizcache = doneName;
}
var diff = elem.nodeIndex - last;
if ( first === 0 ) {
return diff === 0;
} else {
return ( diff % first === 0 && diff / first >= 0 );
}
}
},
ID: function( elem, match ) {
return elem.nodeType === 1 && elem.getAttribute("id") === match;
},
TAG: function( elem, match ) {
return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match;
},
CLASS: function( elem, match ) {
return (" " + (elem.className || elem.getAttribute("class")) + " ")
.indexOf( match ) > -1;
},
ATTR: function( elem, match ) {
var name = match[1],
result = Expr.attrHandle[ name ] ?
Expr.attrHandle[ name ]( elem ) :
elem[ name ] != null ?
elem[ name ] :
elem.getAttribute( name ),
value = result + "",
type = match[2],
check = match[4];
return result == null ?
type === "!=" :
type === "=" ?
value === check :
type === "*=" ?
value.indexOf(check) >= 0 :
type === "~=" ?
(" " + value + " ").indexOf(check) >= 0 :
!check ?
value && result !== false :
type === "!=" ?
value !== check :
type === "^=" ?
value.indexOf(check) === 0 :
type === "$=" ?
value.substr(value.length - check.length) === check :
type === "|=" ?
value === check || value.substr(0, check.length + 1) === check + "-" :
false;
},
POS: function( elem, match, i, array ) {
var name = match[2],
filter = Expr.setFilters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
}
}
}
};
var origPOS = Expr.match.POS,
fescape = function(all, num){
return "\\" + (num - 0 + 1);
};
for ( var type in Expr.match ) {
Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) );
Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) );
}
var makeArray = function( array, results ) {
array = Array.prototype.slice.call( array, 0 );
if ( results ) {
results.push.apply( results, array );
return results;
}
return array;
};
// Perform a simple check to determine if the browser is capable of
// converting a NodeList to an array using builtin methods.
// Also verifies that the returned array holds DOM nodes
// (which is not the case in the Blackberry browser)
try {
Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType;
// Provide a fallback method if it does not work
} catch( e ) {
makeArray = function( array, results ) {
var i = 0,
ret = results || [];
if ( toString.call(array) === "[object Array]" ) {
Array.prototype.push.apply( ret, array );
} else {
if ( typeof array.length === "number" ) {
for ( var l = array.length; i < l; i++ ) {
ret.push( array[i] );
}
} else {
for ( ; array[i]; i++ ) {
ret.push( array[i] );
}
}
}
return ret;
};
}
var sortOrder, siblingCheck;
if ( document.documentElement.compareDocumentPosition ) {
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
return 0;
}
if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) {
return a.compareDocumentPosition ? -1 : 1;
}
return a.compareDocumentPosition(b) & 4 ? -1 : 1;
};
} else {
sortOrder = function( a, b ) {
// The nodes are identical, we can exit early
if ( a === b ) {
hasDuplicate = true;
return 0;
// Fallback to using sourceIndex (in IE) if it's available on both nodes
} else if ( a.sourceIndex && b.sourceIndex ) {
return a.sourceIndex - b.sourceIndex;
}
var al, bl,
ap = [],
bp = [],
aup = a.parentNode,
bup = b.parentNode,
cur = aup;
// If the nodes are siblings (or identical) we can do a quick check
if ( aup === bup ) {
return siblingCheck( a, b );
// If no parents were found then the nodes are disconnected
} else if ( !aup ) {
return -1;
} else if ( !bup ) {
return 1;
}
// Otherwise they're somewhere else in the tree so we need
// to build up a full list of the parentNodes for comparison
while ( cur ) {
ap.unshift( cur );
cur = cur.parentNode;
}
cur = bup;
while ( cur ) {
bp.unshift( cur );
cur = cur.parentNode;
}
al = ap.length;
bl = bp.length;
// Start walking down the tree looking for a discrepancy
for ( var i = 0; i < al && i < bl; i++ ) {
if ( ap[i] !== bp[i] ) {
return siblingCheck( ap[i], bp[i] );
}
}
// We ended someplace up the tree so do a sibling check
return i === al ?
siblingCheck( a, bp[i], -1 ) :
siblingCheck( ap[i], b, 1 );
};
siblingCheck = function( a, b, ret ) {
if ( a === b ) {
return ret;
}
var cur = a.nextSibling;
while ( cur ) {
if ( cur === b ) {
return -1;
}
cur = cur.nextSibling;
}
return 1;
};
}
// Utility function for retreiving the text value of an array of DOM nodes
Sizzle.getText = function( elems ) {
var ret = "", elem;
for ( var i = 0; elems[i]; i++ ) {
elem = elems[i];
// Get the text from text nodes and CDATA nodes
if ( elem.nodeType === 3 || elem.nodeType === 4 ) {
ret += elem.nodeValue;
// Traverse everything else, except comment nodes
} else if ( elem.nodeType !== 8 ) {
ret += Sizzle.getText( elem.childNodes );
}
}
return ret;
};
// Check to see if the browser returns elements by name when
// querying by getElementById (and provide a workaround)
(function(){
// We're going to inject a fake input element with a specified name
var form = document.createElement("div"),
id = "script" + (new Date()).getTime(),
root = document.documentElement;
form.innerHTML = "<a name='" + id + "'/>";
// Inject it into the root element, check its status, and remove it quickly
root.insertBefore( form, root.firstChild );
// The workaround has to do additional checks after a getElementById
// Which slows things down for other browsers (hence the branching)
if ( document.getElementById( id ) ) {
Expr.find.ID = function( match, context, isXML ) {
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
return m ?
m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ?
[m] :
undefined :
[];
}
};
Expr.filter.ID = function( elem, match ) {
var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
return elem.nodeType === 1 && node && node.nodeValue === match;
};
}
root.removeChild( form );
// release memory in IE
root = form = null;
})();
(function(){
// Check to see if the browser returns only elements
// when doing getElementsByTagName("*")
// Create a fake element
var div = document.createElement("div");
div.appendChild( document.createComment("") );
// Make sure no comments are found
if ( div.getElementsByTagName("*").length > 0 ) {
Expr.find.TAG = function( match, context ) {
var results = context.getElementsByTagName( match[1] );
// Filter out possible comments
if ( match[1] === "*" ) {
var tmp = [];
for ( var i = 0; results[i]; i++ ) {
if ( results[i].nodeType === 1 ) {
tmp.push( results[i] );
}
}
results = tmp;
}
return results;
};
}
// Check to see if an attribute returns normalized href attributes
div.innerHTML = "<a href='#'></a>";
if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
div.firstChild.getAttribute("href") !== "#" ) {
Expr.attrHandle.href = function( elem ) {
return elem.getAttribute( "href", 2 );
};
}
// release memory in IE
div = null;
})();
if ( document.querySelectorAll ) {
(function(){
var oldSizzle = Sizzle,
div = document.createElement("div"),
id = "__sizzle__";
div.innerHTML = "<p class='TEST'></p>";
// Safari can't handle uppercase or unicode characters when
// in quirks mode.
if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
return;
}
Sizzle = function( query, context, extra, seed ) {
context = context || document;
// Only use querySelectorAll on non-XML documents
// (ID selectors don't work in non-HTML documents)
if ( !seed && !Sizzle.isXML(context) ) {
// See if we find a selector to speed up
var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query );
if ( match && (context.nodeType === 1 || context.nodeType === 9) ) {
// Speed-up: Sizzle("TAG")
if ( match[1] ) {
return makeArray( context.getElementsByTagName( query ), extra );
// Speed-up: Sizzle(".CLASS")
} else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) {
return makeArray( context.getElementsByClassName( match[2] ), extra );
}
}
if ( context.nodeType === 9 ) {
// Speed-up: Sizzle("body")
// The body element only exists once, optimize finding it
if ( query === "body" && context.body ) {
return makeArray( [ context.body ], extra );
// Speed-up: Sizzle("#ID")
} else if ( match && match[3] ) {
var elem = context.getElementById( match[3] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id === match[3] ) {
return makeArray( [ elem ], extra );
}
} else {
return makeArray( [], extra );
}
}
try {
return makeArray( context.querySelectorAll(query), extra );
} catch(qsaError) {}
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
} else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
var oldContext = context,
old = context.getAttribute( "id" ),
nid = old || id,
hasParent = context.parentNode,
relativeHierarchySelector = /^\s*[+~]/.test( query );
if ( !old ) {
context.setAttribute( "id", nid );
} else {
nid = nid.replace( /'/g, "\\$&" );
}
if ( relativeHierarchySelector && hasParent ) {
context = context.parentNode;
}
try {
if ( !relativeHierarchySelector || hasParent ) {
return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra );
}
} catch(pseudoError) {
} finally {
if ( !old ) {
oldContext.removeAttribute( "id" );
}
}
}
}
return oldSizzle(query, context, extra, seed);
};
for ( var prop in oldSizzle ) {
Sizzle[ prop ] = oldSizzle[ prop ];
}
// release memory in IE
div = null;
})();
}
(function(){
var html = document.documentElement,
matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector;
if ( matches ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9 fails this)
var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ),
pseudoWorks = false;
try {
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( document.documentElement, "[test!='']:sizzle" );
} catch( pseudoError ) {
pseudoWorks = true;
}
Sizzle.matchesSelector = function( node, expr ) {
// Make sure that attribute selectors are quoted
expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']");
if ( !Sizzle.isXML( node ) ) {
try {
if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) {
var ret = matches.call( node, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || !disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9, so check for that
node.document && node.document.nodeType !== 11 ) {
return ret;
}
}
} catch(e) {}
}
return Sizzle(expr, null, null, [node]).length > 0;
};
}
})();
(function(){
var div = document.createElement("div");
div.innerHTML = "<div class='test e'></div><div class='test'></div>";
// Opera can't find a second classname (in 9.6)
// Also, make sure that getElementsByClassName actually exists
if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) {
return;
}
// Safari caches class attributes, doesn't catch changes (in 3.2)
div.lastChild.className = "e";
if ( div.getElementsByClassName("e").length === 1 ) {
return;
}
Expr.order.splice(1, 0, "CLASS");
Expr.find.CLASS = function( match, context, isXML ) {
if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
return context.getElementsByClassName(match[1]);
}
};
// release memory in IE
div = null;
})();
function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
var match = false;
elem = elem[dir];
while ( elem ) {
if ( elem.sizcache === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 && !isXML ){
elem.sizcache = doneName;
elem.sizset = i;
}
if ( elem.nodeName.toLowerCase() === cur ) {
match = elem;
break;
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
var match = false;
elem = elem[dir];
while ( elem ) {
if ( elem.sizcache === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 ) {
if ( !isXML ) {
elem.sizcache = doneName;
elem.sizset = i;
}
if ( typeof cur !== "string" ) {
if ( elem === cur ) {
match = true;
break;
}
} else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
match = elem;
break;
}
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
if ( document.documentElement.contains ) {
Sizzle.contains = function( a, b ) {
return a !== b && (a.contains ? a.contains(b) : true);
};
} else if ( document.documentElement.compareDocumentPosition ) {
Sizzle.contains = function( a, b ) {
return !!(a.compareDocumentPosition(b) & 16);
};
} else {
Sizzle.contains = function() {
return false;
};
}
Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
var posProcess = function( selector, context ) {
var match,
tmpSet = [],
later = "",
root = context.nodeType ? [context] : context;
// Position selectors must be done after the filter
// And so must :not(positional) so we move all PSEUDOs to the end
while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
later += match[0];
selector = selector.replace( Expr.match.PSEUDO, "" );
}
selector = Expr.relative[selector] ? selector + "*" : selector;
for ( var i = 0, l = root.length; i < l; i++ ) {
Sizzle( selector, root[i], tmpSet );
}
return Sizzle.filter( later, tmpSet );
};
// EXPOSE
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.filters;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})();
var runtil = /Until$/,
rparentsprev = /^(?:parents|prevUntil|prevAll)/,
// Note: This RegExp should be improved, or likely pulled from Sizzle
rmultiselector = /,/,
isSimple = /^.[^:#\[\.,]*$/,
slice = Array.prototype.slice,
POS = jQuery.expr.match.POS,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function( selector ) {
var self = this,
i, l;
if ( typeof selector !== "string" ) {
return jQuery( selector ).filter(function() {
for ( i = 0, l = self.length; i < l; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
});
}
var ret = this.pushStack( "", "find", selector ),
length, n, r;
for ( i = 0, l = this.length; i < l; i++ ) {
length = ret.length;
jQuery.find( selector, this[i], ret );
if ( i > 0 ) {
// Make sure that the results are unique
for ( n = length; n < ret.length; n++ ) {
for ( r = 0; r < length; r++ ) {
if ( ret[r] === ret[n] ) {
ret.splice(n--, 1);
break;
}
}
}
}
}
return ret;
},
has: function( target ) {
var targets = jQuery( target );
return this.filter(function() {
for ( var i = 0, l = targets.length; i < l; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector, false), "not", selector);
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector, true), "filter", selector );
},
is: function( selector ) {
return !!selector && ( typeof selector === "string" ?
jQuery.filter( selector, this ).length > 0 :
this.filter( selector ).length > 0 );
},
closest: function( selectors, context ) {
var ret = [], i, l, cur = this[0];
// Array
if ( jQuery.isArray( selectors ) ) {
var match, selector,
matches = {},
level = 1;
if ( cur && selectors.length ) {
for ( i = 0, l = selectors.length; i < l; i++ ) {
selector = selectors[i];
if ( !matches[ selector ] ) {
matches[ selector ] = POS.test( selector ) ?
jQuery( selector, context || this.context ) :
selector;
}
}
while ( cur && cur.ownerDocument && cur !== context ) {
for ( selector in matches ) {
match = matches[ selector ];
if ( match.jquery ? match.index( cur ) > -1 : jQuery( cur ).is( match ) ) {
ret.push({ selector: selector, elem: cur, level: level });
}
}
cur = cur.parentNode;
level++;
}
}
return ret;
}
// String
var pos = POS.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( i = 0, l = this.length; i < l; i++ ) {
cur = this[i];
while ( cur ) {
if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
ret.push( cur );
break;
} else {
cur = cur.parentNode;
if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) {
break;
}
}
}
}
ret = ret.length > 1 ? jQuery.unique( ret ) : ret;
return this.pushStack( ret, "closest", selectors );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
if ( !elem || typeof elem === "string" ) {
return jQuery.inArray( this[0],
// If it receives a string, the selector is used
// If it receives nothing, the siblings are used
elem ? jQuery( elem ) : this.parent().children() );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
all :
jQuery.unique( all ) );
},
andSelf: function() {
return this.add( this.prevObject );
}
});
// A painfully simple check to see if an element is disconnected
// from a document (should be improved, where feasible).
function isDisconnected( node ) {
return !node || !node.parentNode || node.parentNode.nodeType === 11;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return jQuery.nth( elem, 2, "nextSibling" );
},
prev: function( elem ) {
return jQuery.nth( elem, 2, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( elem.parentNode.firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.makeArray( elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until ),
// The variable 'args' was introduced in
// https://github.com/jquery/jquery/commit/52a0238
// to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed.
// http://code.google.com/p/v8/issues/detail?id=1050
args = slice.call(arguments);
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, args.join(",") );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 ?
jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
jQuery.find.matches(expr, elems);
},
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
nth: function( cur, result, dir, elem ) {
result = result || 1;
var num = 0;
for ( ; cur; cur = cur[dir] ) {
if ( cur.nodeType === 1 && ++num === result ) {
break;
}
}
return cur;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, keep ) {
// Can't pass null or undefined to indexOf in Firefox 4
// Set to 0 to skip string check
qualifier = qualifier || 0;
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep(elements, function( elem, i ) {
var retVal = !!qualifier.call( elem, i, elem );
return retVal === keep;
});
} else if ( qualifier.nodeType ) {
return jQuery.grep(elements, function( elem, i ) {
return (elem === qualifier) === keep;
});
} else if ( typeof qualifier === "string" ) {
var filtered = jQuery.grep(elements, function( elem ) {
return elem.nodeType === 1;
});
if ( isSimple.test( qualifier ) ) {
return jQuery.filter(qualifier, filtered, !keep);
} else {
qualifier = jQuery.filter( qualifier, filtered );
}
}
return jQuery.grep(elements, function( elem, i ) {
return (jQuery.inArray( elem, qualifier ) >= 0) === keep;
});
}
var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g,
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnocache = /<(?:script|object|embed|option|style)/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /\/(java|ecma)script/i,
rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)/,
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
area: [ 1, "<map>", "</map>" ],
_default: [ 0, "", "" ]
};
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
// IE can't serialize <link> and <script> tags normally
if ( !jQuery.support.htmlSerialize ) {
wrapMap._default = [ 1, "div<div>", "</div>" ];
}
jQuery.fn.extend({
text: function( text ) {
if ( jQuery.isFunction(text) ) {
return this.each(function(i) {
var self = jQuery( this );
self.text( text.call(this, i, self.text()) );
});
}
if ( typeof text !== "object" && text !== undefined ) {
return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
}
return jQuery.text( this );
},
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapAll( html.call(this, i) );
});
}
if ( this[0] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
if ( this[0].parentNode ) {
wrap.insertBefore( this[0] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
return this.each(function() {
jQuery( this ).wrapAll( html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
},
append: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 ) {
this.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 ) {
this.insertBefore( elem, this.firstChild );
}
});
},
before: function() {
if ( this[0] && this[0].parentNode ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this );
});
} else if ( arguments.length ) {
var set = jQuery(arguments[0]);
set.push.apply( set, this.toArray() );
return this.pushStack( set, "before", arguments );
}
},
after: function() {
if ( this[0] && this[0].parentNode ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this.nextSibling );
});
} else if ( arguments.length ) {
var set = this.pushStack( this, "after", arguments );
set.push.apply( set, jQuery(arguments[0]).toArray() );
return set;
}
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
jQuery.cleanData( [ elem ] );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
}
}
return this;
},
empty: function() {
for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
if ( value === undefined ) {
return this[0] && this[0].nodeType === 1 ?
this[0].innerHTML.replace(rinlinejQuery, "") :
null;
// See if we can take a shortcut and just use innerHTML
} else if ( typeof value === "string" && !rnocache.test( value ) &&
(jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
!wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {
value = value.replace(rxhtmlTag, "<$1></$2>");
try {
for ( var i = 0, l = this.length; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
if ( this[i].nodeType === 1 ) {
jQuery.cleanData( this[i].getElementsByTagName("*") );
this[i].innerHTML = value;
}
}
// If using innerHTML throws an exception, use the fallback method
} catch(e) {
this.empty().append( value );
}
} else if ( jQuery.isFunction( value ) ) {
this.each(function(i){
var self = jQuery( this );
self.html( value.call(this, i, self.html()) );
});
} else {
this.empty().append( value );
}
return this;
},
replaceWith: function( value ) {
if ( this[0] && this[0].parentNode ) {
// Make sure that the elements are removed from the DOM before they are inserted
// this can help fix replacing a parent with child elements
if ( jQuery.isFunction( value ) ) {
return this.each(function(i) {
var self = jQuery(this), old = self.html();
self.replaceWith( value.call( this, i, old ) );
});
}
if ( typeof value !== "string" ) {
value = jQuery( value ).detach();
}
return this.each(function() {
var next = this.nextSibling,
parent = this.parentNode;
jQuery( this ).remove();
if ( next ) {
jQuery(next).before( value );
} else {
jQuery(parent).append( value );
}
});
} else {
return this.length ?
this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) :
this;
}
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, table, callback ) {
var results, first, fragment, parent,
value = args[0],
scripts = [];
// We can't cloneNode fragments that contain checked, in WebKit
if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) {
return this.each(function() {
jQuery(this).domManip( args, table, callback, true );
});
}
if ( jQuery.isFunction(value) ) {
return this.each(function(i) {
var self = jQuery(this);
args[0] = value.call(this, i, table ? self.html() : undefined);
self.domManip( args, table, callback );
});
}
if ( this[0] ) {
parent = value && value.parentNode;
// If we're in a fragment, just use that instead of building a new one
if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) {
results = { fragment: parent };
} else {
results = jQuery.buildFragment( args, this, scripts );
}
fragment = results.fragment;
if ( fragment.childNodes.length === 1 ) {
first = fragment = fragment.firstChild;
} else {
first = fragment.firstChild;
}
if ( first ) {
table = table && jQuery.nodeName( first, "tr" );
for ( var i = 0, l = this.length, lastIndex = l - 1; i < l; i++ ) {
callback.call(
table ?
root(this[i], first) :
this[i],
// Make sure that we do not leak memory by inadvertently discarding
// the original fragment (which might have attached data) instead of
// using it; in addition, use the original fragment object for the last
// item instead of first because it can end up being emptied incorrectly
// in certain situations (Bug #8070).
// Fragments from the fragment cache must always be cloned and never used
// in place.
results.cacheable || (l > 1 && i < lastIndex) ?
jQuery.clone( fragment, true, true ) :
fragment
);
}
}
if ( scripts.length ) {
jQuery.each( scripts, evalScript );
}
}
return this;
}
});
function root( elem, cur ) {
return jQuery.nodeName(elem, "table") ?
(elem.getElementsByTagName("tbody")[0] ||
elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
elem;
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var internalKey = jQuery.expando,
oldData = jQuery.data( src ),
curData = jQuery.data( dest, oldData );
// Switch to use the internal data object, if it exists, for the next
// stage of data copying
if ( (oldData = oldData[ internalKey ]) ) {
var events = oldData.events;
curData = curData[ internalKey ] = jQuery.extend({}, oldData);
if ( events ) {
delete curData.handle;
curData.events = {};
for ( var type in events ) {
for ( var i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type + ( events[ type ][ i ].namespace ? "." : "" ) + events[ type ][ i ].namespace, events[ type ][ i ], events[ type ][ i ].data );
}
}
}
}
}
function cloneFixAttributes( src, dest ) {
var nodeName;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
// clearAttributes removes the attributes, which we don't want,
// but also removes the attachEvent events, which we *do* want
if ( dest.clearAttributes ) {
dest.clearAttributes();
}
// mergeAttributes, in contrast, only merges back on the
// original attributes, not the events
if ( dest.mergeAttributes ) {
dest.mergeAttributes( src );
}
nodeName = dest.nodeName.toLowerCase();
// IE6-8 fail to clone children inside object elements that use
// the proprietary classid attribute value (rather than the type
// attribute) to identify the type of content to display
if ( nodeName === "object" ) {
dest.outerHTML = src.outerHTML;
} else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
if ( src.checked ) {
dest.defaultChecked = dest.checked = src.checked;
}
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
// Event data gets referenced instead of copied if the expando
// gets copied too
dest.removeAttribute( jQuery.expando );
}
jQuery.buildFragment = function( args, nodes, scripts ) {
var fragment, cacheable, cacheresults, doc;
// nodes may contain either an explicit document object,
// a jQuery collection or context object.
// If nodes[0] contains a valid object to assign to doc
if ( nodes && nodes[0] ) {
doc = nodes[0].ownerDocument || nodes[0];
}
// Ensure that an attr object doesn't incorrectly stand in as a document object
// Chrome and Firefox seem to allow this to occur and will throw exception
// Fixes #8950
if ( !doc.createDocumentFragment ) {
doc = document;
}
// Only cache "small" (1/2 KB) HTML strings that are associated with the main document
// Cloning options loses the selected state, so don't cache them
// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document &&
args[0].charAt(0) === "<" && !rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) {
cacheable = true;
cacheresults = jQuery.fragments[ args[0] ];
if ( cacheresults && cacheresults !== 1 ) {
fragment = cacheresults;
}
}
if ( !fragment ) {
fragment = doc.createDocumentFragment();
jQuery.clean( args, doc, fragment, scripts );
}
if ( cacheable ) {
jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1;
}
return { fragment: fragment, cacheable: cacheable };
};
jQuery.fragments = {};
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var ret = [],
insert = jQuery( selector ),
parent = this.length === 1 && this[0].parentNode;
if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
insert[ original ]( this[0] );
return this;
} else {
for ( var i = 0, l = insert.length; i < l; i++ ) {
var elems = (i > 0 ? this.clone(true) : this).get();
jQuery( insert[i] )[ original ]( elems );
ret = ret.concat( elems );
}
return this.pushStack( ret, name, insert.selector );
}
};
});
function getAll( elem ) {
if ( "getElementsByTagName" in elem ) {
return elem.getElementsByTagName( "*" );
} else if ( "querySelectorAll" in elem ) {
return elem.querySelectorAll( "*" );
} else {
return [];
}
}
// Used in clean, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( elem.type === "checkbox" || elem.type === "radio" ) {
elem.defaultChecked = elem.checked;
}
}
// Finds all inputs and passes them to fixDefaultChecked
function findInputs( elem ) {
if ( jQuery.nodeName( elem, "input" ) ) {
fixDefaultChecked( elem );
} else if ( "getElementsByTagName" in elem ) {
jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked );
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var clone = elem.cloneNode(true),
srcElements,
destElements,
i;
if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// IE copies events bound via attachEvent when using cloneNode.
// Calling detachEvent on the clone will also remove the events
// from the original. In order to get around this, we use some
// proprietary methods to clear the events. Thanks to MooTools
// guys for this hotness.
cloneFixAttributes( elem, clone );
// Using Sizzle here is crazy slow, so we use getElementsByTagName
// instead
srcElements = getAll( elem );
destElements = getAll( clone );
// Weird iteration because IE will replace the length property
// with an element if you are cloning the body and one of the
// elements on the page has a name or id of "length"
for ( i = 0; srcElements[i]; ++i ) {
cloneFixAttributes( srcElements[i], destElements[i] );
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
cloneCopyEvent( elem, clone );
if ( deepDataAndEvents ) {
srcElements = getAll( elem );
destElements = getAll( clone );
for ( i = 0; srcElements[i]; ++i ) {
cloneCopyEvent( srcElements[i], destElements[i] );
}
}
}
srcElements = destElements = null;
// Return the cloned set
return clone;
},
clean: function( elems, context, fragment, scripts ) {
var checkScriptType;
context = context || document;
// !context.createElement fails in IE with an error but returns typeof 'object'
if ( typeof context.createElement === "undefined" ) {
context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
}
var ret = [], j;
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
if ( typeof elem === "number" ) {
elem += "";
}
if ( !elem ) {
continue;
}
// Convert html string into DOM nodes
if ( typeof elem === "string" ) {
if ( !rhtml.test( elem ) ) {
elem = context.createTextNode( elem );
} else {
// Fix "XHTML"-style tags in all browsers
elem = elem.replace(rxhtmlTag, "<$1></$2>");
// Trim whitespace, otherwise indexOf won't work as expected
var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(),
wrap = wrapMap[ tag ] || wrapMap._default,
depth = wrap[0],
div = context.createElement("div");
// Go to html and back, then peel off extra wrappers
div.innerHTML = wrap[1] + elem + wrap[2];
// Move to the right depth
while ( depth-- ) {
div = div.lastChild;
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
var hasBody = rtbody.test(elem),
tbody = tag === "table" && !hasBody ?
div.firstChild && div.firstChild.childNodes :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !hasBody ?
div.childNodes :
[];
for ( j = tbody.length - 1; j >= 0 ; --j ) {
if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
tbody[ j ].parentNode.removeChild( tbody[ j ] );
}
}
}
// IE completely kills leading whitespace when innerHTML is used
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
}
elem = div.childNodes;
}
}
// Resets defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
var len;
if ( !jQuery.support.appendChecked ) {
if ( elem[0] && typeof (len = elem.length) === "number" ) {
for ( j = 0; j < len; j++ ) {
findInputs( elem[j] );
}
} else {
findInputs( elem );
}
}
if ( elem.nodeType ) {
ret.push( elem );
} else {
ret = jQuery.merge( ret, elem );
}
}
if ( fragment ) {
checkScriptType = function( elem ) {
return !elem.type || rscriptType.test( elem.type );
};
for ( i = 0; ret[i]; i++ ) {
if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
} else {
if ( ret[i].nodeType === 1 ) {
var jsTags = jQuery.grep( ret[i].getElementsByTagName( "script" ), checkScriptType );
ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );
}
fragment.appendChild( ret[i] );
}
}
}
return ret;
},
cleanData: function( elems ) {
var data, id, cache = jQuery.cache, internalKey = jQuery.expando, special = jQuery.event.special,
deleteExpando = jQuery.support.deleteExpando;
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) {
continue;
}
id = elem[ jQuery.expando ];
if ( id ) {
data = cache[ id ] && cache[ id ][ internalKey ];
if ( data && data.events ) {
for ( var type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
// Null the DOM reference to avoid IE6/7/8 leak (#7054)
if ( data.handle ) {
data.handle.elem = null;
}
}
if ( deleteExpando ) {
delete elem[ jQuery.expando ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( jQuery.expando );
}
delete cache[ id ];
}
}
}
});
function evalScript( i, elem ) {
if ( elem.src ) {
jQuery.ajax({
url: elem.src,
async: false,
dataType: "script"
});
} else {
jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "/*$0*/" ) );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
}
var ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity=([^)]*)/,
// fixed for IE9, see #8346
rupper = /([A-Z]|^ms)/g,
rnumpx = /^-?\d+(?:px)?$/i,
rnum = /^-?\d/,
rrelNum = /^[+\-]=/,
rrelNumFilter = /[^+\-\.\de]+/g,
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssWidth = [ "Left", "Right" ],
cssHeight = [ "Top", "Bottom" ],
curCSS,
getComputedStyle,
currentStyle;
jQuery.fn.css = function( name, value ) {
// Setting 'undefined' is a no-op
if ( arguments.length === 2 && value === undefined ) {
return this;
}
return jQuery.access( this, name, value, true, function( elem, name, value ) {
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
});
};
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity", "opacity" );
return ret === "" ? "1" : ret;
} else {
return elem.style.opacity;
}
}
}
},
// Exclude the following css properties to add px
cssNumber: {
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, origName = jQuery.camelCase( name ),
style = elem.style, hooks = jQuery.cssHooks[ origName ];
name = jQuery.cssProps[ origName ] || origName;
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// Make sure that NaN and null values aren't set. See: #7116
if ( type === "number" && isNaN( value ) || value == null ) {
return;
}
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && rrelNum.test( value ) ) {
value = +value.replace( rrelNumFilter, "" ) + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) {
// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
// Fixes bug #5509
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra ) {
var ret, hooks;
// Make sure that we're working with the right name
name = jQuery.camelCase( name );
hooks = jQuery.cssHooks[ name ];
name = jQuery.cssProps[ name ] || name;
// cssFloat needs a special treatment
if ( name === "cssFloat" ) {
name = "float";
}
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) {
return ret;
// Otherwise, if a way to get the computed value exists, use that
} else if ( curCSS ) {
return curCSS( elem, name );
}
},
// A method for quickly swapping in/out CSS properties to get correct calculations
swap: function( elem, options, callback ) {
var old = {};
// Remember the old values, and insert the new ones
for ( var name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
callback.call( elem );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
}
});
// DEPRECATED, Use jQuery.css() instead
jQuery.curCSS = jQuery.css;
jQuery.each(["height", "width"], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
var val;
if ( computed ) {
if ( elem.offsetWidth !== 0 ) {
return getWH( elem, name, extra );
} else {
jQuery.swap( elem, cssShow, function() {
val = getWH( elem, name, extra );
});
}
return val;
}
},
set: function( elem, value ) {
if ( rnumpx.test( value ) ) {
// ignore negative width and height values #1599
value = parseFloat( value );
if ( value >= 0 ) {
return value + "px";
}
} else {
return value;
}
}
};
});
if ( !jQuery.support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( parseFloat( RegExp.$1 ) / 100 ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle;
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// Set the alpha filter to set the opacity
var opacity = jQuery.isNaN( value ) ?
"" :
"alpha(opacity=" + value * 100 + ")",
filter = currentStyle && currentStyle.filter || style.filter || "";
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
jQuery(function() {
// This hook cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
if ( !jQuery.support.reliableMarginRight ) {
jQuery.cssHooks.marginRight = {
get: function( elem, computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
var ret;
jQuery.swap( elem, { "display": "inline-block" }, function() {
if ( computed ) {
ret = curCSS( elem, "margin-right", "marginRight" );
} else {
ret = elem.style.marginRight;
}
});
return ret;
}
};
}
});
if ( document.defaultView && document.defaultView.getComputedStyle ) {
getComputedStyle = function( elem, name ) {
var ret, defaultView, computedStyle;
name = name.replace( rupper, "-$1" ).toLowerCase();
if ( !(defaultView = elem.ownerDocument.defaultView) ) {
return undefined;
}
if ( (computedStyle = defaultView.getComputedStyle( elem, null )) ) {
ret = computedStyle.getPropertyValue( name );
if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) {
ret = jQuery.style( elem, name );
}
}
return ret;
};
}
if ( document.documentElement.currentStyle ) {
currentStyle = function( elem, name ) {
var left,
ret = elem.currentStyle && elem.currentStyle[ name ],
rsLeft = elem.runtimeStyle && elem.runtimeStyle[ name ],
style = elem.style;
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
if ( !rnumpx.test( ret ) && rnum.test( ret ) ) {
// Remember the original values
left = style.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
elem.runtimeStyle.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : (ret || 0);
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
elem.runtimeStyle.left = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
}
curCSS = getComputedStyle || currentStyle;
function getWH( elem, name, extra ) {
// Start with offset property
var val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
which = name === "width" ? cssWidth : cssHeight;
if ( val > 0 ) {
if ( extra !== "border" ) {
jQuery.each( which, function() {
if ( !extra ) {
val -= parseFloat( jQuery.css( elem, "padding" + this ) ) || 0;
}
if ( extra === "margin" ) {
val += parseFloat( jQuery.css( elem, extra + this ) ) || 0;
} else {
val -= parseFloat( jQuery.css( elem, "border" + this + "Width" ) ) || 0;
}
});
}
return val + "px";
}
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name, name );
if ( val < 0 || val == null ) {
val = elem.style[ name ] || 0;
}
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
// Add padding, border, margin
if ( extra ) {
jQuery.each( which, function() {
val += parseFloat( jQuery.css( elem, "padding" + this ) ) || 0;
if ( extra !== "padding" ) {
val += parseFloat( jQuery.css( elem, "border" + this + "Width" ) ) || 0;
}
if ( extra === "margin" ) {
val += parseFloat( jQuery.css( elem, extra + this ) ) || 0;
}
});
}
return val + "px";
}
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
var width = elem.offsetWidth,
height = elem.offsetHeight;
return (width === 0 && height === 0) || (!jQuery.support.reliableHiddenOffsets && (elem.style.display || jQuery.css( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rhash = /#.*$/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
rinput = /^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rquery = /\?/,
rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
rselectTextarea = /^(?:select|textarea)/i,
rspacesAjax = /\s+/,
rts = /([?&])_=[^&]*/,
rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,
// Keep a copy of the old load method
_load = jQuery.fn.load,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Document location
ajaxLocation,
// Document location segments
ajaxLocParts;
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
if ( jQuery.isFunction( func ) ) {
var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ),
i = 0,
length = dataTypes.length,
dataType,
list,
placeBefore;
// For each dataType in the dataTypeExpression
for(; i < length; i++ ) {
dataType = dataTypes[ i ];
// We control if we're asked to add before
// any existing element
placeBefore = /^\+/.test( dataType );
if ( placeBefore ) {
dataType = dataType.substr( 1 ) || "*";
}
list = structure[ dataType ] = structure[ dataType ] || [];
// then we add to the structure accordingly
list[ placeBefore ? "unshift" : "push" ]( func );
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR,
dataType /* internal */, inspected /* internal */ ) {
dataType = dataType || options.dataTypes[ 0 ];
inspected = inspected || {};
inspected[ dataType ] = true;
var list = structure[ dataType ],
i = 0,
length = list ? list.length : 0,
executeOnly = ( structure === prefilters ),
selection;
for(; i < length && ( executeOnly || !selection ); i++ ) {
selection = list[ i ]( options, originalOptions, jqXHR );
// If we got redirected to another dataType
// we try there if executing only and not done already
if ( typeof selection === "string" ) {
if ( !executeOnly || inspected[ selection ] ) {
selection = undefined;
} else {
options.dataTypes.unshift( selection );
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, selection, inspected );
}
}
}
// If we're only executing or nothing was selected
// we try the catchall dataType if not done already
if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, "*", inspected );
}
// unnecessary when only executing (prefilters)
// but it'll be ignored by the caller in that case
return selection;
}
jQuery.fn.extend({
load: function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
// Don't do a request if no elements are being requested
} else if ( !this.length ) {
return this;
}
var off = url.indexOf( " " );
if ( off >= 0 ) {
var selector = url.slice( off, url.length );
url = url.slice( 0, off );
}
// Default to a GET request
var type = "GET";
// If the second parameter was provided
if ( params ) {
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( typeof params === "object" ) {
params = jQuery.param( params, jQuery.ajaxSettings.traditional );
type = "POST";
}
}
var self = this;
// Request the remote document
jQuery.ajax({
url: url,
type: type,
dataType: "html",
data: params,
// Complete callback (responseText is used internally)
complete: function( jqXHR, status, responseText ) {
// Store the response as specified by the jqXHR object
responseText = jqXHR.responseText;
// If successful, inject the HTML into all the matched elements
if ( jqXHR.isResolved() ) {
// #4825: Get the actual response in case
// a dataFilter is present in ajaxSettings
jqXHR.done(function( r ) {
responseText = r;
});
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("<div>")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append(responseText.replace(rscript, ""))
// Locate the specified elements
.find(selector) :
// If not, just inject the full result
responseText );
}
if ( callback ) {
self.each( callback, [ responseText, status, jqXHR ] );
}
}
});
return this;
},
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
return this.elements ? jQuery.makeArray( this.elements ) : this;
})
.filter(function(){
return this.name && !this.disabled &&
( this.checked || rselectTextarea.test( this.nodeName ) ||
rinput.test( this.type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val, i ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
// Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){
jQuery.fn[ o ] = function( f ){
return this.bind( o, f );
};
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
type: method,
url: url,
data: data,
success: callback,
dataType: type
});
};
});
jQuery.extend({
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function ( target, settings ) {
if ( !settings ) {
// Only one parameter, we extend ajaxSettings
settings = target;
target = jQuery.extend( true, jQuery.ajaxSettings, settings );
} else {
// target was provided, we extend into it
jQuery.extend( true, target, jQuery.ajaxSettings, settings );
}
// Flatten fields we don't want deep extended
for( var field in { context: 1, url: 1 } ) {
if ( field in settings ) {
target[ field ] = settings[ field ];
} else if( field in jQuery.ajaxSettings ) {
target[ field ] = jQuery.ajaxSettings[ field ];
}
}
return target;
},
ajaxSettings: {
url: ajaxLocation,
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
type: "GET",
contentType: "application/x-www-form-urlencoded",
processData: true,
async: true,
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
traditional: false,
headers: {},
*/
accepts: {
xml: "application/xml, text/xml",
html: "text/html",
text: "text/plain",
json: "application/json, text/javascript",
"*": "*/*"
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText"
},
// List of data converters
// 1) key format is "source_type destination_type" (a single space in-between)
// 2) the catchall symbol "*" can be used for source_type
converters: {
// Convert anything to text
"* text": window.String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
}
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events
// It's the callbackContext if one was provided in the options
// and if it's a DOM node or a jQuery collection
globalEventContext = callbackContext !== s &&
( callbackContext.nodeType || callbackContext instanceof jQuery ) ?
jQuery( callbackContext ) : jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery._Deferred(),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// ifModified key
ifModifiedKey,
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// Response headers
responseHeadersString,
responseHeaders,
// transport
transport,
// timeout handle
timeoutTimer,
// Cross-domain detection vars
parts,
// The jqXHR state
state = 0,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// Fake xhr
jqXHR = {
readyState: 0,
// Caches the header
setRequestHeader: function( name, value ) {
if ( !state ) {
var lname = name.toLowerCase();
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while( ( match = rheaders.exec( responseHeadersString ) ) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match === undefined ? null : match;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Cancel the request
abort: function( statusText ) {
statusText = statusText || "abort";
if ( transport ) {
transport.abort( statusText );
}
done( 0, statusText );
return this;
}
};
// Callback for when everything is done
// It is defined here because jslint complains if it is declared
// at the end of the function (which would be more logical and readable)
function done( status, statusText, responses, headers ) {
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status ? 4 : 0;
var isSuccess,
success,
error,
response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined,
lastModified,
etag;
// If successful, handle type chaining
if ( status >= 200 && status < 300 || status === 304 ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) {
jQuery.lastModified[ ifModifiedKey ] = lastModified;
}
if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) {
jQuery.etag[ ifModifiedKey ] = etag;
}
}
// If not modified
if ( status === 304 ) {
statusText = "notmodified";
isSuccess = true;
// If we have data
} else {
try {
success = ajaxConvert( s, response );
statusText = "success";
isSuccess = true;
} catch(e) {
// We have a parsererror
statusText = "parsererror";
error = e;
}
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if( !statusText || status ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = statusText;
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.resolveWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger( "ajaxStop" );
}
}
}
// Attach deferreds
deferred.promise( jqXHR );
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
jqXHR.complete = completeDeferred.done;
// Status-dependent callbacks
jqXHR.statusCode = function( map ) {
if ( map ) {
var tmp;
if ( state < 2 ) {
for( tmp in map ) {
statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
}
} else {
tmp = map[ jqXHR.status ];
jqXHR.then( tmp, tmp );
}
}
return this;
};
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// We also use the url parameter if available
s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax );
// Determine if a cross-domain request is in order
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefiler, stop there
if ( state === 2 ) {
return false;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger( "ajaxStart" );
}
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
}
// Get ifModifiedKey before adding the anti-cache parameter
ifModifiedKey = s.url;
// Add anti-cache in url if needed
if ( s.cache === false ) {
var ts = jQuery.now(),
// try replacing _= if it is there
ret = s.url.replace( rts, "$1_=" + ts );
// if nothing was replaced, add timestamp to the end
s.url = ret + ( (ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
ifModifiedKey = ifModifiedKey || s.url;
if ( jQuery.lastModified[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] );
}
if ( jQuery.etag[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] );
}
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already
jqXHR.abort();
return false;
}
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout( function(){
jqXHR.abort( "timeout" );
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch (e) {
// Propagate exception as error if not done
if ( status < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
jQuery.error( e );
}
}
}
return jqXHR;
},
// Serialize an array of form elements or a set of
// key/values into a query string
param: function( a, traditional ) {
var s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : value;
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( var prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
}
});
function buildParams( prefix, obj, traditional, add ) {
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// If array item is non-scalar (array or object), encode its
// numeric index to resolve deserialization ambiguity issues.
// Note that rack (as of 1.0.0) can't currently deserialize
// nested arrays properly, and attempting to do so may cause
// a server error. Possible fixes are to modify rack's
// deserialization algorithm or to provide an option or flag
// to force array serialization to be shallow.
buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && obj != null && typeof obj === "object" ) {
// Serialize object item.
for ( var name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
// This is still on the jQuery object... for now
// Want to move this to jQuery.ajax some day
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {}
});
/* Handles responses to an ajax request:
* - sets all responseXXX fields accordingly
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var contents = s.contents,
dataTypes = s.dataTypes,
responseFields = s.responseFields,
ct,
type,
finalDataType,
firstDataType;
// Fill responseXXX fields
for( type in responseFields ) {
if ( type in responses ) {
jqXHR[ responseFields[type] ] = responses[ type ];
}
}
// Remove auto dataType and get content-type in the process
while( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader( "content-type" );
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
// Chain conversions given the request and the original response
function ajaxConvert( s, response ) {
// Apply the dataFilter if provided
if ( s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
var dataTypes = s.dataTypes,
converters = {},
i,
key,
length = dataTypes.length,
tmp,
// Current and previous dataTypes
current = dataTypes[ 0 ],
prev,
// Conversion expression
conversion,
// Conversion function
conv,
// Conversion functions (transitive conversion)
conv1,
conv2;
// For each dataType in the chain
for( i = 1; i < length; i++ ) {
// Create converters map
// with lowercased keys
if ( i === 1 ) {
for( key in s.converters ) {
if( typeof key === "string" ) {
converters[ key.toLowerCase() ] = s.converters[ key ];
}
}
}
// Get the dataTypes
prev = current;
current = dataTypes[ i ];
// If current is auto dataType, update it to prev
if( current === "*" ) {
current = prev;
// If no auto and dataTypes are actually different
} else if ( prev !== "*" && prev !== current ) {
// Get the converter
conversion = prev + " " + current;
conv = converters[ conversion ] || converters[ "* " + current ];
// If there is no direct converter, search transitively
if ( !conv ) {
conv2 = undefined;
for( conv1 in converters ) {
tmp = conv1.split( " " );
if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) {
conv2 = converters[ tmp[1] + " " + current ];
if ( conv2 ) {
conv1 = converters[ conv1 ];
if ( conv1 === true ) {
conv = conv2;
} else if ( conv2 === true ) {
conv = conv1;
}
break;
}
}
}
}
// If we found no converter, dispatch an error
if ( !( conv || conv2 ) ) {
jQuery.error( "No conversion from " + conversion.replace(" "," to ") );
}
// If found converter is not an equivalence
if ( conv !== true ) {
// Convert with 1 or 2 converters accordingly
response = conv ? conv( response ) : conv2( conv1(response) );
}
}
}
return response;
}
var jsc = jQuery.now(),
jsre = /(\=)\?(&|$)|\?\?/i;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
return jQuery.expando + "_" + ( jsc++ );
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var inspectData = s.contentType === "application/x-www-form-urlencoded" &&
( typeof s.data === "string" );
if ( s.dataTypes[ 0 ] === "jsonp" ||
s.jsonp !== false && ( jsre.test( s.url ) ||
inspectData && jsre.test( s.data ) ) ) {
var responseContainer,
jsonpCallback = s.jsonpCallback =
jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback,
previous = window[ jsonpCallback ],
url = s.url,
data = s.data,
replace = "$1" + jsonpCallback + "$2";
if ( s.jsonp !== false ) {
url = url.replace( jsre, replace );
if ( s.url === url ) {
if ( inspectData ) {
data = data.replace( jsre, replace );
}
if ( s.data === data ) {
// Add callback manually
url += (/\?/.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback;
}
}
}
s.url = url;
s.data = data;
// Install callback
window[ jsonpCallback ] = function( response ) {
responseContainer = [ response ];
};
// Clean-up function
jqXHR.always(function() {
// Set callback back to previous value
window[ jsonpCallback ] = previous;
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( previous ) ) {
window[ jsonpCallback ]( responseContainer[ 0 ] );
}
});
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( jsonpCallback + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Delegate to script
return "script";
}
});
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /javascript|ecmascript/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement( "script" );
script.async = "async";
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( head && script.parentNode ) {
head.removeChild( script );
}
// Dereference the script
script = undefined;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709 and #4378).
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( 0, 1 );
}
}
};
}
});
var // #5280: Internet Explorer will keep connections alive if we don't abort on unload
xhrOnUnloadAbort = window.ActiveXObject ? function() {
// Abort all pending requests
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]( 0, 1 );
}
} : false,
xhrId = 0,
xhrCallbacks;
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject( "Microsoft.XMLHTTP" );
} catch( e ) {}
}
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
/* Microsoft failed to properly
* implement the XMLHttpRequest in IE7 (can't request local files),
* so we use the ActiveXObject when it is available
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so
* we need a fallback.
*/
function() {
return !this.isLocal && createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
// Determine support properties
(function( xhr ) {
jQuery.extend( jQuery.support, {
ajax: !!xhr,
cors: !!xhr && ( "withCredentials" in xhr )
});
})( jQuery.ajaxSettings.xhr() );
// Create transport if the browser can provide an xhr
if ( jQuery.support.ajax ) {
jQuery.ajaxTransport(function( s ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !s.crossDomain || jQuery.support.cors ) {
var callback;
return {
send: function( headers, complete ) {
// Get a new xhr
var xhr = s.xhr(),
handle,
i;
// Open the socket
// Passing null username, generates a
popup on Opera (#2865)
if ( s.username ) {
xhr.open( s.type, s.url, s.async, s.username, s.password );
} else {
xhr.open( s.type, s.url, s.async );
}
// Apply custom fields if provided
if ( s.xhrFields ) {
for ( i in s.xhrFields ) {
xhr[ i ] = s.xhrFields[ i ];
}
}
// Override mime type if needed
if ( s.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( s.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !s.crossDomain && !headers["X-Requested-With"] ) {
headers[ "X-Requested-With" ] = "XMLHttpRequest";
}
// Need an extra try/catch for cross domain requests in Firefox 3
try {
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
} catch( _ ) {}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( s.hasContent && s.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status,
statusText,
responseHeaders,
responses,
xml;
// Firefox throws exceptions when accessing properties
// of an xhr when a network error occured
// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
try {
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Only called once
callback = undefined;
// Do not keep as active anymore
if ( handle ) {
xhr.onreadystatechange = jQuery.noop;
if ( xhrOnUnloadAbort ) {
delete xhrCallbacks[ handle ];
}
}
// If it's an abort
if ( isAbort ) {
// Abort it manually if needed
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
status = xhr.status;
responseHeaders = xhr.getAllResponseHeaders();
responses = {};
xml = xhr.responseXML;
// Construct response list
if ( xml && xml.documentElement /* #4958 */ ) {
responses.xml = xml;
}
responses.text = xhr.responseText;
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && s.isLocal && !s.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
} catch( firefoxAccessException ) {
if ( !isAbort ) {
complete( -1, firefoxAccessException );
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, responseHeaders );
}
};
// if we're in sync mode or it's in cache
// and has been retrieved directly (IE6 & IE7)
// we need to manually fire the callback
if ( !s.async || xhr.readyState === 4 ) {
callback();
} else {
handle = ++xhrId;
if ( xhrOnUnloadAbort ) {
// Create the active xhrs callbacks list if needed
// and attach the unload handler
if ( !xhrCallbacks ) {
xhrCallbacks = {};
jQuery( window ).unload( xhrOnUnloadAbort );
}
// Add to list of active xhrs callbacks
xhrCallbacks[ handle ] = callback;
}
xhr.onreadystatechange = callback;
}
},
abort: function() {
if ( callback ) {
callback(0,1);
}
}
};
}
});
}
var elemdisplay = {},
iframe, iframeDoc,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,
timerId,
fxAttrs = [
// height animations
[ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ],
// width animations
[ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ],
// opacity animations
[ "opacity" ]
],
fxNow,
requestAnimationFrame = window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame;
jQuery.fn.extend({
show: function( speed, easing, callback ) {
var elem, display;
if ( speed || speed === 0 ) {
return this.animate( genFx("show", 3), speed, easing, callback);
} else {
for ( var i = 0, j = this.length; i < j; i++ ) {
elem = this[i];
if ( elem.style ) {
display = elem.style.display;
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !jQuery._data(elem, "olddisplay") && display === "none" ) {
display = elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( display === "" && jQuery.css( elem, "display" ) === "none" ) {
jQuery._data(elem, "olddisplay", defaultDisplay(elem.nodeName));
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( i = 0; i < j; i++ ) {
elem = this[i];
if ( elem.style ) {
display = elem.style.display;
if ( display === "" || display === "none" ) {
elem.style.display = jQuery._data(elem, "olddisplay") || "";
}
}
}
return this;
}
},
hide: function( speed, easing, callback ) {
if ( speed || speed === 0 ) {
return this.animate( genFx("hide", 3), speed, easing, callback);
} else {
for ( var i = 0, j = this.length; i < j; i++ ) {
if ( this[i].style ) {
var display = jQuery.css( this[i], "display" );
if ( display !== "none" && !jQuery._data( this[i], "olddisplay" ) ) {
jQuery._data( this[i], "olddisplay", display );
}
}
}
// Set the display of the elements in a second loop
// to avoid the constant reflow
for ( i = 0; i < j; i++ ) {
if ( this[i].style ) {
this[i].style.display = "none";
}
}
return this;
}
},
// Save the old toggle function
_toggle: jQuery.fn.toggle,
toggle: function( fn, fn2, callback ) {
var bool = typeof fn === "boolean";
if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) {
this._toggle.apply( this, arguments );
} else if ( fn == null || bool ) {
this.each(function() {
var state = bool ? fn : jQuery(this).is(":hidden");
jQuery(this)[ state ? "show" : "hide" ]();
});
} else {
this.animate(genFx("toggle", 3), fn, fn2, callback);
}
return this;
},
fadeTo: function( speed, to, easing, callback ) {
return this.filter(":hidden").css("opacity", 0).show().end()
.animate({opacity: to}, speed, easing, callback);
},
animate: function( prop, speed, easing, callback ) {
var optall = jQuery.speed(speed, easing, callback);
if ( jQuery.isEmptyObject( prop ) ) {
return this.each( optall.complete, [ false ] );
}
// Do not change referenced properties as per-property easing will be lost
prop = jQuery.extend( {}, prop );
return this[ optall.queue === false ? "each" : "queue" ](function() {
// XXX 'this' does not always have a nodeName when running the
// test suite
if ( optall.queue === false ) {
jQuery._mark( this );
}
var opt = jQuery.extend( {}, optall ),
isElement = this.nodeType === 1,
hidden = isElement && jQuery(this).is(":hidden"),
name, val, p,
display, e,
parts, start, end, unit;
// will store per property easing and be used to determine when an animation is complete
opt.animatedProperties = {};
for ( p in prop ) {
// property name normalization
name = jQuery.camelCase( p );
if ( p !== name ) {
prop[ name ] = prop[ p ];
delete prop[ p ];
}
val = prop[ name ];
// easing resolution: per property > opt.specialEasing > opt.easing > 'swing' (default)
if ( jQuery.isArray( val ) ) {
opt.animatedProperties[ name ] = val[ 1 ];
val = prop[ name ] = val[ 0 ];
} else {
opt.animatedProperties[ name ] = opt.specialEasing && opt.specialEasing[ name ] || opt.easing || 'swing';
}
if ( val === "hide" && hidden || val === "show" && !hidden ) {
return opt.complete.call( this );
}
if ( isElement && ( name === "height" || name === "width" ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height
// animated
if ( jQuery.css( this, "display" ) === "inline" &&
jQuery.css( this, "float" ) === "none" ) {
if ( !jQuery.support.inlineBlockNeedsLayout ) {
this.style.display = "inline-block";
} else {
display = defaultDisplay( this.nodeName );
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( display === "inline" ) {
this.style.display = "inline-block";
} else {
this.style.display = "inline";
this.style.zoom = 1;
}
}
}
}
}
if ( opt.overflow != null ) {
this.style.overflow = "hidden";
}
for ( p in prop ) {
e = new jQuery.fx( this, opt, p );
val = prop[ p ];
if ( rfxtypes.test(val) ) {
e[ val === "toggle" ? hidden ? "show" : "hide" : val ]();
} else {
parts = rfxnum.exec( val );
start = e.cur();
if ( parts ) {
end = parseFloat( parts[2] );
unit = parts[3] || ( jQuery.cssNumber[ p ] ? "" : "px" );
// We need to compute starting value
if ( unit !== "px" ) {
jQuery.style( this, p, (end || 1) + unit);
start = ((end || 1) / e.cur()) * start;
jQuery.style( this, p, start + unit);
}
// If a +=/-= token was provided, we're doing a relative animation
if ( parts[1] ) {
end = ( (parts[ 1 ] === "-=" ? -1 : 1) * end ) + start;
}
e.custom( start, end, unit );
} else {
e.custom( start, val, "" );
}
}
}
// For JS strict compliance
return true;
});
},
stop: function( clearQueue, gotoEnd ) {
if ( clearQueue ) {
this.queue([]);
}
this.each(function() {
var timers = jQuery.timers,
i = timers.length;
// clear marker counters if we know they won't be
if ( !gotoEnd ) {
jQuery._unmark( true, this );
}
while ( i-- ) {
if ( timers[i].elem === this ) {
if (gotoEnd) {
// force the next step to be the last
timers[i](true);
}
timers.splice(i, 1);
}
}
});
// start the next in the queue if the last step wasn't forced
if ( !gotoEnd ) {
this.dequeue();
}
return this;
}
});
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout( clearFxNow, 0 );
return ( fxNow = jQuery.now() );
}
function clearFxNow() {
fxNow = undefined;
}
// Generate parameters to create a standard animation
function genFx( type, num ) {
var obj = {};
jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function() {
obj[ this ] = type;
});
return obj;
}
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show", 1),
slideUp: genFx("hide", 1),
slideToggle: genFx("toggle", 1),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.extend({
speed: function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend({}, speed) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction(easing) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[opt.duration] : jQuery.fx.speeds._default;
// Queueing
opt.old = opt.complete;
opt.complete = function( noUnmark ) {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue !== false ) {
jQuery.dequeue( this );
} else if ( noUnmark !== false ) {
jQuery._unmark( this );
}
};
return opt;
},
easing: {
linear: function( p, n, firstNum, diff ) {
return firstNum + diff * p;
},
swing: function( p, n, firstNum, diff ) {
return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum;
}
},
timers: [],
fx: function( elem, options, prop ) {
this.options = options;
this.elem = elem;
this.prop = prop;
options.orig = options.orig || {};
}
});
jQuery.fx.prototype = {
// Simple function for setting a style value
update: function() {
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
(jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this );
},
// Get the current size
cur: function() {
if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) {
return this.elem[ this.prop ];
}
var parsed,
r = jQuery.css( this.elem, this.prop );
// Empty strings, null, undefined and "auto" are converted to 0,
// complex values such as "rotate(1rad)" are returned as is,
// simple values such as "10px" are parsed to Float.
return isNaN( parsed = parseFloat( r ) ) ? !r || r === "auto" ? 0 : r : parsed;
},
// Start an animation from one number to another
custom: function( from, to, unit ) {
var self = this,
fx = jQuery.fx,
raf;
this.startTime = fxNow || createFxNow();
this.start = from;
this.end = to;
this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "px" );
this.now = this.start;
this.pos = this.state = 0;
function t( gotoEnd ) {
return self.step(gotoEnd);
}
t.elem = this.elem;
if ( t() && jQuery.timers.push(t) && !timerId ) {
// Use requestAnimationFrame instead of setInterval if available
if ( requestAnimationFrame ) {
timerId = true;
raf = function() {
// When timerId gets set to null at any point, this stops
if ( timerId ) {
requestAnimationFrame( raf );
fx.tick();
}
};
requestAnimationFrame( raf );
} else {
timerId = setInterval( fx.tick, fx.interval );
}
}
},
// Simple 'show' function
show: function() {
// Remember where we started, so that we can go back to it later
this.options.orig[this.prop] = jQuery.style( this.elem, this.prop );
this.options.show = true;
// Begin the animation
// Make sure that we start at a small width/height to avoid any
// flash of content
this.custom(this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur());
// Start by showing the element
jQuery( this.elem ).show();
},
// Simple 'hide' function
hide: function() {
// Remember where we started, so that we can go back to it later
this.options.orig[this.prop] = jQuery.style( this.elem, this.prop );
this.options.hide = true;
// Begin the animation
this.custom(this.cur(), 0);
},
// Each step of an animation
step: function( gotoEnd ) {
var t = fxNow || createFxNow(),
done = true,
elem = this.elem,
options = this.options,
i, n;
if ( gotoEnd || t >= options.duration + this.startTime ) {
this.now = this.end;
this.pos = this.state = 1;
this.update();
options.animatedProperties[ this.prop ] = true;
for ( i in options.animatedProperties ) {
if ( options.animatedProperties[i] !== true ) {
done = false;
}
}
if ( done ) {
// Reset the overflow
if ( options.overflow != null && !jQuery.support.shrinkWrapBlocks ) {
jQuery.each( [ "", "X", "Y" ], function (index, value) {
elem.style[ "overflow" + value ] = options.overflow[index];
});
}
// Hide the element if the "hide" operation was done
if ( options.hide ) {
jQuery(elem).hide();
}
// Reset the properties, if the item has been hidden or shown
if ( options.hide || options.show ) {
for ( var p in options.animatedProperties ) {
jQuery.style( elem, p, options.orig[p] );
}
}
// Execute the complete function
options.complete.call( elem );
}
return false;
} else {
// classical easing cannot be used with an Infinity duration
if ( options.duration == Infinity ) {
this.now = t;
} else {
n = t - this.startTime;
this.state = n / options.duration;
// Perform the easing function, defaults to swing
this.pos = jQuery.easing[ options.animatedProperties[ this.prop ] ]( this.state, n, 0, 1, options.duration );
this.now = this.start + ((this.end - this.start) * this.pos);
}
// Perform the next step of the animation
this.update();
}
return true;
}
};
jQuery.extend( jQuery.fx, {
tick: function() {
for ( var timers = jQuery.timers, i = 0 ; i < timers.length ; ++i ) {
if ( !timers[i]() ) {
timers.splice(i--, 1);
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
},
interval: 13,
stop: function() {
clearInterval( timerId );
timerId = null;
},
speeds: {
slow: 600,
fast: 200,
// Default speed
_default: 400
},
step: {
opacity: function( fx ) {
jQuery.style( fx.elem, "opacity", fx.now );
},
_default: function( fx ) {
if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) {
fx.elem.style[ fx.prop ] = (fx.prop === "width" || fx.prop === "height" ? Math.max(0, fx.now) : fx.now) + fx.unit;
} else {
fx.elem[ fx.prop ] = fx.now;
}
}
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
}
// Try to restore the default display value of an element
function defaultDisplay( nodeName ) {
if ( !elemdisplay[ nodeName ] ) {
var body = document.body,
elem = jQuery( "<" + nodeName + ">" ).appendTo( body ),
display = elem.css( "display" );
elem.remove();
// If the simple way fails,
// get element's real default display by attaching it to a temp iframe
if ( display === "none" || display === "" ) {
// No iframe to use yet, so create it
if ( !iframe ) {
iframe = document.createElement( "iframe" );
iframe.frameBorder = iframe.width = iframe.height = 0;
}
body.appendChild( iframe );
// Create a cacheable copy of the iframe document on first call.
// IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML
// document to it; WebKit & Firefox won't allow reusing the iframe document.
if ( !iframeDoc || !iframe.createElement ) {
iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document;
iframeDoc.write( ( document.compatMode === "CSS1Compat" ? "<!doctype html>" : "" ) + "<html><body>" );
iframeDoc.close();
}
elem = iframeDoc.createElement( nodeName );
iframeDoc.body.appendChild( elem );
display = jQuery.css( elem, "display" );
body.removeChild( iframe );
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return elemdisplay[ nodeName ];
}
var rtable = /^t(?:able|d|h)$/i,
rroot = /^(?:body|html)$/i;
if ( "getBoundingClientRect" in document.documentElement ) {
jQuery.fn.offset = function( options ) {
var elem = this[0], box;
if ( options ) {
return this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
if ( !elem || !elem.ownerDocument ) {
return null;
}
if ( elem === elem.ownerDocument.body ) {
return jQuery.offset.bodyOffset( elem );
}
try {
box = elem.getBoundingClientRect();
} catch(e) {}
var doc = elem.ownerDocument,
docElem = doc.documentElement;
// Make sure we're not dealing with a disconnected DOM node
if ( !box || !jQuery.contains( docElem, elem ) ) {
return box ? { top: box.top, left: box.left } : { top: 0, left: 0 };
}
var body = doc.body,
win = getWindow(doc),
clientTop = docElem.clientTop || body.clientTop || 0,
clientLeft = docElem.clientLeft || body.clientLeft || 0,
scrollTop = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop,
scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft,
top = box.top + scrollTop - clientTop,
left = box.left + scrollLeft - clientLeft;
return { top: top, left: left };
};
} else {
jQuery.fn.offset = function( options ) {
var elem = this[0];
if ( options ) {
return this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
if ( !elem || !elem.ownerDocument ) {
return null;
}
if ( elem === elem.ownerDocument.body ) {
return jQuery.offset.bodyOffset( elem );
}
jQuery.offset.initialize();
var computedStyle,
offsetParent = elem.offsetParent,
prevOffsetParent = elem,
doc = elem.ownerDocument,
docElem = doc.documentElement,
body = doc.body,
defaultView = doc.defaultView,
prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle,
top = elem.offsetTop,
left = elem.offsetLeft;
while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) {
if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) {
break;
}
computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle;
top -= elem.scrollTop;
left -= elem.scrollLeft;
if ( elem === offsetParent ) {
top += elem.offsetTop;
left += elem.offsetLeft;
if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) {
top += parseFloat( computedStyle.borderTopWidth ) || 0;
left += parseFloat( computedStyle.borderLeftWidth ) || 0;
}
prevOffsetParent = offsetParent;
offsetParent = elem.offsetParent;
}
if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) {
top += parseFloat( computedStyle.borderTopWidth ) || 0;
left += parseFloat( computedStyle.borderLeftWidth ) || 0;
}
prevComputedStyle = computedStyle;
}
if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) {
top += body.offsetTop;
left += body.offsetLeft;
}
if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) {
top += Math.max( docElem.scrollTop, body.scrollTop );
left += Math.max( docElem.scrollLeft, body.scrollLeft );
}
return { top: top, left: left };
};
}
jQuery.offset = {
initialize: function() {
var body = document.body, container = document.createElement("div"), innerDiv, checkDiv, table, td, bodyMarginTop = parseFloat( jQuery.css(body, "marginTop") ) || 0,
html = "<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";
jQuery.extend( container.style, { position: "absolute", top: 0, left: 0, margin: 0, border: 0, width: "1px", height: "1px", visibility: "hidden" } );
container.innerHTML = html;
body.insertBefore( container, body.firstChild );
innerDiv = container.firstChild;
checkDiv = innerDiv.firstChild;
td = innerDiv.nextSibling.firstChild.firstChild;
this.doesNotAddBorder = (checkDiv.offsetTop !== 5);
this.doesAddBorderForTableAndCells = (td.offsetTop === 5);
checkDiv.style.position = "fixed";
checkDiv.style.top = "20px";
// safari subtracts parent border width here which is 5px
this.supportsFixedPosition = (checkDiv.offsetTop === 20 || checkDiv.offsetTop === 15);
checkDiv.style.position = checkDiv.style.top = "";
innerDiv.style.overflow = "hidden";
innerDiv.style.position = "relative";
this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5);
this.doesNotIncludeMarginInBodyOffset = (body.offsetTop !== bodyMarginTop);
body.removeChild( container );
jQuery.offset.initialize = jQuery.noop;
},
bodyOffset: function( body ) {
var top = body.offsetTop,
left = body.offsetLeft;
jQuery.offset.initialize();
if ( jQuery.offset.doesNotIncludeMarginInBodyOffset ) {
top += parseFloat( jQuery.css(body, "marginTop") ) || 0;
left += parseFloat( jQuery.css(body, "marginLeft") ) || 0;
}
return { top: top, left: left };
},
setOffset: function( elem, options, i ) {
var position = jQuery.css( elem, "position" );
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
var curElem = jQuery( elem ),
curOffset = curElem.offset(),
curCSSTop = jQuery.css( elem, "top" ),
curCSSLeft = jQuery.css( elem, "left" ),
calculatePosition = (position === "absolute" || position === "fixed") && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
props = {}, curPosition = {}, curTop, curLeft;
// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if (options.top != null) {
props.top = (options.top - curOffset.top) + curTop;
}
if (options.left != null) {
props.left = (options.left - curOffset.left) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
position: function() {
if ( !this[0] ) {
return null;
}
var elem = this[0],
// Get *real* offsetParent
offsetParent = this.offsetParent(),
// Get correct offsets
offset = this.offset(),
parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset();
// Subtract element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0;
offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0;
// Add offsetParent borders
parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0;
parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0;
// Subtract the two offsets
return {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || document.body;
while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( ["Left", "Top"], function( i, name ) {
var method = "scroll" + name;
jQuery.fn[ method ] = function( val ) {
var elem, win;
if ( val === undefined ) {
elem = this[ 0 ];
if ( !elem ) {
return null;
}
win = getWindow( elem );
// Return the scroll offset
return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] :
jQuery.support.boxModel && win.document.documentElement[ method ] ||
win.document.body[ method ] :
elem[ method ];
}
// Set the scroll offset
return this.each(function() {
win = getWindow( this );
if ( win ) {
win.scrollTo(
!i ? val : jQuery( win ).scrollLeft(),
i ? val : jQuery( win ).scrollTop()
);
} else {
this[ method ] = val;
}
});
};
});
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
// Create width, height, innerHeight, innerWidth, outerHeight and outerWidth methods
jQuery.each([ "Height", "Width" ], function( i, name ) {
var type = name.toLowerCase();
// innerHeight and innerWidth
jQuery.fn[ "inner" + name ] = function() {
var elem = this[0];
return elem && elem.style ?
parseFloat( jQuery.css( elem, type, "padding" ) ) :
null;
};
// outerHeight and outerWidth
jQuery.fn[ "outer" + name ] = function( margin ) {
var elem = this[0];
return elem && elem.style ?
parseFloat( jQuery.css( elem, type, margin ? "margin" : "border" ) ) :
null;
};
jQuery.fn[ type ] = function( size ) {
// Get window width or height
var elem = this[0];
if ( !elem ) {
return size == null ? null : this;
}
if ( jQuery.isFunction( size ) ) {
return this.each(function( i ) {
var self = jQuery( this );
self[ type ]( size.call( this, i, self[ type ]() ) );
});
}
if ( jQuery.isWindow( elem ) ) {
// Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
// 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat
var docElemProp = elem.document.documentElement[ "client" + name ];
return elem.document.compatMode === "CSS1Compat" && docElemProp ||
elem.document.body[ "client" + name ] || docElemProp;
// Get document width or height
} else if ( elem.nodeType === 9 ) {
// Either scroll[Width/Height] or offset[Width/Height], whichever is greater
return Math.max(
elem.documentElement["client" + name],
elem.body["scroll" + name], elem.documentElement["scroll" + name],
elem.body["offset" + name], elem.documentElement["offset" + name]
);
// Get or set width or height on the element
} else if ( size === undefined ) {
var orig = jQuery.css( elem, type ),
ret = parseFloat( orig );
return jQuery.isNaN( ret ) ? orig : ret;
// Set the width or height on the element (default to pixels if value is unitless)
} else {
return this.css( type, typeof size === "string" ? size : size + "px" );
}
};
});
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
})(window);
|
module.exports = {
UA_CONFIGURATION: {
uri: 'sip:f%61keUA@jssip.net',
password: '1234ññññ',
ws_servers: 'ws://localhost:12345',
display_name: 'Fake UA ð→€ł !!!',
authorization_user: 'fakeUA',
instance_id: 'uuid:8f1fa16a-1165-4a96-8341-785b1ef24f12',
registrar_server: 'registrar.jssip.NET:6060;TRansport=TCP',
register_expires: 600,
register: false,
connection_recovery_min_interval: 2,
connection_recovery_max_interval: 30,
use_preloaded_route: true,
no_answer_timeout: 60000,
session_timers: true,
hack_via_tcp: false,
hack_via_ws: true,
hack_ip_in_contact: false
},
UA_CONFIGURATION_AFTER_START: {
uri: 'sip:fakeUA@jssip.net',
password: '1234ññññ',
ws_servers: [{'ws_uri':'ws://localhost:12345','sip_uri':'<sip:localhost:12345;transport=ws;lr>','weight':0,'status':0,'scheme':'WS'}],
display_name: 'Fake UA ð→€ł !!!',
authorization_user: 'fakeUA',
instance_id: '8f1fa16a-1165-4a96-8341-785b1ef24f12', // Without 'uuid:'.
registrar_server: 'sip:registrar.jssip.net:6060;transport=tcp',
register_expires: 600,
register: false,
connection_recovery_min_interval: 2,
connection_recovery_max_interval: 30,
use_preloaded_route: true,
no_answer_timeout: 60000 * 1000, // Internally converted to miliseconds.
session_timers: true,
hack_via_tcp: false,
hack_via_ws: true,
hack_ip_in_contact: false
}
};
|
!function(a){var n="mmenu",t="navbars",e="next";a[n].addons[t][e]=function(e,s){var r,i,h,d=a[n]._c,o=a('<a class="'+d.btn+" "+d.btn+"_next "+d.navbar+'__btn" href="#" />').appendTo(e);this.bind("openPanel:start",function(a){r=a.find("."+this.conf.classNames[t].panelNext),i=r.attr("href"),h=r.html(),i?o.attr("href",i):o.removeAttr("href"),o[i||h?"removeClass":"addClass"](d.hidden),o.html(h)}),this.bind("openPanel:start:sr-aria",function(a){this.__sr_aria(o,"hidden",o.hasClass(d.hidden)),this.__sr_aria(o,"owns",(o.attr("href")||"").slice(1))})},a[n].configuration.classNames[t].panelNext="Next"}(jQuery); |
var core = require("../level1/core").dom.level1.core;
var defineGetter = require('../utils').defineGetter;
var defineSetter = require('../utils').defineSetter;
// modify cloned instance for more info check: https://github.com/tmpvar/jsdom/issues/325
core = Object.create(core);
var INVALID_STATE_ERR = core.INVALID_STATE_ERR = 11,
SYNTAX_ERR = core.SYNTAX_ERR = 12,
INVALID_MODIFICATION_ERR = core.INVALID_MODIFICATION_ERR = 13,
NAMESPACE_ERR = core.NAMESPACE_ERR = 14,
INVALID_ACCESS_ERR = core.INVALID_ACCESS_ERR = 15,
ns = {
validate : function(ns, URI) {
if (!ns) {
throw new core.DOMException(core.INVALID_CHARACTER_ERR, "namespace is undefined");
}
if(ns.match(/[^0-9a-z\.:\-_]/i) !== null) {
throw new core.DOMException(core.INVALID_CHARACTER_ERR, ns);
}
var msg = false, parts = ns.split(':');
if (ns === 'xmlns' &&
URI !== "http://www.w3.org/2000/xmlns/")
{
msg = "localName is 'xmlns' but the namespaceURI is invalid";
} else if (ns === "xml" &&
URI !== "http://www.w3.org/XML/1998/namespace")
{
msg = "localName is 'xml' but the namespaceURI is invalid";
} else if (ns[ns.length-1] === ':') {
msg = "Namespace seperator found with no localName";
} else if (ns[0] === ':') {
msg = "Namespace seperator found, without a prefix";
} else if (parts.length > 2) {
msg = "Too many namespace seperators";
}
if (msg) {
throw new core.DOMException(NAMESPACE_ERR, msg + " (" + ns + "@" + URI + ")");
}
}
};
core.exceptionMessages['NAMESPACE_ERR'] = "Invalid namespace";
core.DOMImplementation.prototype.createDocumentType = function(/* String */ qualifiedName,
/* String */ publicId,
/* String */ systemId)
{
ns.validate(qualifiedName);
var doctype = new core.DocumentType(null, qualifiedName);
doctype._publicId = String(publicId);
doctype._systemId = String(systemId);
return doctype;
};
/**
Creates an XML Document object of the specified type with its document element.
HTML-only DOM implementations do not need to implement this method.
*/
core.DOMImplementation.prototype.createDocument = function(/* String */ namespaceURI,
/* String */ qualifiedName,
/* DocumentType */ doctype)
{
if (qualifiedName || namespaceURI) {
ns.validate(qualifiedName, namespaceURI);
}
if (doctype && doctype._ownerDocument !== null) {
throw new core.DOMException(core.WRONG_DOCUMENT_ERR);
}
if (qualifiedName && qualifiedName.indexOf(':') > -1 && !namespaceURI) {
throw new core.DOMException(NAMESPACE_ERR);
}
var document = new core.Document();
if (doctype) {
document.doctype = doctype;
doctype._ownerDocument = document;
document.appendChild(doctype);
} else {
document.doctype = null;
}
if (doctype && !doctype.entities) {
doctype.entities = new core.EntityNodeMap();
}
document._ownerDocument = document;
if (qualifiedName) {
var docElement = document.createElementNS(namespaceURI, qualifiedName);
document.appendChild(docElement);
}
return document;
};
defineGetter(core.Node.prototype, "ownerDocument", function() {
return this._ownerDocument || null;
});
core.Node.prototype.isSupported = function(/* string */ feature,
/* string */ version)
{
return this._ownerDocument.implementation.hasFeature(feature, version);
};
core.Node.prototype._namespaceURI = null;
defineGetter(core.Node.prototype, "namespaceURI", function() {
return this._namespaceURI || null;
});
defineSetter(core.Node.prototype, "namespaceURI", function(value) {
this._namespaceURI = value;
});
defineGetter(core.Node.prototype, "prefix", function() {
return this._prefix || null;
});
defineSetter(core.Node.prototype, "prefix", function(value) {
if (this.readonly) {
throw new core.DOMException(core.NO_MODIFICATION_ALLOWED_ERR);
}
ns.validate(value, this._namespaceURI);
if ((this._created && !this._namespaceURI) ||
this._prefix === "xmlns" ||
(!this._prefix && this._created))
{
throw new core.DOMException(core.NAMESPACE_ERR);
}
if (this._localName) {
this._nodeName = value + ':' + this._localName;
}
this._prefix = value;
});
defineGetter(core.Node.prototype, "localName", function() {
return this._localName || null;
});
/* return boolean */
core.Node.prototype.hasAttributes = function() {
return (this.nodeType === this.ELEMENT_NODE &&
this._attributes &&
this._attributes.length > 0);
};
core.NamedNodeMap.prototype.getNamedItemNS = function(/* string */ namespaceURI,
/* string */ localName)
{
if (this._nsStore[namespaceURI] && this._nsStore[namespaceURI][localName]) {
return this._nsStore[namespaceURI][localName];
}
return null;
};
core.NamedNodeMap.prototype.setNamedItemNS = function(/* Node */ arg)
{
if (this._readonly) {
throw new core.DOMException(core.NO_MODIFICATION_ALLOWED_ERR);
}
var owner = this._ownerDocument;
if (this._parentNode &&
this._parentNode._parentNode &&
this._parentNode._parentNode.nodeType === owner.ENTITY_NODE)
{
throw new core.DOMException(core.NO_MODIFICATION_ALLOWED_ERR);
}
if (this._ownerDocument !== arg.ownerDocument) {
throw new core.DOMException(core.WRONG_DOCUMENT_ERR);
}
if (arg._ownerElement) {
throw new core.DOMException(core.INUSE_ATTRIBUTE_ERR);
}
// readonly
if (this._readonly === true) {
throw new core.DOMException(core.NO_MODIFICATION_ALLOWED_ERR);
}
if (!this._nsStore[arg.namespaceURI]) {
this._nsStore[arg.namespaceURI] = {};
}
var existing = null;
if (this._nsStore[arg.namespaceURI][arg.localName]) {
var existing = this._nsStore[arg.namespaceURI][arg.localName];
}
this._nsStore[arg.namespaceURI][arg.localName] = arg;
arg._specified = true;
arg._ownerDocument = this._ownerDocument;
return this.setNamedItem(arg);
};
core.NamedNodeMap.prototype.removeNamedItemNS = function(/*string */ namespaceURI,
/* string */ localName)
{
if (this.readonly) {
throw new core.DOMException(core.NO_MODIFICATION_ALLOWED_ERR);
}
var parent = this._parentNode,
found = null,
defaults,
clone,
defaultEl,
defaultAttr;
if (this._parentNode &&
this._parentNode._parentNode &&
this._parentNode._parentNode.nodeType === this._ownerDocument.ENTITY_NODE)
{
throw new core.DOMException(core.NO_MODIFICATION_ALLOWED_ERR);
}
if (this._nsStore[namespaceURI] &&
this._nsStore[namespaceURI][localName])
{
found = this._nsStore[namespaceURI][localName];
this.removeNamedItem(found.qualifiedName);
delete this._nsStore[namespaceURI][localName];
}
if (!found) {
throw new core.DOMException(core.NOT_FOUND_ERR);
}
if (parent.ownerDocument.doctype && parent.ownerDocument.doctype._attributes) {
defaults = parent.ownerDocument.doctype._attributes;
defaultEl = defaults.getNamedItemNS(parent._namespaceURI, parent._localName);
}
if (defaultEl) {
defaultAttr = defaultEl._attributes.getNamedItemNS(namespaceURI, localName);
if (defaultAttr) {
clone = defaultAttr.cloneNode(true);
clone._created = false;
clone._namespaceURI = found._namespaceURI;
clone._nodeName = found.name;
clone._localName = found._localName;
clone._prefix = found._prefix
this.setNamedItemNS(clone);
clone._created = true;
clone._specified = false;
}
}
return found;
};
defineGetter(core.Attr.prototype, "ownerElement", function() {
return this._ownerElement || null;
});
core.Node.prototype._prefix = false;
defineSetter(core.Node.prototype, "qualifiedName", function(qualifiedName) {
ns.validate(qualifiedName, this._namespaceURI);
qualifiedName = qualifiedName || "";
this._localName = qualifiedName.split(":")[1] || null;
this.prefix = qualifiedName.split(":")[0] || null;
this._nodeName = qualifiedName;
});
defineGetter(core.Node.prototype, "qualifiedName", function() {
return this._nodeName;
});
core.NamedNodeMap.prototype._map = function(fn) {
var ret = [], l = this.length, i = 0, node;
for(i; i<l; i++) {
node = this.item(i);
if (fn && fn(node)) {
ret.push(node);
}
}
return ret;
};
core.Element.prototype.getAttribute = function(/* string */ name)
{
var attr = this.getAttributeNode(name);
return attr && attr.value;
};
core.Element.prototype.getAttributeNode = function(/* string */ name)
{
return this._attributes.$getNoNS(name);
};
core.Element.prototype.removeAttribute = function(/* string */ name)
{
return this._attributes.$removeNoNS(name);
};
core.Element.prototype.getAttributeNS = function(/* string */ namespaceURI,
/* string */ localName)
{
if (namespaceURI === "") {
namespaceURI = null;
}
var attr = this._attributes.$getNode(namespaceURI, localName);
return attr && attr.value;
};
core.Element.prototype.setAttribute = function(/* string */ name,
/* string */ value)
{
this._attributes.$setNoNS(name, value);
};
core.Element.prototype.setAttributeNS = function(/* string */ namespaceURI,
/* string */ qualifiedName,
/* string */ value)
{
if (namespaceURI === "") {
namespaceURI = null;
}
var s = qualifiedName.split(':'),
local = s.pop(),
prefix = s.pop() || null,
attr;
ns.validate(qualifiedName, namespaceURI);
if (prefix !== null && !namespaceURI) {
throw new core.DOMException(core.NAMESPACE_ERR);
}
if (prefix === "xml" &&
namespaceURI !== "http://www.w3.org/XML/1998/namespace") {
throw new core.DOMException(core.NAMESPACE_ERR);
}
if (prefix === "xmlns" && namespaceURI !== "http://www.w3.org/2000/xmlns/") {
throw new core.DOMException(core.NAMESPACE_ERR);
}
this._attributes.$set(local, value, qualifiedName, prefix, namespaceURI);
};
core.Element.prototype.removeAttributeNS = function(/* string */ namespaceURI,
/* string */ localName)
{
if (namespaceURI === "") {
namespaceURI = null;
}
this._attributes.$remove(namespaceURI, localName);
};
core.Element.prototype.getAttributeNodeNS = function(/* string */ namespaceURI,
/* string */ localName)
{
if (namespaceURI === "") {
namespaceURI = null;
}
return this._attributes.$getNode(namespaceURI, localName);
};
core.Element.prototype._created = false;
core.Element.prototype.setAttributeNodeNS = function(/* Attr */ newAttr)
{
if (newAttr.ownerElement) {
throw new core.DOMException(core.INUSE_ATTRIBUTE_ERR);
}
return this._attributes.$setNode(newAttr);
};
core.Element.prototype.getElementsByTagNameNS = core.memoizeQuery(function(/* String */ namespaceURI,
/* String */ localName)
{
var nsPrefixCache = {};
function filterByTagName(child) {
if (child.nodeType && child.nodeType === this.ENTITY_REFERENCE_NODE) {
child = child._entity;
}
var localMatch = child.localName === localName,
nsMatch = child.namespaceURI === namespaceURI;
if ((localMatch || localName === "*") &&
(nsMatch || namespaceURI === "*"))
{
if (child.nodeType === child.ELEMENT_NODE) {
return true;
}
}
return false;
}
return new core.NodeList(this.ownerDocument || this,
core.mapper(this, filterByTagName));
});
core.Element.prototype.hasAttribute = function(/* string */name)
{
if (!this._attributes) {
return false;
}
// Note: you might think you only need the latter condition. However, it makes a test case fail.
// HOWEVER, that test case is for a XML DTD feature called "default attributes" that never was implemented by
// browsers, so when we remove default attributes, we should be able to fix this code too.
return !!this._attributes.$getNoNS(name) || !!this._attributes.$getNoNS(name.toLowerCase());
};
core.Element.prototype.hasAttributeNS = function(/* string */namespaceURI,
/* string */localName)
{
if (namespaceURI === "") {
namespaceURI = null;
}
return (this._attributes.getNamedItemNS(namespaceURI, localName) ||
this.hasAttribute(localName));
};
defineGetter(core.DocumentType.prototype, "publicId", function() {
return this._publicId || "";
});
defineGetter(core.DocumentType.prototype, "systemId", function() {
return this._systemId || "";
});
defineGetter(core.DocumentType.prototype, "internalSubset", function() {
return this._internalSubset || null;
});
core.Document.prototype.importNode = function(/* Node */ importedNode,
/* bool */ deep)
{
if (importedNode && importedNode.nodeType) {
if (importedNode.nodeType === this.DOCUMENT_NODE ||
importedNode.nodeType === this.DOCUMENT_TYPE_NODE) {
throw new core.DOMException(core.NOT_SUPPORTED_ERR);
}
}
var self = this,
newNode = importedNode.cloneNode(deep, function(a, b) {
b._namespaceURI = a._namespaceURI;
b._nodeName = a._nodeName;
b._localName = a._localName;
}),
defaults = false,
defaultEl;
if (this.doctype && this.doctype._attributes) {
defaults = this.doctype._attributes;
}
function lastChance(el) {
var attr, defaultEl, i, len;
el._ownerDocument = self;
if (el.id) {
if (!self._ids) {self._ids = {};}
if (!self._ids[el.id]) {self._ids[el.id] = [];}
self._ids[el.id].push(el);
}
if (el._attributes) {
var drop = [];
el._attributes._ownerDocument = self;
for (i=0,len=el._attributes.length; i < len; i++) {
attr = el._attributes[i];
// Attributes nodes that were expressing default values in the
// original document must not be copied over. Record them.
if (!attr._specified) {
drop.push(attr);
continue;
}
attr._ownerDocument = self;
}
// Remove obsolete default nodes.
for(i = 0; i < drop.length; ++i) {
el._attributes.$removeNode(drop[i]);
}
}
if (defaults) {
defaultEl = defaults.getNamedItemNS(el._namespaceURI,
el._localName);
// TODO: This could use some love
if (defaultEl) {
for(i = 0; i < defaultEl._attributes.length; ++i) {
var defaultAttr = defaultEl._attributes[i];
if (!el.hasAttributeNS(defaultAttr.namespaceURL,
defaultAttr.localName))
{
var clone = defaultAttr.cloneNode(true);
clone._namespaceURI = defaultAttr._namespaceURI;
clone._prefix = defaultAttr._prefix;
clone._localName = defaultAttr._localName;
el.setAttributeNodeNS(clone);
clone._specified = false;
}
}
}
}
}
if (deep) {
core.visitTree(newNode, lastChance);
}
else {
lastChance(newNode);
}
if (newNode.nodeType == newNode.ATTRIBUTE_NODE) {
newNode._specified = true;
}
return newNode;
};
core.Document.prototype.createElementNS = function(/* string */ namespaceURI,
/* string */ qualifiedName)
{
var parts = qualifiedName.split(':'),
element, prefix;
if (parts.length > 1 && !namespaceURI) {
throw new core.DOMException(core.NAMESPACE_ERR);
}
ns.validate(qualifiedName, namespaceURI);
element = this.createElement(qualifiedName),
element._created = false;
element._namespaceURI = namespaceURI;
element._nodeName = qualifiedName;
element._localName = parts.pop();
if (parts.length > 0) {
prefix = parts.pop();
element.prefix = prefix;
}
element._created = true;
return element;
};
core.Document.prototype.createAttributeNS = function(/* string */ namespaceURI,
/* string */ qualifiedName)
{
var attribute, parts = qualifiedName.split(':');
if (parts.length > 1 && !namespaceURI) {
throw new core.DOMException(core.NAMESPACE_ERR,
"Prefix specified without namespaceURI (" + qualifiedName + ")");
}
ns.validate(qualifiedName, namespaceURI);
attribute = this.createAttribute(qualifiedName);
attribute.namespaceURI = namespaceURI;
attribute.qualifiedName = qualifiedName;
attribute._localName = parts.pop();
attribute._prefix = (parts.length > 0) ? parts.pop() : null;
return attribute;
};
core.Document.prototype.getElementsByTagNameNS = function(/* String */ namespaceURI,
/* String */ localName)
{
return core.Element.prototype.getElementsByTagNameNS.call(this,
namespaceURI,
localName);
};
defineSetter(core.Element.prototype, "id", function(id) {
this.setAttribute("id", id);
});
defineGetter(core.Element.prototype, "id", function() {
return this.getAttribute("id");
});
core.Document.prototype.getElementById = function(id) {
// return the first element
return (this._ids && this._ids[id] && this._ids[id].length > 0 ? this._ids[id][0] : null);
};
exports.dom =
{
level2 : {
core : core
}
};
|
//////////////////////////////////////////////////////////////////////////////
// Code Separator
//////////////////////////////////////////////////////////////////////////////
AFRAME.registerPrimitive('a-minecraft', AFRAME.utils.extendDeep({}, AFRAME.primitives.getMeshMixin(), {
defaultComponents: {
minecraft: {},
'minecraft-head-anim': 'still',
'minecraft-body-anim': 'stand',
'minecraft-nickname': 'John',
'minecraft-bubble': '',
'minecraft-controls': {},
},
mappings: {
'head-anim': 'minecraft-head-anim',
'body-anim': 'minecraft-body-anim',
'nickname': 'minecraft-nickname',
'bubble': 'minecraft-bubble',
'controls': 'minecraft-controls',
}
}));
//////////////////////////////////////////////////////////////////////////////
// Code Separator
//////////////////////////////////////////////////////////////////////////////
AFRAME.registerComponent('minecraft', {
schema: {
skinUrl: {
type: 'string',
default : ''
},
wellKnownSkin: {
type: 'string',
default : ''
},
heightMeter : {
default : 1.6
}
},
init: function () {
var character = new THREEx.MinecraftChar()
this.character = character
this.el.object3D.add( character.root )
// this.el.setObject3D('superRoot', character.root);
},
update: function () {
if( Object.keys(this.data).length === 0 ) return
var character = this.character
character.root.scale.set(1,1,1).multiplyScalar(this.data.heightMeter)
if( this.data.skinUrl ){
character.loadSkin(this.data.skinUrl)
}else if( this.data.wellKnownSkin ){
character.loadWellKnownSkin(this.data.wellKnownSkin)
}
},
});
//////////////////////////////////////////////////////////////////////////////
// Code Separator
//////////////////////////////////////////////////////////////////////////////
AFRAME.registerComponent('minecraft-head-anim', {
schema: {
type: 'string',
default : 'yes',
},
init: function () {
var character = this.el.components.minecraft.character
this.headAnims = new THREEx.MinecraftCharHeadAnimations(character);
},
tick : function(now, delta){
this.headAnims.update(delta/1000,now/1000)
},
update: function () {
if( Object.keys(this.data).length === 0 ) return
console.assert( this.headAnims.names().indexOf(this.data) !== -1 )
this.headAnims.start(this.data);
},
});
//////////////////////////////////////////////////////////////////////////////
// Code Separator
//////////////////////////////////////////////////////////////////////////////
AFRAME.registerComponent('minecraft-body-anim', {
schema: {
type: 'string',
default : 'wave',
},
init: function () {
var character = this.el.components.minecraft.character
this.bodyAnims = new THREEx.MinecraftCharBodyAnimations(character);
},
tick : function(now, delta){
// force the animation according to controls
var minecraftControls = this.el.components['minecraft-controls']
if( minecraftControls ){
var input = minecraftControls.controls.input
if( input.up || input.down ){
this.bodyAnims.start('run');
}else if( input.strafeLeft || input.strafeRight ){
this.bodyAnims.start('strafe');
}else {
this.bodyAnims.start('stand');
}
}
// update the animation
this.bodyAnims.update(delta/1000,now/1000)
},
update: function () {
if( Object.keys(this.data).length === 0 ) return
console.assert( this.bodyAnims.names().indexOf(this.data) !== -1 )
this.bodyAnims.start(this.data);
},
});
//////////////////////////////////////////////////////////////////////////////
// Code Separator
//////////////////////////////////////////////////////////////////////////////
AFRAME.registerComponent('minecraft-nickname', {
schema: {
type: 'string',
default : 'Joe',
},
init: function () {
var character = this.el.components.minecraft.character
this.nickName = new THREEx.MinecraftNickname(character);
},
update: function () {
if( Object.keys(this.data).length === 0 ) return
this.nickName.set(this.data);
},
});
//////////////////////////////////////////////////////////////////////////////
// Code Separator
//////////////////////////////////////////////////////////////////////////////
AFRAME.registerComponent('minecraft-bubble', {
schema: {
type: 'string',
default : 'Hello world.',
},
init: function () {
var character = this.el.components.minecraft.character
this.bubble = new THREEx.MinecraftBubble(character);
},
update: function () {
if( Object.keys(this.data).length === 0 ) return
this.bubble.set(this.data);
},
tick : function(now, delta){
this.bubble.update(delta/1000,now/1000)
},
});
//////////////////////////////////////////////////////////////////////////////
// Code Separator
//////////////////////////////////////////////////////////////////////////////
AFRAME.registerComponent('minecraft-controls', {
schema: {
},
init: function () {
var character = this.el.components.minecraft.character
this.controls = new THREEx.MinecraftControls(character)
THREEx.MinecraftControls.setKeyboardInput(this.controls, ['wasd', 'arrows', 'ijkl'])
},
tick : function(now, delta){
this.controls.update(delta/1000,now/1000)
},
});
|
(function () {
function scopeClone(scope) {
var newScope = {};
_.each(scope, function (value, name) {
if (value instanceof Function) {
newScope[name] = value;
} else {
newScope[name] = math.clone(value);
}
});
return newScope;
}
function Calque(inputEl, outputEl) {
this.inputEl = inputEl;
this.outputEl = outputEl;
this.raw = '';
this.lines = [];
this.expressions = [];
this.activeLine = 0;
var handler = function () {
this.updateActiveLine();
this.input();
if (this.inputEl.scrollTop !== this.outputEl.scrollTop) {
this.outputEl.scrollTop = this.inputEl.scrollTop;
}
}.bind(this);
handler();
inputEl.onkeydown = handler;
inputEl.onkeyup = handler;
setInterval(handler, 50);
outputEl.scrollTop = inputEl.scrollTop;
inputEl.onscroll = function () {
outputEl.scrollTop = inputEl.scrollTop;
};
}
Calque.prototype.updateActiveLine = function () {
var value = this.inputEl.value;
var selectionStart = this.inputEl.selectionStart;
var match = value.substr(0, selectionStart).match(/\n/g);
if (!match) {
var activeLine = 1;
} else {
var activeLine = value.substr(0, selectionStart).match(/\n/g).length + 1;
}
if (this.activeLine !== activeLine) {
this.activeLine = activeLine;
this.repaint();
}
}
Calque.prototype.input = function () {
var raw = this.inputEl.value;
if (raw !== this.raw) {
this.raw = raw;
this.lines = this.raw.split("\n");
this.recalc();
}
}
Calque.prototype.recalc = function () {
this.expressions.forEach(function (expression) {
expression.line = null;
});
var scope = {
last: null
};
this.lines.forEach(function (code, index) {
var oldSimilarExpressions = this.expressions.filter(function (expression) {
if (expression.line !== null) return;
if (expression.code !== code) return;
return true;
});
if (oldSimilarExpressions.length) {
var expression = oldSimilarExpressions[0];
expression.eval(scope);
} else {
var expression = new Expression(code, scope);
this.expressions.push(expression);
}
scope = scopeClone(expression.scopeOutput);
if (expression.result !== undefined) {
scope.last = expression.result;
}
expression.line = index;
}.bind(this));
_.remove(this.expressions, { line: null });
this.repaint();
};
Calque.prototype.repaint = function () {
var html = '';
this.lines.forEach(function (line, index) {
var expression = this.expressions.filter(function (expression) {
return expression.line === index;
})[0];
if (expression.error) {
if (this.activeLine === index + 1) {
var type = 'empty';
} else {
var type = 'error';
}
} else if (expression.result === undefined) {
var type = 'empty';
} else {
var type = 'result';
}
var prefix = '';
for (var s = 0; s <= expression.code.length; s++) prefix += ' ';
if (type === 'empty') prefix += ' ';
if (type === 'result') {
if (expression.result instanceof Function) {
prefix += 'fn';
} else {
prefix += '= ';
}
}
if (type === 'error') prefix += '// ';
var data = '';
if (type === 'result') {
if (expression.result === null) {
data = 'null';
} else if (expression.result instanceof Function) {
var source = expression.result.toString();
data = '';
} else {
data = expression.result.toString();
}
};
if (type === 'error') data = expression.error;
var lineHtml = '<div class="' + type + '">';
lineHtml += '<span class="prefix" data-prefix="' + prefix + '"></span>';
lineHtml += '<span class="data">' + data + '</span>';
lineHtml += '</div>';
html += lineHtml;
}.bind(this));
this.outputEl.innerHTML = html;
};
function Expression(code, scope) {
this.code = code;
this.scopeInput = scopeClone(scope);
this.scopeOutput = scopeClone(this.scopeInput);
try {
this.parse = math.parse(code);
this.dependencies = [];
this.parse.traverse(function (node) {
if (node.isSymbolNode || node.isFunctionNode) {
this.dependencies.push(node.name);
}
}.bind(this));
this.eval(scope);
} catch (e) {
this.result = null;
this.error = e;
}
this.line = null;
};
Expression.prototype.eval = function (scope) {
this.scopeInput = scopeClone(scope);
this.scopeOutput = scopeClone(this.scopeInput);
try {
this.result = this.parse.eval(this.scopeOutput);
this.error = null;
} catch (e) {
this.result = null;
this.error = e;
}
};
window.Calque = Calque;
})(); |
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.withInsets = withInsets;
var _jsxRuntime = require("../lib/jsxRuntime");
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _useInsets = require("../hooks/useInsets");
function withInsets(Component) {
function WithInsets(props) {
var insets = (0, _useInsets.useInsets)(); // @ts-ignore
return (0, _jsxRuntime.createScopedElement)(Component, (0, _extends2.default)({}, props, {
insets: insets
}));
}
return WithInsets;
}
//# sourceMappingURL=withInsets.js.map |
var gleak = require('../deps/gleak')();
gleak.ignore('AssertionError');
module.exports = gleak;
|
/* ========================================================================
* Bootstrap: alert.js v3.0.0
* http://twbs.github.com/bootstrap/javascript.html#alerts
* ========================================================================
* Copyright 2013 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";
// ALERT CLASS DEFINITION
// ======================
var dismiss = '[data-dismiss="alert"]'
var Alert = function (el) {
$(el).on('click', dismiss, this.close)
}
Alert.prototype.close = function (e) {
var $this = $(this)
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = $(selector)
if (e) e.preventDefault()
if (!$parent.length) {
$parent = $this.hasClass('alert') ? $this : $this.parent()
}
$parent.trigger(e = $.Event('close.bs.alert'))
if (e.isDefaultPrevented()) return
$parent.removeClass('in')
function removeElement() {
$parent.trigger('closed.bs.alert').remove()
}
$.support.transition && $parent.hasClass('fade') ?
$parent
.one($.support.transition.end, removeElement)
.emulateTransitionEnd(150) :
removeElement()
}
// ALERT PLUGIN DEFINITION
// =======================
var old = $.fn.alert
$.fn.alert = function (option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.alert')
if (!data) $this.data('bs.alert', (data = new Alert(this)))
if (typeof option == 'string') data[option].call($this)
})
}
$.fn.alert.Constructor = Alert
// ALERT NO CONFLICT
// =================
$.fn.alert.noConflict = function () {
$.fn.alert = old
return this
}
// ALERT DATA-API
// ==============
$(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close)
}(window.jQuery);
(function() {
Bootstrap.BsAlertComponent = Ember.Component.extend(Bootstrap.TypeSupport, {
classNames: ['alert'],
classNameBindings: ['fade', 'fade:in'],
layoutName: 'components/bs-alert',
classTypePrefix: 'alert',
attributeBindings: ['data-timeout'],
dismissAfter: 0,
closedParam: null,
didInsertElement: function() {
var _this = this;
if (this.dismissAfter > 0) {
Ember.run.later(this, 'dismiss', this.dismissAfter * 1000);
}
Ember.$("#" + this.elementId).bind('closed.bs.alert', function() {
_this.sendAction('closed', _this.get('closedParam'));
return _this.destroy();
});
return Ember.$("#" + this.elementId).bind('close.bs.alert', function() {
return _this.sendAction('close', _this.get('closedParam'));
});
},
dismiss: function() {
return Ember.$("#" + this.elementId).alert('close');
}
});
Ember.Handlebars.helper('bs-alert', Bootstrap.BsAlertComponent);
}).call(this);
this["Ember"] = this["Ember"] || {};
this["Ember"]["TEMPLATES"] = this["Ember"]["TEMPLATES"] || {};
this["Ember"]["TEMPLATES"]["components/bs-alert"] = Ember.Handlebars.template(function anonymous(Handlebars,depth0,helpers,partials,data) {
this.compilerInfo = [4,'>= 1.0.0'];
helpers = this.merge(helpers, Ember.Handlebars.helpers); data = data || {};
var buffer = '', stack1, hashTypes, hashContexts, self=this, escapeExpression=this.escapeExpression;
function program1(depth0,data) {
data.buffer.push("\n <a class=\"close\" data-dismiss=\"alert\" href=\"#\">×</a>\n");
}
hashTypes = {};
hashContexts = {};
stack1 = helpers['if'].call(depth0, "dismiss", {hash:{},inverse:self.noop,fn:self.program(1, program1, data),contexts:[depth0],types:["ID"],hashContexts:hashContexts,hashTypes:hashTypes,data:data});
if(stack1 || stack1 === 0) { data.buffer.push(stack1); }
data.buffer.push("\n");
hashTypes = {};
hashContexts = {};
data.buffer.push(escapeExpression(helpers._triageMustache.call(depth0, "message", {hash:{},contexts:[depth0],types:["ID"],hashContexts:hashContexts,hashTypes:hashTypes,data:data})));
hashTypes = {};
hashContexts = {};
data.buffer.push(escapeExpression(helpers._triageMustache.call(depth0, "yield", {hash:{},contexts:[depth0],types:["ID"],hashContexts:hashContexts,hashTypes:hashTypes,data:data})));
return buffer;
}); |
/* jshint maxlen:false */
describe('formlyApiCheck', () => {
beforeEach(window.module('formly'))
let formlyApiCheck
beforeEach(inject((_formlyApiCheck_) => {
formlyApiCheck = _formlyApiCheck_
}))
describe('formlyFieldOptions', () => {
it(`should pass when validation.messages is an object of functions or strings`, () => {
expectPass({
key: '♪┏(・o・)┛♪┗ ( ・o・) ┓♪',
template: 'hi',
validation: {
messages: {
thing1() {
},
thing2: '"Formly Expression"',
},
},
}, 'formlyFieldOptions')
})
it(`should allow $$hashKey`, () => {
expectPass({
$$hashKey: 'object:1',
template: 'hello',
key: 'whatevs',
}, 'formlyFieldOptions')
})
describe('ngModelAttrs', () => {
it(`should allow property of 'boolean'`, () => {
expectPass({
template: 'hello',
key: 'whatevs',
templateOptions: {
foo: 'bar',
},
ngModelAttrs: {
foo: {
boolean: 'foo-bar',
},
},
}, 'formlyFieldOptions')
})
})
})
describe(`fieldGroup`, () => {
it(`should pass when specifying data`, () => {
expectPass({
fieldGroup: [],
data: {foo: 'bar'},
}, 'fieldGroup')
})
})
describe(`extras`, () => {
describe(`skipNgModelAttrsManipulator`, () => {
it(`should pass with a boolean`, () => {
expectPass({
template: 'foo',
extras: {skipNgModelAttrsManipulator: true},
}, 'formlyFieldOptions')
})
it(`should pass with a string`, () => {
expectPass({
template: 'foo',
extras: {skipNgModelAttrsManipulator: '.selector'},
}, 'formlyFieldOptions')
})
it(`should pass with nothing`, () => {
expectPass({
template: 'foo',
extras: {skipNgModelAttrsManipulator: '.selector'},
}, 'formlyFieldOptions')
})
it(`should fail with anything else`, () => {
expectFail({
template: 'foo',
extras: {skipNgModelAttrsManipulator: 32},
}, 'formlyFieldOptions')
})
})
})
function expectPass(options, checker) {
const result = formlyApiCheck[checker](options)
expect(result).to.be.undefined
}
function expectFail(options, checker) {
const result = formlyApiCheck[checker](options)
expect(result).to.be.an.instanceOf(Error)
}
})
|
/**
* Copyright (c) Nicolas Gallagher.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
import { render } from 'react-dom';
export default render; |
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getRatingUtilityClass=getRatingUtilityClass,exports.default=void 0;var _unstyled=require("@material-ui/unstyled");function getRatingUtilityClass(e){return(0,_unstyled.generateUtilityClass)("MuiRating",e)}const ratingClasses=(0,_unstyled.generateUtilityClasses)("MuiRating",["root","sizeSmall","sizeMedium","sizeLarge","readOnly","disabled","focusVisible","visuallyHidden","pristine","label","labelEmptyValueActive","icon","iconEmpty","iconFilled","iconHover","iconFocus","iconActive","decimal"]);var _default=ratingClasses;exports.default=_default; |
/*!
* ZUI - v1.3.2 - 2015-05-26
* http://zui.sexy
* GitHub: https://github.com/easysoft/zui.git
* Copyright (c) 2015 cnezsoft.com; Licensed MIT
*/
!function(a,b){var c=a.zui;if(c){var d=function(e,f){return a.isArray(e)?void a.each(e,function(a,b){d(b,f)}):void(f?a.extend(b,{name:c[e]}):a.extend({name:c[e]}))};d(["uuid","callEvent","clientLang","browser","messager","Messager","showMessager","closeModal","ajustModalPosition","ModalTrigger","modalTrigger","store"]),d(["Color","imgReady","messager","Messager","showMessager","closeModal","ajustModalPosition","ModalTrigger","modalTrigger","store"],!0)}}(jQuery,window); |
"use strict";
exports.__esModule = true;
exports.lib = void 0;
var helper_1 = require("./helper");
exports.lib = {
one: helper_1.helper.one,
two: helper_1.helper.two,
three: helper_1.helper.three
};
//# sourceMappingURL=index.js.map |
/*globals describe, before, beforeEach, afterEach, it*/
var testUtils = require('./testUtils'),
should = require('should'),
sinon = require('sinon'),
when = require('when'),
_ = require("underscore"),
errors = require('../../server/errorHandling'),
// Stuff we are testing
migration = require('../../server/data/migration'),
exporter = require('../../server/data/export'),
Settings = require('../../server/models/settings').Settings;
describe("Exporter", function () {
should.exist(exporter);
before(function (done) {
testUtils.clearData().then(function () {
done();
}, done);
});
beforeEach(function (done) {
this.timeout(5000);
testUtils.initData().then(function () {
done();
}, done);
});
afterEach(function (done) {
testUtils.clearData().then(function () {
done();
}, done);
});
it("exports data", function (done) {
// Stub migrations to return 000 as the current database version
var migrationStub = sinon.stub(migration, "getDatabaseVersion", function () {
return when.resolve("000");
});
exporter().then(function (exportData) {
var tables = ['posts', 'users', 'roles', 'roles_users', 'permissions', 'permissions_roles', 'permissions_users',
'settings', 'tags', 'posts_tags'];
should.exist(exportData);
should.exist(exportData.meta);
should.exist(exportData.data);
exportData.meta.version.should.equal("000");
_.findWhere(exportData.data.settings, {key: "databaseVersion"}).value.should.equal("000");
_.each(tables, function (name) {
should.exist(exportData.data[name]);
});
// should not export sqlite data
should.not.exist(exportData.data.sqlite_sequence);
migrationStub.restore();
done();
}).then(null, done);
});
});
|
#!/usr/bin/env node
'use strict';
const clear = require('clear');
const {readFileSync, writeFileSync} = require('fs');
const {readJson, writeJson} = require('fs-extra');
const {join, relative} = require('path');
const {confirm, execRead, printDiff} = require('../utils');
const theme = require('../theme');
const run = async ({cwd, packages, version}, versionsMap) => {
const nodeModulesPath = join(cwd, 'build/node_modules');
// Cache all package JSONs for easy lookup below.
const sourcePackageJSONs = new Map();
for (let i = 0; i < packages.length; i++) {
const packageName = packages[i];
const sourcePackageJSON = await readJson(
join(cwd, 'packages', packageName, 'package.json')
);
sourcePackageJSONs.set(packageName, sourcePackageJSON);
}
const updateDependencies = async (targetPackageJSON, key) => {
const targetDependencies = targetPackageJSON[key];
if (targetDependencies) {
const sourceDependencies = sourcePackageJSONs.get(targetPackageJSON.name)[
key
];
for (let i = 0; i < packages.length; i++) {
const dependencyName = packages[i];
const targetDependency = targetDependencies[dependencyName];
if (targetDependency) {
// For example, say we're updating react-dom's dependency on scheduler.
// We compare source packages to determine what the new scheduler dependency constraint should be.
// To do this, we look at both the local version of the scheduler (e.g. 0.11.0),
// and the dependency constraint in the local version of react-dom (e.g. scheduler@^0.11.0).
const sourceDependencyVersion = sourcePackageJSONs.get(dependencyName)
.version;
const sourceDependencyConstraint = sourceDependencies[dependencyName];
// If the source dependency's version and the constraint match,
// we will need to update the constraint to point at the dependency's new release version,
// (e.g. scheduler@^0.11.0 becomes scheduler@^0.12.0 when we release scheduler 0.12.0).
// Otherwise we leave the constraint alone (e.g. react@^16.0.0 doesn't change between releases).
// Note that in both cases, we must update the target package JSON,
// since canary releases are all locked to the canary version (e.g. 0.0.0-ddaf2b07c).
if (
sourceDependencyVersion ===
sourceDependencyConstraint.replace(/^[\^\~]/, '')
) {
targetDependencies[
dependencyName
] = sourceDependencyConstraint.replace(
sourceDependencyVersion,
versionsMap.get(dependencyName)
);
} else {
targetDependencies[dependencyName] = sourceDependencyConstraint;
}
}
}
}
};
// Update all package JSON versions and their dependencies/peerDependencies.
// This must be done in a way that respects semver constraints (e.g. 16.7.0, ^16.7.0, ^16.0.0).
// To do this, we use the dependencies defined in the source package JSONs,
// because the canary dependencies have already been flattened to an exact match (e.g. 0.0.0-ddaf2b07c).
for (let i = 0; i < packages.length; i++) {
const packageName = packages[i];
const packageJSONPath = join(nodeModulesPath, packageName, 'package.json');
const packageJSON = await readJson(packageJSONPath);
packageJSON.version = versionsMap.get(packageName);
await updateDependencies(packageJSON, 'dependencies');
await updateDependencies(packageJSON, 'peerDependencies');
await writeJson(packageJSONPath, packageJSON, {spaces: 2});
}
clear();
// Print the map of versions and their dependencies for confirmation.
const printDependencies = (maybeDependency, label) => {
if (maybeDependency) {
for (let dependencyName in maybeDependency) {
if (packages.includes(dependencyName)) {
console.log(
theme`• {package ${dependencyName}} {version ${
maybeDependency[dependencyName]
}} {dimmed ${label}}`
);
}
}
}
};
for (let i = 0; i < packages.length; i++) {
const packageName = packages[i];
const packageJSONPath = join(nodeModulesPath, packageName, 'package.json');
const packageJSON = await readJson(packageJSONPath);
console.log(
theme`\n{package ${packageName}} {version ${versionsMap.get(
packageName
)}}`
);
printDependencies(packageJSON.dependencies, 'dependency');
printDependencies(packageJSON.peerDependencies, 'peer');
}
await confirm('Do the versions above look correct?');
clear();
// A separate "React version" is used for the embedded renderer version to support DevTools,
// since it needs to distinguish between different version ranges of React.
// We need to replace it as well as the canary version number.
const buildInfoPath = join(nodeModulesPath, 'react', 'build-info.json');
const {reactVersion} = await readJson(buildInfoPath);
if (!reactVersion) {
console.error(
theme`{error Unsupported or invalid build metadata in} {path build/node_modules/react/build-info.json}` +
theme`{error . This could indicate that you have specified an outdated canary version.}`
);
process.exit(1);
}
// We print the diff to the console for review,
// but it can be large so let's also write it to disk.
const diffPath = join(cwd, 'build', 'temp.diff');
let diff = '';
let numFilesModified = 0;
// Find-and-replace hard coded version (in built JS) for renderers.
for (let i = 0; i < packages.length; i++) {
const packageName = packages[i];
const packagePath = join(nodeModulesPath, packageName);
let files = await execRead(
`find ${packagePath} -name '*.js' -exec echo {} \\;`,
{cwd}
);
files = files.split('\n');
files.forEach(path => {
const newStableVersion = versionsMap.get(packageName);
const beforeContents = readFileSync(path, 'utf8', {cwd});
let afterContents = beforeContents;
// Replace all canary version numbers (e.g. header @license).
while (afterContents.indexOf(version) >= 0) {
afterContents = afterContents.replace(version, newStableVersion);
}
// Replace inline renderer version numbers (e.g. shared/ReactVersion).
while (afterContents.indexOf(reactVersion) >= 0) {
afterContents = afterContents.replace(reactVersion, newStableVersion);
}
if (beforeContents !== afterContents) {
numFilesModified++;
// Using a relative path for diff helps with the snapshot test
diff += printDiff(relative(cwd, path), beforeContents, afterContents);
writeFileSync(path, afterContents, {cwd});
}
});
}
writeFileSync(diffPath, diff, {cwd});
console.log(theme.header(`\n${numFilesModified} files have been updated.`));
console.log(
theme`A full diff is available at {path ${relative(cwd, diffPath)}}.`
);
await confirm('Do the changes above look correct?');
clear();
};
// Run this directly because logPromise would interfere with printing package dependencies.
module.exports = run;
|
/*
* Gijgo Checkbox v1.3.0
* http://gijgo.com/checkbox
*
* Copyright 2014, 2017 gijgo.com
* Released under the MIT license
*/
if (typeof (gj) === 'undefined') {
gj = {};
}
gj.widget = function () {
var self = this;
self.xhr = null;
self.generateGUID = function () {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
};
self.mouseX = function (e) {
if (e) {
if (e.pageX) {
return e.pageX;
} else if (e.clientX) {
return e.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
}
}
return null;
};
self.mouseY = function (e) {
if (e) {
if (e.pageY) {
return e.pageY;
} else if (e.clientY) {
return e.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
}
}
return null;
};
};
gj.widget.prototype.init = function (jsConfig, type) {
var option, clientConfig, fullConfig;
clientConfig = $.extend(true, {}, this.getHTMLConfig() || {});
$.extend(true, clientConfig, jsConfig || {});
fullConfig = this.getConfig(clientConfig, type);
this.attr('data-guid', fullConfig.guid);
this.data(fullConfig);
// Initialize events configured as options
for (option in fullConfig) {
if (gj[type].events.hasOwnProperty(option)) {
this.on(option, fullConfig[option]);
delete fullConfig[option];
}
}
// Initialize all plugins
for (plugin in gj[type].plugins) {
if (gj[type].plugins.hasOwnProperty(plugin)) {
gj[type].plugins[plugin].configure(this, fullConfig, clientConfig);
}
}
return this;
};
gj.widget.prototype.getConfig = function (clientConfig, type) {
var config, uiLibrary, iconsLibrary, plugin;
config = $.extend(true, {}, gj[type].config.base);
uiLibrary = clientConfig.hasOwnProperty('uiLibrary') ? clientConfig.uiLibrary : config.uiLibrary;
if (gj[type].config[uiLibrary]) {
$.extend(true, config, gj[type].config[uiLibrary]);
}
iconsLibrary = clientConfig.hasOwnProperty('iconsLibrary') ? clientConfig.iconsLibrary : config.iconsLibrary;
if (gj[type].config[iconsLibrary]) {
$.extend(true, config, gj[type].config[iconsLibrary]);
}
for (plugin in gj[type].plugins) {
if (gj[type].plugins.hasOwnProperty(plugin)) {
$.extend(true, config, gj[type].plugins[plugin].config.base);
if (gj[type].plugins[plugin].config[uiLibrary]) {
$.extend(true, config, gj[type].plugins[plugin].config[uiLibrary]);
}
if (gj[type].plugins[plugin].config[iconsLibrary]) {
$.extend(true, config, gj[type].plugins[plugin].config[iconsLibrary]);
}
}
}
$.extend(true, config, clientConfig);
if (!config.guid) {
config.guid = this.generateGUID();
}
return config;
}
gj.widget.prototype.getHTMLConfig = function () {
var result = this.data(),
attrs = this[0].attributes;
if (attrs['width']) {
result.width = attrs['width'].nodeValue;
}
if (attrs['height']) {
result.height = attrs['height'].nodeValue;
}
if (attrs['align']) {
result.align = attrs['align'].nodeValue;
}
if (result && result.source) {
result.dataSource = result.source;
delete result.source;
}
return result;
};
gj.widget.prototype.createDoneHandler = function () {
var $widget = this;
return function (response) {
if (typeof (response) === 'string' && JSON) {
response = JSON.parse(response);
}
gj[$widget.data('type')].methods.render($widget, response);
};
};
gj.widget.prototype.createErrorHandler = function () {
var $widget = this;
return function (response) {
if (response && response.statusText && response.statusText !== 'abort') {
alert(response.statusText);
}
};
};
gj.widget.prototype.reload = function (params) {
var ajaxOptions, result, data = this.data(), type = this.data('type');
if (data.dataSource === undefined) {
gj[type].methods.useHtmlDataSource(this, data);
}
$.extend(data.params, params);
if ($.isArray(data.dataSource)) {
result = gj[type].methods.filter(this);
gj[type].methods.render(this, result);
} else if (typeof(data.dataSource) === 'string') {
ajaxOptions = { url: data.dataSource, data: data.params };
if (this.xhr) {
this.xhr.abort();
}
this.xhr = $.ajax(ajaxOptions).done(this.createDoneHandler()).fail(this.createErrorHandler());
} else if (typeof (data.dataSource) === 'object') {
if (!data.dataSource.data) {
data.dataSource.data = {};
}
$.extend(data.dataSource.data, data.params);
ajaxOptions = $.extend(true, {}, data.dataSource); //clone dataSource object
if (ajaxOptions.dataType === 'json' && typeof(ajaxOptions.data) === 'object') {
ajaxOptions.data = JSON.stringify(ajaxOptions.data);
}
if (!ajaxOptions.success) {
ajaxOptions.success = this.createDoneHandler();
}
if (!ajaxOptions.error) {
ajaxOptions.error = this.createErrorHandler();
}
if (this.xhr) {
this.xhr.abort();
}
this.xhr = $.ajax(ajaxOptions);
}
return this;
}
gj.documentManager = {
events: {},
subscribeForEvent: function (eventName, widgetId, callback) {
if (!gj.documentManager.events[eventName] || gj.documentManager.events[eventName].length === 0) {
gj.documentManager.events[eventName] = [{ widgetId: widgetId, callback: callback }];
$(document).on(eventName, gj.documentManager.executeCallbacks);
} else if (!gj.documentManager.events[eventName][widgetId]) {
gj.documentManager.events[eventName].push({ widgetId: widgetId, callback: callback });
} else {
throw "Event " + eventName + " for widget with guid='" + widgetId + "' is already attached.";
}
},
executeCallbacks: function (e) {
var callbacks = gj.documentManager.events[e.type];
if (callbacks) {
for (var i = 0; i < callbacks.length; i++) {
callbacks[i].callback(e);
}
}
},
unsubscribeForEvent: function (eventName, widgetId) {
var success = false,
events = gj.documentManager.events[eventName];
if (events) {
for (var i = 0; i < events.length; i++) {
if (events[i].widgetId === widgetId) {
events.splice(i, 1);
success = true;
if (events.length === 0) {
$(document).off(eventName);
delete gj.documentManager.events[eventName];
}
}
}
}
if (!success) {
throw 'The "' + eventName + '" for widget with guid="' + widgetId + '" can\'t be removed.';
}
}
};
/* global window alert jQuery */
/**
* @widget Checkbox
* @plugin Base
*/
if (typeof (gj.checkbox) === 'undefined') {
gj.checkbox = {};
}
gj.checkbox.config = {
base: {
/** The name of the UI library that is going to be in use. Currently we support only Material Design Lite and Bootstrap.
* @additionalinfo The css files for Material Design Lite or Bootstrap should be manually included to the page where the checkbox is in use.
* @type string (bootstrap|materialdesign)
* @default undefined
* @example Bootstrap <!-- bootstrap, checkbox -->
* <div class="container-fluid" style="margin-top:10px">
* <input type="checkbox" id="checkbox"/><br/><br/>
* <button onclick="$chkb.state('checked')" class="btn btn-default">Checked</button>
* <button onclick="$chkb.state('unchecked')" class="btn btn-default">Unchecked</button>
* <button onclick="$chkb.state('indeterminate')" class="btn btn-default">Indeterminate</button>
* </div>
* <script>
* var $chkb = $('#checkbox').checkbox({
* uiLibrary: 'bootstrap'
* });
* </script>
* @example Material.Design <!-- materialdesign, checkbox -->
* <div class="mdl-layout" style="margin:10px">
* <div class="mdl-layout__content">
* <input type="checkbox" id="checkbox"/><br/><br/>
* <button onclick="$chkb.state('checked')" class="btn btn-default">Checked</button>
* <button onclick="$chkb.state('unchecked')" class="btn btn-default">Unchecked</button>
* <button onclick="$chkb.state('indeterminate')" class="btn btn-default">Indeterminate</button>
* <button onclick="$chkb.prop('disabled', false)" class="btn btn-default">Enable</button>
* <button onclick="$chkb.prop('disabled', true)" class="btn btn-default">Disable</button>
* </div>
* </div>
* <script>
* var $chkb = $('#checkbox').checkbox({
* uiLibrary: 'materialdesign'
* });
* </script>
*/
uiLibrary: undefined,
style: {
wrapperCssClass: undefined,
inputCssClass: undefined,
spanCssClass: undefined
}
},
bootstrap: {
style: {
wrapperCssClass: 'gj-checkbox-bootstrap',
inputCssClass: undefined,
spanCssClass: undefined
}
},
materialdesign: {
style: {
wrapperCssClass: 'gj-checkbox-md',
inputCssClass: undefined,
spanCssClass: 'material-icons md-light'
}
}
};
gj.checkbox.methods = {
init: function (jsConfig) {
var $chkb = this;
gj.widget.prototype.init.call(this, jsConfig, 'checkbox');
$chkb.attr('data-checkbox', 'true');
gj.checkbox.methods.initialize($chkb);
return $chkb;
},
initialize: function ($chkb) {
var data = $chkb.data(), $wrapper, $span;
$chkb.on('change', function (e) {
$chkb.state(this.checked ? 'checked' : 'unchecked');
});
if (data.style.inputCssClass) {
$chkb.addClass(data.style.inputCssClass);
}
if (data.style.wrapperCssClass) {
$wrapper = $('<label class="' + data.style.wrapperCssClass + '"></label>');
if ($chkb.attr('id')) {
$wrapper.attr('for', $chkb.attr('id'));
}
$chkb.wrap($wrapper);
$span = $('<span />');
if (data.style.spanCssClass) {
$span.addClass(data.style.spanCssClass);
}
$chkb.parent().append($span);
}
},
state: function ($chkb, value) {
if (value) {
if ('checked' === value) {
$chkb.prop('indeterminate', false);
$chkb.prop('checked', true);
} else if ('unchecked' === value) {
$chkb.prop('indeterminate', false);
$chkb.prop('checked', false);
} else if ('indeterminate' === value) {
$chkb.prop('checked', true);
$chkb.prop('indeterminate', true);
}
gj.checkbox.events.stateChange($chkb, value);
return $chkb;
} else {
if ($chkb.prop('indeterminate')) {
value = 'indeterminate';
} else if ($chkb.prop('checked')) {
value = 'checked';
} else {
value = 'unchecked';
}
return value;
}
},
toggle: function ($chkb) {
if ($chkb.data('state') == 'checked') {
$chkb.state('unchecked');
} else {
$chkb.state('checked');
}
return $chkb;
},
destroy: function ($chkb) {
if ($chkb.attr('data-checkbox') === 'true') {
$chkb.removeData();
$chkb.removeAttr('data-guid');
$chkb.removeAttr('data-checkbox');
$chkb.off();
}
return $chkb;
}
};
gj.checkbox.events = {
/**
* Triggered when the state of the checkbox is changed
*
* @event drag
* @param {object} e - event data
* @param {object} state - The new state of the checkbox.
* @example sample <!-- checkbox -->
* <input type="checkbox" id="checkbox"/>
* <script>
* $('#checkbox').checkbox({
* stateChange: function (e, state) {
* alert(state);
* }
* });
* </script>
*/
stateChange: function ($chkb, state) {
return $chkb.triggerHandler('stateChange', [state]);
}
};
gj.checkbox.widget = function ($element, arguments) {
var self = this,
methods = gj.checkbox.methods;
/** Toogle the state of the checkbox.
* @method
* @fires change
* @return checked|unchecked|indeterminate|jquery
* @example sample <!-- checkbox -->
* <button onclick="$chkb.toggle()">toggle</button>
* <hr/>
* <input type="checkbox" id="checkbox"/>
* <script>
* var $chkb = $('#checkbox').checkbox();
* </script>
*/
self.toggle = function () {
return methods.toggle(this);
};
/** Return state or set state if you pass parameter.
* @method
* @fires change
* @param {string} value - State of the checkbox. Accept only checked, unchecked or indeterminate as values.
* @return checked|unchecked|indeterminate|jquery
* @example sample <!-- checkbox -->
* <button onclick="$chkb.state('checked')">Set to checked</button>
* <button onclick="$chkb.state('unchecked')">Set to unchecked</button>
* <button onclick="$chkb.state('indeterminate')">Set to indeterminate</button>
* <button onclick="alert($chkb.state())">Get state</button>
* <hr/>
* <input type="checkbox" id="checkbox"/>
* <script>
* var $chkb = $('#checkbox').checkbox();
* </script>
*/
self.state = function (value) {
return methods.state(this, value);
};
/** Remove checkbox functionality from the element.
* @method
* @return jquery element
* @example sample <!-- checkbox -->
* <button onclick="$chkb.destroy()">Destroy</button>
* <input type="checkbox" id="checkbox"/>
* <script>
* var $chkb = $('#checkbox').checkbox();
* </script>
*/
self.destroy = function () {
return methods.destroy(this);
};
$.extend($element, self);
if ('true' !== $element.attr('data-checkbox')) {
methods.init.apply($element, arguments);
}
return $element;
};
gj.checkbox.widget.prototype = new gj.widget();
gj.checkbox.widget.constructor = gj.checkbox.widget;
(function ($) {
$.fn.checkbox = function (method) {
var $widget;
if (this && this.length) {
if (typeof method === 'object' || !method) {
return new gj.checkbox.widget(this, arguments);
} else {
$widget = new gj.checkbox.widget(this, null);
if ($widget[method]) {
return $widget[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else {
throw 'Method ' + method + ' does not exist.';
}
}
}
};
})(jQuery); |
/*!
* Ext JS Library 3.2.1
* Copyright(c) 2006-2010 Ext JS, Inc.
* licensing@extjs.com
* http://www.extjs.com/license
*/
/**
* @class Ext.direct.PollingProvider
* @extends Ext.direct.JsonProvider
*
* <p>Provides for repetitive polling of the server at distinct {@link #interval intervals}.
* The initial request for data originates from the client, and then is responded to by the
* server.</p>
*
* <p>All configurations for the PollingProvider should be generated by the server-side
* API portion of the Ext.Direct stack.</p>
*
* <p>An instance of PollingProvider may be created directly via the new keyword or by simply
* specifying <tt>type = 'polling'</tt>. For example:</p>
* <pre><code>
var pollA = new Ext.direct.PollingProvider({
type:'polling',
url: 'php/pollA.php',
});
Ext.Direct.addProvider(pollA);
pollA.disconnect();
Ext.Direct.addProvider(
{
type:'polling',
url: 'php/pollB.php',
id: 'pollB-provider'
}
);
var pollB = Ext.Direct.getProvider('pollB-provider');
* </code></pre>
*/
Ext.direct.PollingProvider = Ext.extend(Ext.direct.JsonProvider, {
/**
* @cfg {Number} priority
* Priority of the request (defaults to <tt>3</tt>). See {@link Ext.direct.Provider#priority}.
*/
// override default priority
priority: 3,
/**
* @cfg {Number} interval
* How often to poll the server-side in milliseconds (defaults to <tt>3000</tt> - every
* 3 seconds).
*/
interval: 3000,
/**
* @cfg {Object} baseParams An object containing properties which are to be sent as parameters
* on every polling request
*/
/**
* @cfg {String/Function} url
* The url which the PollingProvider should contact with each request. This can also be
* an imported Ext.Direct method which will accept the baseParams as its only argument.
*/
// private
constructor : function(config){
Ext.direct.PollingProvider.superclass.constructor.call(this, config);
this.addEvents(
/**
* @event beforepoll
* Fired immediately before a poll takes place, an event handler can return false
* in order to cancel the poll.
* @param {Ext.direct.PollingProvider}
*/
'beforepoll',
/**
* @event poll
* This event has not yet been implemented.
* @param {Ext.direct.PollingProvider}
*/
'poll'
);
},
// inherited
isConnected: function(){
return !!this.pollTask;
},
/**
* Connect to the server-side and begin the polling process. To handle each
* response subscribe to the data event.
*/
connect: function(){
if(this.url && !this.pollTask){
this.pollTask = Ext.TaskMgr.start({
run: function(){
if(this.fireEvent('beforepoll', this) !== false){
if(typeof this.url == 'function'){
this.url(this.baseParams);
}else{
Ext.Ajax.request({
url: this.url,
callback: this.onData,
scope: this,
params: this.baseParams
});
}
}
},
interval: this.interval,
scope: this
});
this.fireEvent('connect', this);
}else if(!this.url){
throw 'Error initializing PollingProvider, no url configured.';
}
},
/**
* Disconnect from the server-side and stop the polling process. The disconnect
* event will be fired on a successful disconnect.
*/
disconnect: function(){
if(this.pollTask){
Ext.TaskMgr.stop(this.pollTask);
delete this.pollTask;
this.fireEvent('disconnect', this);
}
},
// private
onData: function(opt, success, xhr){
if(success){
var events = this.getEvents(xhr);
for(var i = 0, len = events.length; i < len; i++){
var e = events[i];
this.fireEvent('data', this, e);
}
}else{
var e = new Ext.Direct.ExceptionEvent({
data: e,
code: Ext.Direct.exceptions.TRANSPORT,
message: 'Unable to connect to the server.',
xhr: xhr
});
this.fireEvent('data', this, e);
}
}
});
Ext.Direct.PROVIDERS['polling'] = Ext.direct.PollingProvider; |
var selftest = require('../selftest.js');
var Sandbox = selftest.Sandbox;
var files = require('../files.js');
var catalog = require('../catalog.js');
selftest.define("source maps from checkout", ['checkout'], function () {
try {
throw new Error();
} catch (e) {
selftest.expectEqual(e.stack.split(":")[1], "8");
}
});
selftest.define("source maps from an app", ['checkout'], function () {
var s = new Sandbox({
warehouse: {
v1: { recommended: true }
}
});
// If run not in an app dir, runs the latest version ...
var run = s.run("--version");
run.read('Meteor v1\n');
run.expectEnd();
run.expectExit(0);
// Starting a run
s.createApp("myapp", "app-throws-error", {
release: "v1"
});
s.cd("myapp");
s.set("METEOR_TEST_TMP", files.convertToOSPath(files.mkdtemp())); // XXX why?
run = s.run("run");
run.waitSecs(10);
run.match(/at throw.js:3\b/);
run.stop();
s.set('THROW_FROM_PACKAGE', 't');
run = s.run('run');
run.waitSecs(10);
run.match(/packages\/throwing-package\/thrower\.js:2\b/);
run.stop();
});
selftest.define("source maps from built meteor tool", ['checkout'], function () {
var s = new Sandbox({
warehouse: {
v1: { recommended: true }
}
});
// Find the line number that is supposed to throw an error
var commandsJs = files.readFile(files.pathJoin(
files.convertToStandardPath(__dirname), "../commands.js"), "utf8");
var lineNumber = 0;
commandsJs.split("\n").some((line, index) => {
if (line.indexOf("#StackTraceTest") != -1) {
// Lines aren't zero-indexed
lineNumber = index + 1;
// Short-circuit the some
return true;
}
});
if (lineNumber === 0) {
throw new Error("Couldn't find the right line. This test is broken.");
}
var run = s.run("throw-error");
run.matchErr('(/tools/commands.js:' + lineNumber);
run.expectExit(8);
});
selftest.define("source maps from a build plugin implementation", ['checkout'], function () {
var s = new Sandbox({
warehouse: {
v1: { recommended: true }
}
});
// Starting a run
s.createApp("myapp", "build-plugin-throws-error", {
release: "v1"
});
s.cd("myapp");
var run = s.run("run");
run.waitSecs(10);
// XXX This is wrong! The path on disk is
// packages/build-plugin/build-plugin.js, but at some point we switched to the
// servePath which is based on the *plugin*'s "package" name.
run.match(/packages\/build-plugin-itself\/build-plugin.js:2:1/);
run.stop();
});
|
var IS_TEST_MODE = !!process.env.IS_TEST_MODE;
var Board = require("../board.js");
var nanosleep = require("../sleep.js").nano;
var Animation = require("../animation.js");
var __ = require("../../lib/fn.js");
var Pins = Board.Pins;
var priv = new Map();
var Controllers = {
PCA9685: {
COMMANDS: {
value: {
PCA9685_MODE1: 0x0,
PCA9685_PRESCALE: 0xFE,
LED0_ON_L: 0x6
}
},
initialize: {
value: function(opts) {
var state = priv.get(this);
this.address = opts.address || 0x40;
this.pwmRange = opts.pwmRange || [0, 4095];
if (!this.board.Drivers[this.address]) {
this.io.i2cConfig();
this.board.Drivers[this.address] = {
initialized: false
};
// Reset
this.io.i2cWrite(this.address, [this.COMMANDS.PCA9685_MODE1, 0x0]);
// Sleep
this.io.i2cWrite(this.address, [this.COMMANDS.PCA9685_MODE1, 0x10]);
// Set prescalar
this.io.i2cWrite(this.address, [this.COMMANDS.PCA9685_PRESCALE, 0x70]);
// Wake up
this.io.i2cWrite(this.address, [this.COMMANDS.PCA9685_MODE1, 0x0]);
// Wait 5 nanoseconds for restart
nanosleep(5);
// Auto-increment
this.io.i2cWrite(this.address, [this.COMMANDS.PCA9685_MODE1, 0xa1]);
this.board.Drivers[this.address].initialized = true;
}
this.pin = typeof opts.pin === "undefined" ? 0 : opts.pin;
state.mode = this.io.MODES.PWM;
}
},
write: {
value: function() {
var on, off;
var state = priv.get(this);
var value = state.isAnode ? 255 - Board.constrain(state.value, 0, 255) : state.value;
on = 0;
off = this.pwmRange[1] * value / 255;
this.io.i2cWrite(this.address, [this.COMMANDS.LED0_ON_L + 4 * (this.pin), on, on >> 8, off, off >> 8]);
}
}
},
DEFAULT: {
initialize: {
value: function(opts, pinValue) {
var state = priv.get(this);
var isFirmata = true;
var defaultLed;
isFirmata = Pins.isFirmata(this);
if (isFirmata && typeof pinValue === "string" && pinValue[0] === "A") {
pinValue = this.io.analogPins[+pinValue.slice(1)];
}
defaultLed = this.io.defaultLed || 13;
pinValue = +pinValue;
if (isFirmata && this.io.analogPins.includes(pinValue)) {
this.pin = pinValue;
state.mode = this.io.MODES.OUTPUT;
} else {
this.pin = typeof opts.pin === "undefined" ? defaultLed : opts.pin;
state.mode = this.io.MODES[
(this.board.pins.isPwm(this.pin) ? "PWM" : "OUTPUT")
];
}
this.io.pinMode(this.pin, state.mode);
}
},
write: {
value: function() {
var state = priv.get(this);
var value = state.value;
// If pin is not a PWM pin and brightness is not HIGH or LOW, emit an error
if (value !== this.io.LOW && value !== this.io.HIGH && this.mode !== this.io.MODES.PWM) {
Board.Pins.Error({
pin: this.pin,
type: "PWM",
via: "Led"
});
}
if (state.mode === this.io.MODES.OUTPUT) {
this.io.digitalWrite(this.pin, value);
}
if (state.mode === this.io.MODES.PWM) {
if (state.isAnode) {
value = 255 - Board.constrain(value, 0, 255);
}
this.io.analogWrite(this.pin, value);
}
}
}
}
};
/**
* Led
* @constructor
*
* five.Led(pin);
*
* five.Led({
* pin: number
* });
*
*
* @param {Object} opts [description]
*
*/
function Led(opts) {
if (!(this instanceof Led)) {
return new Led(opts);
}
var state;
var controller;
var pinValue = typeof opts === "object" ? opts.pin : opts;
Board.Component.call(
this, opts = Board.Options(opts)
);
if (opts.controller && typeof opts.controller === "string") {
controller = Controllers[opts.controller.toUpperCase()];
} else {
controller = opts.controller;
}
if (controller == null) {
controller = Controllers["DEFAULT"];
}
Object.defineProperties(this, controller);
state = {
isOn: false,
isRunning: false,
value: null,
direction: 1,
mode: null,
isAnode: opts.isAnode,
interval: null
};
priv.set(this, state);
Object.defineProperties(this, {
value: {
get: function() {
return state.value;
}
},
mode: {
get: function() {
return state.mode;
}
},
isOn: {
get: function() {
return !!state.value;
}
},
isRunning: {
get: function() {
return state.isRunning;
}
},
animation: {
get: function() {
return state.animation;
}
}
});
if (typeof this.initialize === "function") {
this.initialize(opts, pinValue);
}
}
/**
* on Turn the led on
* @return {Led}
*/
Led.prototype.on = function() {
var state = priv.get(this);
if (state.mode === this.io.MODES.OUTPUT) {
state.value = this.io.HIGH;
}
if (state.mode === this.io.MODES.PWM) {
// Assume we need to simply turn this all the way on, when:
// ...state.value is null
if (state.value === null) {
state.value = 255;
}
// ...there is no active interval
if (!state.interval) {
state.value = 255;
}
// ...the last value was 0
if (state.value === 0) {
state.value = 255;
}
}
this.write();
return this;
};
/**
* off Turn the led off
* @return {Led}
*/
Led.prototype.off = function() {
var state = priv.get(this);
state.value = 0;
this.write();
return this;
};
/**
* toggle Toggle the on/off state of an led
* @return {Led}
*/
Led.prototype.toggle = function() {
return this[this.isOn ? "off" : "on"]();
};
/**
* brightness
* @param {Number} value analog brightness value 0-255
* @return {Led}
*/
Led.prototype.brightness = function(value) {
var state = priv.get(this);
state.value = value;
this.write();
return this;
};
/**
* Animation.normalize
*
* @param [number || object] keyFrames An array of step values or a keyFrame objects
*/
Led.prototype[Animation.normalize] = function(keyFrames) {
var state = priv.get(this);
var last = state.value || 0;
// If user passes null as the first element in keyFrames use current value
if (keyFrames[0] === null) {
keyFrames[0] = {
value: last
};
}
keyFrames.forEach(function(keyFrame, i) {
if (keyFrame !== null) {
// keyFrames that are just numbers represent values
if (typeof keyFrame === "number") {
keyFrames[i] = {
value: keyFrame,
easing: "linear"
};
}
}
});
return keyFrames;
};
/**
* Animation.render
*
* @position [number] value to set the led to
*/
Led.prototype[Animation.render] = function(position) {
var state = priv.get(this);
state.value = position[0];
return this.write();
};
/**
* pulse Fade the Led in and out in a loop with specified time
* @param {number} rate Time in ms that a fade in/out will elapse
* @return {Led}
*
* - or -
*
* @param {Object} val An Animation() segment config object
*/
Led.prototype.pulse = function(rate, callback) {
var state = priv.get(this);
var options = {
duration: typeof rate === "number" ? rate : 1000,
keyFrames: [0, 0xff],
metronomic: true,
loop: true,
easing: "inOutSine",
onloop: function() {
if (typeof callback === "function") {
callback();
}
}
};
if (typeof rate === "object") {
__.extend(options, rate);
}
if (typeof rate === "function") {
callback = rate;
}
state.isRunning = true;
state.animation = state.animation || new Animation(this);
state.animation.enqueue(options);
return this;
};
/**
* fade Fade an led in and out
* @param {Number} val Analog brightness value 0-255
* @param {Number} time Time in ms that a fade in/out will elapse
* @return {Led}
*
* - or -
*
* @param {Object} val An Animation() segment config object
*/
Led.prototype.fade = function(val, time, callback) {
var state = priv.get(this);
var options = {
duration: typeof time === "number" ? time : 1000,
keyFrames: [null, typeof val === "number" ? val : 0xff],
easing: "outSine",
oncomplete: function() {
state.isRunning = false;
if (typeof callback === "function") {
callback();
}
}
};
if (typeof val === "object") {
__.extend(options, val);
}
if (typeof val === "function") {
callback = val;
}
if (typeof time === "function") {
callback = time;
}
state.isRunning = true;
state.animation = state.animation || new Animation(this);
state.animation.enqueue(options);
};
Led.prototype.fadeIn = function(time, callback) {
return this.fade(255, time || 1000, callback);
};
Led.prototype.fadeOut = function(time, callback) {
return this.fade(0, time || 1000, callback);
};
/**
* strobe
* @param {Number} rate Time in ms to strobe/blink
* @return {Led}
*/
Led.prototype.strobe = function(rate, callback) {
var state = priv.get(this);
// Avoid traffic jams
if (state.interval) {
clearInterval(state.interval);
}
if (typeof rate === "function") {
callback = rate;
rate = null;
}
state.isRunning = true;
state.interval = setInterval(function() {
this.toggle();
if (typeof callback === "function") {
callback();
}
}.bind(this), rate || 100);
return this;
};
Led.prototype.blink = Led.prototype.strobe;
/**
* stop Stop the led from strobing, pulsing or fading
* @return {Led}
*/
Led.prototype.stop = function() {
var state = priv.get(this);
clearInterval(state.interval);
if (state.animation) {
state.animation.stop();
}
state.isRunning = false;
return this;
};
if (IS_TEST_MODE) {
Led.purge = function() {
priv.clear();
};
}
module.exports = Led;
|
define(["exports", "./_base/kernel", "./sniff", "./_base/window", "./dom", "./dom-attr"],
function(exports, dojo, has, win, dom, attr){
// module:
// dojo/dom-construct
// summary:
// This module defines the core dojo DOM construction API.
// TODOC: summary not showing up in output, see https://github.com/csnover/js-doc-parse/issues/42
// support stuff for toDom()
var tagWrap = {
option: ["select"],
tbody: ["table"],
thead: ["table"],
tfoot: ["table"],
tr: ["table", "tbody"],
td: ["table", "tbody", "tr"],
th: ["table", "thead", "tr"],
legend: ["fieldset"],
caption: ["table"],
colgroup: ["table"],
col: ["table", "colgroup"],
li: ["ul"]
},
reTag = /<\s*([\w\:]+)/,
masterNode = {}, masterNum = 0,
masterName = "__" + dojo._scopeName + "ToDomId";
// generate start/end tag strings to use
// for the injection for each special tag wrap case.
for(var param in tagWrap){
if(tagWrap.hasOwnProperty(param)){
var tw = tagWrap[param];
tw.pre = param == "option" ? '<select multiple="multiple">' : "<" + tw.join("><") + ">";
tw.post = "</" + tw.reverse().join("></") + ">";
// the last line is destructive: it reverses the array,
// but we don't care at this point
}
}
var html5domfix;
if(has("ie") <= 8){
html5domfix = function(doc){
doc.__dojo_html5_tested = "yes";
var div = create('div', {innerHTML: "<nav>a</nav>", style: {visibility: "hidden"}}, doc.body);
if(div.childNodes.length !== 1){
('abbr article aside audio canvas details figcaption figure footer header ' +
'hgroup mark meter nav output progress section summary time video').replace(
/\b\w+\b/g, function(n){
doc.createElement(n);
}
);
}
destroy(div);
}
}
function _insertBefore(/*DomNode*/ node, /*DomNode*/ ref){
var parent = ref.parentNode;
if(parent){
parent.insertBefore(node, ref);
}
}
function _insertAfter(/*DomNode*/ node, /*DomNode*/ ref){
// summary:
// Try to insert node after ref
var parent = ref.parentNode;
if(parent){
if(parent.lastChild == ref){
parent.appendChild(node);
}else{
parent.insertBefore(node, ref.nextSibling);
}
}
}
exports.toDom = function toDom(frag, doc){
// summary:
// instantiates an HTML fragment returning the corresponding DOM.
// frag: String
// the HTML fragment
// doc: DocumentNode?
// optional document to use when creating DOM nodes, defaults to
// dojo/_base/window.doc if not specified.
// returns:
// Document fragment, unless it's a single node in which case it returns the node itself
// example:
// Create a table row:
// | require(["dojo/dom-construct"], function(domConstruct){
// | var tr = domConstruct.toDom("<tr><td>First!</td></tr>");
// | });
doc = doc || win.doc;
var masterId = doc[masterName];
if(!masterId){
doc[masterName] = masterId = ++masterNum + "";
masterNode[masterId] = doc.createElement("div");
}
if(has("ie") <= 8){
if(!doc.__dojo_html5_tested && doc.body){
html5domfix(doc);
}
}
// make sure the frag is a string.
frag += "";
// find the starting tag, and get node wrapper
var match = frag.match(reTag),
tag = match ? match[1].toLowerCase() : "",
master = masterNode[masterId],
wrap, i, fc, df;
if(match && tagWrap[tag]){
wrap = tagWrap[tag];
master.innerHTML = wrap.pre + frag + wrap.post;
for(i = wrap.length; i; --i){
master = master.firstChild;
}
}else{
master.innerHTML = frag;
}
// one node shortcut => return the node itself
if(master.childNodes.length == 1){
return master.removeChild(master.firstChild); // DOMNode
}
// return multiple nodes as a document fragment
df = doc.createDocumentFragment();
while((fc = master.firstChild)){ // intentional assignment
df.appendChild(fc);
}
return df; // DocumentFragment
};
exports.place = function place(/*DOMNode|String*/ node, /*DOMNode|String*/ refNode, /*String|Number?*/ position){
// summary:
// Attempt to insert node into the DOM, choosing from various positioning options.
// Returns the first argument resolved to a DOM node.
// node: DOMNode|String
// id or node reference, or HTML fragment starting with "<" to place relative to refNode
// refNode: DOMNode|String
// id or node reference to use as basis for placement
// position: String|Number?
// string noting the position of node relative to refNode or a
// number indicating the location in the childNodes collection of refNode.
// Accepted string values are:
//
// - before
// - after
// - replace
// - only
// - first
// - last
//
// "first" and "last" indicate positions as children of refNode, "replace" replaces refNode,
// "only" replaces all children. position defaults to "last" if not specified
// returns: DOMNode
// Returned values is the first argument resolved to a DOM node.
//
// .place() is also a method of `dojo/NodeList`, allowing `dojo/query` node lookups.
// example:
// Place a node by string id as the last child of another node by string id:
// | require(["dojo/dom-construct"], function(domConstruct){
// | domConstruct.place("someNode", "anotherNode");
// | });
// example:
// Place a node by string id before another node by string id
// | require(["dojo/dom-construct"], function(domConstruct){
// | domConstruct.place("someNode", "anotherNode", "before");
// | });
// example:
// Create a Node, and place it in the body element (last child):
// | require(["dojo/dom-construct", "dojo/_base/window"
// | ], function(domConstruct, win){
// | domConstruct.place("<div></div>", win.body());
// | });
// example:
// Put a new LI as the first child of a list by id:
// | require(["dojo/dom-construct"], function(domConstruct){
// | domConstruct.place("<li></li>", "someUl", "first");
// | });
refNode = dom.byId(refNode);
if(typeof node == "string"){ // inline'd type check
node = /^\s*</.test(node) ? exports.toDom(node, refNode.ownerDocument) : dom.byId(node);
}
if(typeof position == "number"){ // inline'd type check
var cn = refNode.childNodes;
if(!cn.length || cn.length <= position){
refNode.appendChild(node);
}else{
_insertBefore(node, cn[position < 0 ? 0 : position]);
}
}else{
switch(position){
case "before":
_insertBefore(node, refNode);
break;
case "after":
_insertAfter(node, refNode);
break;
case "replace":
refNode.parentNode.replaceChild(node, refNode);
break;
case "only":
exports.empty(refNode);
refNode.appendChild(node);
break;
case "first":
if(refNode.firstChild){
_insertBefore(node, refNode.firstChild);
break;
}
// else fallthrough...
default: // aka: last
refNode.appendChild(node);
}
}
return node; // DomNode
};
var create = exports.create = function create(/*DOMNode|String*/ tag, /*Object*/ attrs, /*DOMNode|String?*/ refNode, /*String?*/ pos){
// summary:
// Create an element, allowing for optional attribute decoration
// and placement.
// description:
// A DOM Element creation function. A shorthand method for creating a node or
// a fragment, and allowing for a convenient optional attribute setting step,
// as well as an optional DOM placement reference.
//
// Attributes are set by passing the optional object through `dojo.setAttr`.
// See `dojo.setAttr` for noted caveats and nuances, and API if applicable.
//
// Placement is done via `dojo.place`, assuming the new node to be the action
// node, passing along the optional reference node and position.
// tag: DOMNode|String
// A string of the element to create (eg: "div", "a", "p", "li", "script", "br"),
// or an existing DOM node to process.
// attrs: Object
// An object-hash of attributes to set on the newly created node.
// Can be null, if you don't want to set any attributes/styles.
// See: `dojo.setAttr` for a description of available attributes.
// refNode: DOMNode|String?
// Optional reference node. Used by `dojo.place` to place the newly created
// node somewhere in the dom relative to refNode. Can be a DomNode reference
// or String ID of a node.
// pos: String?
// Optional positional reference. Defaults to "last" by way of `dojo.place`,
// though can be set to "first","after","before","last", "replace" or "only"
// to further control the placement of the new node relative to the refNode.
// 'refNode' is required if a 'pos' is specified.
// example:
// Create a DIV:
// | require(["dojo/dom-construct"], function(domConstruct){
// | var n = domConstruct.create("div");
// | });
//
// example:
// Create a DIV with content:
// | require(["dojo/dom-construct"], function(domConstruct){
// | var n = domConstruct.create("div", { innerHTML:"<p>hi</p>" });
// | });
//
// example:
// Place a new DIV in the BODY, with no attributes set
// | require(["dojo/dom-construct"], function(domConstruct){
// | var n = domConstruct.create("div", null, dojo.body());
// | });
//
// example:
// Create an UL, and populate it with LI's. Place the list as the first-child of a
// node with id="someId":
// | require(["dojo/dom-construct", "dojo/_base/array"],
// | function(domConstruct, arrayUtil){
// | var ul = domConstruct.create("ul", null, "someId", "first");
// | var items = ["one", "two", "three", "four"];
// | arrayUtil.forEach(items, function(data){
// | domConstruct.create("li", { innerHTML: data }, ul);
// | });
// | });
//
// example:
// Create an anchor, with an href. Place in BODY:
// | require(["dojo/dom-construct"], function(domConstruct){
// | domConstruct.create("a", { href:"foo.html", title:"Goto FOO!" }, dojo.body());
// | });
var doc = win.doc;
if(refNode){
refNode = dom.byId(refNode);
doc = refNode.ownerDocument;
}
if(typeof tag == "string"){ // inline'd type check
tag = doc.createElement(tag);
}
if(attrs){ attr.set(tag, attrs); }
if(refNode){ exports.place(tag, refNode, pos); }
return tag; // DomNode
};
function _empty(/*DomNode*/ node){
if(node.canHaveChildren){
try{
// fast path
node.innerHTML = "";
return;
}catch(e){
// innerHTML is readOnly (e.g. TABLE (sub)elements in quirks mode)
// Fall through (saves bytes)
}
}
// SVG/strict elements don't support innerHTML/canHaveChildren, and OBJECT/APPLET elements in quirks node have canHaveChildren=false
for(var c; c = node.lastChild;){ // intentional assignment
_destroy(c, node); // destroy is better than removeChild so TABLE subelements are removed in proper order
}
}
exports.empty = function empty(/*DOMNode|String*/ node){
// summary:
// safely removes all children of the node.
// node: DOMNode|String
// a reference to a DOM node or an id.
// example:
// Destroy node's children byId:
// | require(["dojo/dom-construct"], function(domConstruct){
// | domConstruct.empty("someId");
// | });
_empty(dom.byId(node));
};
function _destroy(/*DomNode*/ node, /*DomNode*/ parent){
// in IE quirks, node.canHaveChildren can be false but firstChild can be non-null (OBJECT/APPLET)
if(node.firstChild){
_empty(node);
}
if(parent){
// removeNode(false) doesn't leak in IE 6+, but removeChild() and removeNode(true) are known to leak under IE 8- while 9+ is TBD.
// In IE quirks mode, PARAM nodes as children of OBJECT/APPLET nodes have a removeNode method that does nothing and
// the parent node has canHaveChildren=false even though removeChild correctly removes the PARAM children.
// In IE, SVG/strict nodes don't have a removeNode method nor a canHaveChildren boolean.
has("ie") && parent.canHaveChildren && "removeNode" in node ? node.removeNode(false) : parent.removeChild(node);
}
}
var destroy = exports.destroy = function destroy(/*DOMNode|String*/ node){
// summary:
// Removes a node from its parent, clobbering it and all of its
// children.
//
// description:
// Removes a node from its parent, clobbering it and all of its
// children. Function only works with DomNodes, and returns nothing.
//
// node: DOMNode|String
// A String ID or DomNode reference of the element to be destroyed
//
// example:
// Destroy a node byId:
// | require(["dojo/dom-construct"], function(domConstruct){
// | domConstruct.destroy("someId");
// | });
node = dom.byId(node);
if(!node){ return; }
_destroy(node, node.parentNode);
};
});
|
Calendar.LANG("ru", "русский", {
fdow: 1, // first day of week for this locale; 0 = Sunday, 1 = Monday, etc.
goToday: "Сегодня",
today: "Сегодня", // appears in bottom bar
wk: "нед",
weekend: "0,6", // 0 = Sunday, 1 = Monday, etc.
AM: "am",
PM: "pm",
mn : [ "январь",
"февраль",
"март",
"апрель",
"май",
"июнь",
"июль",
"август",
"сентябрь",
"октябрь",
"ноябрь",
"декабрь" ],
smn : [ "янв",
"фев",
"мар",
"апр",
"май",
"июн",
"июл",
"авг",
"сен",
"окт",
"ноя",
"дек" ],
dn : [ "воскресенье",
"понедельник",
"вторник",
"среда",
"четверг",
"пятница",
"суббота",
"воскресенье" ],
sdn : [ "вск",
"пон",
"втр",
"срд",
"чет",
"пят",
"суб",
"вск" ]
});
|
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'stylescombo', 'fr-ca', {
label: 'Style',
panelTitle: 'Formatting Styles', // MISSING
panelTitle1: 'Block Styles', // MISSING
panelTitle2: 'Inline Styles', // MISSING
panelTitle3: 'Object Styles' // MISSING
});
|
/*
Highcharts JS v6.1.1 (2018-06-27)
Indicator series type for Highstock
(c) 2010-2017 Sebastian Bochan
License: www.highcharts.com/license
*/
(function(n){"object"===typeof module&&module.exports?module.exports=n:n(Highcharts)})(function(n){(function(k){function n(a){return a.reduce(function(a,b){return Math.max(a,b[1])},-Infinity)}function B(a){return a.reduce(function(a,b){return Math.min(a,b[2])},Infinity)}function x(a){return{high:n(a),low:B(a)}}function C(a){var c,b,f,g,h;w(a.series,function(a){if(a.xData)for(g=a.xData,h=b=a.xIncrement?1:g.length-1;0<h;h--)if(f=g[h]-g[h-1],c===t||f<c)c=f});return c}var t,D=k.seriesType,w=k.each,y=
k.merge,z=k.color,E=k.isArray,A=k.defined,v=k.seriesTypes.sma;k.approximations["ichimoku-averages"]=function(){var a=[],c;w(arguments,function(b,f){a.push(k.approximations.average(b));c=!c&&void 0===a[f]});return c?void 0:a};D("ikh","sma",{params:{period:26,periodTenkan:9,periodSenkouSpanB:52},marker:{enabled:!1},tooltip:{pointFormat:'\x3cspan style\x3d"color:{point.color}"\x3e\u25cf\x3c/span\x3e \x3cb\x3e {series.name}\x3c/b\x3e\x3cbr/\x3eTENKAN SEN: {point.tenkanSen:.3f}\x3cbr/\x3eKIJUN SEN: {point.kijunSen:.3f}\x3cbr/\x3eCHIKOU SPAN: {point.chikouSpan:.3f}\x3cbr/\x3eSENKOU SPAN A: {point.senkouSpanA:.3f}\x3cbr/\x3eSENKOU SPAN B: {point.senkouSpanB:.3f}\x3cbr/\x3e'},
tenkanLine:{styles:{lineWidth:1,lineColor:void 0}},kijunLine:{styles:{lineWidth:1,lineColor:void 0}},chikouLine:{styles:{lineWidth:1,lineColor:void 0}},senkouSpanA:{styles:{lineWidth:1,lineColor:void 0}},senkouSpanB:{styles:{lineWidth:1,lineColor:void 0}},senkouSpan:{styles:{fill:"rgba(255, 0, 0, 0.5)"}},dataGrouping:{approximation:"ichimoku-averages"}},{pointArrayMap:["tenkanSen","kijunSen","chikouSpan","senkouSpanA","senkouSpanB"],pointValKey:"tenkanSen",nameComponents:["periodSenkouSpanB","period",
"periodTenkan"],init:function(){v.prototype.init.apply(this,arguments);this.options=y({tenkanLine:{styles:{lineColor:this.color}},kijunLine:{styles:{lineColor:this.color}},chikouLine:{styles:{lineColor:this.color}},senkouSpanA:{styles:{lineColor:this.color,fill:z(this.color).setOpacity(.5).get()}},senkouSpanB:{styles:{lineColor:this.color,fill:z(this.color).setOpacity(.5).get()}},senkouSpan:{styles:{fill:z(this.color).setOpacity(.2).get()}}},this.options)},toYData:function(a){return[a.tenkanSen,a.kijunSen,
a.chikouSpan,a.senkouSpanA,a.senkouSpanB]},translate:function(){var a=this;v.prototype.translate.apply(a);w(a.points,function(c){w(a.pointArrayMap,function(b){A(c[b])&&(c["plot"+b]=a.yAxis.toPixels(c[b],!0),c.plotY=c["plot"+b],c.tooltipPos=[c.plotX,c["plot"+b]],c.isNull=!1)})})},drawGraph:function(){for(var a=this,c=a.points,b=c.length,f=a.options,g=a.graph,h=a.color,k={options:{gapSize:f.gapSize}},e=a.pointArrayMap.length,m=[[],[],[],[],[],[]],p,q,l;b--;)for(q=c[b],l=0;l<e;l++)p=a.pointArrayMap[l],
A(q[p])&&m[l].push({plotX:q.plotX,plotY:q["plot"+p],isNull:!1});w("tenkanLine kijunLine chikouLine senkouSpanA senkouSpanB senkouSpan".split(" "),function(b,c){a.points=m[c];a.options=y(f[b].styles,k);a.graph=a["graph"+b];a.nextPoints=m[c-1];5===c?(a.points=m[c-1],a.options=y(f[b].styles,k),a.graph=a["graph"+b],a.nextPoints=m[c-2],a.fillGraph=!0,a.color=a.options.fill):(a.fillGraph=!1,a.color=h);v.prototype.drawGraph.call(a);a["graph"+b]=a.graph});delete a.nextPoints;delete a.fillGraph;a.points=c;
a.options=f;a.graph=g},getGraphPath:function(a){var c,b,f=[];a=a||this.points;if(this.fillGraph&&this.nextPoints){b=v.prototype.getGraphPath.call(this,this.nextPoints);b[0]="L";c=v.prototype.getGraphPath.call(this,a);b=b.slice(0,c.length);for(var g=b.length-1;0<g;g-=3)f.push(b[g-2],b[g-1],b[g]);c=c.concat(f)}else c=v.prototype.getGraphPath.apply(this,arguments);return c},getValues:function(a,c){var b=c.period,f=c.periodTenkan;c=c.periodSenkouSpanB;var g=a.xData,h=a.yData,k=h&&h.length||0;a=C(a.xAxis);
var e=[],m=[],p,q,l,r,u,d,n;if(g.length<=b||!E(h[0])||4!==h[0].length)return!1;p=g[0]-b*a;for(d=0;d<b;d++)m.push(p+d*a);for(d=0;d<k;d++)d>=f&&(l=h.slice(d-f,d),l=x(l),l=(l.high+l.low)/2),d>=b&&(r=h.slice(d-b,d),r=x(r),r=(r.high+r.low)/2,n=(l+r)/2),d>=c&&(u=h.slice(d-c,d),u=x(u),u=(u.high+u.low)/2),p=h[d][0],q=g[d],e[d]===t&&(e[d]=[]),e[d+b]===t&&(e[d+b]=[]),e[d+b][0]=l,e[d+b][1]=r,e[d+b][2]=t,d>=b?e[d-b][2]=p:(e[d+b][3]=t,e[d+b][4]=t),e[d+2*b]===t&&(e[d+2*b]=[]),e[d+2*b][3]=n,e[d+2*b][4]=u,m.push(q);
for(d=1;d<=b;d++)m.push(q+d*a);return{values:e,xData:m,yData:e}}})})(n)});
|
console.warn("warn -",`Imports like "const crystal = require('simple-icons/icons/crystal');" have been deprecated in v6.0.0 and will no longer work from v7.0.0, use "const { siCrystal } = require('simple-icons/icons');" instead`),module.exports={title:"Crystal",slug:"crystal",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Crystal</title><path d="'+this.path+'"/></svg>'},path:"M23.964 15.266l-8.687 8.669c-.034.035-.086.052-.121.035L3.29 20.79c-.052-.017-.087-.052-.087-.086L.007 8.856c-.018-.053 0-.087.035-.122L8.728.065c.035-.035.087-.052.121-.035l11.866 3.18c.052.017.087.052.087.086l3.18 11.848c.034.053.016.087-.018.122zm-11.64-9.433L.667 8.943c-.017 0-.035.034-.017.052l8.53 8.512c.017.017.052.017.052-.017l3.127-11.64c.017 0-.018-.035-.035-.017Z",source:"https://crystal-lang.org/media/",hex:"000000",guidelines:void 0,license:void 0}; |
"use strict";
var assert = require("assert");
var fs = require("fs");
var pather = require("path");
var packageName = require("./package.json").name;
function findPackageDir(paths) {
if (!paths) {
return null;
}
for (var i = 0; i < paths.length; ++i) {
var dir = pather.dirname(paths[i]);
var dirName = dir.split(pather.sep).pop();
if (dirName !== packageName && fs.existsSync(pather.join(dir, 'package.json'))) {
return dir;
}
}
}
function getPackageJSON() {
var dir = findPackageDir(module.paths);
assert(dir, "package.json is not found");
return require(pather.resolve(dir, "package.json"));
}
var directories = getPackageJSON().directories;
assert.equal(typeof directories, "object", 'You should setting `directories : { test : "test/" }`');
assert.equal(typeof directories.test, "string", 'You should setting `directories : { test : "test/" }`');
var testDirectory = directories.test;
require('espower-loader')({
cwd: process.cwd(),
pattern: testDirectory + "**" + pather.sep + "*.js"
});
|
// Copyright 2013 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Unit tests for goog.labs.net.webChannel.WebChannelBase.
* @suppress {accessControls} Private methods are accessed for test purposes.
*
*/
goog.provide('goog.labs.net.webChannel.webChannelBaseTest');
goog.require('goog.Timer');
goog.require('goog.array');
goog.require('goog.dom');
goog.require('goog.functions');
goog.require('goog.json');
goog.require('goog.labs.net.webChannel.ChannelRequest');
goog.require('goog.labs.net.webChannel.ForwardChannelRequestPool');
goog.require('goog.labs.net.webChannel.WebChannelBase');
goog.require('goog.labs.net.webChannel.WebChannelBaseTransport');
goog.require('goog.labs.net.webChannel.WebChannelDebug');
goog.require('goog.labs.net.webChannel.Wire');
goog.require('goog.labs.net.webChannel.netUtils');
goog.require('goog.labs.net.webChannel.requestStats');
goog.require('goog.labs.net.webChannel.requestStats.Stat');
goog.require('goog.structs.Map');
goog.require('goog.testing.MockClock');
goog.require('goog.testing.PropertyReplacer');
goog.require('goog.testing.asserts');
goog.require('goog.testing.jsunit');
goog.setTestOnly('goog.labs.net.webChannel.webChannelBaseTest');
/**
* Delay between a network failure and the next network request.
*/
var RETRY_TIME = 1000;
/**
* A really long time - used to make sure no more timeouts will fire.
*/
var ALL_DAY_MS = 1000 * 60 * 60 * 24;
var stubs = new goog.testing.PropertyReplacer();
var channel;
var deliveredMaps;
var handler;
var mockClock;
var gotError;
var numStatEvents;
var lastStatEvent;
var numTimingEvents;
var lastPostSize;
var lastPostRtt;
var lastPostRetryCount;
// Set to true to see the channel debug output in the browser window.
var debug = false;
// Debug message to print out when debug is true.
var debugMessage = '';
function debugToWindow(message) {
if (debug) {
debugMessage += message + '<br>';
goog.dom.getElement('debug').innerHTML = debugMessage;
}
}
/**
* Stubs goog.labs.net.webChannel.netUtils to always time out. It maintains the
* contract given by goog.labs.net.webChannel.netUtils.testNetwork, but always
* times out (calling callback(false)).
*
* stubNetUtils should be called in tests that require it before
* a call to testNetwork happens. It is reset at tearDown.
*/
function stubNetUtils() {
stubs.set(goog.labs.net.webChannel.netUtils, 'testLoadImage',
function(url, timeout, callback) {
goog.Timer.callOnce(goog.partial(callback, false), timeout);
});
}
/**
* Stubs goog.labs.net.webChannel.ForwardChannelRequestPool.isSpdyEnabled_
* to manage the max pool size for the forward channel.
*
* @param {boolean} spdyEnabled Whether SPDY is enabled for the test.
*/
function stubSpdyCheck(spdyEnabled) {
stubs.set(goog.labs.net.webChannel.ForwardChannelRequestPool,
'isSpdyEnabled_',
function() {
return spdyEnabled;
});
}
/**
* Mock ChannelRequest.
* @constructor
* @struct
* @final
*/
var MockChannelRequest = function(channel, channelDebug, opt_sessionId,
opt_requestId, opt_retryId) {
this.channel_ = channel;
this.channelDebug_ = channelDebug;
this.sessionId_ = opt_sessionId;
this.requestId_ = opt_requestId;
this.successful_ = true;
this.lastError_ = null;
this.lastStatusCode_ = 200;
// For debugging, keep track of whether this is a back or forward channel.
this.isBack = !!(opt_requestId == 'rpc');
this.isForward = !this.isBack;
};
MockChannelRequest.prototype.postData_ = null;
MockChannelRequest.prototype.requestStartTime_ = null;
MockChannelRequest.prototype.setExtraHeaders = function(extraHeaders) {};
MockChannelRequest.prototype.setTimeout = function(timeout) {};
MockChannelRequest.prototype.setReadyStateChangeThrottle =
function(throttle) {};
MockChannelRequest.prototype.xmlHttpPost = function(uri, postData,
decodeChunks) {
this.channelDebug_.debug('---> POST: ' + uri + ', ' + postData + ', ' +
decodeChunks);
this.postData_ = postData;
this.requestStartTime_ = goog.now();
};
MockChannelRequest.prototype.xmlHttpGet = function(uri, decodeChunks,
opt_noClose) {
this.channelDebug_.debug('<--- GET: ' + uri + ', ' + decodeChunks + ', ' +
opt_noClose);
this.requestStartTime_ = goog.now();
};
MockChannelRequest.prototype.sendUsingImgTag = function(uri) {
this.requestStartTime_ = goog.now();
};
MockChannelRequest.prototype.cancel = function() {
this.successful_ = false;
};
MockChannelRequest.prototype.getSuccess = function() {
return this.successful_;
};
MockChannelRequest.prototype.getLastError = function() {
return this.lastError_;
};
MockChannelRequest.prototype.getLastStatusCode = function() {
return this.lastStatusCode_;
};
MockChannelRequest.prototype.getSessionId = function() {
return this.sessionId_;
};
MockChannelRequest.prototype.getRequestId = function() {
return this.requestId_;
};
MockChannelRequest.prototype.getPostData = function() {
return this.postData_;
};
MockChannelRequest.prototype.getRequestStartTime = function() {
return this.requestStartTime_;
};
MockChannelRequest.prototype.getXhr = function() {
return null;
};
function shouldRunTests() {
return goog.labs.net.webChannel.ChannelRequest.supportsXhrStreaming();
}
/**
* @suppress {invalidCasts} The cast from MockChannelRequest to
* ChannelRequest is invalid and will not compile.
*/
function setUpPage() {
// Use our MockChannelRequests instead of the real ones.
goog.labs.net.webChannel.ChannelRequest.createChannelRequest = function(
channel, channelDebug, opt_sessionId, opt_requestId, opt_retryId) {
return /** @type {!goog.labs.net.webChannel.ChannelRequest} */ (
new MockChannelRequest(channel, channelDebug, opt_sessionId,
opt_requestId, opt_retryId));
};
// Mock out the stat notification code.
goog.labs.net.webChannel.requestStats.notifyStatEvent = function(
stat) {
numStatEvents++;
lastStatEvent = stat;
};
goog.labs.net.webChannel.requestStats.notifyTimingEvent = function(
size, rtt, retries) {
numTimingEvents++;
lastPostSize = size;
lastPostRtt = rtt;
lastPostRetryCount = retries;
};
}
function setUp() {
numTimingEvents = 0;
lastPostSize = null;
lastPostRtt = null;
lastPostRetryCount = null;
mockClock = new goog.testing.MockClock(true);
channel = new goog.labs.net.webChannel.WebChannelBase('1');
gotError = false;
handler = new goog.labs.net.webChannel.WebChannelBase.Handler();
handler.channelOpened = function() {};
handler.channelError = function(channel, error) {
gotError = true;
};
handler.channelSuccess = function(channel, maps) {
deliveredMaps = goog.array.clone(maps);
};
/**
* @suppress {checkTypes} The callback function type declaration is skipped.
*/
handler.channelClosed = function(
channel, opt_pendingMaps, opt_undeliveredMaps) {
// Mock out the handler, and let it set a formatted user readable string
// of the undelivered maps which we can use when verifying our assertions.
if (opt_pendingMaps) {
handler.pendingMapsString = formatArrayOfMaps(opt_pendingMaps);
}
if (opt_undeliveredMaps) {
handler.undeliveredMapsString = formatArrayOfMaps(opt_undeliveredMaps);
}
};
handler.channelHandleMultipleArrays = function() {};
handler.channelHandleArray = function() {};
channel.setHandler(handler);
// Provide a predictable retry time for testing.
channel.getRetryTime_ = function(retryCount) {
return RETRY_TIME;
};
var channelDebug = new goog.labs.net.webChannel.WebChannelDebug();
channelDebug.debug = function(message) {
debugToWindow(message);
};
channel.setChannelDebug(channelDebug);
numStatEvents = 0;
lastStatEvent = null;
}
function tearDown() {
mockClock.dispose();
stubs.reset();
debugToWindow('<hr>');
}
function getSingleForwardRequest() {
var pool = channel.forwardChannelRequestPool_;
if (!pool.hasPendingRequest()) {
return null;
}
return pool.request_ || pool.requestPool_.getValues()[0];
}
/**
* Helper function to return a formatted string representing an array of maps.
*/
function formatArrayOfMaps(arrayOfMaps) {
var result = [];
for (var i = 0; i < arrayOfMaps.length; i++) {
var map = arrayOfMaps[i];
var keys = map.map.getKeys();
for (var j = 0; j < keys.length; j++) {
var tmp = keys[j] + ':' + map.map.get(keys[j]) + (map.context ?
':' + map.context : '');
result.push(tmp);
}
}
return result.join(', ');
}
function testFormatArrayOfMaps() {
// This function is used in a non-trivial test, so let's verify that it works.
var map1 = new goog.structs.Map();
map1.set('k1', 'v1');
map1.set('k2', 'v2');
var map2 = new goog.structs.Map();
map2.set('k3', 'v3');
var map3 = new goog.structs.Map();
map3.set('k4', 'v4');
map3.set('k5', 'v5');
map3.set('k6', 'v6');
// One map.
var a = [];
a.push(new goog.labs.net.webChannel.Wire.QueuedMap(0, map1));
assertEquals('k1:v1, k2:v2',
formatArrayOfMaps(a));
// Many maps.
var b = [];
b.push(new goog.labs.net.webChannel.Wire.QueuedMap(0, map1));
b.push(new goog.labs.net.webChannel.Wire.QueuedMap(0, map2));
b.push(new goog.labs.net.webChannel.Wire.QueuedMap(0, map3));
assertEquals('k1:v1, k2:v2, k3:v3, k4:v4, k5:v5, k6:v6',
formatArrayOfMaps(b));
// One map with a context.
var c = [];
c.push(new goog.labs.net.webChannel.Wire.QueuedMap(
0, map1, new String('c1')));
assertEquals('k1:v1:c1, k2:v2:c1',
formatArrayOfMaps(c));
}
/**
* @param {number=} opt_serverVersion
* @param {string=} opt_hostPrefix
* @param {string=} opt_uriPrefix
* @param {boolean=} opt_spdyEnabled
*/
function connectForwardChannel(
opt_serverVersion, opt_hostPrefix, opt_uriPrefix, opt_spdyEnabled) {
stubSpdyCheck(!!opt_spdyEnabled);
var uriPrefix = opt_uriPrefix || '';
channel.connect(uriPrefix + '/test', uriPrefix + '/bind', null);
mockClock.tick(0);
completeTestConnection();
completeForwardChannel(opt_serverVersion, opt_hostPrefix);
}
/**
* @param {number=} opt_serverVersion
* @param {string=} opt_hostPrefix
* @param {string=} opt_uriPrefix
* @param {boolean=} opt_spdyEnabled
*/
function connect(opt_serverVersion, opt_hostPrefix, opt_uriPrefix,
opt_spdyEnabled) {
connectForwardChannel(opt_serverVersion, opt_hostPrefix, opt_uriPrefix,
opt_spdyEnabled);
completeBackChannel();
}
function disconnect() {
channel.disconnect();
mockClock.tick(0);
}
function completeTestConnection() {
completeForwardTestConnection();
completeBackTestConnection();
assertEquals(goog.labs.net.webChannel.WebChannelBase.State.OPENING,
channel.getState());
}
function completeForwardTestConnection() {
channel.connectionTest_.onRequestData(
channel.connectionTest_.request_,
'["b"]');
channel.connectionTest_.onRequestComplete(
channel.connectionTest_.request_);
mockClock.tick(0);
}
function completeBackTestConnection() {
channel.connectionTest_.onRequestData(
channel.connectionTest_.request_,
'11111');
mockClock.tick(0);
}
/**
* @param {number=} opt_serverVersion
* @param {string=} opt_hostPrefix
*/
function completeForwardChannel(opt_serverVersion, opt_hostPrefix) {
var responseData = '[[0,["c","1234567890ABCDEF",' +
(opt_hostPrefix ? '"' + opt_hostPrefix + '"' : 'null') +
(opt_serverVersion ? ',' + opt_serverVersion : '') +
']]]';
channel.onRequestData(
getSingleForwardRequest(),
responseData);
channel.onRequestComplete(
getSingleForwardRequest());
mockClock.tick(0);
}
function completeBackChannel() {
channel.onRequestData(
channel.backChannelRequest_,
'[[1,["foo"]]]');
channel.onRequestComplete(
channel.backChannelRequest_);
mockClock.tick(0);
}
function responseDone() {
channel.onRequestData(
getSingleForwardRequest(),
'[1,0,0]'); // mock data
channel.onRequestComplete(
getSingleForwardRequest());
mockClock.tick(0);
}
/**
*
* @param {number=} opt_lastArrayIdSentFromServer
* @param {number=} opt_outstandingDataSize
*/
function responseNoBackchannel(
opt_lastArrayIdSentFromServer, opt_outstandingDataSize) {
var responseData = goog.json.serialize(
[0, opt_lastArrayIdSentFromServer, opt_outstandingDataSize]);
channel.onRequestData(
getSingleForwardRequest(),
responseData);
channel.onRequestComplete(
getSingleForwardRequest());
mockClock.tick(0);
}
function response(lastArrayIdSentFromServer, outstandingDataSize) {
var responseData = goog.json.serialize(
[1, lastArrayIdSentFromServer, outstandingDataSize]);
channel.onRequestData(
getSingleForwardRequest(),
responseData
);
channel.onRequestComplete(
getSingleForwardRequest());
mockClock.tick(0);
}
function receive(data) {
channel.onRequestData(
channel.backChannelRequest_,
'[[1,' + data + ']]');
channel.onRequestComplete(
channel.backChannelRequest_);
mockClock.tick(0);
}
function responseTimeout() {
getSingleForwardRequest().lastError_ =
goog.labs.net.webChannel.ChannelRequest.Error.TIMEOUT;
getSingleForwardRequest().successful_ = false;
channel.onRequestComplete(
getSingleForwardRequest());
mockClock.tick(0);
}
/**
* @param {number=} opt_statusCode
*/
function responseRequestFailed(opt_statusCode) {
getSingleForwardRequest().lastError_ =
goog.labs.net.webChannel.ChannelRequest.Error.STATUS;
getSingleForwardRequest().lastStatusCode_ =
opt_statusCode || 503;
getSingleForwardRequest().successful_ = false;
channel.onRequestComplete(
getSingleForwardRequest());
mockClock.tick(0);
}
function responseUnknownSessionId() {
getSingleForwardRequest().lastError_ =
goog.labs.net.webChannel.ChannelRequest.Error.UNKNOWN_SESSION_ID;
getSingleForwardRequest().successful_ = false;
channel.onRequestComplete(
getSingleForwardRequest());
mockClock.tick(0);
}
/**
* @param {string} key
* @param {string} value
* @param {string=} opt_context
*/
function sendMap(key, value, opt_context) {
var map = new goog.structs.Map();
map.set(key, value);
channel.sendMap(map, opt_context);
mockClock.tick(0);
}
function hasForwardChannel() {
return !!getSingleForwardRequest();
}
function hasBackChannel() {
return !!channel.backChannelRequest_;
}
function hasDeadBackChannelTimer() {
return goog.isDefAndNotNull(channel.deadBackChannelTimerId_);
}
function assertHasForwardChannel() {
assertTrue('Forward channel missing.', hasForwardChannel());
}
function assertHasBackChannel() {
assertTrue('Back channel missing.', hasBackChannel());
}
function testConnect() {
connect();
assertEquals(goog.labs.net.webChannel.WebChannelBase.State.OPENED,
channel.getState());
// If the server specifies no version, the client assumes the latest version
assertEquals(goog.labs.net.webChannel.Wire.LATEST_CHANNEL_VERSION,
channel.channelVersion_);
assertFalse(channel.isBuffered());
}
function testConnect_backChannelEstablished() {
connect();
assertHasBackChannel();
}
function testConnect_withServerHostPrefix() {
connect(undefined, 'serverHostPrefix');
assertEquals('serverHostPrefix', channel.hostPrefix_);
}
function testConnect_withClientHostPrefix() {
handler.correctHostPrefix = function(hostPrefix) {
return 'clientHostPrefix';
};
connect();
assertEquals('clientHostPrefix', channel.hostPrefix_);
}
function testConnect_overrideServerHostPrefix() {
handler.correctHostPrefix = function(hostPrefix) {
return 'clientHostPrefix';
};
connect(undefined, 'serverHostPrefix');
assertEquals('clientHostPrefix', channel.hostPrefix_);
}
function testConnect_withServerVersion() {
connect(8);
assertEquals(8, channel.channelVersion_);
}
function testConnect_notOkToMakeRequestForTest() {
handler.okToMakeRequest = goog.functions.constant(
goog.labs.net.webChannel.WebChannelBase.Error.NETWORK);
channel.connect('/test', '/bind', null);
mockClock.tick(0);
assertEquals(goog.labs.net.webChannel.WebChannelBase.State.CLOSED,
channel.getState());
}
function testConnect_notOkToMakeRequestForBind() {
channel.connect('/test', '/bind', null);
mockClock.tick(0);
completeTestConnection();
handler.okToMakeRequest = goog.functions.constant(
goog.labs.net.webChannel.WebChannelBase.Error.NETWORK);
completeForwardChannel();
assertEquals(goog.labs.net.webChannel.WebChannelBase.State.CLOSED,
channel.getState());
}
function testSendMap() {
connect();
sendMapOnce();
}
function testSendMapWithSpdyEnabled() {
connect(undefined, undefined, undefined, true);
sendMapOnce();
}
function sendMapOnce() {
assertEquals(1, numTimingEvents);
sendMap('foo', 'bar');
responseDone();
assertEquals(2, numTimingEvents);
assertEquals('foo:bar', formatArrayOfMaps(deliveredMaps));
}
function testSendMap_twice() {
connect();
sendMapTwice();
}
function testSendMap_twiceWithSpdyEnabled() {
connect(undefined, undefined, undefined, true);
sendMapTwice();
}
function sendMapTwice() {
sendMap('foo1', 'bar1');
responseDone();
assertEquals('foo1:bar1', formatArrayOfMaps(deliveredMaps));
sendMap('foo2', 'bar2');
responseDone();
assertEquals('foo2:bar2', formatArrayOfMaps(deliveredMaps));
}
function testSendMap_andReceive() {
connect();
sendMap('foo', 'bar');
responseDone();
receive('["the server reply"]');
}
function testReceive() {
connect();
receive('["message from server"]');
assertHasBackChannel();
}
function testReceive_twice() {
connect();
receive('["message one from server"]');
receive('["message two from server"]');
assertHasBackChannel();
}
function testReceive_andSendMap() {
connect();
receive('["the server reply"]');
sendMap('foo', 'bar');
responseDone();
assertHasBackChannel();
}
function testBackChannelRemainsEstablished_afterSingleSendMap() {
connect();
sendMap('foo', 'bar');
responseDone();
receive('["ack"]');
assertHasBackChannel();
}
function testBackChannelRemainsEstablished_afterDoubleSendMap() {
connect();
sendMap('foo1', 'bar1');
sendMap('foo2', 'bar2');
responseDone();
receive('["ack"]');
// This assertion would fail prior to CL 13302660.
assertHasBackChannel();
}
function testTimingEvent() {
connect();
assertEquals(1, numTimingEvents);
sendMap('', '');
assertEquals(1, numTimingEvents);
mockClock.tick(20);
var expSize = getSingleForwardRequest().getPostData().length;
responseDone();
assertEquals(2, numTimingEvents);
assertEquals(expSize, lastPostSize);
assertEquals(20, lastPostRtt);
assertEquals(0, lastPostRetryCount);
sendMap('abcdefg', '123456');
expSize = getSingleForwardRequest().getPostData().length;
responseTimeout();
assertEquals(2, numTimingEvents);
mockClock.tick(RETRY_TIME + 1);
responseDone();
assertEquals(3, numTimingEvents);
assertEquals(expSize, lastPostSize);
assertEquals(1, lastPostRetryCount);
assertEquals(1, lastPostRtt);
}
/**
* Make sure that dropping the forward channel retry limit below the retry count
* reports an error, and prevents another request from firing.
*/
function testSetFailFastWhileWaitingForRetry() {
stubNetUtils();
connect();
setFailFastWhileWaitingForRetry();
}
function testSetFailFastWhileWaitingForRetryWithSpdyEnabled() {
stubNetUtils();
connect(undefined, undefined, undefined, true);
setFailFastWhileWaitingForRetry();
}
function setFailFastWhileWaitingForRetry() {
assertEquals(1, numTimingEvents);
sendMap('foo', 'bar');
assertNull(channel.forwardChannelTimerId_);
assertNotNull(getSingleForwardRequest());
assertEquals(0, channel.forwardChannelRetryCount_);
// Watchdog timeout.
responseTimeout();
assertNotNull(channel.forwardChannelTimerId_);
assertNull(getSingleForwardRequest());
assertEquals(1, channel.forwardChannelRetryCount_);
// Almost finish the between-retry timeout.
mockClock.tick(RETRY_TIME - 1);
assertNotNull(channel.forwardChannelTimerId_);
assertNull(getSingleForwardRequest());
assertEquals(1, channel.forwardChannelRetryCount_);
// Setting max retries to 0 should cancel the timer and raise an error.
channel.setFailFast(true);
assertNull(channel.forwardChannelTimerId_);
assertNull(getSingleForwardRequest());
assertEquals(1, channel.forwardChannelRetryCount_);
assertTrue(gotError);
assertEquals(0, deliveredMaps.length);
// We get the error immediately before starting to ping google.com.
// Simulate that timing out. We should get a network error in addition to the
// initial failure.
gotError = false;
mockClock.tick(goog.labs.net.webChannel.netUtils.NETWORK_TIMEOUT);
assertTrue('No error after network ping timed out.', gotError);
// Make sure no more retry timers are firing.
mockClock.tick(ALL_DAY_MS);
assertNull(channel.forwardChannelTimerId_);
assertNull(getSingleForwardRequest());
assertEquals(1, channel.forwardChannelRetryCount_);
assertEquals(1, numTimingEvents);
}
/**
* Make sure that dropping the forward channel retry limit below the retry count
* reports an error, and prevents another request from firing.
*/
function testSetFailFastWhileRetryXhrIsInFlight() {
stubNetUtils();
connect();
setFailFastWhileRetryXhrIsInFlight();
}
function testSetFailFastWhileRetryXhrIsInFlightWithSpdyEnabled() {
stubNetUtils();
connect(undefined, undefined, undefined, true);
setFailFastWhileRetryXhrIsInFlight();
}
function setFailFastWhileRetryXhrIsInFlight() {
assertEquals(1, numTimingEvents);
sendMap('foo', 'bar');
assertNull(channel.forwardChannelTimerId_);
assertNotNull(getSingleForwardRequest());
assertEquals(0, channel.forwardChannelRetryCount_);
// Watchdog timeout.
responseTimeout();
assertNotNull(channel.forwardChannelTimerId_);
assertNull(getSingleForwardRequest());
assertEquals(1, channel.forwardChannelRetryCount_);
// Wait for the between-retry timeout.
mockClock.tick(RETRY_TIME);
assertNull(channel.forwardChannelTimerId_);
assertNotNull(getSingleForwardRequest());
assertEquals(1, channel.forwardChannelRetryCount_);
// Simulate a second watchdog timeout.
responseTimeout();
assertNotNull(channel.forwardChannelTimerId_);
assertNull(getSingleForwardRequest());
assertEquals(2, channel.forwardChannelRetryCount_);
// Wait for another between-retry timeout.
mockClock.tick(RETRY_TIME);
// Now the third req is in flight.
assertNull(channel.forwardChannelTimerId_);
assertNotNull(getSingleForwardRequest());
assertEquals(2, channel.forwardChannelRetryCount_);
// Set fail fast, killing the request
channel.setFailFast(true);
assertNull(channel.forwardChannelTimerId_);
assertNull(getSingleForwardRequest());
assertEquals(2, channel.forwardChannelRetryCount_);
assertTrue(gotError);
// We get the error immediately before starting to ping google.com.
// Simulate that timing out. We should get a network error in addition to the
gotError = false;
mockClock.tick(goog.labs.net.webChannel.netUtils.NETWORK_TIMEOUT);
assertTrue('No error after network ping timed out.', gotError);
// Make sure no more retry timers are firing.
mockClock.tick(ALL_DAY_MS);
assertNull(channel.forwardChannelTimerId_);
assertNull(getSingleForwardRequest());
assertEquals(2, channel.forwardChannelRetryCount_);
assertEquals(1, numTimingEvents);
}
/**
* Makes sure that setting fail fast while not retrying doesn't cause a failure.
*/
function testSetFailFastAtRetryCount() {
stubNetUtils();
connect();
assertEquals(1, numTimingEvents);
sendMap('foo', 'bar');
assertNull(channel.forwardChannelTimerId_);
assertNotNull(getSingleForwardRequest());
assertEquals(0, channel.forwardChannelRetryCount_);
// Set fail fast.
channel.setFailFast(true);
// Request should still be alive.
assertNull(channel.forwardChannelTimerId_);
assertNotNull(getSingleForwardRequest());
assertEquals(0, channel.forwardChannelRetryCount_);
// Watchdog timeout. Now we should get an error.
responseTimeout();
assertNull(channel.forwardChannelTimerId_);
assertNull(getSingleForwardRequest());
assertEquals(0, channel.forwardChannelRetryCount_);
assertTrue(gotError);
// We get the error immediately before starting to ping google.com.
// Simulate that timing out. We should get a network error in addition to the
// initial failure.
gotError = false;
mockClock.tick(goog.labs.net.webChannel.netUtils.NETWORK_TIMEOUT);
assertTrue('No error after network ping timed out.', gotError);
// Make sure no more retry timers are firing.
mockClock.tick(ALL_DAY_MS);
assertNull(channel.forwardChannelTimerId_);
assertNull(getSingleForwardRequest());
assertEquals(0, channel.forwardChannelRetryCount_);
assertEquals(1, numTimingEvents);
}
function testRequestFailedClosesChannel() {
stubNetUtils();
connect();
requestFailedClosesChannel();
}
function testRequestFailedClosesChannelWithSpdyEnabled() {
stubNetUtils();
connect(undefined, undefined, undefined, true);
requestFailedClosesChannel();
}
function requestFailedClosesChannel() {
assertEquals(1, numTimingEvents);
sendMap('foo', 'bar');
responseRequestFailed();
assertEquals('Should be closed immediately after request failed.',
goog.labs.net.webChannel.WebChannelBase.State.CLOSED, channel.getState());
mockClock.tick(goog.labs.net.webChannel.netUtils.NETWORK_TIMEOUT);
assertEquals('Should remain closed after the ping timeout.',
goog.labs.net.webChannel.WebChannelBase.State.CLOSED, channel.getState());
assertEquals(1, numTimingEvents);
}
function testStatEventReportedOnlyOnce() {
stubNetUtils();
connect();
sendMap('foo', 'bar');
numStatEvents = 0;
lastStatEvent = null;
responseUnknownSessionId();
assertEquals(1, numStatEvents);
assertEquals(goog.labs.net.webChannel.requestStats.Stat.ERROR_OTHER,
lastStatEvent);
numStatEvents = 0;
mockClock.tick(goog.labs.net.webChannel.netUtils.NETWORK_TIMEOUT);
assertEquals('No new stat events should be reported.', 0, numStatEvents);
}
function testStatEventReportedOnlyOnce_onNetworkUp() {
stubNetUtils();
connect();
sendMap('foo', 'bar');
numStatEvents = 0;
lastStatEvent = null;
responseRequestFailed();
assertEquals('No stat event should be reported before we know the reason.',
0, numStatEvents);
// Let the ping time out.
mockClock.tick(goog.labs.net.webChannel.netUtils.NETWORK_TIMEOUT);
// Assert we report the correct stat event.
assertEquals(1, numStatEvents);
assertEquals(
goog.labs.net.webChannel.requestStats.Stat.ERROR_NETWORK,
lastStatEvent);
}
function testStatEventReportedOnlyOnce_onNetworkDown() {
stubNetUtils();
connect();
sendMap('foo', 'bar');
numStatEvents = 0;
lastStatEvent = null;
responseRequestFailed();
assertEquals('No stat event should be reported before we know the reason.',
0, numStatEvents);
// Wait half the ping timeout period, and then fake the network being up.
mockClock.tick(goog.labs.net.webChannel.netUtils.NETWORK_TIMEOUT / 2);
channel.testNetworkCallback_(true);
// Assert we report the correct stat event.
assertEquals(1, numStatEvents);
assertEquals(goog.labs.net.webChannel.requestStats.Stat.ERROR_OTHER,
lastStatEvent);
}
function testOutgoingMapsAwaitsResponse() {
connect();
outgoingMapsAwaitsResponse();
}
function testOutgoingMapsAwaitsResponseWithSpdyEnabled() {
connect(undefined, undefined, undefined, true);
outgoingMapsAwaitsResponse();
}
function outgoingMapsAwaitsResponse() {
assertEquals(0, channel.outgoingMaps_.length);
sendMap('foo1', 'bar');
assertEquals(0, channel.outgoingMaps_.length);
sendMap('foo2', 'bar');
assertEquals(1, channel.outgoingMaps_.length);
sendMap('foo3', 'bar');
assertEquals(2, channel.outgoingMaps_.length);
sendMap('foo4', 'bar');
assertEquals(3, channel.outgoingMaps_.length);
responseDone();
// Now the forward channel request is completed and a new started, so all maps
// are dequeued from the array of outgoing maps into this new forward request.
assertEquals(0, channel.outgoingMaps_.length);
}
function testUndeliveredMaps_doesNotNotifyWhenSuccessful() {
/**
* @suppress {checkTypes} The callback function type declaration is skipped.
*/
handler.channelClosed = function(
channel, opt_pendingMaps, opt_undeliveredMaps) {
if (opt_pendingMaps || opt_undeliveredMaps) {
fail('No pending or undelivered maps should be reported.');
}
};
connect();
sendMap('foo1', 'bar1');
responseDone();
sendMap('foo2', 'bar2');
responseDone();
disconnect();
}
function testUndeliveredMaps_doesNotNotifyIfNothingWasSent() {
/**
* @suppress {checkTypes} The callback function type declaration is skipped.
*/
handler.channelClosed = function(
channel, opt_pendingMaps, opt_undeliveredMaps) {
if (opt_pendingMaps || opt_undeliveredMaps) {
fail('No pending or undelivered maps should be reported.');
}
};
connect();
mockClock.tick(ALL_DAY_MS);
disconnect();
}
function testUndeliveredMaps_clearsPendingMapsAfterNotifying() {
connect();
sendMap('foo1', 'bar1');
sendMap('foo2', 'bar2');
sendMap('foo3', 'bar3');
assertEquals(1, channel.pendingMaps_.length);
assertEquals(2, channel.outgoingMaps_.length);
disconnect();
assertEquals(0, channel.pendingMaps_.length);
assertEquals(0, channel.outgoingMaps_.length);
}
function testUndeliveredMaps_notifiesWithContext() {
connect();
// First send two messages that succeed.
sendMap('foo1', 'bar1', 'context1');
responseDone();
sendMap('foo2', 'bar2', 'context2');
responseDone();
// Pretend the server hangs and no longer responds.
sendMap('foo3', 'bar3', 'context3');
sendMap('foo4', 'bar4', 'context4');
sendMap('foo5', 'bar5', 'context5');
// Give up.
disconnect();
// Assert that we are informed of any undelivered messages; both about
// #3 that was sent but which we don't know if the server received, and
// #4 and #5 which remain in the outgoing maps and have not yet been sent.
assertEquals('foo3:bar3:context3', handler.pendingMapsString);
assertEquals('foo4:bar4:context4, foo5:bar5:context5',
handler.undeliveredMapsString);
}
function testUndeliveredMaps_serviceUnavailable() {
// Send a few maps, and let one fail.
connect();
sendMap('foo1', 'bar1');
responseDone();
sendMap('foo2', 'bar2');
responseRequestFailed();
// After a failure, the channel should be closed.
disconnect();
assertEquals('foo2:bar2', handler.pendingMapsString);
assertEquals('', handler.undeliveredMapsString);
}
function testUndeliveredMaps_onPingTimeout() {
stubNetUtils();
connect();
// Send a message.
sendMap('foo1', 'bar1');
// Fake REQUEST_FAILED, triggering a ping to check the network.
responseRequestFailed();
// Let the ping time out, unsuccessfully.
mockClock.tick(goog.labs.net.webChannel.netUtils.NETWORK_TIMEOUT);
// Assert channel is closed.
assertEquals(goog.labs.net.webChannel.WebChannelBase.State.CLOSED,
channel.getState());
// Assert that the handler is notified about the undelivered messages.
assertEquals('foo1:bar1', handler.pendingMapsString);
assertEquals('', handler.undeliveredMapsString);
}
function testResponseNoBackchannelPostNotBeforeBackchannel() {
connect(8);
sendMap('foo1', 'bar1');
mockClock.tick(10);
assertFalse(channel.backChannelRequest_.getRequestStartTime() <
getSingleForwardRequest().getRequestStartTime());
responseNoBackchannel();
assertNotEquals(
goog.labs.net.webChannel.requestStats.Stat.BACKCHANNEL_MISSING,
lastStatEvent);
}
function testResponseNoBackchannel() {
connect(8);
sendMap('foo1', 'bar1');
response(-1, 0);
mockClock.tick(goog.labs.net.webChannel.WebChannelBase.RTT_ESTIMATE + 1);
sendMap('foo2', 'bar2');
assertTrue(channel.backChannelRequest_.getRequestStartTime() +
goog.labs.net.webChannel.WebChannelBase.RTT_ESTIMATE <
getSingleForwardRequest().getRequestStartTime());
responseNoBackchannel();
assertEquals(
goog.labs.net.webChannel.requestStats.Stat.BACKCHANNEL_MISSING,
lastStatEvent);
}
function testResponseNoBackchannelWithNoBackchannel() {
connect(8);
sendMap('foo1', 'bar1');
assertNull(channel.backChannelTimerId_);
channel.backChannelRequest_.cancel();
channel.backChannelRequest_ = null;
responseNoBackchannel();
assertEquals(
goog.labs.net.webChannel.requestStats.Stat.BACKCHANNEL_MISSING,
lastStatEvent);
}
function testResponseNoBackchannelWithStartTimer() {
connect(8);
sendMap('foo1', 'bar1');
channel.backChannelRequest_.cancel();
channel.backChannelRequest_ = null;
channel.backChannelTimerId_ = 123;
responseNoBackchannel();
assertNotEquals(
goog.labs.net.webChannel.requestStats.Stat.BACKCHANNEL_MISSING,
lastStatEvent);
}
function testResponseWithNoArraySent() {
connect(8);
sendMap('foo1', 'bar1');
// Send a response as if the server hasn't sent down an array.
response(-1, 0);
// POST response with an array ID lower than our last received is OK.
assertEquals(1, channel.lastArrayId_);
assertEquals(-1, channel.lastPostResponseArrayId_);
}
function testResponseWithArraysMissing() {
connect(8);
sendMap('foo1', 'bar1');
assertEquals(-1, channel.lastPostResponseArrayId_);
// Send a response as if the server has sent down seven arrays.
response(7, 111);
assertEquals(1, channel.lastArrayId_);
assertEquals(7, channel.lastPostResponseArrayId_);
mockClock.tick(goog.labs.net.webChannel.WebChannelBase.RTT_ESTIMATE * 2);
assertEquals(
goog.labs.net.webChannel.requestStats.Stat.BACKCHANNEL_DEAD,
lastStatEvent);
}
function testMultipleResponsesWithArraysMissing() {
connect(8);
sendMap('foo1', 'bar1');
assertEquals(-1, channel.lastPostResponseArrayId_);
// Send a response as if the server has sent down seven arrays.
response(7, 111);
assertEquals(1, channel.lastArrayId_);
assertEquals(7, channel.lastPostResponseArrayId_);
sendMap('foo2', 'bar2');
mockClock.tick(goog.labs.net.webChannel.WebChannelBase.RTT_ESTIMATE);
response(8, 119);
mockClock.tick(goog.labs.net.webChannel.WebChannelBase.RTT_ESTIMATE);
// The original timer should still fire.
assertEquals(
goog.labs.net.webChannel.requestStats.Stat.BACKCHANNEL_DEAD,
lastStatEvent);
}
function testOnlyRetryOnceBasedOnResponse() {
connect(8);
sendMap('foo1', 'bar1');
assertEquals(-1, channel.lastPostResponseArrayId_);
// Send a response as if the server has sent down seven arrays.
response(7, 111);
assertEquals(1, channel.lastArrayId_);
assertEquals(7, channel.lastPostResponseArrayId_);
assertTrue(hasDeadBackChannelTimer());
mockClock.tick(goog.labs.net.webChannel.WebChannelBase.RTT_ESTIMATE * 2);
assertEquals(
goog.labs.net.webChannel.requestStats.Stat.BACKCHANNEL_DEAD,
lastStatEvent);
assertEquals(1, channel.backChannelRetryCount_);
mockClock.tick(goog.labs.net.webChannel.WebChannelBase.RTT_ESTIMATE);
sendMap('foo2', 'bar2');
assertFalse(hasDeadBackChannelTimer());
response(8, 119);
assertFalse(hasDeadBackChannelTimer());
}
function testResponseWithArraysMissingAndLiveChannel() {
connect(8);
sendMap('foo1', 'bar1');
assertEquals(-1, channel.lastPostResponseArrayId_);
// Send a response as if the server has sent down seven arrays.
response(7, 111);
assertEquals(1, channel.lastArrayId_);
assertEquals(7, channel.lastPostResponseArrayId_);
mockClock.tick(goog.labs.net.webChannel.WebChannelBase.RTT_ESTIMATE);
assertTrue(hasDeadBackChannelTimer());
receive('["ack"]');
assertFalse(hasDeadBackChannelTimer());
mockClock.tick(goog.labs.net.webChannel.WebChannelBase.RTT_ESTIMATE);
assertNotEquals(
goog.labs.net.webChannel.requestStats.Stat.BACKCHANNEL_DEAD,
lastStatEvent);
}
function testResponseWithBigOutstandingData() {
connect(8);
sendMap('foo1', 'bar1');
assertEquals(-1, channel.lastPostResponseArrayId_);
// Send a response as if the server has sent down seven arrays and 50kbytes.
response(7, 50000);
assertEquals(1, channel.lastArrayId_);
assertEquals(7, channel.lastPostResponseArrayId_);
assertFalse(hasDeadBackChannelTimer());
mockClock.tick(goog.labs.net.webChannel.WebChannelBase.RTT_ESTIMATE * 2);
assertNotEquals(
goog.labs.net.webChannel.requestStats.Stat.BACKCHANNEL_DEAD,
lastStatEvent);
}
function testResponseInBufferedMode() {
connect(8);
channel.useChunked_ = false;
sendMap('foo1', 'bar1');
assertEquals(-1, channel.lastPostResponseArrayId_);
response(7, 111);
assertEquals(1, channel.lastArrayId_);
assertEquals(7, channel.lastPostResponseArrayId_);
assertFalse(hasDeadBackChannelTimer());
mockClock.tick(goog.labs.net.webChannel.WebChannelBase.RTT_ESTIMATE * 2);
assertNotEquals(
goog.labs.net.webChannel.requestStats.Stat.BACKCHANNEL_DEAD,
lastStatEvent);
}
function testResponseWithGarbage() {
connect(8);
sendMap('foo1', 'bar1');
channel.onRequestData(
getSingleForwardRequest(),
'garbage'
);
assertEquals(goog.labs.net.webChannel.WebChannelBase.State.CLOSED,
channel.getState());
}
function testResponseWithGarbageInArray() {
connect(8);
sendMap('foo1', 'bar1');
channel.onRequestData(
getSingleForwardRequest(),
'["garbage"]'
);
assertEquals(goog.labs.net.webChannel.WebChannelBase.State.CLOSED,
channel.getState());
}
function testResponseWithEvilData() {
connect(8);
sendMap('foo1', 'bar1');
channel.onRequestData(
getSingleForwardRequest(),
'foo=<script>evil()\<\/script>&' + 'bar=<script>moreEvil()\<\/script>');
assertEquals(goog.labs.net.webChannel.WebChannelBase.State.CLOSED,
channel.getState());
}
function testPathAbsolute() {
connect(8, undefined, '/talkgadget');
assertEquals(channel.backChannelUri_.getDomain(),
window.location.hostname);
assertEquals(channel.forwardChannelUri_.getDomain(),
window.location.hostname);
}
function testPathRelative() {
connect(8, undefined, 'talkgadget');
assertEquals(channel.backChannelUri_.getDomain(),
window.location.hostname);
assertEquals(channel.forwardChannelUri_.getDomain(),
window.location.hostname);
}
function testPathWithHost() {
connect(8, undefined, 'https://example.com');
assertEquals(channel.backChannelUri_.getScheme(), 'https');
assertEquals(channel.backChannelUri_.getDomain(), 'example.com');
assertEquals(channel.forwardChannelUri_.getScheme(), 'https');
assertEquals(channel.forwardChannelUri_.getDomain(), 'example.com');
}
function testCreateXhrIo() {
var xhr = channel.createXhrIo(null);
assertFalse(xhr.getWithCredentials());
assertThrows(
'Error connection to different host without CORS',
goog.bind(channel.createXhrIo, channel, 'some_host'));
channel.setSupportsCrossDomainXhrs(true);
xhr = channel.createXhrIo(null);
assertTrue(xhr.getWithCredentials());
xhr = channel.createXhrIo('some_host');
assertTrue(xhr.getWithCredentials());
}
function testSpdyLimitOption() {
var webChannelTransport =
new goog.labs.net.webChannel.WebChannelBaseTransport();
stubSpdyCheck(true);
var webChannelDefault = webChannelTransport.createWebChannel('/foo');
assertEquals(10,
webChannelDefault.getRuntimeProperties().getConcurrentRequestLimit());
assertTrue(webChannelDefault.getRuntimeProperties().isSpdyEnabled());
var options = {'concurrentRequestLimit': 100};
stubSpdyCheck(false);
var webChannelDisabled = webChannelTransport.createWebChannel(
'/foo', options);
assertEquals(1,
webChannelDisabled.getRuntimeProperties().getConcurrentRequestLimit());
assertFalse(webChannelDisabled.getRuntimeProperties().isSpdyEnabled());
stubSpdyCheck(true);
var webChannelEnabled = webChannelTransport.createWebChannel('/foo', options);
assertEquals(100,
webChannelEnabled.getRuntimeProperties().getConcurrentRequestLimit());
assertTrue(webChannelEnabled.getRuntimeProperties().isSpdyEnabled());
}
|
/// <reference path='../typings/tsd.d.ts' />
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, '/../views'));
app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, '/../public')));
app.get('/', function (req, res) {
res.render('index');
});
var port = process.env.PORT || 3000;
var server = app.listen(port, function () {
var listeningPort = server.address().port;
console.log('The server is listening on port: ' + listeningPort);
});
|
/*!
* js-comments <https://githuc.com/jonschlinkert/js-comments>
*
* Copyright (c) 2014 Jon Schlinkert, contributors
* Licensed under the MIT License (MIT)
*/
var file = require('fs-utils');
var expect = require('chai').expect;
var strip = require('strip-banner');
function readFixture(src) {
var str = file.readFileSync('test/fixtures/' + src + '.js');
return strip(str);
}
describe('utils:', function () {
it('should strip banners', function () {
var actual = readFixture('params');
expect(actual).to.have.length.of.at.least(0);
});
}); |
/*
* Built-in functions internal prototype is required to be the initial
* Function.prototype. This prevents Duktape/C functions from having
* an intermediate prototype providing a virtual 'length'.
*/
/*===
true
===*/
try {
print(Object.getPrototypeOf(Math.cos) === Function.prototype);
} catch (e) {
print(e);
}
|
export * from './inputswitch';
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicHVibGljX2FwaS5qcyIsInNvdXJjZVJvb3QiOiIuLi8uLi8uLi9zcmMvYXBwL2NvbXBvbmVudHMvaW5wdXRzd2l0Y2gvIiwic291cmNlcyI6WyJwdWJsaWNfYXBpLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLGNBQWMsZUFBZSxDQUFDIiwic291cmNlc0NvbnRlbnQiOlsiZXhwb3J0ICogZnJvbSAnLi9pbnB1dHN3aXRjaCc7Il19 |
/*************************************************************
*
* MathJax/localization/qqq/MathML.js
*
* Copyright (c) 2009-2016 The MathJax Consortium
*
* 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.
*
*/
MathJax.Localization.addTranslation("qqq","MathML",{
version: "2.7.2",
isLoaded: true,
strings: {
BadMglyph: "This error is displayed when processing a MathML mglyph element with a bad URL. Parameters:\n* %1 - the value of the src attribute",
BadMglyphFont: "Parameters:\n* %1 - font family",
MathPlayer: "This alert is displayed when the Native MathML output Jax fails to set up MathPlayer. The instructions are IE specific.\n\nThe new line character is used to force new lines in the alert box.",
CantCreateXMLParser: "This alert is displayed when the MathML input Jax fails to create an XML parser. The instructions are IE specific.\n\nThe new line character is used to force new lines in the alert box.",
UnknownNodeType: "Used as error message. Parameters:\n* %1 - node type",
UnexpectedTextNode: "Used as error message. Parameters:\n* %1 - text, enclosed in \"'\"",
ErrorParsingMathML: "This error is displayed when a MathML element fails to be parsed.\n\nIt can only be produced by old versions of Internet Explorer.",
ParsingError: "This error is displayed when an XML parsing error happens.\n\nThe argument is the error returned by the XML parser.",
MathMLSingleElement: "This error is displayed when a MathML input Jax contains more than one \u003Ccode\u003E\u003Cnowiki\u003E\u003Cmath\u003E\u003C/nowiki\u003E\u003C/code\u003E root.\n\nIt can only be produced by very old browsers.",
MathMLRootElement: "{{doc-important|Do not translate the \u003Ccode\u003E\u003Cnowiki\u003E\u003Cmath\u003E\u003C/nowiki\u003E\u003C/code\u003E tag! It is a MathML tag.}} \n\nThis error is displayed when a MathML input Jax contains a root other than \u003Ccode\u003E\u003Cnowiki\u003E\u003Cmath\u003E\u003C/nowiki\u003E\u003C/code\u003E.\n\nParameters:\n* %1 - the root name"
}
});
MathJax.Ajax.loadComplete("[MathJax]/localization/qqq/MathML.js");
|
steal.loading('steal/test/package/1.js','steal/test/package/0.js','steal/test/package/2.js');
steal("./0.js").then(function(){
packagesStolen.push("1");
},"./2.js");
;
steal.loaded('steal/test/package/1.js');
steal(function(){
packagesStolen = ["0"]
});
steal.loaded('steal/test/package/0.js');
packagesStolen.push("2");;
steal.loaded('steal/test/package/2.js'); |
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
import { loopAsync } from './AsyncUtils';
import { isPromise } from './PromiseUtils';
import { matchPattern } from './PatternUtils';
import warning from './routerWarning';
import { createRoutes } from './RouteUtils';
function getChildRoutes(route, location, paramNames, paramValues, callback) {
if (route.childRoutes) {
return [null, route.childRoutes];
}
if (!route.getChildRoutes) {
return [];
}
var sync = true,
result = void 0;
var partialNextState = {
location: location,
params: createParams(paramNames, paramValues)
};
var childRoutesReturn = route.getChildRoutes(partialNextState, function (error, childRoutes) {
childRoutes = !error && createRoutes(childRoutes);
if (sync) {
result = [error, childRoutes];
return;
}
callback(error, childRoutes);
});
if (isPromise(childRoutesReturn)) childRoutesReturn.then(function (childRoutes) {
return callback(null, createRoutes(childRoutes));
}, callback);
sync = false;
return result; // Might be undefined.
}
function getIndexRoute(route, location, paramNames, paramValues, callback) {
if (route.indexRoute) {
callback(null, route.indexRoute);
} else if (route.getIndexRoute) {
var partialNextState = {
location: location,
params: createParams(paramNames, paramValues)
};
var indexRoutesReturn = route.getIndexRoute(partialNextState, function (error, indexRoute) {
callback(error, !error && createRoutes(indexRoute)[0]);
});
if (isPromise(indexRoutesReturn)) indexRoutesReturn.then(function (indexRoute) {
return callback(null, createRoutes(indexRoute)[0]);
}, callback);
} else if (route.childRoutes) {
(function () {
var pathless = route.childRoutes.filter(function (childRoute) {
return !childRoute.path;
});
loopAsync(pathless.length, function (index, next, done) {
getIndexRoute(pathless[index], location, paramNames, paramValues, function (error, indexRoute) {
if (error || indexRoute) {
var routes = [pathless[index]].concat(Array.isArray(indexRoute) ? indexRoute : [indexRoute]);
done(error, routes);
} else {
next();
}
});
}, function (err, routes) {
callback(null, routes);
});
})();
} else {
callback();
}
}
function assignParams(params, paramNames, paramValues) {
return paramNames.reduce(function (params, paramName, index) {
var paramValue = paramValues && paramValues[index];
if (Array.isArray(params[paramName])) {
params[paramName].push(paramValue);
} else if (paramName in params) {
params[paramName] = [params[paramName], paramValue];
} else {
params[paramName] = paramValue;
}
return params;
}, params);
}
function createParams(paramNames, paramValues) {
return assignParams({}, paramNames, paramValues);
}
function matchRouteDeep(route, location, remainingPathname, paramNames, paramValues, callback) {
var pattern = route.path || '';
if (pattern.charAt(0) === '/') {
remainingPathname = location.pathname;
paramNames = [];
paramValues = [];
}
// Only try to match the path if the route actually has a pattern, and if
// we're not just searching for potential nested absolute paths.
if (remainingPathname !== null && pattern) {
try {
var matched = matchPattern(pattern, remainingPathname);
if (matched) {
remainingPathname = matched.remainingPathname;
paramNames = [].concat(paramNames, matched.paramNames);
paramValues = [].concat(paramValues, matched.paramValues);
} else {
remainingPathname = null;
}
} catch (error) {
callback(error);
}
// By assumption, pattern is non-empty here, which is the prerequisite for
// actually terminating a match.
if (remainingPathname === '') {
var _ret2 = function () {
var match = {
routes: [route],
params: createParams(paramNames, paramValues)
};
getIndexRoute(route, location, paramNames, paramValues, function (error, indexRoute) {
if (error) {
callback(error);
} else {
if (Array.isArray(indexRoute)) {
var _match$routes;
process.env.NODE_ENV !== 'production' ? warning(indexRoute.every(function (route) {
return !route.path;
}), 'Index routes should not have paths') : void 0;
(_match$routes = match.routes).push.apply(_match$routes, indexRoute);
} else if (indexRoute) {
process.env.NODE_ENV !== 'production' ? warning(!indexRoute.path, 'Index routes should not have paths') : void 0;
match.routes.push(indexRoute);
}
callback(null, match);
}
});
return {
v: void 0
};
}();
if ((typeof _ret2 === 'undefined' ? 'undefined' : _typeof(_ret2)) === "object") return _ret2.v;
}
}
if (remainingPathname != null || route.childRoutes) {
// Either a) this route matched at least some of the path or b)
// we don't have to load this route's children asynchronously. In
// either case continue checking for matches in the subtree.
var onChildRoutes = function onChildRoutes(error, childRoutes) {
if (error) {
callback(error);
} else if (childRoutes) {
// Check the child routes to see if any of them match.
matchRoutes(childRoutes, location, function (error, match) {
if (error) {
callback(error);
} else if (match) {
// A child route matched! Augment the match and pass it up the stack.
match.routes.unshift(route);
callback(null, match);
} else {
callback();
}
}, remainingPathname, paramNames, paramValues);
} else {
callback();
}
};
var result = getChildRoutes(route, location, paramNames, paramValues, onChildRoutes);
if (result) {
onChildRoutes.apply(undefined, result);
}
} else {
callback();
}
}
/**
* Asynchronously matches the given location to a set of routes and calls
* callback(error, state) when finished. The state object will have the
* following properties:
*
* - routes An array of routes that matched, in hierarchical order
* - params An object of URL parameters
*
* Note: This operation may finish synchronously if no routes have an
* asynchronous getChildRoutes method.
*/
export default function matchRoutes(routes, location, callback, remainingPathname) {
var paramNames = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : [];
var paramValues = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : [];
if (remainingPathname === undefined) {
// TODO: This is a little bit ugly, but it works around a quirk in history
// that strips the leading slash from pathnames when using basenames with
// trailing slashes.
if (location.pathname.charAt(0) !== '/') {
location = _extends({}, location, {
pathname: '/' + location.pathname
});
}
remainingPathname = location.pathname;
}
loopAsync(routes.length, function (index, next, done) {
matchRouteDeep(routes[index], location, remainingPathname, paramNames, paramValues, function (error, match) {
if (error || match) {
done(error, match);
} else {
next();
}
});
}, callback);
} |
/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'liststyle', 'bs', {
armenian: 'Armenian numbering',
bulletedTitle: 'Bulleted List Properties',
circle: 'Circle',
decimal: 'Decimal (1, 2, 3, etc.)',
decimalLeadingZero: 'Decimal leading zero (01, 02, 03, etc.)',
disc: 'Disc',
georgian: 'Georgian numbering (an, ban, gan, etc.)',
lowerAlpha: 'Lower Alpha (a, b, c, d, e, etc.)',
lowerGreek: 'Lower Greek (alpha, beta, gamma, etc.)',
lowerRoman: 'Lower Roman (i, ii, iii, iv, v, etc.)',
none: 'None',
notset: '<not set>',
numberedTitle: 'Numbered List Properties',
square: 'Square',
start: 'Start',
type: 'Type',
upperAlpha: 'Upper Alpha (A, B, C, D, E, etc.)',
upperRoman: 'Upper Roman (I, II, III, IV, V, etc.)',
validateStartNumber: 'List start number must be a whole number.'
} );
|
/*!
* jQuery UI Accordion @VERSION
* http://jqueryui.com
*
* Copyright 2013 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/accordion/
*
* Depends:
* jquery.ui.core.js
* jquery.ui.widget.js
*/
(function( $, undefined ) {
var uid = 0,
hideProps = {},
showProps = {};
hideProps.height = hideProps.paddingTop = hideProps.paddingBottom =
hideProps.borderTopWidth = hideProps.borderBottomWidth = "hide";
showProps.height = showProps.paddingTop = showProps.paddingBottom =
showProps.borderTopWidth = showProps.borderBottomWidth = "show";
$.widget( "ui.accordion", {
version: "@VERSION",
options: {
active: 0,
animate: {},
collapsible: false,
event: "click",
header: "> li > :first-child,> :not(li):even",
heightStyle: "auto",
icons: {
activeHeader: "ui-icon-triangle-1-s",
header: "ui-icon-triangle-1-e"
},
// callbacks
activate: null,
beforeActivate: null
},
_create: function() {
var options = this.options;
this.prevShow = this.prevHide = $();
this.element.addClass( "ui-accordion ui-widget ui-helper-reset" )
// ARIA
.attr( "role", "tablist" );
// don't allow collapsible: false and active: false / null
if ( !options.collapsible && (options.active === false || options.active == null) ) {
options.active = 0;
}
this._processPanels();
// handle negative values
if ( options.active < 0 ) {
options.active += this.headers.length;
}
this._refresh();
},
_getCreateEventData: function() {
return {
header: this.active,
panel: !this.active.length ? $() : this.active.next()
};
},
_createIcons: function() {
var icons = this.options.icons;
if ( icons ) {
$( "<span>" )
.addClass( "ui-accordion-header-icon ui-icon " + icons.header )
.prependTo( this.headers );
this.active.children( ".ui-accordion-header-icon" )
.removeClass( icons.header )
.addClass( icons.activeHeader );
this.headers.addClass( "ui-accordion-icons" );
}
},
_destroyIcons: function() {
this.headers
.removeClass( "ui-accordion-icons" )
.children( ".ui-accordion-header-icon" )
.remove();
},
_destroy: function() {
var contents;
// clean up main element
this.element
.removeClass( "ui-accordion ui-widget ui-helper-reset" )
.removeAttr( "role" );
// clean up headers
this.headers
.removeClass( "ui-accordion-header ui-accordion-header-active ui-state-default ui-corner-all ui-state-active ui-state-disabled ui-corner-top" )
.removeAttr( "role" )
.removeAttr( "aria-selected" )
.removeAttr( "aria-controls" )
.removeAttr( "tabIndex" )
.each(function() {
if ( /^ui-accordion/.test( this.id ) ) {
this.removeAttribute( "id" );
}
});
this._destroyIcons();
// clean up content panels
contents = this.headers.next()
.css( "display", "" )
.removeAttr( "role" )
.removeAttr( "aria-expanded" )
.removeAttr( "aria-hidden" )
.removeAttr( "aria-labelledby" )
.removeClass( "ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active ui-state-disabled" )
.each(function() {
if ( /^ui-accordion/.test( this.id ) ) {
this.removeAttribute( "id" );
}
});
if ( this.options.heightStyle !== "content" ) {
contents.css( "height", "" );
}
},
_setOption: function( key, value ) {
if ( key === "active" ) {
// _activate() will handle invalid values and update this.options
this._activate( value );
return;
}
if ( key === "event" ) {
if ( this.options.event ) {
this._off( this.headers, this.options.event );
}
this._setupEvents( value );
}
this._super( key, value );
// setting collapsible: false while collapsed; open first panel
if ( key === "collapsible" && !value && this.options.active === false ) {
this._activate( 0 );
}
if ( key === "icons" ) {
this._destroyIcons();
if ( value ) {
this._createIcons();
}
}
// #5332 - opacity doesn't cascade to positioned elements in IE
// so we need to add the disabled class to the headers and panels
if ( key === "disabled" ) {
this.element
.toggleClass( "ui-state-disabled", !!value )
.attr( "aria-disabled", value );
this.headers.add( this.headers.next() )
.toggleClass( "ui-state-disabled", !!value );
}
},
_keydown: function( event ) {
if ( event.altKey || event.ctrlKey ) {
return;
}
var keyCode = $.ui.keyCode,
length = this.headers.length,
currentIndex = this.headers.index( event.target ),
toFocus = false;
switch ( event.keyCode ) {
case keyCode.RIGHT:
case keyCode.DOWN:
toFocus = this.headers[ ( currentIndex + 1 ) % length ];
break;
case keyCode.LEFT:
case keyCode.UP:
toFocus = this.headers[ ( currentIndex - 1 + length ) % length ];
break;
case keyCode.SPACE:
case keyCode.ENTER:
this._eventHandler( event );
break;
case keyCode.HOME:
toFocus = this.headers[ 0 ];
break;
case keyCode.END:
toFocus = this.headers[ length - 1 ];
break;
}
if ( toFocus ) {
$( event.target ).attr( "tabIndex", -1 );
$( toFocus ).attr( "tabIndex", 0 );
toFocus.focus();
event.preventDefault();
}
},
_panelKeyDown : function( event ) {
if ( event.keyCode === $.ui.keyCode.UP && event.ctrlKey ) {
$( event.currentTarget ).prev().focus();
}
},
refresh: function() {
var options = this.options;
this._processPanels();
// was collapsed or no panel
if ( ( options.active === false && options.collapsible === true ) || !this.headers.length ) {
options.active = false;
this.active = $();
// active false only when collapsible is true
} else if ( options.active === false ) {
this._activate( 0 );
// was active, but active panel is gone
} else if ( this.active.length && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) {
// all remaining panel are disabled
if ( this.headers.length === this.headers.find(".ui-state-disabled").length ) {
options.active = false;
this.active = $();
// activate previous panel
} else {
this._activate( Math.max( 0, options.active - 1 ) );
}
// was active, active panel still exists
} else {
// make sure active index is correct
options.active = this.headers.index( this.active );
}
this._destroyIcons();
this._refresh();
},
_processPanels: function() {
this.headers = this.element.find( this.options.header )
.addClass( "ui-accordion-header ui-state-default ui-corner-all" );
this.headers.next()
.addClass( "ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom" )
.filter(":not(.ui-accordion-content-active)")
.hide();
},
_refresh: function() {
var maxHeight,
options = this.options,
heightStyle = options.heightStyle,
parent = this.element.parent(),
accordionId = this.accordionId = "ui-accordion-" +
(this.element.attr( "id" ) || ++uid);
this.active = this._findActive( options.active )
.addClass( "ui-accordion-header-active ui-state-active ui-corner-top" )
.removeClass( "ui-corner-all" );
this.active.next()
.addClass( "ui-accordion-content-active" )
.show();
this.headers
.attr( "role", "tab" )
.each(function( i ) {
var header = $( this ),
headerId = header.attr( "id" ),
panel = header.next(),
panelId = panel.attr( "id" );
if ( !headerId ) {
headerId = accordionId + "-header-" + i;
header.attr( "id", headerId );
}
if ( !panelId ) {
panelId = accordionId + "-panel-" + i;
panel.attr( "id", panelId );
}
header.attr( "aria-controls", panelId );
panel.attr( "aria-labelledby", headerId );
})
.next()
.attr( "role", "tabpanel" );
this.headers
.not( this.active )
.attr({
"aria-selected": "false",
tabIndex: -1
})
.next()
.attr({
"aria-expanded": "false",
"aria-hidden": "true"
})
.hide();
// make sure at least one header is in the tab order
if ( !this.active.length ) {
this.headers.eq( 0 ).attr( "tabIndex", 0 );
} else {
this.active.attr({
"aria-selected": "true",
tabIndex: 0
})
.next()
.attr({
"aria-expanded": "true",
"aria-hidden": "false"
});
}
this._createIcons();
this._setupEvents( options.event );
if ( heightStyle === "fill" ) {
maxHeight = parent.height();
this.element.siblings( ":visible" ).each(function() {
var elem = $( this ),
position = elem.css( "position" );
if ( position === "absolute" || position === "fixed" ) {
return;
}
maxHeight -= elem.outerHeight( true );
});
this.headers.each(function() {
maxHeight -= $( this ).outerHeight( true );
});
this.headers.next()
.each(function() {
$( this ).height( Math.max( 0, maxHeight -
$( this ).innerHeight() + $( this ).height() ) );
})
.css( "overflow", "auto" );
} else if ( heightStyle === "auto" ) {
maxHeight = 0;
this.headers.next()
.each(function() {
maxHeight = Math.max( maxHeight, $( this ).css( "height", "" ).height() );
})
.height( maxHeight );
}
},
_activate: function( index ) {
var active = this._findActive( index )[ 0 ];
// trying to activate the already active panel
if ( active === this.active[ 0 ] ) {
return;
}
// trying to collapse, simulate a click on the currently active header
active = active || this.active[ 0 ];
this._eventHandler({
target: active,
currentTarget: active,
preventDefault: $.noop
});
},
_findActive: function( selector ) {
return typeof selector === "number" ? this.headers.eq( selector ) : $();
},
_setupEvents: function( event ) {
var events = {
keydown: "_keydown"
};
if ( event ) {
$.each( event.split(" "), function( index, eventName ) {
events[ eventName ] = "_eventHandler";
});
}
this._off( this.headers.add( this.headers.next() ) );
this._on( this.headers, events );
this._on( this.headers.next(), { keydown: "_panelKeyDown" });
this._hoverable( this.headers );
this._focusable( this.headers );
},
_eventHandler: function( event ) {
var options = this.options,
active = this.active,
clicked = $( event.currentTarget ),
clickedIsActive = clicked[ 0 ] === active[ 0 ],
collapsing = clickedIsActive && options.collapsible,
toShow = collapsing ? $() : clicked.next(),
toHide = active.next(),
eventData = {
oldHeader: active,
oldPanel: toHide,
newHeader: collapsing ? $() : clicked,
newPanel: toShow
};
event.preventDefault();
if (
// click on active header, but not collapsible
( clickedIsActive && !options.collapsible ) ||
// allow canceling activation
( this._trigger( "beforeActivate", event, eventData ) === false ) ) {
return;
}
options.active = collapsing ? false : this.headers.index( clicked );
// when the call to ._toggle() comes after the class changes
// it causes a very odd bug in IE 8 (see #6720)
this.active = clickedIsActive ? $() : clicked;
this._toggle( eventData );
// switch classes
// corner classes on the previously active header stay after the animation
active.removeClass( "ui-accordion-header-active ui-state-active" );
if ( options.icons ) {
active.children( ".ui-accordion-header-icon" )
.removeClass( options.icons.activeHeader )
.addClass( options.icons.header );
}
if ( !clickedIsActive ) {
clicked
.removeClass( "ui-corner-all" )
.addClass( "ui-accordion-header-active ui-state-active ui-corner-top" );
if ( options.icons ) {
clicked.children( ".ui-accordion-header-icon" )
.removeClass( options.icons.header )
.addClass( options.icons.activeHeader );
}
clicked
.next()
.addClass( "ui-accordion-content-active" );
}
},
_toggle: function( data ) {
var toShow = data.newPanel,
toHide = this.prevShow.length ? this.prevShow : data.oldPanel;
// handle activating a panel during the animation for another activation
this.prevShow.add( this.prevHide ).stop( true, true );
this.prevShow = toShow;
this.prevHide = toHide;
if ( this.options.animate ) {
this._animate( toShow, toHide, data );
} else {
toHide.hide();
toShow.show();
this._toggleComplete( data );
}
toHide.attr({
"aria-expanded": "false",
"aria-hidden": "true"
});
toHide.prev().attr( "aria-selected", "false" );
// if we're switching panels, remove the old header from the tab order
// if we're opening from collapsed state, remove the previous header from the tab order
// if we're collapsing, then keep the collapsing header in the tab order
if ( toShow.length && toHide.length ) {
toHide.prev().attr( "tabIndex", -1 );
} else if ( toShow.length ) {
this.headers.filter(function() {
return $( this ).attr( "tabIndex" ) === 0;
})
.attr( "tabIndex", -1 );
}
toShow
.attr({
"aria-expanded": "true",
"aria-hidden": "false"
})
.prev()
.attr({
"aria-selected": "true",
tabIndex: 0
});
},
_animate: function( toShow, toHide, data ) {
var total, easing, duration,
that = this,
adjust = 0,
down = toShow.length &&
( !toHide.length || ( toShow.index() < toHide.index() ) ),
animate = this.options.animate || {},
options = down && animate.down || animate,
complete = function() {
that._toggleComplete( data );
};
if ( typeof options === "number" ) {
duration = options;
}
if ( typeof options === "string" ) {
easing = options;
}
// fall back from options to animation in case of partial down settings
easing = easing || options.easing || animate.easing;
duration = duration || options.duration || animate.duration;
if ( !toHide.length ) {
return toShow.animate( showProps, duration, easing, complete );
}
if ( !toShow.length ) {
return toHide.animate( hideProps, duration, easing, complete );
}
total = toShow.show().outerHeight();
toHide.animate( hideProps, {
duration: duration,
easing: easing,
step: function( now, fx ) {
fx.now = Math.round( now );
}
});
toShow
.hide()
.animate( showProps, {
duration: duration,
easing: easing,
complete: complete,
step: function( now, fx ) {
fx.now = Math.round( now );
if ( fx.prop !== "height" ) {
adjust += fx.now;
} else if ( that.options.heightStyle !== "content" ) {
fx.now = Math.round( total - toHide.outerHeight() - adjust );
adjust = 0;
}
}
});
},
_toggleComplete: function( data ) {
var toHide = data.oldPanel;
toHide
.removeClass( "ui-accordion-content-active" )
.prev()
.removeClass( "ui-corner-top" )
.addClass( "ui-corner-all" );
// Work around for rendering bug in IE (#5421)
if ( toHide.length ) {
toHide.parent()[0].className = toHide.parent()[0].className;
}
this._trigger( "activate", null, data );
}
});
})( jQuery );
|
/* global Pikaday */
var React = require('react');
var _ = require('underscore');
var moment = require('moment');
var Button = require('elemental').Button;
var FormField = require('elemental').FormField;
var FormInput = require('elemental').FormInput;
var lastId = 0;
function newItem(value) {
lastId++;
return { key: 'i' + lastId, value: value, picker: null };
}
module.exports = {
// set default properties
getDefaultProps: function() {
return {
format: 'YYYY-MM-DD',
pickers: []
};
},
getInitialState: function() {
return {
values: this.props.value.map(newItem)
};
},
componentWillReceiveProps: function(nextProps) {
if (nextProps.value.join('|') !== _.pluck(this.state.values, 'value').join('|')) {
this.setState({
values: nextProps.value.map(newItem)
});
}
},
componentWillUpdate: function() {
this.props.value.forEach(function (val, i) {
// Destroy each of our datepickers
if (this.props.pickers[i]) {
this.props.pickers[i].destroy();
}
}, this);
},
componentDidUpdate: function() {
this.props.value.forEach(function (val, i) {
var dateInput = this.getDOMNode().getElementsByClassName('datepicker_' + this.state.values[i].key)[0];
// Add a date picker to each updated field
this.props.pickers[i] = new Pikaday({
field: dateInput,
format: this.props.format,
onSelect: function(date) {//eslint-disable-line no-unused-vars
if (this.props.onChange && this.props.pickers[i].toString() !== val.value) {
this.props.value[i] = this.props.pickers[i].toString();
this.props.onChange(this.props.pickers[i].toString());
}
}.bind(this)
});
}, this);
},
componentDidMount: function() {
this.props.value.forEach(function (val, i) {
var dateInput = this.getDOMNode().getElementsByClassName('datepicker_' + this.state.values[i].key)[0];
if (this.props.pickers[i]) this.props.pickers[i].destroy();
this.props.pickers[i] = new Pikaday({
field: dateInput,
format: this.props.format,
onSelect: function(date) {//eslint-disable-line no-unused-vars
if (this.props.onChange && this.props.pickers[i].toString() !== val.value) {
this.props.value[i] = this.props.pickers[i].toString();
this.props.onChange(this.props.pickers[i].toString());
}
}.bind(this)
});
}, this);
},
addItem: function() {
var self = this;
var newValues = this.state.values.concat(newItem(''));
this.setState({
values: newValues
}, function() {
if (!self.state.values.length) return;
self.refs['item_' + self.state.values.length].getDOMNode().focus();
});
this.valueChanged(_.pluck(newValues, 'value'));
},
removeItem: function(i) {
var newValues = _.without(this.state.values, i);
this.setState({
values: newValues
}, function() {
this.refs.button.getDOMNode().focus();
});
this.valueChanged(_.pluck(newValues, 'value'));
},
updateItem: function(i, event) {
var updatedValues = this.state.values;
var updateIndex = updatedValues.indexOf(i);
updatedValues[updateIndex].value = this.cleanInput ? this.cleanInput(event.target.value) : event.target.value;
this.setState({
values: updatedValues
});
this.valueChanged(_.pluck(updatedValues, 'value'));
},
valueChanged: function(values) {
this.props.onChange({
path: this.props.path,
value: values
});
},
handleBlur: function(e) {//eslint-disable-line no-unused-vars
if (this.state.value === this.props.value) return;
this.picker.setMoment(moment(this.state.value, this.props.format));
},
renderItem: function(item, index) {
return (
<FormField key={item.key}>
<FormInput ref={'item_' + (index + 1)} className={'multi datepicker_' + item.key} name={this.props.path} value={item.value} onChange={this.updateItem.bind(this, item)} placeholder={this.props.format} autoComplete="off" />
<Button type="link-cancel" onClick={this.removeItem.bind(this, item)} className="keystone-relational-button">
<span className="octicon octicon-x" />
</Button>
</FormField>
);
},
renderField: function () {
return (
<div>
{this.state.values.map(this.renderItem)}
<Button ref="button" onClick={this.addItem}>Add date</Button>
</div>
);
},
renderValue: function () {
return (
<div>
{this.state.values.map((item, i) => {
return (
<div key={i} style={i ? { marginTop: '1em' } : null}>
<FormInput noedit value={item.value} />
</div>
);
})}
</div>
);
}
};
|
var common = require("./common")
, odbc = require("../")
, db = new odbc.Database()
, assert = require("assert");
assert.equal(db.connected, false);
db.query("select * from " + common.tableName, function (err, rs, moreResultSets) {
assert.deepEqual(err, { message: 'Connection not open.' });
assert.deepEqual(rs, []);
assert.equal(moreResultSets, false);
assert.equal(db.connected, false);
});
db.open(common.connectionString, function(err) {
assert.equal(err, null);
assert.equal(db.connected, true);
db.close(function () {
assert.equal(db.connected, false);
db.query("select * from " + common.tableName, function (err, rs, moreResultSets) {
assert.deepEqual(err, { message: 'Connection not open.' });
assert.deepEqual(rs, []);
assert.equal(moreResultSets, false);
assert.equal(db.connected, false);
});
});
});
|
#!/usr/bin/env node
var fs = require("fs");
var stitch = require("stitch");
var package = stitch.createPackage({
paths: [__dirname + "/vendor/uglifyjs/lib"]
});
package.compile(function(err, source) {
if (err) throw err;
source = "(function(global) {" +
source + ";\n" +
"global.UglifyJS = {};\n" +
"global.UglifyJS.parser = this.require('parse-js');\n" +
"global.UglifyJS.uglify = this.require('process');\n" +
"}).call({}, this);\n";
fs.writeFile(__dirname + "/lib/uglify.js", source, function(err) {
if (err) throw err;
});
});
|
/**
* @license Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'button', 'uk', {
selectedLabel: '%1 (Вибрано)'
} );
|
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
length = length == null ? MAX_SAFE_INTEGER : length;
return !!length &&
(typeof value == 'number' || reIsUint.test(value)) &&
(value > -1 && value % 1 == 0 && value < length);
}
module.exports = isIndex;
|
/**
* @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.add( 'basicstyles', {
// jscs:disable maximumLineLength
lang: 'af,ar,bg,bn,bs,ca,cs,cy,da,de,el,en,en-au,en-ca,en-gb,eo,es,et,eu,fa,fi,fo,fr,fr-ca,gl,gu,he,hi,hr,hu,id,is,it,ja,ka,km,ko,ku,lt,lv,mk,mn,ms,nb,nl,no,pl,pt,pt-br,ro,ru,si,sk,sl,sq,sr,sr-latn,sv,th,tr,tt,ug,uk,vi,zh,zh-cn', // %REMOVE_LINE_CORE%
// jscs:enable maximumLineLength
icons: 'bold,italic,underline,strike,subscript,superscript', // %REMOVE_LINE_CORE%
hidpi: true, // %REMOVE_LINE_CORE%
init: function( editor ) {
var order = 0;
// All buttons use the same code to register. So, to avoid
// duplications, let's use this tool function.
var addButtonCommand = function( buttonName, buttonLabel, commandName, styleDefiniton ) {
// Disable the command if no definition is configured.
if ( !styleDefiniton )
return;
var style = new CKEDITOR.style( styleDefiniton ),
forms = contentForms[ commandName ];
// Put the style as the most important form.
forms.unshift( style );
// Listen to contextual style activation.
editor.attachStyleStateChange( style, function( state ) {
!editor.readOnly && editor.getCommand( commandName ).setState( state );
} );
// Create the command that can be used to apply the style.
editor.addCommand( commandName, new CKEDITOR.styleCommand( style, {
contentForms: forms
} ) );
// Register the button, if the button plugin is loaded.
if ( editor.ui.addButton ) {
editor.ui.addButton( buttonName, {
label: buttonLabel,
command: commandName,
toolbar: 'basicstyles,' + ( order += 10 )
} );
}
};
var contentForms = {
bold: [
'strong',
'b',
[ 'span', function( el ) {
var fw = el.styles[ 'font-weight' ];
return fw == 'bold' || +fw >= 700;
} ]
],
italic: [
'em',
'i',
[ 'span', function( el ) {
return el.styles[ 'font-style' ] == 'italic';
} ]
],
underline: [
'u',
[ 'span', function( el ) {
return el.styles[ 'text-decoration' ] == 'underline';
} ]
],
strike: [
's',
'strike',
[ 'span', function( el ) {
return el.styles[ 'text-decoration' ] == 'line-through';
} ]
],
subscript: [
'sub'
],
superscript: [
'sup'
]
},
config = editor.config,
lang = editor.lang.basicstyles;
addButtonCommand( 'Bold', lang.bold, 'bold', config.coreStyles_bold );
addButtonCommand( 'Italic', lang.italic, 'italic', config.coreStyles_italic );
addButtonCommand( 'Underline', lang.underline, 'underline', config.coreStyles_underline );
addButtonCommand( 'Strike', lang.strike, 'strike', config.coreStyles_strike );
addButtonCommand( 'Subscript', lang.subscript, 'subscript', config.coreStyles_subscript );
addButtonCommand( 'Superscript', lang.superscript, 'superscript', config.coreStyles_superscript );
editor.setKeystroke( [
[ CKEDITOR.CTRL + 66 /*B*/, 'bold' ],
[ CKEDITOR.CTRL + 73 /*I*/, 'italic' ],
[ CKEDITOR.CTRL + 85 /*U*/, 'underline' ]
] );
}
} );
// Basic Inline Styles.
/**
* The style definition that applies the **bold** style to the text.
*
* config.coreStyles_bold = { element: 'b', overrides: 'strong' };
*
* config.coreStyles_bold = {
* element: 'span',
* attributes: { 'class': 'Bold' }
* };
*
* @cfg
* @member CKEDITOR.config
*/
CKEDITOR.config.coreStyles_bold = { element: 'strong', overrides: 'b' };
/**
* The style definition that applies the *italics* style to the text.
*
* config.coreStyles_italic = { element: 'i', overrides: 'em' };
*
* CKEDITOR.config.coreStyles_italic = {
* element: 'span',
* attributes: { 'class': 'Italic' }
* };
*
* @cfg
* @member CKEDITOR.config
*/
CKEDITOR.config.coreStyles_italic = { element: 'em', overrides: 'i' };
/**
* The style definition that applies the <u>underline</u> style to the text.
*
* CKEDITOR.config.coreStyles_underline = {
* element: 'span',
* attributes: { 'class': 'Underline' }
* };
*
* @cfg
* @member CKEDITOR.config
*/
CKEDITOR.config.coreStyles_underline = { element: 'u' };
/**
* The style definition that applies the <strike>strikethrough</strike> style to the text.
*
* CKEDITOR.config.coreStyles_strike = {
* element: 'span',
* attributes: { 'class': 'Strikethrough' },
* overrides: 'strike'
* };
*
* @cfg
* @member CKEDITOR.config
*/
CKEDITOR.config.coreStyles_strike = { element: 's', overrides: 'strike' };
/**
* The style definition that applies the subscript style to the text.
*
* CKEDITOR.config.coreStyles_subscript = {
* element: 'span',
* attributes: { 'class': 'Subscript' },
* overrides: 'sub'
* };
*
* @cfg
* @member CKEDITOR.config
*/
CKEDITOR.config.coreStyles_subscript = { element: 'sub' };
/**
* The style definition that applies the superscript style to the text.
*
* CKEDITOR.config.coreStyles_superscript = {
* element: 'span',
* attributes: { 'class': 'Superscript' },
* overrides: 'sup'
* };
*
* @cfg
* @member CKEDITOR.config
*/
CKEDITOR.config.coreStyles_superscript = { element: 'sup' };
|
var createHash = require('create-hash')
function hash160 (buffer) {
return ripemd160(sha256(buffer))
}
function hash256 (buffer) {
return sha256(sha256(buffer))
}
function ripemd160 (buffer) {
return createHash('rmd160').update(buffer).digest()
}
function sha1 (buffer) {
return createHash('sha1').update(buffer).digest()
}
function sha256 (buffer) {
return createHash('sha256').update(buffer).digest()
}
module.exports = {
hash160: hash160,
hash256: hash256,
ripemd160: ripemd160,
sha1: sha1,
sha256: sha256
}
|
var five = require("../lib/johnny-five.js"),
board = new five.Board();
board.on("ready", function() {
var motor;
/*
Arduino Motor Shield R3
Motor A
pwm: 3
dir: 12
brake: 9
current: "A0"
Motor B
pwm: 11
dir: 13
brake: 8
current: "A1"
*/
motor = new five.Motor({
pins: {
pwm: 3,
dir: 12,
brake: 9
},
// The current options are passed to a new instance of Sensor
current: {
pin: "A0",
freq: 250,
threshold: 10
}
});
board.repl.inject({
motor: motor
});
motor.current.scale([0, 3030]).on("change", function() {
console.log("Motor A: " + this.value.toFixed(2) + "mA");
});
motor.on("start", function() {
console.log("start");
});
motor.on("stop", function() {
console.log("automated stop on timer");
});
motor.on("brake", function() {
console.log("automated brake on timer");
});
motor.on("forward", function() {
console.log("forward");
// demonstrate switching to reverse after 5 seconds
board.wait(5000, function() {
motor.reverse(150);
});
});
motor.on("reverse", function() {
console.log("reverse");
// demonstrate stopping after 5 seconds
board.wait(5000, function() {
// Apply the brake for 500ms and call stop()
motor.brake(500);
});
});
// set the motor going forward full speed
motor.forward(255);
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.