code stringlengths 2 1.05M |
|---|
/*
* jQuery OrgChart Plugin
* https://github.com/dabeng/OrgChart
*
* Demos of jQuery OrgChart Plugin
* http://dabeng.github.io/OrgChart/local-datasource/
* http://dabeng.github.io/OrgChart/ajax-datasource/
* http://dabeng.github.io/OrgChart/ondemand-loading-data/
* http://dabeng.github.io/OrgChart/option-createNode/
* http://dabeng.github.io/OrgChart/export-orgchart/
* http://dabeng.github.io/OrgChart/integrate-map/
*
* Copyright 2016, dabeng
* http://dabeng.github.io/
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
'use strict';
(function(factory) {
if (typeof module === 'object' && typeof module.exports === 'object') {
factory(require('jquery'), window, document);
} else {
factory(jQuery, window, document);
}
}(function($, window, document, undefined) {
$.fn.orgchart = function(options) {
var defaultOptions = {
'nodeTitle': 'name',
'nodeId': 'id',
'nodeChildren': 'children',
'depth': 999,
'chartClass': '',
'exportButton': false,
'exportFilename': 'OrgChart',
'parentNodeSymbol': 'fa-users',
'draggable': false,
'direction': 't2b',
'panzoom': false
};
switch (options) {
case 'buildHierarchy':
return buildHierarchy.apply(this, Array.prototype.splice.call(arguments, 1));
case 'addChildren':
return addChildren.apply(this, Array.prototype.splice.call(arguments, 1));
case 'addParent':
return addParent.apply(this, Array.prototype.splice.call(arguments, 1));
case 'addSiblings':
return addSiblings.apply(this, Array.prototype.splice.call(arguments, 1));
case 'removeNodes':
return removeNodes.apply(this, Array.prototype.splice.call(arguments, 1));
case 'getHierarchy': {
if (!$(this).find('.node:first')[0].id) {
return 'Error: Nodes of orghcart to be exported must have id attribute!';
}
return getHierarchy.apply(this, [$(this)]);
}
default: // initiation time
var opts = $.extend(defaultOptions, options);
this.data('orgchart', { 'options' : opts });
}
// build the org-chart
var $chartContainer = this;
var data = opts.data;
var $chart = $('<div>', {
'class': 'orgchart' + (opts.chartClass !== '' ? ' ' + opts.chartClass : '') + (opts.direction !== 't2b' ? ' ' + opts.direction : ''),
'click': function(event) {
if (!$(event.target).closest('.node').length) {
$chart.find('.node.focused').removeClass('focused');
}
}
});
if ($.type(data) === 'object') {
if (data instanceof $) { // ul datasource
buildHierarchy($chart, buildJsonDS(data.children()), 0, opts);
} else { // local json datasource
buildHierarchy($chart, opts.ajaxURL ? data : attachRel(data, '00'), 0, opts);
}
} else {
$.ajax({
'url': data,
'dataType': 'json',
'beforeSend': function () {
$chart.append('<i class="fa fa-circle-o-notch fa-spin spinner"></i>');
}
})
.done(function(data, textStatus, jqXHR) {
buildHierarchy($chart, opts.ajaxURL ? data : attachRel(data, '00'), 0, opts);
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
})
.always(function() {
$chart.children('.spinner').remove();
});
}
$chartContainer.append($chart);
// append the export button
if (opts.exportButton) {
var $exportBtn = $('<button>', {
'class': 'oc-export-btn' + (opts.chartClass !== '' ? ' ' + opts.chartClass : ''),
'text': 'Export',
'click': function() {
if ($(this).children('.spinner').length) {
return false;
}
var $mask = $chartContainer.find('.mask');
if (!$mask.length) {
$chartContainer.append('<div class="mask"><i class="fa fa-circle-o-notch fa-spin spinner"></i></div>');
} else {
$mask.removeClass('hidden');
}
html2canvas($chart[0], {
'onrendered': function(canvas) {
$chartContainer.find('.mask').addClass('hidden')
.end().find('.oc-download-btn').attr('href', canvas.toDataURL())[0].click();
}
});
}
});
var downloadBtn = '<a class="oc-download-btn' + (opts.chartClass !== '' ? ' ' + opts.chartClass : '') + '"'
+ ' download="' + opts.exportFilename + '.png"></a>';
$chartContainer.append($exportBtn).append(downloadBtn);
}
if (opts.panzoom) {
$chartContainer.css('overflow', 'hidden');
$chart.on('mousedown',function(e){
var $this = $(this);
if ($(e.target).closest('.node').length) {
$this.data('panning', false);
return;
} else {
$this.css('cursor', 'move').data('panning', true);
}
var lastX = 0;
var lastY = 0;
var lastTf = $this.css('transform');
if (lastTf !== 'none') {
var temp = lastTf.split(',');
if (lastTf.indexOf('3d') === -1) {
lastX = parseInt(temp[4]);
lastY = parseInt(temp[5]);
} else {
lastX = parseInt(temp[12]);
lastY = parseInt(temp[13]);
}
}
var startX = e.pageX - lastX;
var startY = e.pageY - lastY;
$(document).on('mousemove',function(ev) {
var newX = ev.pageX - startX;
var newY = ev.pageY - startY;
var lastTf = $this.css('transform');
if (lastTf === 'none') {
if (lastTf.indexOf('3d') === -1) {
$this.css('transform', 'matrix(1, 0, 0, 1, ' + newX + ', ' + newY + ')');
} else {
$this.css('transform', 'matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, ' + newX + ', ' + newY + ', 0, 1)');
}
} else {
var matrix = lastTf.split(',');
if (lastTf.indexOf('3d') === -1) {
matrix[4] = ' ' + newX;
matrix[5] = ' ' + newY + ')';
} else {
matrix[12] = ' ' + newX;
matrix[13] = ' ' + newY;
}
$this.css('transform', matrix.join(','));
}
});
});
$(document).on('mouseup',function() {
if ($chart.data('panning')) {
$chart.css('cursor', 'default');
$(this).off('mousemove');
}
});
$chartContainer.on('wheel', function(event) {
event.preventDefault();
var lastTf = $chart.css('transform');
var newScale = 1 + (event.originalEvent.deltaY > 0 ? -0.2 : 0.2);
if (lastTf === 'none') {
$chart.css('transform', 'scale(' + newScale + ',' + newScale + ')');
} else {
if (lastTf.indexOf('3d') === -1) {
$chart.css('transform', lastTf + ' scale(' + newScale + ',' + newScale + ')');
} else {
$chart.css('transform', lastTf + ' scale3d(' + newScale + ',' + newScale + ', 1)');
}
}
});
}
return $chartContainer;
};
function buildJsonDS($li) {
var subObj = {
'name': $li.contents().eq(0).text().trim(),
'relationship': ($li.parent().parent().is('li') ? '1': '0') + ($li.siblings('li').length ? 1: 0) + ($li.children('ul').length ? 1 : 0)
};
if ($li[0].id) {
subObj.id = $li[0].id;
}
$li.children('ul').children().each(function() {
if (!subObj.children) { subObj.children = []; }
subObj.children.push(buildJsonDS($(this)));
});
return subObj;
}
function attachRel(data, flags) {
data.relationship = flags + (data.children ? 1 : 0);
if (data.children) {
data.children.forEach(function(item) {
attachRel(item, '1' + (data.children.length > 1 ? 1 :0));
});
}
return data;
}
function getHierarchy($orgchart) {
var $tr = $orgchart.find('tr:first');
var subObj = { 'id': $tr.find('.node')[0].id };
$tr.siblings(':last').children().each(function() {
if (!subObj.children) { subObj.children = []; }
subObj.children.push(getHierarchy($(this)));
});
return subObj;
}
// detect the exist/display state of related node
function getNodeState($node, relation) {
var $target = {};
if (relation === 'parent') {
$target = $node.closest('table').closest('tr').siblings(':first').find('.node');
} else if (relation === 'children') {
$target = $node.closest('tr').siblings();
} else {
$target = $node.closest('table').parent().siblings();
}
if ($target.length) {
if ($target.is(':visible')) {
return {"exist": true, "visible": true};
}
return {"exist": true, "visible": false};
}
return {"exist": false, "visible": false};
}
// recursively hide the ancestor node and sibling nodes of the specified node
function hideAncestorsSiblings($node) {
var $temp = $node.closest('table').closest('tr').siblings();
if ($temp.eq(0).find('.spinner').length) {
$node.closest('.orgchart').data('inAjax', false);
}
// hide the sibling nodes
if (getNodeState($node, 'siblings').visible) {
hideSiblings($node);
}
// hide the lines
var $lines = $temp.slice(1);
$lines.css('visibility', 'hidden');
// hide the superior nodes with transition
var $parent = $temp.eq(0).find('.node');
var grandfatherVisible = getNodeState($parent, 'parent').visible;
if ($parent.length && $parent.is(':visible')) {
$parent.addClass('slide slide-down').one('transitionend', function() {
$parent.removeClass('slide');
$lines.removeAttr('style');
$temp.addClass('hidden');
});
}
// if the current node has the parent node, hide it recursively
if ($parent.length && grandfatherVisible) {
hideAncestorsSiblings($parent);
}
}
// show the parent node of the specified node
function showParent($node) {
// just show only one superior level
var $temp = $node.closest('table').closest('tr').siblings().removeClass('hidden');
// just show only one line
$temp.eq(2).children().slice(1, -1).addClass('hidden');
// show parent node with animation
var parent = $temp.eq(0).find('.node')[0];
repaint(parent);
$(parent).addClass('slide').removeClass('slide-down').one('transitionend', function() {
$(parent).removeClass('slide');
if (isInAction($node)) {
switchVerticalArrow($node.children('.topEdge'));
}
});
}
// recursively hide the descendant nodes of the specified node
function hideDescendants($node) {
var $temp = $node.closest('tr').siblings();
if ($temp.last().find('.spinner').length) {
$node.closest('.orgchart').data('inAjax', false);
}
var $visibleNodes = $temp.last().find('.node:visible');
var $lines = $visibleNodes.closest('table').closest('tr').prevAll('.lines').css('visibility', 'hidden');
$visibleNodes.addClass('slide slide-up').eq(0).one('transitionend', function() {
$visibleNodes.removeClass('slide');
$lines.removeAttr('style').addClass('hidden').siblings('.nodes').addClass('hidden');
if (isInAction($node)) {
switchVerticalArrow($node.children('.bottomEdge'));
}
});
}
// show the children nodes of the specified node
function showDescendants($node) {
var $descendants = $node.closest('tr').siblings().removeClass('hidden')
.eq(2).children().find('tr:first').find('.node:visible');
// the two following statements are used to enforce browser to repaint
repaint($descendants.get(0));
$descendants.addClass('slide').removeClass('slide-up').eq(0).one('transitionend', function() {
$descendants.removeClass('slide');
if (isInAction($node)) {
switchVerticalArrow($node.children('.bottomEdge'));
}
});
}
// hide the sibling nodes of the specified node
function hideSiblings($node) {
var $nodeContainer = $node.closest('table').parent();
if ($nodeContainer.siblings().find('.spinner').length) {
$node.closest('.orgchart').data('inAjax', false);
}
$nodeContainer.prevAll().find('.node:visible').addClass('slide slide-right');
$nodeContainer.nextAll().find('.node:visible').addClass('slide slide-left');
var $animatedNodes = $nodeContainer.siblings().find('.slide');
var $lines = $animatedNodes.closest('.nodes').prevAll('.lines').css('visibility', 'hidden');
$animatedNodes.eq(0).one('transitionend', function() {
$lines.removeAttr('style');
$nodeContainer.closest('.nodes').prev().children().slice(1, -1).addClass('hidden');
$animatedNodes.removeClass('slide');
$nodeContainer.siblings().find('.node:visible:gt(0)').removeClass('slide-left slide-right').addClass('slide-up');
$nodeContainer.siblings().find('.lines, .nodes').addClass('hidden');
$nodeContainer.siblings().addClass('hidden');
if (isInAction($node)) {
switchHorizontalArrow($node, true);
}
});
}
// show the sibling nodes of the specified node
function showSiblings($node) {
// firstly, show the sibling td tags
var $siblings = $node.closest('table').parent().siblings().removeClass('hidden');
// secondly, show the lines
var $upperLevel = $node.closest('table').closest('tr').siblings();
$upperLevel.eq(2).children().slice(1, -1).removeClass('hidden');
// thirdly, do some cleaning stuff
if (!getNodeState($node, 'parent').visible) {
$upperLevel.removeClass('hidden');
var parent = $upperLevel.find('.node')[0];
repaint(parent);
$(parent).addClass('slide').removeClass('slide-down').one('transitionend', function() {
$(this).removeClass('slide');
});
}
// lastly, show the sibling nodes with animation
$siblings.find('.node:visible').addClass('slide').removeClass('slide-left slide-right').eq(-1).one('transitionend', function() {
$siblings.find('.node:visible').removeClass('slide');
if (isInAction($node)) {
collapseArrow($node);
}
});
}
// start up loading status for requesting new nodes
function startLoading($arrow, $node, options) {
var $chart = $node.closest('.orgchart');
if (typeof $chart.data('inAjax') !== 'undefined' && $chart.data('inAjax') === true) {
return false;
}
$arrow.addClass('hidden');
$node.append('<i class="fa fa-circle-o-notch fa-spin spinner"></i>');
$node.children().not('.spinner').css('opacity', 0.2);
$chart.data('inAjax', true);
$('.oc-export-btn' + (options.chartClass !== '' ? '.' + options.chartClass : '')).prop('disabled', true);
return true;
}
// terminate loading status for requesting new nodes
function endLoading($arrow, $node, options) {
var $chart = $node.closest('div.orgchart');
$arrow.removeClass('hidden');
$node.find('.spinner').remove();
$node.children().removeAttr('style');
$chart.data('inAjax', false);
$('.oc-export-btn' + (options.chartClass !== '' ? '.' + options.chartClass : '')).prop('disabled', false);
}
// whether the cursor is hovering over the node
function isInAction($node) {
return $node.children('.edge').attr('class').indexOf('fa-') > -1 ? true : false;
}
function switchVerticalArrow($arrow) {
$arrow.toggleClass('fa-chevron-up').toggleClass('fa-chevron-down');
}
function collapseArrow($node) {
switchHorizontalArrow($node, false);
$node.children('.topEdge').removeClass('fa-chevron-up').addClass('fa-chevron-down');
}
function switchHorizontalArrow($node, isExpand) {
$node.children('.leftEdge').toggleClass('fa-chevron-right', !isExpand).toggleClass('fa-chevron-left', isExpand);
$node.children('.rightEdge').toggleClass('fa-chevron-left', !isExpand).toggleClass('fa-chevron-right', isExpand);
}
function repaint(node) {
node.style.offsetWidth = node.offsetWidth;
}
// create node
function createNode(nodeData, level, opts) {
var dtd = $.Deferred();
// construct the content of node
var $nodeDiv = $('<div' + (opts.draggable ? ' draggable="true"' : '') + (nodeData[opts.nodeId] ? ' id="' + nodeData[opts.nodeId] + '"' : '') + '>')
.addClass('node ' + (nodeData.className || '') + (level >= opts.depth ? ' slide-up' : ''))
.append('<div class="title">' + nodeData[opts.nodeTitle] + '</div>')
.append(typeof opts.nodeContent !== 'undefined' ? '<div class="content">' + nodeData[opts.nodeContent] + '</div>' : '');
// append 4 direction arrows
var flags = nodeData.relationship;
if (Number(flags.substr(0,1))) {
$nodeDiv.append('<i class="edge verticalEdge topEdge fa"></i>');
}
if(Number(flags.substr(1,1))) {
$nodeDiv.append('<i class="edge horizontalEdge rightEdge fa"></i>' +
'<i class="edge horizontalEdge leftEdge fa"></i>');
}
if(Number(flags.substr(2,1))) {
$nodeDiv.append('<i class="edge verticalEdge bottomEdge fa"></i>')
.children('.title').prepend('<i class="fa '+ opts.parentNodeSymbol + ' symbol"></i>');
}
$nodeDiv.on('mouseenter mouseleave', function(event) {
var $node = $(this), flag = false;
var $topEdge = $node.children('.topEdge');
var $rightEdge = $node.children('.rightEdge');
var $bottomEdge = $node.children('.bottomEdge');
var $leftEdge = $node.children('.leftEdge');
if (event.type === 'mouseenter') {
if ($topEdge.length) {
flag = getNodeState($node, 'parent').visible;
$topEdge.toggleClass('fa-chevron-up', !flag).toggleClass('fa-chevron-down', flag);
}
if ($bottomEdge.length) {
flag = getNodeState($node, 'children').visible;
$bottomEdge.toggleClass('fa-chevron-down', !flag).toggleClass('fa-chevron-up', flag);
}
if ($leftEdge.length) {
switchHorizontalArrow($node, !getNodeState($node, 'siblings').visible);
}
} else {
$node.children('.edge').removeClass('fa-chevron-up fa-chevron-down fa-chevron-right fa-chevron-left');
}
});
// define click event handler
$nodeDiv.on('click', function(event) {
$(this).closest('.orgchart').find('.focused').removeClass('focused');
$(this).addClass('focused');
});
// define click event handler for the top edge
$nodeDiv.on('click', '.topEdge', function(event) {
var $that = $(this);
var $node = $that.parent();
var parentState = getNodeState($node, 'parent');
if (parentState.exist) {
var $parent = $node.closest('table').closest('tr').siblings(':first').find('.node');
if ($parent.is('.slide')) { return; }
// hide the ancestor nodes and sibling nodes of the specified node
if (parentState.visible) {
hideAncestorsSiblings($node);
$parent.one('transitionend', function() {
if (isInAction($node)) {
switchVerticalArrow($that);
switchHorizontalArrow($node, true);
}
});
} else { // show the ancestors and siblings
showParent($node);
}
} else {
// load the new parent node of the specified node by ajax request
var nodeId = $that.parent()[0].id;
// start up loading status
if (startLoading($that, $node, opts)) {
// load new nodes
$.ajax({ 'url': opts.ajaxURL.parent + nodeId + '/', 'dataType': 'json' })
.done(function(data) {
if ($node.closest('div.orgchart').data('inAjax')) {
if (!$.isEmptyObject(data)) {
addParent.call($node.closest('.orgchart').parent(), data, opts);
}
}
})
.fail(function() { console.log('Failed to get parent node data'); })
.always(function() { endLoading($that, $node, opts); });
}
}
});
// bind click event handler for the bottom edge
$nodeDiv.on('click', '.bottomEdge', function(event) {
var $that = $(this);
var $node = $that.parent();
var childrenState = getNodeState($node, 'children');
if (childrenState.exist) {
var $children = $node.closest('tr').siblings(':last');
if ($children.find('.node:visible').is('.slide')) { return; }
// hide the descendant nodes of the specified node
if (childrenState.visible) {
hideDescendants($node);
} else { // show the descendants
showDescendants($node);
}
} else { // load the new children nodes of the specified node by ajax request
var nodeId = $that.parent()[0].id;
if (startLoading($that, $node, opts)) {
$.ajax({ 'url': opts.ajaxURL.children + nodeId + '/', 'dataType': 'json' })
.done(function(data, textStatus, jqXHR) {
if ($node.closest('.orgchart').data('inAjax')) {
if (data.children.length) {
addChildren($node, data, $.extend({}, opts, { depth: 0 }));
}
}
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log('Failed to get children nodes data');
})
.always(function() {
endLoading($that, $node, opts);
});
}
}
});
// bind click event handler for the left and right edges
$nodeDiv.on('click', '.leftEdge, .rightEdge', function(event) {
var $that = $(this);
var $node = $that.parent();
var siblingsState = getNodeState($node, 'siblings');
if (siblingsState.exist) {
var $siblings = $node.closest('table').parent().siblings();
if ($siblings.find('.node:visible').is('.slide')) { return; }
if (siblingsState.visible) { // hide the sibling nodes of the specified node
hideSiblings($node);
} else { // show the siblings
showSiblings($node);
}
} else {
// load the new sibling nodes of the specified node by ajax request
var nodeId = $that.parent()[0].id;
var url = (getNodeState($node, 'parent').exist) ? opts.ajaxURL.siblings : opts.ajaxURL.families;
if (startLoading($that, $node, opts)) {
$.ajax({ 'url': url + nodeId + '/', 'dataType': 'json' })
.done(function(data, textStatus, jqXHR) {
if ($node.closest('.orgchart').data('inAjax')) {
if (data.siblings || data.children) {
addSiblings($node, data, opts);
}
}
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log('Failed to get sibling nodes data');
})
.always(function() {
endLoading($that, $node, opts);
});
}
}
});
if (opts.draggable) {
$nodeDiv.on('dragstart', function(event) {
event.originalEvent.dataTransfer.setData('text/html', 'hack for firefox');
var $dragged = $(this);
var $draggedZone = $dragged.closest('table').find('.node');
$dragged.closest('.orgchart')
.data('dragged', $dragged)
.find('.node').each(function(index, node) {
if ($draggedZone.index(node) === -1) {
$(node).addClass('allowedDrop');
}
});
})
.on('dragover', function(event) {
event.preventDefault();
var $dropZone = $(this);
var $dragged = $dropZone.closest('.orgchart').data('dragged');
if ($dragged.closest('table').find('.node').index($dropZone) > -1) {
event.originalEvent.dataTransfer.dropEffect = 'none';
}
})
.on('dragend', function(event) {
$(this).closest('.orgchart').find('.allowedDrop').removeClass('allowedDrop');
})
.on('drop', function(event) {
var $dropZone = $(this);
var $orgchart = $dropZone.closest('.orgchart');
var $dragged = $orgchart.data('dragged');
$orgchart.find('.allowedDrop').removeClass('allowedDrop');
var $dragZone = $dragged.closest('.nodes').siblings().eq(0).children();
// firstly, deal with the hierarchy of drop zone
if (!$dropZone.closest('tr').siblings().length) { // if the drop zone is a leaf node
$dropZone.append('<i class="edge verticalEdge bottomEdge fa"></i>')
.parent().attr('colspan', 2)
.parent().after('<tr class="lines"><td colspan="2"><div class="down"></div></td></tr>'
+ '<tr class="lines"><td class="right"> </td><td class="left"> </td></tr>'
+ '<tr class="nodes"></tr>')
.siblings(':last').append($dragged.find('.horizontalEdge').remove().end().closest('table').parent());
} else {
var dropColspan = parseInt($dropZone.parent().attr('colspan')) + 2;
var horizontalEdges = '<i class="edge horizontalEdge rightEdge fa"></i><i class="edge horizontalEdge leftEdge fa"></i>';
$dropZone.closest('tr').next().addBack().children().attr('colspan', dropColspan);
if (!$dragged.find('.horizontalEdge').length) {
$dragged.append(horizontalEdges);
}
$dropZone.closest('tr').siblings().eq(1).children(':last').before('<td class="left top"> </td><td class="right top"> </td>')
.end().next().append($dragged.closest('table').parent());
var $dropSibs = $dragged.closest('table').parent().siblings().find('.node:first');
if ($dropSibs.length === 1) {
$dropSibs.append(horizontalEdges);
}
}
// secondly, deal with the hierarchy of dragged node
var dragColspan = parseInt($dragZone.attr('colspan'));
if (dragColspan > 2) {
$dragZone.attr('colspan', dragColspan - 2)
.parent().next().children().attr('colspan', dragColspan - 2)
.end().next().children().slice(1, 3).remove();
var $dragSibs = $dragZone.parent().siblings('.nodes').children().find('.node:first');
if ($dragSibs.length ===1) {
$dragSibs.find('.horizontalEdge').remove();
}
} else {
$dragZone.removeAttr('colspan')
.find('.bottomEdge').remove()
.end().end().siblings().remove();
}
$orgchart.triggerHandler({ 'type': 'nodedropped.orgchart', 'draggedNode': $dragged, 'dragZone': $dragZone.children(), 'dropZone': $dropZone });
});
}
// allow user to append dom modification after finishing node create of orgchart
if (opts.createNode) {
opts.createNode($nodeDiv, nodeData);
}
dtd.resolve($nodeDiv);
return dtd.promise();
}
// recursively build the tree
function buildHierarchy ($appendTo, nodeData, level, opts, callback) {
var $table;
// Construct the node
var $childNodes = nodeData[opts.nodeChildren];
var hasChildren = $childNodes ? $childNodes.length : false;
if (Object.keys(nodeData).length > 1) { // if nodeData has nested structure
$table = $('<table>');
$appendTo.append($table);
$.when(createNode(nodeData, level, opts))
.done(function($nodeDiv) {
$table.append($nodeDiv.wrap('<tr><td' + (hasChildren ? ' colspan="' + $childNodes.length * 2 + '"' : '') + '></td></tr>').closest('tr'));
if (callback) {
callback();
}
})
.fail(function() {
console.log('Failed to creat node')
});
}
// Construct the inferior nodes and connectiong lines
if (hasChildren) {
if (Object.keys(nodeData).length === 1) { // if nodeData is just an array
$table = $appendTo;
}
var isHidden = level + 1 >= opts.depth ? ' hidden' : '';
// draw the line close to parent node
$table.append('<tr class="lines' + isHidden + '"><td colspan="' + $childNodes.length * 2 + '"><div class="down"></div></td></tr>');
// draw the lines close to children nodes
var linesRow = '<tr class="lines' + isHidden + '"><td class="right"> </td>';
for (var i=1; i<$childNodes.length; i++) {
linesRow += '<td class="left top"> </td><td class="right top"> </td>';
}
linesRow += '<td class="left"> </td></tr>';
$table.append(linesRow);
// recurse through children nodes
var $childNodesRow = $('<tr class="nodes' + isHidden + '">');
$table.append($childNodesRow);
$.each($childNodes, function() {
var $td = $('<td colspan="2">');
$childNodesRow.append($td);
buildHierarchy($td, this, level + 1, opts, callback);
});
}
}
// build the child nodes of specific node
function buildChildNode ($appendTo, nodeData, opts, callback) {
var opts = opts || this.data('orgchart').options;
var data = nodeData.children || nodeData.siblings;
$appendTo.find('td:first').attr('colspan', data.length * 2);
buildHierarchy($appendTo, { 'children': data }, 0, opts, callback);
}
// exposed method
function addChildren($node, data, opts) {
var count = 0;
buildChildNode.call($node.closest('.orgchart').parent(), $node.closest('table'), data, opts, function() {
if (++count === data.children.length) {
if (!$node.children('.bottomEdge').length) {
$node.append('<i class="edge verticalEdge bottomEdge fa"></i>');
}
if (!$node.find('.symbol').length) {
$node.children('.title').prepend('<i class="fa '+ opts.parentNodeSymbol + ' symbol"></i>');
}
showDescendants($node);
}
});
}
// build the parent node of specific node
function buildParentNode(nodeData, opts, callback) {
var that = this;
var $table = $('<table>');
nodeData.relationship = '001';
$.when(createNode(nodeData, 0, opts ? opts : this.data('orgchart').options))
.done(function($nodeDiv) {
$table.append($nodeDiv.removeClass('slide-up').addClass('slide-down').wrap('<tr class="hidden"><td colspan="2"></td></tr>').closest('tr'));
$table.append('<tr class="lines hidden"><td colspan="2"><div class="down"></div></td></tr>');
var linesRow = '<td class="right"> </td><td class="left"> </td>';
$table.append('<tr class="lines hidden">' + linesRow + '</tr>');
var oc = that.children('.orgchart');
oc.prepend($table)
.children('table:first').append('<tr class="nodes"><td colspan="2"></td></tr>')
.children().children('tr:last').children().append(oc.children('table').last());
callback();
})
.fail(function() {
console.log('Failed to create parent node');
});
}
// exposed method
function addParent(data, opts) {
var $currentRoot = this.find('.node:first');
buildParentNode.call(this, data, opts, function() {
if (!$currentRoot.children('.topEdge').length) {
$currentRoot.children('.title').after('<i class="edge verticalEdge topEdge fa"></i>');
}
showParent($currentRoot);
});
}
// subsequent processing of build sibling nodes
function complementLine($oneSibling, siblingCount, existingSibligCount) {
var lines = '';
for (var i = 0; i < existingSibligCount; i++) {
lines += '<td class="left top"> </td><td class="right top"> </td>';
}
$oneSibling.parent().prevAll('tr:gt(0)').children().attr('colspan', siblingCount * 2)
.end().next().children(':first').after(lines);
}
// build the sibling nodes of specific node
function buildSiblingNode($nodeChart, nodeData, opts, callback) {
var opts = opts || this.data('orgchart').options;
var newSiblingCount = nodeData.siblings ? nodeData.siblings.length : nodeData.children.length;
var existingSibligCount = $nodeChart.parent().is('td') ? $nodeChart.closest('tr').children().length : 1;
var siblingCount = existingSibligCount + newSiblingCount;
var insertPostion = (siblingCount > 1) ? Math.floor(siblingCount/2 - 1) : 0;
// just build the sibling nodes for the specific node
if ($nodeChart.parent().is('td')) {
var $parent = $nodeChart.closest('tr').prevAll('tr:last');
$nodeChart.closest('tr').prevAll('tr:lt(2)').remove();
var childCount = 0;
buildChildNode.call($nodeChart.closest('.orgchart').parent(),$nodeChart.parent().closest('table'), nodeData, opts, function() {
if (++childCount === newSiblingCount) {
var $siblingTds = $nodeChart.parent().closest('table').children().children('tr:last').children('td');
if (existingSibligCount > 1) {
complementLine($siblingTds.eq(0).before($nodeChart.closest('td').siblings().andSelf().unwrap()), siblingCount, existingSibligCount);
$siblingTds.addClass('hidden').find('.node').addClass('slide-left');
} else {
complementLine($siblingTds.eq(insertPostion).after($nodeChart.closest('td').unwrap()), siblingCount, 1);
$siblingTds.not(':eq(' + insertPostion + 1 + ')').addClass('hidden')
.slice(0, insertPostion).find('.node').addClass('slide-right')
.end().end().slice(insertPostion).find('.node').addClass('slide-left');
}
callback();
}
});
} else { // build the sibling nodes and parent node for the specific ndoe
var nodeCount = 0;
buildHierarchy($nodeChart.closest('.orgchart'), nodeData, 0, opts, function() {
if (++nodeCount === siblingCount) {
complementLine($nodeChart.next().children().children('tr:last')
.children().eq(insertPostion).after($('<td colspan="2">')
.append($nodeChart)), siblingCount, 1);
$nodeChart.closest('tr').siblings().eq(0).addClass('hidden').find('.node').addClass('slide-down');
$nodeChart.parent().siblings().addClass('hidden')
.slice(0, insertPostion).find('.node').addClass('slide-right')
.end().end().slice(insertPostion).find('.node').addClass('slide-left');
callback();
}
});
}
}
function addSiblings($node, data, opts) {
buildSiblingNode.call($node.closest('.orgchart').parent(), $node.closest('table'), data, opts, function() {
if (!$node.children('.leftEdge').length) {
$node.children('.topEdge').after('<i class="edge horizontalEdge rightEdge fa"></i><i class="edge horizontalEdge leftEdge fa"></i>');
}
showSiblings($node);
});
}
function removeNodes($node) {
var $parent = $node.closest('table').parent();
var $sibs = $parent.parent().siblings();
if ($parent.is('td')) {
if (getNodeState($node, 'siblings').exist) {
$sibs.eq(2).children('.top:lt(2)').remove();
$sibs.eq(':lt(2)').children().attr('colspan', $sibs.eq(2).children().length);
$parent.remove();
} else {
$sibs.eq(0).children().removeAttr('colspan')
.find('.bottomEdge').remove()
.end().end().siblings().remove();
}
} else {
$parent.add($parent.siblings()).remove();
}
}
}));
|
// # Local File System Image Storage module
// The (default) module for storing images, using the local file system
var _ = require('lodash'),
express = require('express'),
fs = require('fs-extra'),
nodefn = require('when/node/function'),
path = require('path'),
when = require('when'),
errors = require('../errors'),
config = require('../config'),
baseStore = require('./base'),
localFileStore;
localFileStore = _.extend(baseStore, {
// ### Save
// Saves the image to storage (the file system)
// - image is the express image object
// - returns a promise which ultimately returns the full url to the uploaded image
'save': function (image) {
var saved = when.defer(),
targetDir = this.getTargetDir(config().paths.imagesPath),
targetFilename;
this.getUniqueFileName(this, image, targetDir).then(function (filename) {
targetFilename = filename;
return nodefn.call(fs.mkdirs, targetDir);
}).then(function () {
return nodefn.call(fs.copy, image.path, targetFilename);
}).then(function () {
return nodefn.call(fs.unlink, image.path).otherwise(errors.logError);
}).then(function () {
// The src for the image must be in URI format, not a file system path, which in Windows uses \
// For local file system storage can use relative path so add a slash
var fullUrl = (config().paths.subdir + '/' + config().paths.imagesRelPath + '/' + path.relative(config().paths.imagesPath, targetFilename)).replace(new RegExp('\\' + path.sep, 'g'), '/');
return saved.resolve(fullUrl);
}).otherwise(function (e) {
errors.logError(e);
return saved.reject(e);
});
return saved.promise;
},
'exists': function (filename) {
// fs.exists does not play nicely with nodefn because the callback doesn't have an error argument
var done = when.defer();
fs.exists(filename, function (exists) {
done.resolve(exists);
});
return done.promise;
},
// middleware for serving the files
'serve': function () {
var ONE_HOUR_MS = 60 * 60 * 1000,
ONE_YEAR_MS = 365 * 24 * ONE_HOUR_MS;
// For some reason send divides the max age number by 1000
return express['static'](config().paths.imagesPath, {maxAge: ONE_YEAR_MS});
}
});
module.exports = localFileStore;
|
/**
* struct.js - chainable ArrayBuffer DataView wrapper
*
* @author Meiguro / http://meiguro.com/
* @license MIT
*/
var capitalize = function(str) {
return str.charAt(0).toUpperCase() + str.substr(1);
};
var struct = function(def) {
this._littleEndian = true;
this._offset = 0;
this._cursor = 0;
this._makeAccessors(def);
this._view = new DataView(new ArrayBuffer(this._size));
this._def = def;
};
struct.types = {
int8: { size: 1 },
uint8: { size: 1 },
int16: { size: 2 },
uint16: { size: 2 },
int32: { size: 4 },
uint32: { size: 4 },
int64: { size: 8 },
uint64: { size: 8 },
float32: { size: 2 },
float64: { size: 4 },
cstring: { size: 1, dynamic: true },
data: { size: 0, dynamic: true },
};
var makeDataViewAccessor = function(type, typeName) {
var getName = 'get' + capitalize(typeName);
var setName = 'set' + capitalize(typeName);
type.get = function(offset, little) {
this._advance = type.size;
return this._view[getName](offset, little);
};
type.set = function(offset, value, little) {
this._advance = type.size;
this._view[setName](offset, value, little);
};
};
for (var k in struct.types) {
var type = struct.types[k];
makeDataViewAccessor(type, k);
}
struct.types.bool = struct.types.uint8;
struct.types.uint64.get = function(offset, little) {
var buffer = this._view;
var a = buffer.getUint32(offset, little);
var b = buffer.getUint32(offset + 4, little);
this._advance = 8;
return ((little ? b : a) << 32) + (little ? a : b);
};
struct.types.uint64.set = function(offset, value, little) {
var a = value & 0xFFFFFFFF;
var b = (value >> 32) & 0xFFFFFFFF;
var buffer = this._view;
buffer.setUint32(offset, little ? a : b, little);
buffer.setUint32(offset + 4, little ? b : a, little);
this._advance = 8;
};
struct.types.cstring.get = function(offset) {
var chars = [];
var buffer = this._view;
for (var i = offset, ii = buffer.byteLength, j = 0; i < ii && buffer.getUint8(i) !== 0; ++i, ++j) {
chars[j] = String.fromCharCode(buffer.getUint8(i));
}
this._advance = chars.length + 1;
return decodeURIComponent(escape(chars.join('')));
};
struct.types.cstring.set = function(offset, value) {
value = unescape(encodeURIComponent(value));
this._grow(offset + value.length + 1);
var i = offset;
var buffer = this._view;
for (var j = 0, jj = value.length; j < jj && value[i] !== '\0'; ++i, ++j) {
buffer.setUint8(i, value.charCodeAt(j));
}
buffer.setUint8(i, 0);
this._advance = value.length + 1;
};
struct.types.data.get = function(offset) {
var length = this._value;
this._cursor = offset;
var buffer = this._view;
var copy = new DataView(new ArrayBuffer(length));
for (var i = 0; i < length; ++i) {
copy.setUint8(i, buffer.getUint8(i + offset));
}
this._advance = length;
return copy;
};
struct.types.data.set = function(offset, value) {
var length = value.byteLength || value.length;
this._cursor = offset;
this._grow(offset + length);
var buffer = this._view;
if (value instanceof ArrayBuffer) {
value = new DataView(value);
}
for (var i = 0; i < length; ++i) {
buffer.setUint8(i + offset, value instanceof DataView ? value.getUint8(i) : value[i]);
}
this._advance = length;
};
struct.prototype._grow = function(target) {
var buffer = this._view;
var size = buffer.byteLength;
if (target <= size) { return; }
while (size < target) { size *= 2; }
var copy = new DataView(new ArrayBuffer(size));
for (var i = 0; i < buffer.byteLength; ++i) {
copy.setUint8(i, buffer.getUint8(i));
}
this._view = copy;
};
struct.prototype._prevField = function(field) {
field = field || this._access;
var fieldIndex = this._fields.indexOf(field);
return this._fields[fieldIndex - 1];
};
struct.prototype._makeAccessor = function(field) {
this[field.name] = function(value) {
var type = field.type;
if (field.dynamic) {
var prevField = this._prevField(field);
if (prevField === undefined) {
this._cursor = 0;
} else if (this._access === field) {
this._cursor -= this._advance;
} else if (this._access !== prevField) {
throw new Error('dynamic field requires sequential access');
}
} else {
this._cursor = field.index;
}
this._access = field;
var result = this;
if (arguments.length === 0) {
result = type.get.call(this, this._offset + this._cursor, this._littleEndian);
this._value = result;
} else {
if (field.transform) {
value = field.transform(value, field);
}
type.set.call(this, this._offset + this._cursor, value, this._littleEndian);
this._value = value;
}
this._cursor += this._advance;
return result;
};
return this;
};
struct.prototype._makeMetaAccessor = function(name, transform) {
this[name] = function(value, field) {
transform.call(this, value, field);
return this;
};
};
struct.prototype._makeAccessors = function(def, index, fields, prefix) {
index = index || 0;
this._fields = ( fields = fields || [] );
var prevField = fields[fields.length];
for (var i = 0, ii = def.length; i < ii; ++i) {
var member = def[i];
var type = member[0];
if (typeof type === 'string') {
type = struct.types[type];
}
var name = member[1];
if (prefix) {
name = prefix + capitalize(name);
}
var transform = member[2];
if (type instanceof struct) {
if (transform) {
this._makeMetaAccessor(name, transform);
}
this._makeAccessors(type._def, index, fields, name);
index = this._size;
continue;
}
var field = {
index: index,
type: type,
name: name,
transform: transform,
dynamic: type.dynamic || prevField && prevField.dynamic,
};
this._makeAccessor(field);
fields.push(field);
index += type.size;
prevField = field;
}
this._size = index;
return this;
};
struct.prototype.prop = function(def) {
var fields = this._fields;
var i = 0, ii = fields.length, name;
if (arguments.length === 0) {
var obj = {};
for (; i < ii; ++i) {
name = fields[i].name;
obj[name] = this[name]();
}
return obj;
}
for (; i < ii; ++i) {
name = fields[i].name;
if (name in def) {
this[name](def[name]);
}
}
return this;
};
struct.prototype.view = function(view) {
if (arguments.length === 0) {
return this._view;
}
if (view instanceof ArrayBuffer) {
view = new DataView(view);
}
this._view = view;
return this;
};
struct.prototype.offset = function(offset) {
if (arguments.length === 0) {
return this._offset;
}
this._offset = offset;
return this;
};
module.exports = struct;
|
'use strict';
var _ = require('../../lib/helpers/lambda-ramda.js'),
fs = require('fs'),
filePath = require("path").join(__dirname),
modules = {},
requireFile = function(file) {
var properyName = _.replace('.js', file);
myModule[properyName] = require(file);
};
_.map(requireFile, fs.readdirSync(filePath));
module.exports = modules;
|
describe("Rivets.TextTemplateParser", function() {
var Rivets = rivets._
describe("parse()", function() {
it("tokenizes a text template", function() {
template = "Hello {{ user.name }}, you have {{ user.messages.unread | length }} unread messages."
expected = [
{type: 0, value: "Hello "},
{type: 1, value: "user.name"},
{type: 0, value: ", you have "},
{type: 1, value: "user.messages.unread | length"},
{type: 0, value: " unread messages."}
]
results = Rivets.TextTemplateParser.parse(template, ['{{', '}}'])
results.length.should.equal(5)
for (i = 0; i < results.length; i++) {
results[i].type.should.equal(expected[i].type)
results[i].value.should.equal(expected[i].value)
}
})
describe("with no binding fragments", function() {
it("should return a single text token", function() {
template = "Hello World!"
expected = [{type: 0, value: "Hello World!"}]
results = Rivets.TextTemplateParser.parse(template, ['{{', '}}'])
results.length.should.equal(1)
for (i = 0; i < results.length; i++) {
results[i].type.should.equal(expected[i].type)
results[i].value.should.equal(expected[i].value)
}
})
})
describe("with only a binding fragment", function() {
it("should return a single binding token", function() {
template = "{{ user.name }}"
expected = [{type: 1, value: "user.name"}]
results = Rivets.TextTemplateParser.parse(template, ['{{', '}}'])
results.length.should.equal(1)
for (i = 0; i < results.length; i++) {
results[i].type.should.equal(expected[i].type)
results[i].value.should.equal(expected[i].value)
}
})
})
})
})
|
/**
* @license Highcharts JS v6.1.3 (2018-09-12)
*
* (c) 2009-2017 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
(function (factory) {
if (typeof module === 'object' && module.exports) {
module.exports = factory;
} else if (typeof define === 'function' && define.amd) {
define(function () {
return factory;
});
} else {
factory(Highcharts);
}
}(function (Highcharts) {
}));
|
var _ = require('../util')
module.exports = {
acceptStatement: true,
priority: 700,
bind: function () {
// deal with iframes
if (
this.el.tagName === 'IFRAME' &&
this.arg !== 'load'
) {
var self = this
this.iframeBind = function () {
_.on(self.el.contentWindow, self.arg, self.handler)
}
_.on(this.el, 'load', this.iframeBind)
}
},
update: function (handler) {
if (typeof handler !== 'function') {
process.env.NODE_ENV !== 'production' && _.warn(
'Directive v-on="' + this.arg + ': ' +
this.expression + '" expects a function value, ' +
'got ' + handler
)
return
}
this.reset()
var vm = this.vm
this.handler = function (e) {
e.targetVM = vm
vm.$event = e
var res = handler(e)
vm.$event = null
return res
}
if (this.iframeBind) {
this.iframeBind()
} else {
_.on(this.el, this.arg, this.handler)
}
},
reset: function () {
var el = this.iframeBind
? this.el.contentWindow
: this.el
if (this.handler) {
_.off(el, this.arg, this.handler)
}
},
unbind: function () {
this.reset()
_.off(this.el, 'load', this.iframeBind)
}
}
|
function meaningOfLife() {
throw new Error(42);
}
function boom() {
throw new Error('boom');
}
function somethingElse() {
throw new Error("somethign else");
}
// Hello world
function fourth(){
throw new Error('fourth');
}
function third(){
throw new Error("oh no");
}
//# sourceMappingURL=all.map |
/*! jQuery UI - v1.10.4 - 2014-02-09
* http://jqueryui.com
* Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */
jQuery(function(e){e.datepicker.regional.nb={closeText:"Lukk",prevText:"«Forrige",nextText:"Neste»",currentText:"I dag",monthNames:["januar","februar","mars","april","mai","juni","juli","august","september","oktober","november","desember"],monthNamesShort:["jan","feb","mar","apr","mai","jun","jul","aug","sep","okt","nov","des"],dayNamesShort:["søn","man","tir","ons","tor","fre","lør"],dayNames:["søndag","mandag","tirsdag","onsdag","torsdag","fredag","lørdag"],dayNamesMin:["sø","ma","ti","on","to","fr","lø"],weekHeader:"Uke",dateFormat:"dd.mm.yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},e.datepicker.setDefaults(e.datepicker.regional.nb)}); |
/*global device*/
var TrimFocusInput = Ember.TextField.extend({
focus: true,
attributeBindings: ['autofocus'],
autofocus: Ember.computed(function () {
if (this.get('focus')) {
return (device.ios()) ? false : 'autofocus';
}
return false;
}),
didInsertElement: function () {
// This fix is required until Mobile Safari has reliable
// autofocus, select() or focus() support
if (this.get('focus') && !device.ios()) {
this.$().val(this.$().val()).focus();
}
},
focusOut: function () {
var text = this.$().val();
this.$().val(text.trim());
}
});
export default TrimFocusInput;
|
#!/usr/bin/env node
'use strict';
const shell = require('shelljs');
const exec = require('child_process').exec;
const path = require('path');
const fs = require('fs');
const animateProgress = require('./helpers/progress');
const addCheckMark = require('./helpers/checkmark');
const readline = require('readline');
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdout.write('\n');
let interval = animateProgress('Cleaning old repository');
process.stdout.write('Cleaning old repository');
cleanRepo(function () {
clearInterval(interval);
process.stdout.write('\nInstalling dependencies... (This might take a while)');
setTimeout(function () {
readline.cursorTo(process.stdout, 0);
interval = animateProgress('Installing dependencies');
}, 500);
process.stdout.write('Installing dependencies');
installDeps();
});
/**
* Deletes the .git folder in dir
*/
function cleanRepo(callback) {
shell.rm('-rf', '.git/');
addCheckMark(callback);
}
/**
* Initializes git again
*/
function initGit(callback) {
exec('git init && git add . && git commit -m "Initial commit"', addCheckMark.bind(null, callback));
}
/**
* Deletes a file in the current directory
*/
function deleteFileInCurrentDir(file, callback) {
fs.unlink(path.join(__dirname, file), callback);
}
/**
* Installs dependencies
*/
function installDeps() {
exec('yarn --version', function (err, stdout, stderr) {
if (parseFloat(stdout) < 0.15 || err || process.env.USE_YARN === 'false') {
exec('npm install', addCheckMark.bind(null, installDepsCallback));
} else {
exec('yarn install', addCheckMark.bind(null, installDepsCallback));
}
});
}
/**
* Callback function after installing dependencies
*/
function installDepsCallback(error) {
clearInterval(interval);
if (error) {
process.stdout.write(error);
}
deleteFileInCurrentDir('setup.js', function () {
process.stdout.write('\n');
interval = animateProgress('Initialising new repository');
process.stdout.write('Initialising new repository');
initGit(function () {
clearInterval(interval);
process.stdout.write('\nDone!');
process.exit(0);
});
});
}
|
/***
MochiKit.Logging 1.5
See <http://mochikit.com/> for documentation, downloads, license, etc.
(c) 2005 Bob Ippolito. All rights Reserved.
***/
MochiKit.Base._module('Logging', '1.5', ['Base']);
/** @id MochiKit.Logging.LogMessage */
MochiKit.Logging.LogMessage = function (num, level, info) {
this.num = num;
this.level = level;
this.info = info;
this.timestamp = new Date();
};
MochiKit.Logging.LogMessage.prototype = {
/** @id MochiKit.Logging.LogMessage.prototype.repr */
repr: function () {
var m = MochiKit.Base;
return 'LogMessage(' +
m.map(
m.repr,
[this.num, this.level, this.info]
).join(', ') + ')';
},
/** @id MochiKit.Logging.LogMessage.prototype.toString */
toString: MochiKit.Base.forwardCall("repr")
};
MochiKit.Base.update(MochiKit.Logging, {
/** @id MochiKit.Logging.logLevelAtLeast */
logLevelAtLeast: function (minLevel) {
var self = MochiKit.Logging;
if (typeof(minLevel) == 'string') {
minLevel = self.LogLevel[minLevel];
}
return function (msg) {
var msgLevel = msg.level;
if (typeof(msgLevel) == 'string') {
msgLevel = self.LogLevel[msgLevel];
}
return msgLevel >= minLevel;
};
},
/** @id MochiKit.Logging.isLogMessage */
isLogMessage: function (/* ... */) {
var LogMessage = MochiKit.Logging.LogMessage;
for (var i = 0; i < arguments.length; i++) {
if (!(arguments[i] instanceof LogMessage)) {
return false;
}
}
return true;
},
/** @id MochiKit.Logging.compareLogMessage */
compareLogMessage: function (a, b) {
return MochiKit.Base.compare([a.level, a.info], [b.level, b.info]);
},
/** @id MochiKit.Logging.alertListener */
alertListener: function (msg) {
alert(
"num: " + msg.num +
"\nlevel: " + msg.level +
"\ninfo: " + msg.info.join(" ")
);
}
});
/** @id MochiKit.Logging.Logger */
MochiKit.Logging.Logger = function (/* optional */maxSize) {
this.counter = 0;
if (typeof(maxSize) == 'undefined' || maxSize === null) {
maxSize = -1;
}
this.maxSize = maxSize;
this._messages = [];
this.listeners = {};
this.useNativeConsole = false;
};
MochiKit.Logging.Logger.prototype = {
/** @id MochiKit.Logging.Logger.prototype.clear */
clear: function () {
this._messages.splice(0, this._messages.length);
},
/** @id MochiKit.Logging.Logger.prototype.logToConsole */
logToConsole: function (msg) {
if (typeof(window) != "undefined" && window.console
&& window.console.log) {
// Safari and FireBug 0.4
// Percent replacement is a workaround for cute Safari crashing bug
window.console.log(msg.replace(/%/g, '\uFF05'));
} else if (typeof(opera) != "undefined" && opera.postError) {
// Opera
opera.postError(msg);
} else if (typeof(Debug) != "undefined" && Debug.writeln) {
// IE Web Development Helper (?)
// http://www.nikhilk.net/Entry.aspx?id=93
Debug.writeln(msg);
} else if (typeof(debug) != "undefined" && debug.trace) {
// Atlas framework (?)
// http://www.nikhilk.net/Entry.aspx?id=93
debug.trace(msg);
}
},
/** @id MochiKit.Logging.Logger.prototype.dispatchListeners */
dispatchListeners: function (msg) {
for (var k in this.listeners) {
var pair = this.listeners[k];
if (pair.ident != k || (pair[0] && !pair[0](msg))) {
continue;
}
pair[1](msg);
}
},
/** @id MochiKit.Logging.Logger.prototype.addListener */
addListener: function (ident, filter, listener) {
if (typeof(filter) == 'string') {
filter = MochiKit.Logging.logLevelAtLeast(filter);
}
var entry = [filter, listener];
entry.ident = ident;
this.listeners[ident] = entry;
},
/** @id MochiKit.Logging.Logger.prototype.removeListener */
removeListener: function (ident) {
delete this.listeners[ident];
},
/** @id MochiKit.Logging.Logger.prototype.baseLog */
baseLog: function (level, message/*, ...*/) {
if (typeof(level) == "number") {
if (level >= MochiKit.Logging.LogLevel.FATAL) {
level = 'FATAL';
} else if (level >= MochiKit.Logging.LogLevel.ERROR) {
level = 'ERROR';
} else if (level >= MochiKit.Logging.LogLevel.WARNING) {
level = 'WARNING';
} else if (level >= MochiKit.Logging.LogLevel.INFO) {
level = 'INFO';
} else {
level = 'DEBUG';
}
}
var msg = new MochiKit.Logging.LogMessage(
this.counter,
level,
MochiKit.Base.extend(null, arguments, 1)
);
this._messages.push(msg);
this.dispatchListeners(msg);
if (this.useNativeConsole) {
this.logToConsole(msg.level + ": " + msg.info.join(" "));
}
this.counter += 1;
while (this.maxSize >= 0 && this._messages.length > this.maxSize) {
this._messages.shift();
}
},
/** @id MochiKit.Logging.Logger.prototype.getMessages */
getMessages: function (howMany) {
var firstMsg = 0;
if (!(typeof(howMany) == 'undefined' || howMany === null)) {
firstMsg = Math.max(0, this._messages.length - howMany);
}
return this._messages.slice(firstMsg);
},
/** @id MochiKit.Logging.Logger.prototype.getMessageText */
getMessageText: function (howMany) {
if (typeof(howMany) == 'undefined' || howMany === null) {
howMany = 30;
}
var messages = this.getMessages(howMany);
if (messages.length) {
var lst = map(function (m) {
return '\n [' + m.num + '] ' + m.level + ': ' + m.info.join(' ');
}, messages);
lst.unshift('LAST ' + messages.length + ' MESSAGES:');
return lst.join('');
}
return '';
},
/** @id MochiKit.Logging.Logger.prototype.debuggingBookmarklet */
debuggingBookmarklet: function (inline) {
if (typeof(MochiKit.LoggingPane) == "undefined") {
alert(this.getMessageText());
} else {
MochiKit.LoggingPane.createLoggingPane(inline || false);
}
}
};
MochiKit.Logging.__new__ = function () {
this.LogLevel = {
ERROR: 40,
FATAL: 50,
WARNING: 30,
INFO: 20,
DEBUG: 10
};
var m = MochiKit.Base;
m.registerComparator("LogMessage",
this.isLogMessage,
this.compareLogMessage
);
var partial = m.partial;
var Logger = this.Logger;
var baseLog = Logger.prototype.baseLog;
m.update(this.Logger.prototype, {
debug: partial(baseLog, 'DEBUG'),
log: partial(baseLog, 'INFO'),
error: partial(baseLog, 'ERROR'),
fatal: partial(baseLog, 'FATAL'),
warning: partial(baseLog, 'WARNING')
});
// indirectly find logger so it can be replaced
var self = this;
var connectLog = function (name) {
return function () {
self.logger[name].apply(self.logger, arguments);
};
};
/** @id MochiKit.Logging.log */
this.log = connectLog('log');
/** @id MochiKit.Logging.logError */
this.logError = connectLog('error');
/** @id MochiKit.Logging.logDebug */
this.logDebug = connectLog('debug');
/** @id MochiKit.Logging.logFatal */
this.logFatal = connectLog('fatal');
/** @id MochiKit.Logging.logWarning */
this.logWarning = connectLog('warning');
this.logger = new Logger();
this.logger.useNativeConsole = true;
m.nameFunctions(this);
};
MochiKit.Logging.__new__();
MochiKit.Base._exportSymbols(this, MochiKit.Logging);
|
{
"VALIDATOR.FIELDREQUIRED": "Whakakīa \"%s\", he whakaritenga tēnei.",
"HASMANYFILEFIELD.UPLOADING": "Tukuatu ana... %s",
"TABLEFIELD.DELETECONFIRMMESSAGE": "Kei te tino hiahia muku i tēnei pūkete?",
"LOADING": "Uta ana...",
"UNIQUEFIELD.SUGGESTED": "I hurihia te uara ki te '%s' : %s",
"UNIQUEFIELD.ENTERNEWVALUE": "Me tāuru he uara hōu mō tēnei āpure",
"UNIQUEFIELD.CANNOTLEAVEEMPTY": "Kāore e whakaaetia kia noho piako tēnei āpure",
"RESTRICTEDTEXTFIELD.CHARCANTBEUSED": "Kāore e taea te whakamahi i te pūāhua '%s' i tēnei āpure",
"UPDATEURL.CONFIRM": "Kei te hiahia koe kia huri au i te PRO ki:\n\n%s/\n\nPāwhiri Āe kia hurihia te PRO, pāwhiri Whakakore kia waiho:\n\n%s",
"UPDATEURL.CONFIRMURLCHANGED": "Kua hurihia te PRO ki \n\"%s\"",
"FILEIFRAMEFIELD.DELETEFILE": "Muku Kōnae",
"FILEIFRAMEFIELD.UNATTACHFILE": "Wehetāpiri Kōnae",
"FILEIFRAMEFIELD.DELETEIMAGE": "Muku Atahanga",
"FILEIFRAMEFIELD.CONFIRMDELETE": "Kei te tino hiahia muku i tēnei kōnae?",
"LeftAndMain.IncompatBrowserWarning": "Kāore tō pūtirotiro i te hototahi ki te atanga CMS. Whakamahia Internet Explorer 7+, Google Chrome 10+, Mozilla Firefox 3.5+ rānei.",
"GRIDFIELD.ERRORINTRANSACTION": "Kua puta mai he hapa i te tiki raraunga mai i te tūmau\n Ngāna anō ā muri atu.",
"HtmlEditorField.SelectAnchor": "Select an anchor",
"UploadField.ConfirmDelete": "He tika tonu kia tangohia tēnei kōnae i te pūnahakōnae tūmau?",
"UploadField.PHP_MAXFILESIZE": "Kua hipa te mōrahi_rahikōnae_tukuatu i te kōnae (whakaritenga php.ini)",
"UploadField.HTML_MAXFILESIZE": "Kua hipa te mōrahi_rahi_kōnae i te kōnae (whakaritenga puka HTML)",
"UploadField.ONLYPARTIALUPLOADED": "Kua tukuna atu he wāhanga anake o te kōnae",
"UploadField.NOFILEUPLOADED": "Kāore he Kōnae i tukuna atu",
"UploadField.NOTMPFOLDER": "Kua ngaro tētahi kōpaki rangitahi",
"UploadField.WRITEFAILED": "I rahua te tuhi kōnae ki te kōpae",
"UploadField.STOPEDBYEXTENSION": "I whakamutua te tukuatu kōnae e te toronga",
"UploadField.TOOLARGE": "He rahi rawa te rahikōnae",
"UploadField.TOOSMALL": "He iti rawa te rahikōnae",
"UploadField.INVALIDEXTENSION": "Kāore te toronga i te whakaaetia",
"UploadField.MAXNUMBEROFFILESSIMPLE": "Kua hipa te mōrahi kōnae",
"UploadField.UPLOADEDBYTES": "Kua hipa te rahi kōnae i ngā paita kua tukuna atu",
"UploadField.EMPTYRESULT": "Otinga tukuatu kōnae piako",
"UploadField.LOADING": "Uta ana...",
"UploadField.Editing": "Whakatika ana ...",
"UploadField.Uploaded": "Kua tukuna atu",
"UploadField.OVERWRITEWARNING": "Kei te tīari kē tētahi kōnae me te ingoa ōrite",
"TreeDropdownField.ENTERTOSEARCH": "Pēhi tāuru hei rapu",
"TreeDropdownField.OpenLink": "Whakatuwhera",
"TreeDropdownField.FieldTitle": "Kōwhiri",
"TreeDropdownField.SearchFieldTitle": "Kōwhiri ka Rapu rānei"
} |
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v13.2.0
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
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 gridOptionsWrapper_1 = require("../../gridOptionsWrapper");
var expressionService_1 = require("../../valueService/expressionService");
var eventService_1 = require("../../eventService");
var constants_1 = require("../../constants");
var utils_1 = require("../../utils");
var context_1 = require("../../context/context");
var component_1 = require("../../widgets/component");
var rowNode_1 = require("../../entities/rowNode");
var cellRendererService_1 = require("../cellRendererService");
var valueFormatterService_1 = require("../valueFormatterService");
var checkboxSelectionComponent_1 = require("../checkboxSelectionComponent");
var columnController_1 = require("../../columnController/columnController");
var column_1 = require("../../entities/column");
var componentAnnotations_1 = require("../../widgets/componentAnnotations");
var GroupCellRenderer = (function (_super) {
__extends(GroupCellRenderer, _super);
function GroupCellRenderer() {
return _super.call(this, GroupCellRenderer.TEMPLATE) || this;
}
GroupCellRenderer.prototype.init = function (params) {
this.params = params;
var embeddedRowMismatch = this.isEmbeddedRowMismatch();
// This allows for empty strings to appear as groups since
// it will only return for null or undefined.
var cellIsEmpty = params.value == null;
this.cellIsBlank = embeddedRowMismatch || cellIsEmpty;
if (this.cellIsBlank) {
return;
}
this.setupDragOpenParents();
this.addExpandAndContract();
this.addCheckboxIfNeeded();
this.addValueElement();
this.addPadding();
};
// if we are doing embedded full width rows, we only show the renderer when
// in the body, or if pinning in the pinned section, or if pinning and RTL,
// in the right section. otherwise we would have the cell repeated in each section.
GroupCellRenderer.prototype.isEmbeddedRowMismatch = function () {
if (this.gridOptionsWrapper.isEmbedFullWidthRows()) {
var pinnedLeftCell = this.params.pinned === column_1.Column.PINNED_LEFT;
var pinnedRightCell = this.params.pinned === column_1.Column.PINNED_RIGHT;
var bodyCell = !pinnedLeftCell && !pinnedRightCell;
if (this.gridOptionsWrapper.isEnableRtl()) {
if (this.columnController.isPinningLeft()) {
return !pinnedRightCell;
}
else {
return !bodyCell;
}
}
else {
if (this.columnController.isPinningLeft()) {
return !pinnedLeftCell;
}
else {
return !bodyCell;
}
}
}
else {
return false;
}
};
GroupCellRenderer.prototype.setPadding = function () {
if (this.gridOptionsWrapper.isGroupHideOpenParents()) {
return;
}
var params = this.params;
var rowNode = params.node;
var paddingPx;
// never any padding on top level nodes
if (rowNode.uiLevel <= 0) {
paddingPx = 0;
}
else {
var paddingFactor = (params.padding >= 0) ? params.padding : this.gridOptionsWrapper.getGroupPaddingSize();
paddingPx = rowNode.uiLevel * paddingFactor;
var reducedLeafNode = this.columnController.isPivotMode() && params.node.leafGroup;
if (rowNode.footer) {
paddingPx += this.gridOptionsWrapper.getFooterPaddingAddition();
}
else if (!rowNode.isExpandable() || reducedLeafNode) {
paddingPx += this.gridOptionsWrapper.getLeafNodePaddingAddition();
}
}
if (this.gridOptionsWrapper.isEnableRtl()) {
// if doing rtl, padding is on the right
this.getHtmlElement().style.paddingRight = paddingPx + 'px';
}
else {
// otherwise it is on the left
this.getHtmlElement().style.paddingLeft = paddingPx + 'px';
}
};
GroupCellRenderer.prototype.addPadding = function () {
// only do this if an indent - as this overwrites the padding that
// the theme set, which will make things look 'not aligned' for the
// first group level.
var node = this.params.node;
var suppressPadding = this.params.suppressPadding;
if (!suppressPadding) {
this.addDestroyableEventListener(node, rowNode_1.RowNode.EVENT_UI_LEVEL_CHANGED, this.setPadding.bind(this));
this.setPadding();
}
};
GroupCellRenderer.prototype.addValueElement = function () {
var params = this.params;
var rowNode = this.displayedGroup;
if (rowNode.footer) {
this.createFooterCell();
}
else if (rowNode.group ||
utils_1.Utils.get(params.colDef, 'cellRendererParams.innerRenderer', null) ||
utils_1.Utils.get(params.colDef, 'cellRendererParams.innerRendererFramework', null)) {
this.createGroupCell();
if (rowNode.group) {
this.addChildCount();
}
}
else {
this.createLeafCell();
}
};
GroupCellRenderer.prototype.createFooterCell = function () {
var footerValue;
var footerValueGetter = this.params.footerValueGetter;
if (footerValueGetter) {
// params is same as we were given, except we set the value as the item to display
var paramsClone = utils_1.Utils.cloneObject(this.params);
paramsClone.value = this.params.value;
if (typeof footerValueGetter === 'function') {
footerValue = footerValueGetter(paramsClone);
}
else if (typeof footerValueGetter === 'string') {
footerValue = this.expressionService.evaluate(footerValueGetter, paramsClone);
}
else {
console.warn('ag-Grid: footerValueGetter should be either a function or a string (expression)');
}
}
else {
footerValue = 'Total ' + this.params.value;
}
this.eValue.innerHTML = footerValue;
};
GroupCellRenderer.prototype.createGroupCell = function () {
var params = this.params;
var rowGroupColumn = this.displayedGroup.rowGroupColumn;
// we try and use the cellRenderer of the column used for the grouping if we can
var columnToUse = rowGroupColumn ? rowGroupColumn : params.column;
var groupName = this.params.value;
var valueFormatted = this.valueFormatterService.formatValue(columnToUse, params.node, params.scope, groupName);
params.valueFormatted = valueFormatted;
if (params.fullWidth == true) {
this.cellRendererService.useFullWidthGroupRowInnerCellRenderer(this.eValue, params);
}
else {
this.cellRendererService.useInnerCellRenderer(this.params.colDef.cellRendererParams, columnToUse.getColDef(), this.eValue, params);
}
};
GroupCellRenderer.prototype.addChildCount = function () {
// only include the child count if it's included, eg if user doing custom aggregation,
// then this could be left out, or set to -1, ie no child count
if (this.params.suppressCount) {
return;
}
this.addDestroyableEventListener(this.displayedGroup, rowNode_1.RowNode.EVENT_ALL_CHILDREN_COUNT_CELL_CHANGED, this.updateChildCount.bind(this));
// filtering changes the child count, so need to cater for it
this.updateChildCount();
};
GroupCellRenderer.prototype.updateChildCount = function () {
var allChildrenCount = this.displayedGroup.allChildrenCount;
this.eChildCount.innerHTML = allChildrenCount >= 0 ? "(" + allChildrenCount + ")" : "";
};
GroupCellRenderer.prototype.createLeafCell = function () {
if (utils_1.Utils.exists(this.params.value)) {
this.eValue.innerHTML = this.params.value;
}
};
GroupCellRenderer.prototype.isUserWantsSelected = function () {
var paramsCheckbox = this.params.checkbox;
if (typeof paramsCheckbox === 'function') {
return paramsCheckbox(this.params);
}
else {
return paramsCheckbox === true;
}
};
GroupCellRenderer.prototype.addCheckboxIfNeeded = function () {
var rowNode = this.params.node;
var checkboxNeeded = this.isUserWantsSelected()
&& !rowNode.footer
&& !rowNode.rowPinned
&& !rowNode.flower;
if (checkboxNeeded) {
var cbSelectionComponent_1 = new checkboxSelectionComponent_1.CheckboxSelectionComponent();
this.context.wireBean(cbSelectionComponent_1);
cbSelectionComponent_1.init({ rowNode: rowNode, column: this.params.column });
this.eCheckbox.appendChild(cbSelectionComponent_1.getHtmlElement());
this.addDestroyFunc(function () { return cbSelectionComponent_1.destroy(); });
}
};
GroupCellRenderer.prototype.addExpandAndContract = function () {
var params = this.params;
var eGroupCell = params.eGridCell;
var eExpandedIcon = utils_1.Utils.createIconNoSpan('groupExpanded', this.gridOptionsWrapper, null);
var eContractedIcon = utils_1.Utils.createIconNoSpan('groupContracted', this.gridOptionsWrapper, null);
this.eExpanded.appendChild(eExpandedIcon);
this.eContracted.appendChild(eContractedIcon);
this.addDestroyableEventListener(this.eExpanded, 'click', this.onExpandClicked.bind(this));
this.addDestroyableEventListener(this.eContracted, 'click', this.onExpandClicked.bind(this));
// expand / contract as the user hits enter
this.addDestroyableEventListener(eGroupCell, 'keydown', this.onKeyDown.bind(this));
this.addDestroyableEventListener(params.node, rowNode_1.RowNode.EVENT_EXPANDED_CHANGED, this.showExpandAndContractIcons.bind(this));
this.showExpandAndContractIcons();
// if editing groups, then double click is to start editing
if (!this.gridOptionsWrapper.isEnableGroupEdit() && this.isExpandable()) {
this.addDestroyableEventListener(eGroupCell, 'dblclick', this.onCellDblClicked.bind(this));
}
};
GroupCellRenderer.prototype.onKeyDown = function (event) {
if (utils_1.Utils.isKeyPressed(event, constants_1.Constants.KEY_ENTER)) {
var cellEditable = this.params.column.isCellEditable(this.params.node);
if (cellEditable) {
return;
}
event.preventDefault();
this.onExpandOrContract();
}
};
GroupCellRenderer.prototype.setupDragOpenParents = function () {
var column = this.params.column;
var rowNode = this.params.node;
if (!this.gridOptionsWrapper.isGroupHideOpenParents()) {
this.draggedFromHideOpenParents = false;
}
else if (!rowNode.group) {
// if we are here, and we are not a group, then we must of been dragged down,
// as otherwise the cell would be blank, and if cell is blank, this method is never called.
this.draggedFromHideOpenParents = true;
}
else {
var rowGroupColumn = rowNode.rowGroupColumn;
// if the displayGroup column for this col matches the rowGroupColumn we grouped by for this node,
// then nothing was dragged down
this.draggedFromHideOpenParents = !column.isRowGroupDisplayed(rowGroupColumn.getId());
}
if (this.draggedFromHideOpenParents) {
var pointer = rowNode.parent;
while (true) {
if (utils_1.Utils.missing(pointer)) {
break;
}
if (pointer.rowGroupColumn && column.isRowGroupDisplayed(pointer.rowGroupColumn.getId())) {
this.displayedGroup = pointer;
break;
}
pointer = pointer.parent;
}
}
// if we didn't find a displayed group, set it to the row node
if (utils_1.Utils.missing(this.displayedGroup)) {
this.displayedGroup = rowNode;
}
};
GroupCellRenderer.prototype.onExpandClicked = function () {
this.onExpandOrContract();
};
GroupCellRenderer.prototype.onCellDblClicked = function (event) {
// we want to avoid acting on double click events on the expand / contract icon,
// as that icons already has expand / collapse functionality on it. otherwise if
// the icon was double clicked, we would get 'click', 'click', 'dblclick' which
// is open->close->open, however double click should be open->close only.
var target = utils_1.Utils.getTarget(event);
var targetIsExpandIcon = target !== this.eExpanded && target !== this.eContracted;
if (!targetIsExpandIcon) {
this.onExpandOrContract();
}
};
GroupCellRenderer.prototype.onExpandOrContract = function () {
// must use the displayedGroup, so if data was dragged down, we expand the parent, not this row
var rowNode = this.displayedGroup;
rowNode.setExpanded(!rowNode.expanded);
if (this.gridOptionsWrapper.isGroupIncludeFooter()) {
this.params.api.redrawRows({ rowNodes: [rowNode] });
}
};
GroupCellRenderer.prototype.isExpandable = function () {
var rowNode = this.params.node;
var reducedLeafNode = this.columnController.isPivotMode() && rowNode.leafGroup;
return this.draggedFromHideOpenParents || (rowNode.isExpandable() && !rowNode.footer && !reducedLeafNode);
};
GroupCellRenderer.prototype.showExpandAndContractIcons = function () {
var rowNode = this.params.node;
if (this.isExpandable()) {
// if expandable, show one based on expand state.
// if we were dragged down, means our parent is always expanded
var expanded = this.draggedFromHideOpenParents ? true : rowNode.expanded;
utils_1.Utils.setVisible(this.eContracted, !expanded);
utils_1.Utils.setVisible(this.eExpanded, expanded);
}
else {
// it not expandable, show neither
utils_1.Utils.setVisible(this.eExpanded, false);
utils_1.Utils.setVisible(this.eContracted, false);
}
};
GroupCellRenderer.prototype.refresh = function () {
return false;
};
GroupCellRenderer.TEMPLATE = '<span>' +
'<span class="ag-group-expanded" ref="eExpanded"></span>' +
'<span class="ag-group-contracted" ref="eContracted"></span>' +
'<span class="ag-group-checkbox" ref="eCheckbox"></span>' +
'<span class="ag-group-value" ref="eValue"></span>' +
'<span class="ag-group-child-count" ref="eChildCount"></span>' +
'</span>';
__decorate([
context_1.Autowired('gridOptionsWrapper'),
__metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper)
], GroupCellRenderer.prototype, "gridOptionsWrapper", void 0);
__decorate([
context_1.Autowired('expressionService'),
__metadata("design:type", expressionService_1.ExpressionService)
], GroupCellRenderer.prototype, "expressionService", void 0);
__decorate([
context_1.Autowired('eventService'),
__metadata("design:type", eventService_1.EventService)
], GroupCellRenderer.prototype, "eventService", void 0);
__decorate([
context_1.Autowired('cellRendererService'),
__metadata("design:type", cellRendererService_1.CellRendererService)
], GroupCellRenderer.prototype, "cellRendererService", void 0);
__decorate([
context_1.Autowired('valueFormatterService'),
__metadata("design:type", valueFormatterService_1.ValueFormatterService)
], GroupCellRenderer.prototype, "valueFormatterService", void 0);
__decorate([
context_1.Autowired('context'),
__metadata("design:type", context_1.Context)
], GroupCellRenderer.prototype, "context", void 0);
__decorate([
context_1.Autowired('columnController'),
__metadata("design:type", columnController_1.ColumnController)
], GroupCellRenderer.prototype, "columnController", void 0);
__decorate([
componentAnnotations_1.RefSelector('eExpanded'),
__metadata("design:type", HTMLElement)
], GroupCellRenderer.prototype, "eExpanded", void 0);
__decorate([
componentAnnotations_1.RefSelector('eContracted'),
__metadata("design:type", HTMLElement)
], GroupCellRenderer.prototype, "eContracted", void 0);
__decorate([
componentAnnotations_1.RefSelector('eCheckbox'),
__metadata("design:type", HTMLElement)
], GroupCellRenderer.prototype, "eCheckbox", void 0);
__decorate([
componentAnnotations_1.RefSelector('eValue'),
__metadata("design:type", HTMLElement)
], GroupCellRenderer.prototype, "eValue", void 0);
__decorate([
componentAnnotations_1.RefSelector('eChildCount'),
__metadata("design:type", HTMLElement)
], GroupCellRenderer.prototype, "eChildCount", void 0);
return GroupCellRenderer;
}(component_1.Component));
exports.GroupCellRenderer = GroupCellRenderer;
|
module.exports={"title":"Verizon","hex":"CD040B","source":"https://www.verizondigitalmedia.com/about/logo-usage/","svg":"<svg role=\"img\" viewBox=\"0 0 24 24\" xmlns=\"http://www.w3.org/2000/svg\"><title>Verizon icon</title><path d=\"M18.302 0H22v.003L10.674 24H7.662L2 12h3.727l3.449 7.337z\"/></svg>"}; |
/**
* `editor` type prompt
*/
var util = require('util');
var chalk = require('chalk');
var ExternalEditor = require('external-editor');
var Base = require('./base');
var observe = require('../utils/events');
/**
* Module exports
*/
module.exports = Prompt;
/**
* Constructor
*/
function Prompt() {
return Base.apply(this, arguments);
}
util.inherits(Prompt, Base);
/**
* Start the Inquiry session
* @param {Function} cb Callback when prompt is done
* @return {this}
*/
Prompt.prototype._run = function (cb) {
this.done = cb;
// Once user confirm (enter key)
var events = observe(this.rl);
var submit = events.line.map(this.startExternalEditor.bind(this));
var validation = this.handleSubmitEvents(submit);
validation.success.forEach(this.onEnd.bind(this));
validation.error.forEach(this.onError.bind(this));
// Prevents default from being printed on screen (can look weird with multiple lines)
this.currentText = this.opt.default;
this.opt.default = null;
// Init
this.render();
return this;
};
/**
* Render the prompt to screen
* @return {Prompt} self
*/
Prompt.prototype.render = function (error) {
var bottomContent = '';
var message = this.getQuestion();
if (this.status === 'answered') {
message += chalk.dim('Received');
} else {
message += chalk.dim('Press <enter> to launch your preferred editor.');
}
if (error) {
bottomContent = chalk.red('>> ') + error;
}
this.screen.render(message, bottomContent);
};
/**
* Launch $EDITOR on user press enter
*/
Prompt.prototype.startExternalEditor = function () {
this.currentText = ExternalEditor.edit(this.currentText);
return this.currentText;
};
Prompt.prototype.onEnd = function (state) {
this.answer = state.value;
this.status = 'answered';
// Re-render prompt
this.render();
this.screen.done();
this.done(this.answer);
};
Prompt.prototype.onError = function (state) {
this.render(state.isValid);
};
|
loadIonicon('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M416 64H96c-17.7 0-32 14.3-32 32v320c0 17.7 14.3 32 32 32h320c17.7 0 32-14.3 32-32V96c0-17.7-14.3-32-32-32zm4 348c0 4.4-3.6 8-8 8H100c-4.4 0-8-3.6-8-8V100c0-4.4 3.6-8 8-8h312c4.4 0 8 3.6 8 8v312z"/><path d="M363.6 192.9L346 174.8c-.7-.8-1.8-1.2-2.8-1.2-1.1 0-2.1.4-2.8 1.2l-122 122.9-44.4-44.4c-.8-.8-1.8-1.2-2.8-1.2-1 0-2 .4-2.8 1.2l-17.8 17.8c-1.6 1.6-1.6 4.1 0 5.7l56 56c3.6 3.6 8 5.7 11.7 5.7 5.3 0 9.9-3.9 11.6-5.5h.1l133.7-134.4c1.4-1.7 1.4-4.2-.1-5.7z"/></svg>','ios-checkbox-outline'); |
version https://git-lfs.github.com/spec/v1
oid sha256:f569a4730a75b6e028411841508e8c7032641b675365483a6bd61205b6ebaf07
size 2295
|
app.game.hud = {
render: function(delta) {
var player = app.game.players[0];
this.renderBar(16, 16, 80, 6, player.hp / player.maxHp, "#08f");
},
renderBar: function(x, y, width, height, progress, color) {
app.layer.fillStyle("#000").fillRect(x, y, width, height);
app.layer.fillStyle(color).fillRect(x, y, width * progress, height);
}
}; |
(function () {
'use strict';
angular
.module('crowdsource.template', [
'crowdsource.template.controllers',
'crowdsource.template.services',
'crowdsource.template.directives'
]);
angular
.module('crowdsource.template.controllers', []);
angular
.module('crowdsource.template.services', []);
angular
.module('crowdsource.template.directives', []);
})(); |
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v9.0.3
* @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 gridOptionsWrapper_1 = require("../gridOptionsWrapper");
var rowNode_1 = require("../entities/rowNode");
var context_1 = require("../context/context");
var eventService_1 = require("../eventService");
var context_2 = require("../context/context");
var events_1 = require("../events");
var context_3 = require("../context/context");
var constants_1 = require("../constants");
var utils_1 = require("../utils");
var FloatingRowModel = (function () {
function FloatingRowModel() {
}
FloatingRowModel.prototype.init = function () {
this.setFloatingTopRowData(this.gridOptionsWrapper.getFloatingTopRowData());
this.setFloatingBottomRowData(this.gridOptionsWrapper.getFloatingBottomRowData());
};
FloatingRowModel.prototype.isEmpty = function (floating) {
var rows = floating === constants_1.Constants.FLOATING_TOP ? this.floatingTopRows : this.floatingBottomRows;
return utils_1.Utils.missingOrEmpty(rows);
};
FloatingRowModel.prototype.isRowsToRender = function (floating) {
return !this.isEmpty(floating);
};
FloatingRowModel.prototype.getRowAtPixel = function (pixel, floating) {
var rows = floating === constants_1.Constants.FLOATING_TOP ? this.floatingTopRows : this.floatingBottomRows;
if (utils_1.Utils.missingOrEmpty(rows)) {
return 0; // this should never happen, just in case, 0 is graceful failure
}
for (var i = 0; i < rows.length; i++) {
var rowNode = rows[i];
var rowTopPixel = rowNode.rowTop + rowNode.rowHeight - 1;
// only need to range check against the top pixel, as we are going through the list
// in order, first row to hit the pixel wins
if (rowTopPixel >= pixel) {
return i;
}
}
return rows.length - 1;
};
FloatingRowModel.prototype.setFloatingTopRowData = function (rowData) {
this.floatingTopRows = this.createNodesFromData(rowData, true);
this.eventService.dispatchEvent(events_1.Events.EVENT_FLOATING_ROW_DATA_CHANGED);
};
FloatingRowModel.prototype.setFloatingBottomRowData = function (rowData) {
this.floatingBottomRows = this.createNodesFromData(rowData, false);
this.eventService.dispatchEvent(events_1.Events.EVENT_FLOATING_ROW_DATA_CHANGED);
};
FloatingRowModel.prototype.createNodesFromData = function (allData, isTop) {
var _this = this;
var rowNodes = [];
if (allData) {
var nextRowTop = 0;
allData.forEach(function (dataItem, index) {
var rowNode = new rowNode_1.RowNode();
_this.context.wireBean(rowNode);
rowNode.data = dataItem;
rowNode.floating = isTop ? constants_1.Constants.FLOATING_TOP : constants_1.Constants.FLOATING_BOTTOM;
rowNode.setRowTop(nextRowTop);
rowNode.setRowHeight(_this.gridOptionsWrapper.getRowHeightForNode(rowNode));
rowNode.setRowIndex(index);
nextRowTop += rowNode.rowHeight;
rowNodes.push(rowNode);
});
}
return rowNodes;
};
FloatingRowModel.prototype.getFloatingTopRowData = function () {
return this.floatingTopRows;
};
FloatingRowModel.prototype.getFloatingBottomRowData = function () {
return this.floatingBottomRows;
};
FloatingRowModel.prototype.getFloatingTopTotalHeight = function () {
return this.getTotalHeight(this.floatingTopRows);
};
FloatingRowModel.prototype.getFloatingTopRowCount = function () {
return this.floatingTopRows ? this.floatingTopRows.length : 0;
};
FloatingRowModel.prototype.getFloatingBottomRowCount = function () {
return this.floatingBottomRows ? this.floatingBottomRows.length : 0;
};
FloatingRowModel.prototype.getFloatingTopRow = function (index) {
return this.floatingTopRows[index];
};
FloatingRowModel.prototype.getFloatingBottomRow = function (index) {
return this.floatingBottomRows[index];
};
FloatingRowModel.prototype.forEachFloatingTopRow = function (callback) {
if (utils_1.Utils.missingOrEmpty(this.floatingTopRows)) {
return;
}
this.floatingTopRows.forEach(callback);
};
FloatingRowModel.prototype.forEachFloatingBottomRow = function (callback) {
if (utils_1.Utils.missingOrEmpty(this.floatingBottomRows)) {
return;
}
this.floatingBottomRows.forEach(callback);
};
FloatingRowModel.prototype.getFloatingBottomTotalHeight = function () {
return this.getTotalHeight(this.floatingBottomRows);
};
FloatingRowModel.prototype.getTotalHeight = function (rowNodes) {
if (!rowNodes || rowNodes.length === 0) {
return 0;
}
else {
var lastNode = rowNodes[rowNodes.length - 1];
return lastNode.rowTop + lastNode.rowHeight;
}
};
return FloatingRowModel;
}());
__decorate([
context_2.Autowired('gridOptionsWrapper'),
__metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper)
], FloatingRowModel.prototype, "gridOptionsWrapper", void 0);
__decorate([
context_2.Autowired('eventService'),
__metadata("design:type", eventService_1.EventService)
], FloatingRowModel.prototype, "eventService", void 0);
__decorate([
context_2.Autowired('context'),
__metadata("design:type", context_1.Context)
], FloatingRowModel.prototype, "context", void 0);
__decorate([
context_3.PostConstruct,
__metadata("design:type", Function),
__metadata("design:paramtypes", []),
__metadata("design:returntype", void 0)
], FloatingRowModel.prototype, "init", null);
FloatingRowModel = __decorate([
context_1.Bean('floatingRowModel')
], FloatingRowModel);
exports.FloatingRowModel = FloatingRowModel;
|
/* ng-infinite-scroll - v1.0.0 - 2013-02-23 */
/*This is custom versiom on infinite-scroll, we have added infiniteContainer attribute which accept container name on which we are applying the scroll*/
var mod;
mod = angular.module('infinite-scroll', []);
mod.directive('infiniteScroll', [
'$rootScope', '$window', '$timeout', function($rootScope, $window, $timeout) {
return {
link: function(scope, elem, attrs) {
var checkWhenEnabled, handler, scrollDistance, scrollEnabled, $parent;
$parent = angular.element(attrs.infiniteContainer || $window);
console.log("PAR",$parent);
scrollDistance = 0;
if (attrs.infiniteScrollDistance != null) {
scope.$watch(attrs.infiniteScrollDistance, function(value) {
return scrollDistance = parseInt(value, 10);
});
}
scrollEnabled = true;
checkWhenEnabled = false;
if (attrs.infiniteScrollDisabled != null) {
scope.$watch(attrs.infiniteScrollDisabled, function(value) {
scrollEnabled = !value;
if (scrollEnabled && checkWhenEnabled) {
checkWhenEnabled = false;
return handler();
}
});
}
handler = function() {
var elementBottom, remaining, shouldScroll, windowBottom;
windowBottom = $parent.height() + $parent.scrollTop();
elementBottom = elem.offset().top + elem.height();
remaining = elementBottom - windowBottom;
shouldScroll = remaining <= $parent.height() * scrollDistance;
if (shouldScroll && scrollEnabled) {
if ($rootScope.$$phase) {
return scope.$eval(attrs.infiniteScroll);
} else {
return scope.$apply(attrs.infiniteScroll);
}
} else if (shouldScroll) {
return checkWhenEnabled = true;
}
};
$parent.on('scroll', handler);
scope.$on('$destroy', function() {
return $parent.off('scroll', handler);
});
return $timeout((function() {
if (attrs.infiniteScrollImmediateCheck) {
if (scope.$eval(attrs.infiniteScrollImmediateCheck)) {
return handler();
}
} else {
return handler();
}
}), 0);
}
};
}
]); |
import ActorClient from 'utils/ActorClient';
import ActorAppDispatcher from 'dispatcher/ActorAppDispatcher';
import { ActionTypes } from 'constants/ActorAppConstants';
import DraftActionCreators from 'actions/DraftActionCreators';
export default {
cleanText: () => {
DraftActionCreators.saveDraft('', true);
ActorAppDispatcher.dispatch({
type: ActionTypes.COMPOSE_CLEAN
});
},
insertMention: (peer, text, caretPosition, mention) => {
ActorAppDispatcher.dispatch({
type: ActionTypes.COMPOSE_MENTION_INSERT,
peer: peer,
text: text,
caretPosition: caretPosition,
mention: mention
});
},
closeMention: () => {
ActorAppDispatcher.dispatch({
type: ActionTypes.COMPOSE_MENTION_CLOSE
});
},
onTyping: function(peer, text, caretPosition) {
if (text !== '') {
ActorClient.onTyping(peer);
}
DraftActionCreators.saveDraft(text);
ActorAppDispatcher.dispatch({
type: ActionTypes.COMPOSE_TYPING,
peer: peer,
text: text,
caretPosition: caretPosition
});
}
};
|
/**
* @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', 'fr', {
selectedLabel: '%1 (Sélectionné)'
} );
|
/**
* Login server abstraction layer
* Pokemon Showdown - http://pokemonshowdown.com/
*
* This file handles communicating with the login server.
*
* @license MIT license
*/
const LOGIN_SERVER_TIMEOUT = 15000;
const LOGIN_SERVER_BATCH_TIME = 1000;
var http = require("http");
var url = require('url');
/* global LoginServer: true */
var LoginServer = module.exports = (function () {
function LoginServer(uri) {
console.log('Creating LoginServer object for ' + uri + '...');
this.uri = uri;
this.requestQueue = [];
LoginServer.loginServers[this.uri] = this;
}
// "static" mapping of URIs to LoginServer objects
LoginServer.loginServers = {};
// "static" flag
LoginServer.disabled = false;
LoginServer.prototype.requestTimer = null;
LoginServer.prototype.requestTimeoutTimer = null;
LoginServer.prototype.requestLog = '';
LoginServer.prototype.lastRequest = 0;
LoginServer.prototype.openRequests = 0;
var getLoginServer = function (action) {
var uri;
if (Config.loginservers) {
uri = Config.loginservers[action] || Config.loginservers[null];
} else {
uri = Config.loginserver;
}
if (!uri) {
console.log('ERROR: No login server specified for action: ' + action);
return;
}
return LoginServer.loginServers[uri] || new LoginServer(uri);
};
LoginServer.instantRequest = function (action, data, callback) {
return getLoginServer(action).instantRequest(action, data, callback);
};
LoginServer.request = function (action, data, callback) {
return getLoginServer(action).request(action, data, callback);
};
var parseJSON = function (json) {
if (json[0] === ']') json = json.substr(1);
return JSON.parse(json);
};
LoginServer.prototype.instantRequest = function (action, data, callback) {
if (typeof data === 'function') {
callback = data;
data = null;
}
if (this.openRequests > 5) {
callback(null, null, 'overflow');
return;
}
this.openRequests++;
var dataString = '';
if (data) {
for (var i in data) {
dataString += '&' + i + '=' + encodeURIComponent('' + data[i]);
}
}
var req = http.get(url.parse(this.uri + 'action.php?act=' + action + '&serverid=' + Config.serverid + '&servertoken=' + Config.servertoken + '&nocache=' + new Date().getTime() + dataString), function (res) {
var buffer = '';
res.setEncoding('utf8');
res.on('data', function (chunk) {
buffer += chunk;
});
res.on('end', function () {
var data = null;
try {
data = parseJSON(buffer);
} catch (e) {}
callback(data, res.statusCode);
this.openRequests--;
});
});
req.on('error', function (error) {
callback(null, null, error);
this.openRequests--;
});
req.end();
};
LoginServer.prototype.request = function (action, data, callback) {
if (typeof data === 'function') {
callback = data;
data = null;
}
if (LoginServer.disabled) {
callback(null, null, 'disabled');
return;
}
if (!data) data = {};
data.act = action;
data.callback = callback;
this.requestQueue.push(data);
this.requestTimerPoke();
};
LoginServer.prototype.requestTimerPoke = function () {
// "poke" the request timer, i.e. make sure it knows it should make
// a request soon
// if we already have it going or the request queue is empty no need to do anything
if (this.openRequests || this.requestTimer || !this.requestQueue.length) return;
this.requestTimer = setTimeout(this.makeRequests.bind(this), LOGIN_SERVER_BATCH_TIME);
};
LoginServer.prototype.makeRequests = function () {
this.requestTimer = null;
var self = this;
var requests = this.requestQueue;
this.requestQueue = [];
if (!requests.length) return;
var requestCallbacks = [];
for (var i = 0, len = requests.length; i < len; i++) {
var request = requests[i];
requestCallbacks[i] = request.callback;
delete request.callback;
}
this.requestStart(requests.length);
var postData = 'serverid=' + Config.serverid + '&servertoken=' + Config.servertoken + '&nocache=' + new Date().getTime() + '&json=' + encodeURIComponent(JSON.stringify(requests)) + '\n';
var requestOptions = url.parse(this.uri + 'action.php');
requestOptions.method = 'post';
requestOptions.headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
};
var req = null;
var reqError = function (error) {
if (self.requestTimeoutTimer) {
clearTimeout(self.requestTimeoutTimer);
self.requestTimeoutTimer = null;
}
req.abort();
for (var i = 0, len = requestCallbacks.length; i < len; i++) {
requestCallbacks[i](null, null, error);
}
self.requestEnd();
};
self.requestTimeoutTimer = setTimeout(function () {
reqError('timeout');
}, LOGIN_SERVER_TIMEOUT);
req = http.request(requestOptions, function (res) {
if (self.requestTimeoutTimer) {
clearTimeout(self.requestTimeoutTimer);
self.requestTimeoutTimer = null;
}
var buffer = '';
res.setEncoding('utf8');
res.on('data', function (chunk) {
buffer += chunk;
});
var endReq = function () {
if (self.requestTimeoutTimer) {
clearTimeout(self.requestTimeoutTimer);
self.requestTimeoutTimer = null;
}
//console.log('RESPONSE: ' + buffer);
var data = null;
try {
data = parseJSON(buffer);
} catch (e) {}
for (var i = 0, len = requestCallbacks.length; i < len; i++) {
if (data) {
requestCallbacks[i](data[i], res.statusCode);
} else {
requestCallbacks[i](null, res.statusCode, 'corruption');
}
}
self.requestEnd();
}.once();
res.on('end', endReq);
res.on('close', endReq);
self.requestTimeoutTimer = setTimeout(function (){
if (res.connection) res.connection.destroy();
endReq();
}, LOGIN_SERVER_TIMEOUT);
});
req.on('error', reqError);
req.write(postData);
req.end();
};
LoginServer.prototype.requestStart = function (size) {
this.lastRequest = Date.now();
this.requestLog += ' | ' + size + ' requests: ';
this.openRequests++;
};
LoginServer.prototype.requestEnd = function () {
this.openRequests = 0;
this.requestLog += '' + (Date.now() - this.lastRequest).duration();
this.requestLog = this.requestLog.substr(-1000);
this.requestTimerPoke();
};
LoginServer.prototype.getLog = function () {
return this.requestLog + (this.lastRequest ? ' (' + (Date.now() - this.lastRequest).duration() + ' since last request)' : '');
};
return LoginServer;
})();
require('fs').watchFile('./config/custom.css', function (curr, prev) {
LoginServer.request('invalidatecss', {}, function () {});
});
LoginServer.request('invalidatecss', {}, function () {});
|
/*! jQuery UI - v1.10.4 - 2014-06-04
* http://jqueryui.com
* Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */
jQuery(function(e){e.datepicker.regional.rm={closeText:"Serrar",prevText:"<Suandant",nextText:"Precedent>",currentText:"Actual",monthNames:["Schaner","Favrer","Mars","Avrigl","Matg","Zercladur","Fanadur","Avust","Settember","October","November","December"],monthNamesShort:["Scha","Fev","Mar","Avr","Matg","Zer","Fan","Avu","Sett","Oct","Nov","Dec"],dayNames:["Dumengia","Glindesdi","Mardi","Mesemna","Gievgia","Venderdi","Sonda"],dayNamesShort:["Dum","Gli","Mar","Mes","Gie","Ven","Som"],dayNamesMin:["Du","Gl","Ma","Me","Gi","Ve","So"],weekHeader:"emna",dateFormat:"dd/mm/yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},e.datepicker.setDefaults(e.datepicker.regional.rm)}); |
/** File: strophe.js
* A JavaScript library for writing XMPP clients.
*
* This library uses either Bidirectional-streams Over Synchronous HTTP (BOSH)
* to emulate a persistent, stateful, two-way connection to an XMPP server or
* alternatively WebSockets.
*
* More information on BOSH can be found in XEP 124.
* For more information on XMPP-over WebSocket see this RFC:
* http://tools.ietf.org/html/rfc7395
*/
/* All of the Strophe globals are defined in this special function below so
* that references to the globals become closures. This will ensure that
* on page reload, these references will still be available to callbacks
* that are still executing.
*/
/* jshint ignore:start */
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
//Allow using this built library as an AMD module
//in another project. That other project will only
//see this AMD call, not the internal modules in
//the closure below.
define([], factory);
} else {
//Browser globals case.
var wrapper = factory();
root.Strophe = wrapper.Strophe;
root.$build = wrapper.$build;
root.$iq = wrapper.$iq;
root.$msg = wrapper.$msg;
root.$pres = wrapper.$pres;
root.SHA1 = wrapper.SHA1;
root.MD5 = wrapper.MD5;
root.b64_hmac_sha1 = wrapper.b64_hmac_sha1;
root.b64_sha1 = wrapper.b64_sha1;
root.str_hmac_sha1 = wrapper.str_hmac_sha1;
root.str_sha1 = wrapper.str_sha1;
}
}(this, function () {
//almond, and your modules will be inlined here
/* jshint ignore:end */
/**
* @license almond 0.3.3 Copyright jQuery Foundation and other contributors.
* Released under MIT license, http://github.com/requirejs/almond/LICENSE
*/
//Going sloppy to avoid 'use strict' string cost, but strict practices should
//be followed.
/*global setTimeout: false */
var requirejs, require, define;
(function (undef) {
var main, req, makeMap, handlers,
defined = {},
waiting = {},
config = {},
defining = {},
hasOwn = Object.prototype.hasOwnProperty,
aps = [].slice,
jsSuffixRegExp = /\.js$/;
function hasProp(obj, prop) {
return hasOwn.call(obj, prop);
}
/**
* Given a relative module name, like ./something, normalize it to
* a real name that can be mapped to a path.
* @param {String} name the relative name
* @param {String} baseName a real name that the name arg is relative
* to.
* @returns {String} normalized name
*/
function normalize(name, baseName) {
var nameParts, nameSegment, mapValue, foundMap, lastIndex,
foundI, foundStarMap, starI, i, j, part, normalizedBaseParts,
baseParts = baseName && baseName.split("/"),
map = config.map,
starMap = (map && map['*']) || {};
//Adjust any relative paths.
if (name) {
name = name.split('/');
lastIndex = name.length - 1;
// If wanting node ID compatibility, strip .js from end
// of IDs. Have to do this here, and not in nameToUrl
// because node allows either .js or non .js to map
// to same file.
if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) {
name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, '');
}
// Starts with a '.' so need the baseName
if (name[0].charAt(0) === '.' && baseParts) {
//Convert baseName to array, and lop off the last part,
//so that . matches that 'directory' and not name of the baseName's
//module. For instance, baseName of 'one/two/three', maps to
//'one/two/three.js', but we want the directory, 'one/two' for
//this normalization.
normalizedBaseParts = baseParts.slice(0, baseParts.length - 1);
name = normalizedBaseParts.concat(name);
}
//start trimDots
for (i = 0; i < name.length; i++) {
part = name[i];
if (part === '.') {
name.splice(i, 1);
i -= 1;
} else if (part === '..') {
// If at the start, or previous value is still ..,
// keep them so that when converted to a path it may
// still work when converted to a path, even though
// as an ID it is less than ideal. In larger point
// releases, may be better to just kick out an error.
if (i === 0 || (i === 1 && name[2] === '..') || name[i - 1] === '..') {
continue;
} else if (i > 0) {
name.splice(i - 1, 2);
i -= 2;
}
}
}
//end trimDots
name = name.join('/');
}
//Apply map config if available.
if ((baseParts || starMap) && map) {
nameParts = name.split('/');
for (i = nameParts.length; i > 0; i -= 1) {
nameSegment = nameParts.slice(0, i).join("/");
if (baseParts) {
//Find the longest baseName segment match in the config.
//So, do joins on the biggest to smallest lengths of baseParts.
for (j = baseParts.length; j > 0; j -= 1) {
mapValue = map[baseParts.slice(0, j).join('/')];
//baseName segment has config, find if it has one for
//this name.
if (mapValue) {
mapValue = mapValue[nameSegment];
if (mapValue) {
//Match, update name to the new value.
foundMap = mapValue;
foundI = i;
break;
}
}
}
}
if (foundMap) {
break;
}
//Check for a star map match, but just hold on to it,
//if there is a shorter segment match later in a matching
//config, then favor over this star map.
if (!foundStarMap && starMap && starMap[nameSegment]) {
foundStarMap = starMap[nameSegment];
starI = i;
}
}
if (!foundMap && foundStarMap) {
foundMap = foundStarMap;
foundI = starI;
}
if (foundMap) {
nameParts.splice(0, foundI, foundMap);
name = nameParts.join('/');
}
}
return name;
}
function makeRequire(relName, forceSync) {
return function () {
//A version of a require function that passes a moduleName
//value for items that may need to
//look up paths relative to the moduleName
var args = aps.call(arguments, 0);
//If first arg is not require('string'), and there is only
//one arg, it is the array form without a callback. Insert
//a null so that the following concat is correct.
if (typeof args[0] !== 'string' && args.length === 1) {
args.push(null);
}
return req.apply(undef, args.concat([relName, forceSync]));
};
}
function makeNormalize(relName) {
return function (name) {
return normalize(name, relName);
};
}
function makeLoad(depName) {
return function (value) {
defined[depName] = value;
};
}
function callDep(name) {
if (hasProp(waiting, name)) {
var args = waiting[name];
delete waiting[name];
defining[name] = true;
main.apply(undef, args);
}
if (!hasProp(defined, name) && !hasProp(defining, name)) {
throw new Error('No ' + name);
}
return defined[name];
}
//Turns a plugin!resource to [plugin, resource]
//with the plugin being undefined if the name
//did not have a plugin prefix.
function splitPrefix(name) {
var prefix,
index = name ? name.indexOf('!') : -1;
if (index > -1) {
prefix = name.substring(0, index);
name = name.substring(index + 1, name.length);
}
return [prefix, name];
}
//Creates a parts array for a relName where first part is plugin ID,
//second part is resource ID. Assumes relName has already been normalized.
function makeRelParts(relName) {
return relName ? splitPrefix(relName) : [];
}
/**
* Makes a name map, normalizing the name, and using a plugin
* for normalization if necessary. Grabs a ref to plugin
* too, as an optimization.
*/
makeMap = function (name, relParts) {
var plugin,
parts = splitPrefix(name),
prefix = parts[0],
relResourceName = relParts[1];
name = parts[1];
if (prefix) {
prefix = normalize(prefix, relResourceName);
plugin = callDep(prefix);
}
//Normalize according
if (prefix) {
if (plugin && plugin.normalize) {
name = plugin.normalize(name, makeNormalize(relResourceName));
} else {
name = normalize(name, relResourceName);
}
} else {
name = normalize(name, relResourceName);
parts = splitPrefix(name);
prefix = parts[0];
name = parts[1];
if (prefix) {
plugin = callDep(prefix);
}
}
//Using ridiculous property names for space reasons
return {
f: prefix ? prefix + '!' + name : name, //fullName
n: name,
pr: prefix,
p: plugin
};
};
function makeConfig(name) {
return function () {
return (config && config.config && config.config[name]) || {};
};
}
handlers = {
require: function (name) {
return makeRequire(name);
},
exports: function (name) {
var e = defined[name];
if (typeof e !== 'undefined') {
return e;
} else {
return (defined[name] = {});
}
},
module: function (name) {
return {
id: name,
uri: '',
exports: defined[name],
config: makeConfig(name)
};
}
};
main = function (name, deps, callback, relName) {
var cjsModule, depName, ret, map, i, relParts,
args = [],
callbackType = typeof callback,
usingExports;
//Use name if no relName
relName = relName || name;
relParts = makeRelParts(relName);
//Call the callback to define the module, if necessary.
if (callbackType === 'undefined' || callbackType === 'function') {
//Pull out the defined dependencies and pass the ordered
//values to the callback.
//Default to [require, exports, module] if no deps
deps = !deps.length && callback.length ? ['require', 'exports', 'module'] : deps;
for (i = 0; i < deps.length; i += 1) {
map = makeMap(deps[i], relParts);
depName = map.f;
//Fast path CommonJS standard dependencies.
if (depName === "require") {
args[i] = handlers.require(name);
} else if (depName === "exports") {
//CommonJS module spec 1.1
args[i] = handlers.exports(name);
usingExports = true;
} else if (depName === "module") {
//CommonJS module spec 1.1
cjsModule = args[i] = handlers.module(name);
} else if (hasProp(defined, depName) ||
hasProp(waiting, depName) ||
hasProp(defining, depName)) {
args[i] = callDep(depName);
} else if (map.p) {
map.p.load(map.n, makeRequire(relName, true), makeLoad(depName), {});
args[i] = defined[depName];
} else {
throw new Error(name + ' missing ' + depName);
}
}
ret = callback ? callback.apply(defined[name], args) : undefined;
if (name) {
//If setting exports via "module" is in play,
//favor that over return value and exports. After that,
//favor a non-undefined return value over exports use.
if (cjsModule && cjsModule.exports !== undef &&
cjsModule.exports !== defined[name]) {
defined[name] = cjsModule.exports;
} else if (ret !== undef || !usingExports) {
//Use the return value from the function.
defined[name] = ret;
}
}
} else if (name) {
//May just be an object definition for the module. Only
//worry about defining if have a module name.
defined[name] = callback;
}
};
requirejs = require = req = function (deps, callback, relName, forceSync, alt) {
if (typeof deps === "string") {
if (handlers[deps]) {
//callback in this case is really relName
return handlers[deps](callback);
}
//Just return the module wanted. In this scenario, the
//deps arg is the module name, and second arg (if passed)
//is just the relName.
//Normalize module name, if it contains . or ..
return callDep(makeMap(deps, makeRelParts(callback)).f);
} else if (!deps.splice) {
//deps is a config object, not an array.
config = deps;
if (config.deps) {
req(config.deps, config.callback);
}
if (!callback) {
return;
}
if (callback.splice) {
//callback is an array, which means it is a dependency list.
//Adjust args if there are dependencies
deps = callback;
callback = relName;
relName = null;
} else {
deps = undef;
}
}
//Support require(['a'])
callback = callback || function () {};
//If relName is a function, it is an errback handler,
//so remove it.
if (typeof relName === 'function') {
relName = forceSync;
forceSync = alt;
}
//Simulate async callback;
if (forceSync) {
main(undef, deps, callback, relName);
} else {
//Using a non-zero value because of concern for what old browsers
//do, and latest browsers "upgrade" to 4 if lower value is used:
//http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#dom-windowtimers-settimeout:
//If want a value immediately, use require('id') instead -- something
//that works in almond on the global level, but not guaranteed and
//unlikely to work in other AMD implementations.
setTimeout(function () {
main(undef, deps, callback, relName);
}, 4);
}
return req;
};
/**
* Just drops the config on the floor, but returns req in case
* the config return value is used.
*/
req.config = function (cfg) {
return req(cfg);
};
/**
* Expose module registry for debugging and tooling
*/
requirejs._defined = defined;
define = function (name, deps, callback) {
if (typeof name !== 'string') {
throw new Error('See almond README: incorrect module build, no module name');
}
//This module may not have dependencies
if (!deps.splice) {
//deps is not an array, so probably means
//an object literal or factory function for
//the value. Adjust args.
callback = deps;
deps = [];
}
if (!hasProp(defined, name) && !hasProp(waiting, name)) {
waiting[name] = [name, deps, callback];
}
};
define.amd = {
jQuery: true
};
}());
define("node_modules/almond/almond.js", function(){});
/*
This program is distributed under the terms of the MIT license.
Please see the LICENSE file for details.
Copyright 2006-2008, OGG, LLC
*/
/* jshint undef: true, unused: true:, noarg: true, latedef: true */
/* global define */
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define('strophe-polyfill',[], function () {
return factory(root);
});
} else {
// Browser globals
return factory(root);
}
}(this, function (root) {
/** Function: Function.prototype.bind
* Bind a function to an instance.
*
* This Function object extension method creates a bound method similar
* to those in Python. This means that the 'this' object will point
* to the instance you want. See <MDC's bind() documentation at https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind>
* and <Bound Functions and Function Imports in JavaScript at http://benjamin.smedbergs.us/blog/2007-01-03/bound-functions-and-function-imports-in-javascript/>
* for a complete explanation.
*
* This extension already exists in some browsers (namely, Firefox 3), but
* we provide it to support those that don't.
*
* Parameters:
* (Object) obj - The object that will become 'this' in the bound function.
* (Object) argN - An option argument that will be prepended to the
* arguments given for the function call
*
* Returns:
* The bound function.
*/
if (!Function.prototype.bind) {
Function.prototype.bind = function (obj /*, arg1, arg2, ... */) {
var func = this;
var _slice = Array.prototype.slice;
var _concat = Array.prototype.concat;
var _args = _slice.call(arguments, 1);
return function () {
return func.apply(obj ? obj : this, _concat.call(_args, _slice.call(arguments, 0)));
};
};
}
/** Function: Array.isArray
* This is a polyfill for the ES5 Array.isArray method.
*/
if (!Array.isArray) {
Array.isArray = function(arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
}
/** Function: Array.prototype.indexOf
* Return the index of an object in an array.
*
* This function is not supplied by some JavaScript implementations, so
* we provide it if it is missing. This code is from:
* http://developer.mozilla.org/En/Core_JavaScript_1.5_Reference:Objects:Array:indexOf
*
* Parameters:
* (Object) elt - The object to look for.
* (Integer) from - The index from which to start looking. (optional).
*
* Returns:
* The index of elt in the array or -1 if not found.
*/
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(elt /*, from*/) {
var len = this.length;
var from = Number(arguments[1]) || 0;
from = (from < 0) ? Math.ceil(from) : Math.floor(from);
if (from < 0) {
from += len;
}
for (; from < len; from++) {
if (from in this && this[from] === elt) {
return from;
}
}
return -1;
};
}
/** Function: Array.prototype.forEach
*
* This function is not available in IE < 9
*
* See <forEach on developer.mozilla.org at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach>
*/
if (!Array.prototype.forEach) {
Array.prototype.forEach = function(callback, thisArg) {
var T, k;
if (this === null) {
throw new TypeError(' this is null or not defined');
}
// 1. Let O be the result of calling toObject() passing the
// |this| value as the argument.
var O = Object(this);
// 2. Let lenValue be the result of calling the Get() internal
// method of O with the argument "length".
// 3. Let len be toUint32(lenValue).
var len = O.length >>> 0;
// 4. If isCallable(callback) is false, throw a TypeError exception.
// See: http://es5.github.com/#x9.11
if (typeof callback !== "function") {
throw new TypeError(callback + ' is not a function');
}
// 5. If thisArg was supplied, let T be thisArg; else let
// T be undefined.
if (arguments.length > 1) {
T = thisArg;
}
// 6. Let k be 0
k = 0;
// 7. Repeat, while k < len
while (k < len) {
var kValue;
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the HasProperty
// internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
if (k in O) {
// i. Let kValue be the result of calling the Get internal
// method of O with argument Pk.
kValue = O[k];
// ii. Call the Call internal method of callback with T as
// the this value and argument list containing kValue, k, and O.
callback.call(T, kValue, k, O);
}
// d. Increase k by 1.
k++;
}
// 8. return undefined
};
}
// This code was written by Tyler Akins and has been placed in the
// public domain. It would be nice if you left this header intact.
// Base64 code from Tyler Akins -- http://rumkin.com
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
if (!root.btoa) {
root.btoa = function (input) {
/**
* Encodes a string in base64
* @param {String} input The string to encode in base64.
*/
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
do {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc2 = ((chr1 & 3) << 4);
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) +
keyStr.charAt(enc3) + keyStr.charAt(enc4);
} while (i < input.length);
return output;
};
}
if (!root.atob) {
root.atob = function (input) {
/**
* Decodes a base64 string.
* @param {String} input The string to decode.
*/
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
// remove all characters that are not A-Z, a-z, 0-9, +, /, or =
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
do {
enc1 = keyStr.indexOf(input.charAt(i++));
enc2 = keyStr.indexOf(input.charAt(i++));
enc3 = keyStr.indexOf(input.charAt(i++));
enc4 = keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 !== 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 !== 64) {
output = output + String.fromCharCode(chr3);
}
} while (i < input.length);
return output;
};
}
}));
/*
* A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
* in FIPS PUB 180-1
* Version 2.1a Copyright Paul Johnston 2000 - 2002.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for details.
*/
/* jshint undef: true, unused: true:, noarg: true, latedef: false */
/* global define */
/* Some functions and variables have been stripped for use with Strophe */
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define('strophe-sha1', [],function () {
return factory();
});
} else {
// Browser globals
root.SHA1 = factory();
}
}(this, function () {
/*
* Calculate the SHA-1 of an array of big-endian words, and a bit length
*/
function core_sha1(x, len)
{
/* append padding */
x[len >> 5] |= 0x80 << (24 - len % 32);
x[((len + 64 >> 9) << 4) + 15] = len;
var w = new Array(80);
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
var e = -1009589776;
var i, j, t, olda, oldb, oldc, oldd, olde;
for (i = 0; i < x.length; i += 16)
{
olda = a;
oldb = b;
oldc = c;
oldd = d;
olde = e;
for (j = 0; j < 80; j++)
{
if (j < 16) { w[j] = x[i + j]; }
else { w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1); }
t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)),
safe_add(safe_add(e, w[j]), sha1_kt(j)));
e = d;
d = c;
c = rol(b, 30);
b = a;
a = t;
}
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
e = safe_add(e, olde);
}
return [a, b, c, d, e];
}
/*
* Perform the appropriate triplet combination function for the current
* iteration
*/
function sha1_ft(t, b, c, d)
{
if (t < 20) { return (b & c) | ((~b) & d); }
if (t < 40) { return b ^ c ^ d; }
if (t < 60) { return (b & c) | (b & d) | (c & d); }
return b ^ c ^ d;
}
/*
* Determine the appropriate additive constant for the current iteration
*/
function sha1_kt(t)
{
return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 :
(t < 60) ? -1894007588 : -899497514;
}
/*
* Calculate the HMAC-SHA1 of a key and some data
*/
function core_hmac_sha1(key, data)
{
var bkey = str2binb(key);
if (bkey.length > 16) { bkey = core_sha1(bkey, key.length * 8); }
var ipad = new Array(16), opad = new Array(16);
for (var i = 0; i < 16; i++)
{
ipad[i] = bkey[i] ^ 0x36363636;
opad[i] = bkey[i] ^ 0x5C5C5C5C;
}
var hash = core_sha1(ipad.concat(str2binb(data)), 512 + data.length * 8);
return core_sha1(opad.concat(hash), 512 + 160);
}
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
function safe_add(x, y)
{
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
function rol(num, cnt)
{
return (num << cnt) | (num >>> (32 - cnt));
}
/*
* Convert an 8-bit or 16-bit string to an array of big-endian words
* In 8-bit function, characters >255 have their hi-byte silently ignored.
*/
function str2binb(str)
{
var bin = [];
var mask = 255;
for (var i = 0; i < str.length * 8; i += 8)
{
bin[i>>5] |= (str.charCodeAt(i / 8) & mask) << (24 - i%32);
}
return bin;
}
/*
* Convert an array of big-endian words to a string
*/
function binb2str(bin)
{
var str = "";
var mask = 255;
for (var i = 0; i < bin.length * 32; i += 8)
{
str += String.fromCharCode((bin[i>>5] >>> (24 - i%32)) & mask);
}
return str;
}
/*
* Convert an array of big-endian words to a base-64 string
*/
function binb2b64(binarray)
{
var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var str = "";
var triplet, j;
for (var i = 0; i < binarray.length * 4; i += 3)
{
triplet = (((binarray[i >> 2] >> 8 * (3 - i %4)) & 0xFF) << 16) |
(((binarray[i+1 >> 2] >> 8 * (3 - (i+1)%4)) & 0xFF) << 8 ) |
((binarray[i+2 >> 2] >> 8 * (3 - (i+2)%4)) & 0xFF);
for (j = 0; j < 4; j++)
{
if (i * 8 + j * 6 > binarray.length * 32) { str += "="; }
else { str += tab.charAt((triplet >> 6*(3-j)) & 0x3F); }
}
}
return str;
}
/*
* These are the functions you'll usually want to call
* They take string arguments and return either hex or base-64 encoded strings
*/
return {
b64_hmac_sha1: function (key, data){ return binb2b64(core_hmac_sha1(key, data)); },
b64_sha1: function (s) { return binb2b64(core_sha1(str2binb(s),s.length * 8)); },
binb2str: binb2str,
core_hmac_sha1: core_hmac_sha1,
str_hmac_sha1: function (key, data){ return binb2str(core_hmac_sha1(key, data)); },
str_sha1: function (s) { return binb2str(core_sha1(str2binb(s),s.length * 8)); },
};
}));
/*
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
* Digest Algorithm, as defined in RFC 1321.
* Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for more info.
*/
/*
* Everything that isn't used by Strophe has been stripped here!
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define('strophe-md5',[], function () {
return factory();
});
} else {
// Browser globals
root.MD5 = factory();
}
}(this, function () {
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
var safe_add = function (x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
};
/*
* Bitwise rotate a 32-bit number to the left.
*/
var bit_rol = function (num, cnt) {
return (num << cnt) | (num >>> (32 - cnt));
};
/*
* Convert a string to an array of little-endian words
*/
var str2binl = function (str) {
var bin = [];
for(var i = 0; i < str.length * 8; i += 8)
{
bin[i>>5] |= (str.charCodeAt(i / 8) & 255) << (i%32);
}
return bin;
};
/*
* Convert an array of little-endian words to a string
*/
var binl2str = function (bin) {
var str = "";
for(var i = 0; i < bin.length * 32; i += 8)
{
str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & 255);
}
return str;
};
/*
* Convert an array of little-endian words to a hex string.
*/
var binl2hex = function (binarray) {
var hex_tab = "0123456789abcdef";
var str = "";
for(var i = 0; i < binarray.length * 4; i++)
{
str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF);
}
return str;
};
/*
* These functions implement the four basic operations the algorithm uses.
*/
var md5_cmn = function (q, a, b, x, s, t) {
return safe_add(bit_rol(safe_add(safe_add(a, q),safe_add(x, t)), s),b);
};
var md5_ff = function (a, b, c, d, x, s, t) {
return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
};
var md5_gg = function (a, b, c, d, x, s, t) {
return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
};
var md5_hh = function (a, b, c, d, x, s, t) {
return md5_cmn(b ^ c ^ d, a, b, x, s, t);
};
var md5_ii = function (a, b, c, d, x, s, t) {
return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
};
/*
* Calculate the MD5 of an array of little-endian words, and a bit length
*/
var core_md5 = function (x, len) {
/* append padding */
x[len >> 5] |= 0x80 << ((len) % 32);
x[(((len + 64) >>> 9) << 4) + 14] = len;
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
var olda, oldb, oldc, oldd;
for (var i = 0; i < x.length; i += 16)
{
olda = a;
oldb = b;
oldc = c;
oldd = d;
a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819);
b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426);
c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416);
d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682);
d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329);
a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
c = md5_gg(c, d, a, b, x[i+11], 14, 643717713);
b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083);
c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438);
d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501);
a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473);
b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562);
b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353);
c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174);
d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189);
a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
c = md5_hh(c, d, a, b, x[i+15], 16, 530742520);
b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415);
c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571);
d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359);
d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649);
a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259);
b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
}
return [a, b, c, d];
};
var obj = {
/*
* These are the functions you'll usually want to call.
* They take string arguments and return either hex or base-64 encoded
* strings.
*/
hexdigest: function (s) {
return binl2hex(core_md5(str2binl(s), s.length * 8));
},
hash: function (s) {
return binl2str(core_md5(str2binl(s), s.length * 8));
}
};
return obj;
}));
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define('strophe-utils',[], function () {
return factory();
});
} else {
// Browser globals
root.stropheUtils = factory();
}
}(this, function () {
var utils = {
utf16to8: function (str) {
var i, c;
var out = "";
var len = str.length;
for (i = 0; i < len; i++) {
c = str.charCodeAt(i);
if ((c >= 0x0000) && (c <= 0x007F)) {
out += str.charAt(i);
} else if (c > 0x07FF) {
out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
} else {
out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
}
}
return out;
},
addCookies: function (cookies) {
/* Parameters:
* (Object) cookies - either a map of cookie names
* to string values or to maps of cookie values.
*
* For example:
* { "myCookie": "1234" }
*
* or:
* { "myCookie": {
* "value": "1234",
* "domain": ".example.org",
* "path": "/",
* "expires": expirationDate
* }
* }
*
* These values get passed to Strophe.Connection via
* options.cookies
*/
var cookieName, cookieObj, isObj, cookieValue, expires, domain, path;
for (cookieName in (cookies || {})) {
expires = '';
domain = '';
path = '';
cookieObj = cookies[cookieName];
isObj = typeof cookieObj === "object";
cookieValue = escape(unescape(isObj ? cookieObj.value : cookieObj));
if (isObj) {
expires = cookieObj.expires ? ";expires="+cookieObj.expires : '';
domain = cookieObj.domain ? ";domain="+cookieObj.domain : '';
path = cookieObj.path ? ";path="+cookieObj.path : '';
}
document.cookie =
cookieName+'='+cookieValue + expires + domain + path;
}
}
};
return utils;
}));
/*
This program is distributed under the terms of the MIT license.
Please see the LICENSE file for details.
Copyright 2006-2008, OGG, LLC
*/
/* jshint undef: true, unused: true:, noarg: true, latedef: true */
/*global define, document, sessionStorage, setTimeout, clearTimeout, ActiveXObject, DOMParser, btoa, atob */
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define('strophe-core',[
'strophe-sha1',
'strophe-md5',
'strophe-utils'
], function () {
return factory.apply(this, arguments);
});
} else {
// Browser globals
var o = factory(root.SHA1, root.MD5, root.stropheUtils);
root.Strophe = o.Strophe;
root.$build = o.$build;
root.$iq = o.$iq;
root.$msg = o.$msg;
root.$pres = o.$pres;
root.SHA1 = o.SHA1;
root.MD5 = o.MD5;
root.b64_hmac_sha1 = o.SHA1.b64_hmac_sha1;
root.b64_sha1 = o.SHA1.b64_sha1;
root.str_hmac_sha1 = o.SHA1.str_hmac_sha1;
root.str_sha1 = o.SHA1.str_sha1;
}
}(this, function (SHA1, MD5, utils) {
var Strophe;
/** Function: $build
* Create a Strophe.Builder.
* This is an alias for 'new Strophe.Builder(name, attrs)'.
*
* Parameters:
* (String) name - The root element name.
* (Object) attrs - The attributes for the root element in object notation.
*
* Returns:
* A new Strophe.Builder object.
*/
function $build(name, attrs) { return new Strophe.Builder(name, attrs); }
/** Function: $msg
* Create a Strophe.Builder with a <message/> element as the root.
*
* Parameters:
* (Object) attrs - The <message/> element attributes in object notation.
*
* Returns:
* A new Strophe.Builder object.
*/
function $msg(attrs) { return new Strophe.Builder("message", attrs); }
/** Function: $iq
* Create a Strophe.Builder with an <iq/> element as the root.
*
* Parameters:
* (Object) attrs - The <iq/> element attributes in object notation.
*
* Returns:
* A new Strophe.Builder object.
*/
function $iq(attrs) { return new Strophe.Builder("iq", attrs); }
/** Function: $pres
* Create a Strophe.Builder with a <presence/> element as the root.
*
* Parameters:
* (Object) attrs - The <presence/> element attributes in object notation.
*
* Returns:
* A new Strophe.Builder object.
*/
function $pres(attrs) { return new Strophe.Builder("presence", attrs); }
/** Class: Strophe
* An object container for all Strophe library functions.
*
* This class is just a container for all the objects and constants
* used in the library. It is not meant to be instantiated, but to
* provide a namespace for library objects, constants, and functions.
*/
Strophe = {
/** Constant: VERSION */
VERSION: "1.2.14",
/** Constants: XMPP Namespace Constants
* Common namespace constants from the XMPP RFCs and XEPs.
*
* NS.HTTPBIND - HTTP BIND namespace from XEP 124.
* NS.BOSH - BOSH namespace from XEP 206.
* NS.CLIENT - Main XMPP client namespace.
* NS.AUTH - Legacy authentication namespace.
* NS.ROSTER - Roster operations namespace.
* NS.PROFILE - Profile namespace.
* NS.DISCO_INFO - Service discovery info namespace from XEP 30.
* NS.DISCO_ITEMS - Service discovery items namespace from XEP 30.
* NS.MUC - Multi-User Chat namespace from XEP 45.
* NS.SASL - XMPP SASL namespace from RFC 3920.
* NS.STREAM - XMPP Streams namespace from RFC 3920.
* NS.BIND - XMPP Binding namespace from RFC 3920.
* NS.SESSION - XMPP Session namespace from RFC 3920.
* NS.XHTML_IM - XHTML-IM namespace from XEP 71.
* NS.XHTML - XHTML body namespace from XEP 71.
*/
NS: {
HTTPBIND: "http://jabber.org/protocol/httpbind",
BOSH: "urn:xmpp:xbosh",
CLIENT: "jabber:client",
AUTH: "jabber:iq:auth",
ROSTER: "jabber:iq:roster",
PROFILE: "jabber:iq:profile",
DISCO_INFO: "http://jabber.org/protocol/disco#info",
DISCO_ITEMS: "http://jabber.org/protocol/disco#items",
MUC: "http://jabber.org/protocol/muc",
SASL: "urn:ietf:params:xml:ns:xmpp-sasl",
STREAM: "http://etherx.jabber.org/streams",
FRAMING: "urn:ietf:params:xml:ns:xmpp-framing",
BIND: "urn:ietf:params:xml:ns:xmpp-bind",
SESSION: "urn:ietf:params:xml:ns:xmpp-session",
VERSION: "jabber:iq:version",
STANZAS: "urn:ietf:params:xml:ns:xmpp-stanzas",
XHTML_IM: "http://jabber.org/protocol/xhtml-im",
XHTML: "http://www.w3.org/1999/xhtml"
},
/** Constants: XHTML_IM Namespace
* contains allowed tags, tag attributes, and css properties.
* Used in the createHtml function to filter incoming html into the allowed XHTML-IM subset.
* See http://xmpp.org/extensions/xep-0071.html#profile-summary for the list of recommended
* allowed tags and their attributes.
*/
XHTML: {
tags: ['a','blockquote','br','cite','em','img','li','ol','p','span','strong','ul','body'],
attributes: {
'a': ['href'],
'blockquote': ['style'],
'br': [],
'cite': ['style'],
'em': [],
'img': ['src', 'alt', 'style', 'height', 'width'],
'li': ['style'],
'ol': ['style'],
'p': ['style'],
'span': ['style'],
'strong': [],
'ul': ['style'],
'body': []
},
css: ['background-color','color','font-family','font-size','font-style','font-weight','margin-left','margin-right','text-align','text-decoration'],
/** Function: XHTML.validTag
*
* Utility method to determine whether a tag is allowed
* in the XHTML_IM namespace.
*
* XHTML tag names are case sensitive and must be lower case.
*/
validTag: function(tag) {
for (var i = 0; i < Strophe.XHTML.tags.length; i++) {
if (tag === Strophe.XHTML.tags[i]) {
return true;
}
}
return false;
},
/** Function: XHTML.validAttribute
*
* Utility method to determine whether an attribute is allowed
* as recommended per XEP-0071
*
* XHTML attribute names are case sensitive and must be lower case.
*/
validAttribute: function(tag, attribute) {
if (typeof Strophe.XHTML.attributes[tag] !== 'undefined' && Strophe.XHTML.attributes[tag].length > 0) {
for (var i = 0; i < Strophe.XHTML.attributes[tag].length; i++) {
if (attribute === Strophe.XHTML.attributes[tag][i]) {
return true;
}
}
}
return false;
},
validCSS: function(style) {
for (var i = 0; i < Strophe.XHTML.css.length; i++) {
if (style === Strophe.XHTML.css[i]) {
return true;
}
}
return false;
}
},
/** Constants: Connection Status Constants
* Connection status constants for use by the connection handler
* callback.
*
* Status.ERROR - An error has occurred
* Status.CONNECTING - The connection is currently being made
* Status.CONNFAIL - The connection attempt failed
* Status.AUTHENTICATING - The connection is authenticating
* Status.AUTHFAIL - The authentication attempt failed
* Status.CONNECTED - The connection has succeeded
* Status.DISCONNECTED - The connection has been terminated
* Status.DISCONNECTING - The connection is currently being terminated
* Status.ATTACHED - The connection has been attached
* Status.REDIRECT - The connection has been redirected
* Status.CONNTIMEOUT - The connection has timed out
*/
Status: {
ERROR: 0,
CONNECTING: 1,
CONNFAIL: 2,
AUTHENTICATING: 3,
AUTHFAIL: 4,
CONNECTED: 5,
DISCONNECTED: 6,
DISCONNECTING: 7,
ATTACHED: 8,
REDIRECT: 9,
CONNTIMEOUT: 10
},
/** Constants: Log Level Constants
* Logging level indicators.
*
* LogLevel.DEBUG - Debug output
* LogLevel.INFO - Informational output
* LogLevel.WARN - Warnings
* LogLevel.ERROR - Errors
* LogLevel.FATAL - Fatal errors
*/
LogLevel: {
DEBUG: 0,
INFO: 1,
WARN: 2,
ERROR: 3,
FATAL: 4
},
/** PrivateConstants: DOM Element Type Constants
* DOM element types.
*
* ElementType.NORMAL - Normal element.
* ElementType.TEXT - Text data element.
* ElementType.FRAGMENT - XHTML fragment element.
*/
ElementType: {
NORMAL: 1,
TEXT: 3,
CDATA: 4,
FRAGMENT: 11
},
/** PrivateConstants: Timeout Values
* Timeout values for error states. These values are in seconds.
* These should not be changed unless you know exactly what you are
* doing.
*
* TIMEOUT - Timeout multiplier. A waiting request will be considered
* failed after Math.floor(TIMEOUT * wait) seconds have elapsed.
* This defaults to 1.1, and with default wait, 66 seconds.
* SECONDARY_TIMEOUT - Secondary timeout multiplier. In cases where
* Strophe can detect early failure, it will consider the request
* failed if it doesn't return after
* Math.floor(SECONDARY_TIMEOUT * wait) seconds have elapsed.
* This defaults to 0.1, and with default wait, 6 seconds.
*/
TIMEOUT: 1.1,
SECONDARY_TIMEOUT: 0.1,
/** Function: addNamespace
* This function is used to extend the current namespaces in
* Strophe.NS. It takes a key and a value with the key being the
* name of the new namespace, with its actual value.
* For example:
* Strophe.addNamespace('PUBSUB', "http://jabber.org/protocol/pubsub");
*
* Parameters:
* (String) name - The name under which the namespace will be
* referenced under Strophe.NS
* (String) value - The actual namespace.
*/
addNamespace: function (name, value) {
Strophe.NS[name] = value;
},
/** Function: forEachChild
* Map a function over some or all child elements of a given element.
*
* This is a small convenience function for mapping a function over
* some or all of the children of an element. If elemName is null, all
* children will be passed to the function, otherwise only children
* whose tag names match elemName will be passed.
*
* Parameters:
* (XMLElement) elem - The element to operate on.
* (String) elemName - The child element tag name filter.
* (Function) func - The function to apply to each child. This
* function should take a single argument, a DOM element.
*/
forEachChild: function (elem, elemName, func) {
var i, childNode;
for (i = 0; i < elem.childNodes.length; i++) {
childNode = elem.childNodes[i];
if (childNode.nodeType === Strophe.ElementType.NORMAL &&
(!elemName || this.isTagEqual(childNode, elemName))) {
func(childNode);
}
}
},
/** Function: isTagEqual
* Compare an element's tag name with a string.
*
* This function is case sensitive.
*
* Parameters:
* (XMLElement) el - A DOM element.
* (String) name - The element name.
*
* Returns:
* true if the element's tag name matches _el_, and false
* otherwise.
*/
isTagEqual: function (el, name) {
return el.tagName === name;
},
/** PrivateVariable: _xmlGenerator
* _Private_ variable that caches a DOM document to
* generate elements.
*/
_xmlGenerator: null,
/** PrivateFunction: _makeGenerator
* _Private_ function that creates a dummy XML DOM document to serve as
* an element and text node generator.
*/
_makeGenerator: function () {
var doc;
// IE9 does implement createDocument(); however, using it will cause the browser to leak memory on page unload.
// Here, we test for presence of createDocument() plus IE's proprietary documentMode attribute, which would be
// less than 10 in the case of IE9 and below.
if (document.implementation.createDocument === undefined ||
document.implementation.createDocument && document.documentMode && document.documentMode < 10) {
doc = this._getIEXmlDom();
doc.appendChild(doc.createElement('strophe'));
} else {
doc = document.implementation
.createDocument('jabber:client', 'strophe', null);
}
return doc;
},
/** Function: xmlGenerator
* Get the DOM document to generate elements.
*
* Returns:
* The currently used DOM document.
*/
xmlGenerator: function () {
if (!Strophe._xmlGenerator) {
Strophe._xmlGenerator = Strophe._makeGenerator();
}
return Strophe._xmlGenerator;
},
/** PrivateFunction: _getIEXmlDom
* Gets IE xml doc object
*
* Returns:
* A Microsoft XML DOM Object
* See Also:
* http://msdn.microsoft.com/en-us/library/ms757837%28VS.85%29.aspx
*/
_getIEXmlDom : function() {
var doc = null;
var docStrings = [
"Msxml2.DOMDocument.6.0",
"Msxml2.DOMDocument.5.0",
"Msxml2.DOMDocument.4.0",
"MSXML2.DOMDocument.3.0",
"MSXML2.DOMDocument",
"MSXML.DOMDocument",
"Microsoft.XMLDOM"
];
for (var d = 0; d < docStrings.length; d++) {
if (doc === null) {
try {
doc = new ActiveXObject(docStrings[d]);
} catch (e) {
doc = null;
}
} else {
break;
}
}
return doc;
},
/** Function: xmlElement
* Create an XML DOM element.
*
* This function creates an XML DOM element correctly across all
* implementations. Note that these are not HTML DOM elements, which
* aren't appropriate for XMPP stanzas.
*
* Parameters:
* (String) name - The name for the element.
* (Array|Object) attrs - An optional array or object containing
* key/value pairs to use as element attributes. The object should
* be in the format {'key': 'value'} or {key: 'value'}. The array
* should have the format [['key1', 'value1'], ['key2', 'value2']].
* (String) text - The text child data for the element.
*
* Returns:
* A new XML DOM element.
*/
xmlElement: function (name) {
if (!name) { return null; }
var node = Strophe.xmlGenerator().createElement(name);
// FIXME: this should throw errors if args are the wrong type or
// there are more than two optional args
var a, i, k;
for (a = 1; a < arguments.length; a++) {
var arg = arguments[a];
if (!arg) { continue; }
if (typeof(arg) === "string" ||
typeof(arg) === "number") {
node.appendChild(Strophe.xmlTextNode(arg));
} else if (typeof(arg) === "object" &&
typeof(arg.sort) === "function") {
for (i = 0; i < arg.length; i++) {
var attr = arg[i];
if (typeof(attr) === "object" &&
typeof(attr.sort) === "function" &&
attr[1] !== undefined &&
attr[1] !== null) {
node.setAttribute(attr[0], attr[1]);
}
}
} else if (typeof(arg) === "object") {
for (k in arg) {
if (arg.hasOwnProperty(k)) {
if (arg[k] !== undefined &&
arg[k] !== null) {
node.setAttribute(k, arg[k]);
}
}
}
}
}
return node;
},
/* Function: xmlescape
* Excapes invalid xml characters.
*
* Parameters:
* (String) text - text to escape.
*
* Returns:
* Escaped text.
*/
xmlescape: function(text) {
text = text.replace(/\&/g, "&");
text = text.replace(/</g, "<");
text = text.replace(/>/g, ">");
text = text.replace(/'/g, "'");
text = text.replace(/"/g, """);
return text;
},
/* Function: xmlunescape
* Unexcapes invalid xml characters.
*
* Parameters:
* (String) text - text to unescape.
*
* Returns:
* Unescaped text.
*/
xmlunescape: function(text) {
text = text.replace(/\&/g, "&");
text = text.replace(/</g, "<");
text = text.replace(/>/g, ">");
text = text.replace(/'/g, "'");
text = text.replace(/"/g, "\"");
return text;
},
/** Function: xmlTextNode
* Creates an XML DOM text node.
*
* Provides a cross implementation version of document.createTextNode.
*
* Parameters:
* (String) text - The content of the text node.
*
* Returns:
* A new XML DOM text node.
*/
xmlTextNode: function (text) {
return Strophe.xmlGenerator().createTextNode(text);
},
/** Function: xmlHtmlNode
* Creates an XML DOM html node.
*
* Parameters:
* (String) html - The content of the html node.
*
* Returns:
* A new XML DOM text node.
*/
xmlHtmlNode: function (html) {
var node;
//ensure text is escaped
if (DOMParser) {
var parser = new DOMParser();
node = parser.parseFromString(html, "text/xml");
} else {
node = new ActiveXObject("Microsoft.XMLDOM");
node.async="false";
node.loadXML(html);
}
return node;
},
/** Function: getText
* Get the concatenation of all text children of an element.
*
* Parameters:
* (XMLElement) elem - A DOM element.
*
* Returns:
* A String with the concatenated text of all text element children.
*/
getText: function (elem) {
if (!elem) { return null; }
var str = "";
if (elem.childNodes.length === 0 && elem.nodeType === Strophe.ElementType.TEXT) {
str += elem.nodeValue;
}
for (var i = 0; i < elem.childNodes.length; i++) {
if (elem.childNodes[i].nodeType === Strophe.ElementType.TEXT) {
str += elem.childNodes[i].nodeValue;
}
}
return Strophe.xmlescape(str);
},
/** Function: copyElement
* Copy an XML DOM element.
*
* This function copies a DOM element and all its descendants and returns
* the new copy.
*
* Parameters:
* (XMLElement) elem - A DOM element.
*
* Returns:
* A new, copied DOM element tree.
*/
copyElement: function (elem) {
var i, el;
if (elem.nodeType === Strophe.ElementType.NORMAL) {
el = Strophe.xmlElement(elem.tagName);
for (i = 0; i < elem.attributes.length; i++) {
el.setAttribute(elem.attributes[i].nodeName,
elem.attributes[i].value);
}
for (i = 0; i < elem.childNodes.length; i++) {
el.appendChild(Strophe.copyElement(elem.childNodes[i]));
}
} else if (elem.nodeType === Strophe.ElementType.TEXT) {
el = Strophe.xmlGenerator().createTextNode(elem.nodeValue);
}
return el;
},
/** Function: createHtml
* Copy an HTML DOM element into an XML DOM.
*
* This function copies a DOM element and all its descendants and returns
* the new copy.
*
* Parameters:
* (HTMLElement) elem - A DOM element.
*
* Returns:
* A new, copied DOM element tree.
*/
createHtml: function (elem) {
var i, el, j, tag, attribute, value, css, cssAttrs, attr, cssName, cssValue;
if (elem.nodeType === Strophe.ElementType.NORMAL) {
tag = elem.nodeName.toLowerCase(); // XHTML tags must be lower case.
if(Strophe.XHTML.validTag(tag)) {
try {
el = Strophe.xmlElement(tag);
for(i = 0; i < Strophe.XHTML.attributes[tag].length; i++) {
attribute = Strophe.XHTML.attributes[tag][i];
value = elem.getAttribute(attribute);
if(typeof value === 'undefined' || value === null || value === '' || value === false || value === 0) {
continue;
}
if(attribute === 'style' && typeof value === 'object') {
if(typeof value.cssText !== 'undefined') {
value = value.cssText; // we're dealing with IE, need to get CSS out
}
}
// filter out invalid css styles
if(attribute === 'style') {
css = [];
cssAttrs = value.split(';');
for(j = 0; j < cssAttrs.length; j++) {
attr = cssAttrs[j].split(':');
cssName = attr[0].replace(/^\s*/, "").replace(/\s*$/, "").toLowerCase();
if(Strophe.XHTML.validCSS(cssName)) {
cssValue = attr[1].replace(/^\s*/, "").replace(/\s*$/, "");
css.push(cssName + ': ' + cssValue);
}
}
if(css.length > 0) {
value = css.join('; ');
el.setAttribute(attribute, value);
}
} else {
el.setAttribute(attribute, value);
}
}
for (i = 0; i < elem.childNodes.length; i++) {
el.appendChild(Strophe.createHtml(elem.childNodes[i]));
}
} catch(e) { // invalid elements
el = Strophe.xmlTextNode('');
}
} else {
el = Strophe.xmlGenerator().createDocumentFragment();
for (i = 0; i < elem.childNodes.length; i++) {
el.appendChild(Strophe.createHtml(elem.childNodes[i]));
}
}
} else if (elem.nodeType === Strophe.ElementType.FRAGMENT) {
el = Strophe.xmlGenerator().createDocumentFragment();
for (i = 0; i < elem.childNodes.length; i++) {
el.appendChild(Strophe.createHtml(elem.childNodes[i]));
}
} else if (elem.nodeType === Strophe.ElementType.TEXT) {
el = Strophe.xmlTextNode(elem.nodeValue);
}
return el;
},
/** Function: escapeNode
* Escape the node part (also called local part) of a JID.
*
* Parameters:
* (String) node - A node (or local part).
*
* Returns:
* An escaped node (or local part).
*/
escapeNode: function (node) {
if (typeof node !== "string") { return node; }
return node.replace(/^\s+|\s+$/g, '')
.replace(/\\/g, "\\5c")
.replace(/ /g, "\\20")
.replace(/\"/g, "\\22")
.replace(/\&/g, "\\26")
.replace(/\'/g, "\\27")
.replace(/\//g, "\\2f")
.replace(/:/g, "\\3a")
.replace(/</g, "\\3c")
.replace(/>/g, "\\3e")
.replace(/@/g, "\\40");
},
/** Function: unescapeNode
* Unescape a node part (also called local part) of a JID.
*
* Parameters:
* (String) node - A node (or local part).
*
* Returns:
* An unescaped node (or local part).
*/
unescapeNode: function (node) {
if (typeof node !== "string") { return node; }
return node.replace(/\\20/g, " ")
.replace(/\\22/g, '"')
.replace(/\\26/g, "&")
.replace(/\\27/g, "'")
.replace(/\\2f/g, "/")
.replace(/\\3a/g, ":")
.replace(/\\3c/g, "<")
.replace(/\\3e/g, ">")
.replace(/\\40/g, "@")
.replace(/\\5c/g, "\\");
},
/** Function: getNodeFromJid
* Get the node portion of a JID String.
*
* Parameters:
* (String) jid - A JID.
*
* Returns:
* A String containing the node.
*/
getNodeFromJid: function (jid) {
if (jid.indexOf("@") < 0) { return null; }
return jid.split("@")[0];
},
/** Function: getDomainFromJid
* Get the domain portion of a JID String.
*
* Parameters:
* (String) jid - A JID.
*
* Returns:
* A String containing the domain.
*/
getDomainFromJid: function (jid) {
var bare = Strophe.getBareJidFromJid(jid);
if (bare.indexOf("@") < 0) {
return bare;
} else {
var parts = bare.split("@");
parts.splice(0, 1);
return parts.join('@');
}
},
/** Function: getResourceFromJid
* Get the resource portion of a JID String.
*
* Parameters:
* (String) jid - A JID.
*
* Returns:
* A String containing the resource.
*/
getResourceFromJid: function (jid) {
var s = jid.split("/");
if (s.length < 2) { return null; }
s.splice(0, 1);
return s.join('/');
},
/** Function: getBareJidFromJid
* Get the bare JID from a JID String.
*
* Parameters:
* (String) jid - A JID.
*
* Returns:
* A String containing the bare JID.
*/
getBareJidFromJid: function (jid) {
return jid ? jid.split("/")[0] : null;
},
/** PrivateFunction: _handleError
* _Private_ function that properly logs an error to the console
*/
_handleError: function (e) {
if (typeof e.stack !== "undefined") {
Strophe.fatal(e.stack);
}
if (e.sourceURL) {
Strophe.fatal("error: " + this.handler + " " + e.sourceURL + ":" +
e.line + " - " + e.name + ": " + e.message);
} else if (e.fileName) {
Strophe.fatal("error: " + this.handler + " " +
e.fileName + ":" + e.lineNumber + " - " +
e.name + ": " + e.message);
} else {
Strophe.fatal("error: " + e.message);
}
},
/** Function: log
* User overrideable logging function.
*
* This function is called whenever the Strophe library calls any
* of the logging functions. The default implementation of this
* function does nothing. If client code wishes to handle the logging
* messages, it should override this with
* > Strophe.log = function (level, msg) {
* > (user code here)
* > };
*
* Please note that data sent and received over the wire is logged
* via Strophe.Connection.rawInput() and Strophe.Connection.rawOutput().
*
* The different levels and their meanings are
*
* DEBUG - Messages useful for debugging purposes.
* INFO - Informational messages. This is mostly information like
* 'disconnect was called' or 'SASL auth succeeded'.
* WARN - Warnings about potential problems. This is mostly used
* to report transient connection errors like request timeouts.
* ERROR - Some error occurred.
* FATAL - A non-recoverable fatal error occurred.
*
* Parameters:
* (Integer) level - The log level of the log message. This will
* be one of the values in Strophe.LogLevel.
* (String) msg - The log message.
*/
/* jshint ignore:start */
log: function (level, msg) {
return;
},
/* jshint ignore:end */
/** Function: debug
* Log a message at the Strophe.LogLevel.DEBUG level.
*
* Parameters:
* (String) msg - The log message.
*/
debug: function(msg) {
this.log(this.LogLevel.DEBUG, msg);
},
/** Function: info
* Log a message at the Strophe.LogLevel.INFO level.
*
* Parameters:
* (String) msg - The log message.
*/
info: function (msg) {
this.log(this.LogLevel.INFO, msg);
},
/** Function: warn
* Log a message at the Strophe.LogLevel.WARN level.
*
* Parameters:
* (String) msg - The log message.
*/
warn: function (msg) {
this.log(this.LogLevel.WARN, msg);
},
/** Function: error
* Log a message at the Strophe.LogLevel.ERROR level.
*
* Parameters:
* (String) msg - The log message.
*/
error: function (msg) {
this.log(this.LogLevel.ERROR, msg);
},
/** Function: fatal
* Log a message at the Strophe.LogLevel.FATAL level.
*
* Parameters:
* (String) msg - The log message.
*/
fatal: function (msg) {
this.log(this.LogLevel.FATAL, msg);
},
/** Function: serialize
* Render a DOM element and all descendants to a String.
*
* Parameters:
* (XMLElement) elem - A DOM element.
*
* Returns:
* The serialized element tree as a String.
*/
serialize: function (elem) {
var result;
if (!elem) { return null; }
if (typeof(elem.tree) === "function") {
elem = elem.tree();
}
var nodeName = elem.nodeName;
var i, child;
if (elem.getAttribute("_realname")) {
nodeName = elem.getAttribute("_realname");
}
result = "<" + nodeName;
for (i = 0; i < elem.attributes.length; i++) {
if(elem.attributes[i].nodeName !== "_realname") {
result += " " + elem.attributes[i].nodeName +
"='" + Strophe.xmlescape(elem.attributes[i].value) + "'";
}
}
if (elem.childNodes.length > 0) {
result += ">";
for (i = 0; i < elem.childNodes.length; i++) {
child = elem.childNodes[i];
switch( child.nodeType ){
case Strophe.ElementType.NORMAL:
// normal element, so recurse
result += Strophe.serialize(child);
break;
case Strophe.ElementType.TEXT:
// text element to escape values
result += Strophe.xmlescape(child.nodeValue);
break;
case Strophe.ElementType.CDATA:
// cdata section so don't escape values
result += "<![CDATA["+child.nodeValue+"]]>";
}
}
result += "</" + nodeName + ">";
} else {
result += "/>";
}
return result;
},
/** PrivateVariable: _requestId
* _Private_ variable that keeps track of the request ids for
* connections.
*/
_requestId: 0,
/** PrivateVariable: Strophe.connectionPlugins
* _Private_ variable Used to store plugin names that need
* initialization on Strophe.Connection construction.
*/
_connectionPlugins: {},
/** Function: addConnectionPlugin
* Extends the Strophe.Connection object with the given plugin.
*
* Parameters:
* (String) name - The name of the extension.
* (Object) ptype - The plugin's prototype.
*/
addConnectionPlugin: function (name, ptype) {
Strophe._connectionPlugins[name] = ptype;
}
};
/** Class: Strophe.Builder
* XML DOM builder.
*
* This object provides an interface similar to JQuery but for building
* DOM elements easily and rapidly. All the functions except for toString()
* and tree() return the object, so calls can be chained. Here's an
* example using the $iq() builder helper.
* > $iq({to: 'you', from: 'me', type: 'get', id: '1'})
* > .c('query', {xmlns: 'strophe:example'})
* > .c('example')
* > .toString()
*
* The above generates this XML fragment
* > <iq to='you' from='me' type='get' id='1'>
* > <query xmlns='strophe:example'>
* > <example/>
* > </query>
* > </iq>
* The corresponding DOM manipulations to get a similar fragment would be
* a lot more tedious and probably involve several helper variables.
*
* Since adding children makes new operations operate on the child, up()
* is provided to traverse up the tree. To add two children, do
* > builder.c('child1', ...).up().c('child2', ...)
* The next operation on the Builder will be relative to the second child.
*/
/** Constructor: Strophe.Builder
* Create a Strophe.Builder object.
*
* The attributes should be passed in object notation. For example
* > var b = new Builder('message', {to: 'you', from: 'me'});
* or
* > var b = new Builder('messsage', {'xml:lang': 'en'});
*
* Parameters:
* (String) name - The name of the root element.
* (Object) attrs - The attributes for the root element in object notation.
*
* Returns:
* A new Strophe.Builder.
*/
Strophe.Builder = function (name, attrs) {
// Set correct namespace for jabber:client elements
if (name === "presence" || name === "message" || name === "iq") {
if (attrs && !attrs.xmlns) {
attrs.xmlns = Strophe.NS.CLIENT;
} else if (!attrs) {
attrs = {xmlns: Strophe.NS.CLIENT};
}
}
// Holds the tree being built.
this.nodeTree = Strophe.xmlElement(name, attrs);
// Points to the current operation node.
this.node = this.nodeTree;
};
Strophe.Builder.prototype = {
/** Function: tree
* Return the DOM tree.
*
* This function returns the current DOM tree as an element object. This
* is suitable for passing to functions like Strophe.Connection.send().
*
* Returns:
* The DOM tree as a element object.
*/
tree: function () {
return this.nodeTree;
},
/** Function: toString
* Serialize the DOM tree to a String.
*
* This function returns a string serialization of the current DOM
* tree. It is often used internally to pass data to a
* Strophe.Request object.
*
* Returns:
* The serialized DOM tree in a String.
*/
toString: function () {
return Strophe.serialize(this.nodeTree);
},
/** Function: up
* Make the current parent element the new current element.
*
* This function is often used after c() to traverse back up the tree.
* For example, to add two children to the same element
* > builder.c('child1', {}).up().c('child2', {});
*
* Returns:
* The Stophe.Builder object.
*/
up: function () {
this.node = this.node.parentNode;
return this;
},
/** Function: root
* Make the root element the new current element.
*
* When at a deeply nested element in the tree, this function can be used
* to jump back to the root of the tree, instead of having to repeatedly
* call up().
*
* Returns:
* The Stophe.Builder object.
*/
root: function () {
this.node = this.nodeTree;
return this;
},
/** Function: attrs
* Add or modify attributes of the current element.
*
* The attributes should be passed in object notation. This function
* does not move the current element pointer.
*
* Parameters:
* (Object) moreattrs - The attributes to add/modify in object notation.
*
* Returns:
* The Strophe.Builder object.
*/
attrs: function (moreattrs) {
for (var k in moreattrs) {
if (moreattrs.hasOwnProperty(k)) {
if (moreattrs[k] === undefined) {
this.node.removeAttribute(k);
} else {
this.node.setAttribute(k, moreattrs[k]);
}
}
}
return this;
},
/** Function: c
* Add a child to the current element and make it the new current
* element.
*
* This function moves the current element pointer to the child,
* unless text is provided. If you need to add another child, it
* is necessary to use up() to go back to the parent in the tree.
*
* Parameters:
* (String) name - The name of the child.
* (Object) attrs - The attributes of the child in object notation.
* (String) text - The text to add to the child.
*
* Returns:
* The Strophe.Builder object.
*/
c: function (name, attrs, text) {
var child = Strophe.xmlElement(name, attrs, text);
this.node.appendChild(child);
if (typeof text !== "string" && typeof text !=="number") {
this.node = child;
}
return this;
},
/** Function: cnode
* Add a child to the current element and make it the new current
* element.
*
* This function is the same as c() except that instead of using a
* name and an attributes object to create the child it uses an
* existing DOM element object.
*
* Parameters:
* (XMLElement) elem - A DOM element.
*
* Returns:
* The Strophe.Builder object.
*/
cnode: function (elem) {
var impNode;
var xmlGen = Strophe.xmlGenerator();
try {
impNode = (xmlGen.importNode !== undefined);
} catch (e) {
impNode = false;
}
var newElem = impNode ?
xmlGen.importNode(elem, true) :
Strophe.copyElement(elem);
this.node.appendChild(newElem);
this.node = newElem;
return this;
},
/** Function: t
* Add a child text element.
*
* This *does not* make the child the new current element since there
* are no children of text elements.
*
* Parameters:
* (String) text - The text data to append to the current element.
*
* Returns:
* The Strophe.Builder object.
*/
t: function (text) {
var child = Strophe.xmlTextNode(text);
this.node.appendChild(child);
return this;
},
/** Function: h
* Replace current element contents with the HTML passed in.
*
* This *does not* make the child the new current element
*
* Parameters:
* (String) html - The html to insert as contents of current element.
*
* Returns:
* The Strophe.Builder object.
*/
h: function (html) {
var fragment = document.createElement('body');
// force the browser to try and fix any invalid HTML tags
fragment.innerHTML = html;
// copy cleaned html into an xml dom
var xhtml = Strophe.createHtml(fragment);
while(xhtml.childNodes.length > 0) {
this.node.appendChild(xhtml.childNodes[0]);
}
return this;
}
};
/** PrivateClass: Strophe.Handler
* _Private_ helper class for managing stanza handlers.
*
* A Strophe.Handler encapsulates a user provided callback function to be
* executed when matching stanzas are received by the connection.
* Handlers can be either one-off or persistant depending on their
* return value. Returning true will cause a Handler to remain active, and
* returning false will remove the Handler.
*
* Users will not use Strophe.Handler objects directly, but instead they
* will use Strophe.Connection.addHandler() and
* Strophe.Connection.deleteHandler().
*/
/** PrivateConstructor: Strophe.Handler
* Create and initialize a new Strophe.Handler.
*
* Parameters:
* (Function) handler - A function to be executed when the handler is run.
* (String) ns - The namespace to match.
* (String) name - The element name to match.
* (String) type - The element type to match.
* (String) id - The element id attribute to match.
* (String) from - The element from attribute to match.
* (Object) options - Handler options
*
* Returns:
* A new Strophe.Handler object.
*/
Strophe.Handler = function (handler, ns, name, type, id, from, options) {
this.handler = handler;
this.ns = ns;
this.name = name;
this.type = type;
this.id = id;
this.options = options || {'matchBareFromJid': false, 'ignoreNamespaceFragment': false};
// BBB: Maintain backward compatibility with old `matchBare` option
if (this.options.matchBare) {
Strophe.warn('The "matchBare" option is deprecated, use "matchBareFromJid" instead.');
this.options.matchBareFromJid = this.options.matchBare;
delete this.options.matchBare;
}
if (this.options.matchBareFromJid) {
this.from = from ? Strophe.getBareJidFromJid(from) : null;
} else {
this.from = from;
}
// whether the handler is a user handler or a system handler
this.user = true;
};
Strophe.Handler.prototype = {
/** PrivateFunction: getNamespace
* Returns the XML namespace attribute on an element.
* If `ignoreNamespaceFragment` was passed in for this handler, then the
* URL fragment will be stripped.
*
* Parameters:
* (XMLElement) elem - The XML element with the namespace.
*
* Returns:
* The namespace, with optionally the fragment stripped.
*/
getNamespace: function (elem) {
var elNamespace = elem.getAttribute("xmlns");
if (elNamespace && this.options.ignoreNamespaceFragment) {
elNamespace = elNamespace.split('#')[0];
}
return elNamespace;
},
/** PrivateFunction: namespaceMatch
* Tests if a stanza matches the namespace set for this Strophe.Handler.
*
* Parameters:
* (XMLElement) elem - The XML element to test.
*
* Returns:
* true if the stanza matches and false otherwise.
*/
namespaceMatch: function (elem) {
var nsMatch = false;
if (!this.ns) {
return true;
} else {
var that = this;
Strophe.forEachChild(elem, null, function (elem) {
if (that.getNamespace(elem) === that.ns) {
nsMatch = true;
}
});
nsMatch = nsMatch || this.getNamespace(elem) === this.ns;
}
return nsMatch;
},
/** PrivateFunction: isMatch
* Tests if a stanza matches the Strophe.Handler.
*
* Parameters:
* (XMLElement) elem - The XML element to test.
*
* Returns:
* true if the stanza matches and false otherwise.
*/
isMatch: function (elem) {
var from = elem.getAttribute('from');
if (this.options.matchBareFromJid) {
from = Strophe.getBareJidFromJid(from);
}
var elem_type = elem.getAttribute("type");
if (this.namespaceMatch(elem) &&
(!this.name || Strophe.isTagEqual(elem, this.name)) &&
(!this.type || (Array.isArray(this.type) ? this.type.indexOf(elem_type) !== -1 : elem_type === this.type)) &&
(!this.id || elem.getAttribute("id") === this.id) &&
(!this.from || from === this.from)) {
return true;
}
return false;
},
/** PrivateFunction: run
* Run the callback on a matching stanza.
*
* Parameters:
* (XMLElement) elem - The DOM element that triggered the
* Strophe.Handler.
*
* Returns:
* A boolean indicating if the handler should remain active.
*/
run: function (elem) {
var result = null;
try {
result = this.handler(elem);
} catch (e) {
Strophe._handleError(e);
throw e;
}
return result;
},
/** PrivateFunction: toString
* Get a String representation of the Strophe.Handler object.
*
* Returns:
* A String.
*/
toString: function () {
return "{Handler: " + this.handler + "(" + this.name + "," +
this.id + "," + this.ns + ")}";
}
};
/** PrivateClass: Strophe.TimedHandler
* _Private_ helper class for managing timed handlers.
*
* A Strophe.TimedHandler encapsulates a user provided callback that
* should be called after a certain period of time or at regular
* intervals. The return value of the callback determines whether the
* Strophe.TimedHandler will continue to fire.
*
* Users will not use Strophe.TimedHandler objects directly, but instead
* they will use Strophe.Connection.addTimedHandler() and
* Strophe.Connection.deleteTimedHandler().
*/
/** PrivateConstructor: Strophe.TimedHandler
* Create and initialize a new Strophe.TimedHandler object.
*
* Parameters:
* (Integer) period - The number of milliseconds to wait before the
* handler is called.
* (Function) handler - The callback to run when the handler fires. This
* function should take no arguments.
*
* Returns:
* A new Strophe.TimedHandler object.
*/
Strophe.TimedHandler = function (period, handler) {
this.period = period;
this.handler = handler;
this.lastCalled = new Date().getTime();
this.user = true;
};
Strophe.TimedHandler.prototype = {
/** PrivateFunction: run
* Run the callback for the Strophe.TimedHandler.
*
* Returns:
* true if the Strophe.TimedHandler should be called again, and false
* otherwise.
*/
run: function () {
this.lastCalled = new Date().getTime();
return this.handler();
},
/** PrivateFunction: reset
* Reset the last called time for the Strophe.TimedHandler.
*/
reset: function () {
this.lastCalled = new Date().getTime();
},
/** PrivateFunction: toString
* Get a string representation of the Strophe.TimedHandler object.
*
* Returns:
* The string representation.
*/
toString: function () {
return "{TimedHandler: " + this.handler + "(" + this.period +")}";
}
};
/** Class: Strophe.Connection
* XMPP Connection manager.
*
* This class is the main part of Strophe. It manages a BOSH or websocket
* connection to an XMPP server and dispatches events to the user callbacks
* as data arrives. It supports SASL PLAIN, SASL DIGEST-MD5, SASL SCRAM-SHA1
* and legacy authentication.
*
* After creating a Strophe.Connection object, the user will typically
* call connect() with a user supplied callback to handle connection level
* events like authentication failure, disconnection, or connection
* complete.
*
* The user will also have several event handlers defined by using
* addHandler() and addTimedHandler(). These will allow the user code to
* respond to interesting stanzas or do something periodically with the
* connection. These handlers will be active once authentication is
* finished.
*
* To send data to the connection, use send().
*/
/** Constructor: Strophe.Connection
* Create and initialize a Strophe.Connection object.
*
* The transport-protocol for this connection will be chosen automatically
* based on the given service parameter. URLs starting with "ws://" or
* "wss://" will use WebSockets, URLs starting with "http://", "https://"
* or without a protocol will use BOSH.
*
* To make Strophe connect to the current host you can leave out the protocol
* and host part and just pass the path, e.g.
*
* > var conn = new Strophe.Connection("/http-bind/");
*
* Options common to both Websocket and BOSH:
* ------------------------------------------
*
* cookies:
*
* The *cookies* option allows you to pass in cookies to be added to the
* document. These cookies will then be included in the BOSH XMLHttpRequest
* or in the websocket connection.
*
* The passed in value must be a map of cookie names and string values.
*
* > { "myCookie": {
* > "value": "1234",
* > "domain": ".example.org",
* > "path": "/",
* > "expires": expirationDate
* > }
* > }
*
* Note that cookies can't be set in this way for other domains (i.e. cross-domain).
* Those cookies need to be set under those domains, for example they can be
* set server-side by making a XHR call to that domain to ask it to set any
* necessary cookies.
*
* mechanisms:
*
* The *mechanisms* option allows you to specify the SASL mechanisms that this
* instance of Strophe.Connection (and therefore your XMPP client) will
* support.
*
* The value must be an array of objects with Strophe.SASLMechanism
* prototypes.
*
* If nothing is specified, then the following mechanisms (and their
* priorities) are registered:
*
* OAUTHBEARER - 60
* SCRAM-SHA1 - 50
* DIGEST-MD5 - 40
* PLAIN - 30
* ANONYMOUS - 20
* EXTERNAL - 10
*
* WebSocket options:
* ------------------
*
* If you want to connect to the current host with a WebSocket connection you
* can tell Strophe to use WebSockets through a "protocol" attribute in the
* optional options parameter. Valid values are "ws" for WebSocket and "wss"
* for Secure WebSocket.
* So to connect to "wss://CURRENT_HOSTNAME/xmpp-websocket" you would call
*
* > var conn = new Strophe.Connection("/xmpp-websocket/", {protocol: "wss"});
*
* Note that relative URLs _NOT_ starting with a "/" will also include the path
* of the current site.
*
* Also because downgrading security is not permitted by browsers, when using
* relative URLs both BOSH and WebSocket connections will use their secure
* variants if the current connection to the site is also secure (https).
*
* BOSH options:
* -------------
*
* By adding "sync" to the options, you can control if requests will
* be made synchronously or not. The default behaviour is asynchronous.
* If you want to make requests synchronous, make "sync" evaluate to true.
* > var conn = new Strophe.Connection("/http-bind/", {sync: true});
*
* You can also toggle this on an already established connection.
* > conn.options.sync = true;
*
* The *customHeaders* option can be used to provide custom HTTP headers to be
* included in the XMLHttpRequests made.
*
* The *keepalive* option can be used to instruct Strophe to maintain the
* current BOSH session across interruptions such as webpage reloads.
*
* It will do this by caching the sessions tokens in sessionStorage, and when
* "restore" is called it will check whether there are cached tokens with
* which it can resume an existing session.
*
* The *withCredentials* option should receive a Boolean value and is used to
* indicate wether cookies should be included in ajax requests (by default
* they're not).
* Set this value to true if you are connecting to a BOSH service
* and for some reason need to send cookies to it.
* In order for this to work cross-domain, the server must also enable
* credentials by setting the Access-Control-Allow-Credentials response header
* to "true". For most usecases however this setting should be false (which
* is the default).
* Additionally, when using Access-Control-Allow-Credentials, the
* Access-Control-Allow-Origin header can't be set to the wildcard "*", but
* instead must be restricted to actual domains.
*
* The *contentType* option can be set to change the default Content-Type
* of "text/xml; charset=utf-8", which can be useful to reduce the amount of
* CORS preflight requests that are sent to the server.
*
* Parameters:
* (String) service - The BOSH or WebSocket service URL.
* (Object) options - A hash of configuration options
*
* Returns:
* A new Strophe.Connection object.
*/
Strophe.Connection = function (service, options) {
// The service URL
this.service = service;
// Configuration options
this.options = options || {};
var proto = this.options.protocol || "";
// Select protocal based on service or options
if (service.indexOf("ws:") === 0 || service.indexOf("wss:") === 0 ||
proto.indexOf("ws") === 0) {
this._proto = new Strophe.Websocket(this);
} else {
this._proto = new Strophe.Bosh(this);
}
/* The connected JID. */
this.jid = "";
/* the JIDs domain */
this.domain = null;
/* stream:features */
this.features = null;
// SASL
this._sasl_data = {};
this.do_session = false;
this.do_bind = false;
// handler lists
this.timedHandlers = [];
this.handlers = [];
this.removeTimeds = [];
this.removeHandlers = [];
this.addTimeds = [];
this.addHandlers = [];
this.protocolErrorHandlers = {
'HTTP': {},
'websocket': {}
};
this._idleTimeout = null;
this._disconnectTimeout = null;
this.authenticated = false;
this.connected = false;
this.disconnecting = false;
this.do_authentication = true;
this.paused = false;
this.restored = false;
this._data = [];
this._uniqueId = 0;
this._sasl_success_handler = null;
this._sasl_failure_handler = null;
this._sasl_challenge_handler = null;
// Max retries before disconnecting
this.maxRetries = 5;
// Call onIdle callback every 1/10th of a second
// XXX: setTimeout should be called only with function expressions (23974bc1)
this._idleTimeout = setTimeout(function() {
this._onIdle();
}.bind(this), 100);
utils.addCookies(this.options.cookies);
this.registerSASLMechanisms(this.options.mechanisms);
// initialize plugins
for (var k in Strophe._connectionPlugins) {
if (Strophe._connectionPlugins.hasOwnProperty(k)) {
var ptype = Strophe._connectionPlugins[k];
// jslint complaints about the below line, but this is fine
var F = function () {}; // jshint ignore:line
F.prototype = ptype;
this[k] = new F();
this[k].init(this);
}
}
};
Strophe.Connection.prototype = {
/** Function: reset
* Reset the connection.
*
* This function should be called after a connection is disconnected
* before that connection is reused.
*/
reset: function () {
this._proto._reset();
// SASL
this.do_session = false;
this.do_bind = false;
// handler lists
this.timedHandlers = [];
this.handlers = [];
this.removeTimeds = [];
this.removeHandlers = [];
this.addTimeds = [];
this.addHandlers = [];
this.authenticated = false;
this.connected = false;
this.disconnecting = false;
this.restored = false;
this._data = [];
this._requests = [];
this._uniqueId = 0;
},
/** Function: pause
* Pause the request manager.
*
* This will prevent Strophe from sending any more requests to the
* server. This is very useful for temporarily pausing
* BOSH-Connections while a lot of send() calls are happening quickly.
* This causes Strophe to send the data in a single request, saving
* many request trips.
*/
pause: function () {
this.paused = true;
},
/** Function: resume
* Resume the request manager.
*
* This resumes after pause() has been called.
*/
resume: function () {
this.paused = false;
},
/** Function: getUniqueId
* Generate a unique ID for use in <iq/> elements.
*
* All <iq/> stanzas are required to have unique id attributes. This
* function makes creating these easy. Each connection instance has
* a counter which starts from zero, and the value of this counter
* plus a colon followed by the suffix becomes the unique id. If no
* suffix is supplied, the counter is used as the unique id.
*
* Suffixes are used to make debugging easier when reading the stream
* data, and their use is recommended. The counter resets to 0 for
* every new connection for the same reason. For connections to the
* same server that authenticate the same way, all the ids should be
* the same, which makes it easy to see changes. This is useful for
* automated testing as well.
*
* Parameters:
* (String) suffix - A optional suffix to append to the id.
*
* Returns:
* A unique string to be used for the id attribute.
*/
getUniqueId: function(suffix) {
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0,
v = c === 'x' ? r : r & 0x3 | 0x8;
return v.toString(16);
});
if (typeof(suffix) === "string" || typeof(suffix) === "number") {
return uuid + ":" + suffix;
} else {
return uuid + "";
}
},
/** Function: addProtocolErrorHandler
* Register a handler function for when a protocol (websocker or HTTP)
* error occurs.
*
* NOTE: Currently only HTTP errors for BOSH requests are handled.
* Patches that handle websocket errors would be very welcome.
*
* Parameters:
* (String) protocol - 'HTTP' or 'websocket'
* (Integer) status_code - Error status code (e.g 500, 400 or 404)
* (Function) callback - Function that will fire on Http error
*
* Example:
* function onError(err_code){
* //do stuff
* }
*
* var conn = Strophe.connect('http://example.com/http-bind');
* conn.addProtocolErrorHandler('HTTP', 500, onError);
* // Triggers HTTP 500 error and onError handler will be called
* conn.connect('user_jid@incorrect_jabber_host', 'secret', onConnect);
*/
addProtocolErrorHandler: function(protocol, status_code, callback){
this.protocolErrorHandlers[protocol][status_code] = callback;
},
/** Function: connect
* Starts the connection process.
*
* As the connection process proceeds, the user supplied callback will
* be triggered multiple times with status updates. The callback
* should take two arguments - the status code and the error condition.
*
* The status code will be one of the values in the Strophe.Status
* constants. The error condition will be one of the conditions
* defined in RFC 3920 or the condition 'strophe-parsererror'.
*
* The Parameters _wait_, _hold_ and _route_ are optional and only relevant
* for BOSH connections. Please see XEP 124 for a more detailed explanation
* of the optional parameters.
*
* Parameters:
* (String) jid - The user's JID. This may be a bare JID,
* or a full JID. If a node is not supplied, SASL OAUTHBEARER or
* SASL ANONYMOUS authentication will be attempted (OAUTHBEARER will
* process the provided password value as an access token).
* (String) pass - The user's password.
* (Function) callback - The connect callback function.
* (Integer) wait - The optional HTTPBIND wait value. This is the
* time the server will wait before returning an empty result for
* a request. The default setting of 60 seconds is recommended.
* (Integer) hold - The optional HTTPBIND hold value. This is the
* number of connections the server will hold at one time. This
* should almost always be set to 1 (the default).
* (String) route - The optional route value.
* (String) authcid - The optional alternative authentication identity
* (username) if intending to impersonate another user.
* When using the SASL-EXTERNAL authentication mechanism, for example
* with client certificates, then the authcid value is used to
* determine whether an authorization JID (authzid) should be sent to
* the server. The authzid should not be sent to the server if the
* authzid and authcid are the same. So to prevent it from being sent
* (for example when the JID is already contained in the client
* certificate), set authcid to that same JID. See XEP-178 for more
* details.
*/
connect: function (jid, pass, callback, wait, hold, route, authcid) {
this.jid = jid;
/** Variable: authzid
* Authorization identity.
*/
this.authzid = Strophe.getBareJidFromJid(this.jid);
/** Variable: authcid
* Authentication identity (User name).
*/
this.authcid = authcid || Strophe.getNodeFromJid(this.jid);
/** Variable: pass
* Authentication identity (User password).
*/
this.pass = pass;
/** Variable: servtype
* Digest MD5 compatibility.
*/
this.servtype = "xmpp";
this.connect_callback = callback;
this.disconnecting = false;
this.connected = false;
this.authenticated = false;
this.restored = false;
// parse jid for domain
this.domain = Strophe.getDomainFromJid(this.jid);
this._changeConnectStatus(Strophe.Status.CONNECTING, null);
this._proto._connect(wait, hold, route);
},
/** Function: attach
* Attach to an already created and authenticated BOSH session.
*
* This function is provided to allow Strophe to attach to BOSH
* sessions which have been created externally, perhaps by a Web
* application. This is often used to support auto-login type features
* without putting user credentials into the page.
*
* Parameters:
* (String) jid - The full JID that is bound by the session.
* (String) sid - The SID of the BOSH session.
* (String) rid - The current RID of the BOSH session. This RID
* will be used by the next request.
* (Function) callback The connect callback function.
* (Integer) wait - The optional HTTPBIND wait value. This is the
* time the server will wait before returning an empty result for
* a request. The default setting of 60 seconds is recommended.
* Other settings will require tweaks to the Strophe.TIMEOUT value.
* (Integer) hold - The optional HTTPBIND hold value. This is the
* number of connections the server will hold at one time. This
* should almost always be set to 1 (the default).
* (Integer) wind - The optional HTTBIND window value. This is the
* allowed range of request ids that are valid. The default is 5.
*/
attach: function (jid, sid, rid, callback, wait, hold, wind) {
if (this._proto instanceof Strophe.Bosh) {
this._proto._attach(jid, sid, rid, callback, wait, hold, wind);
} else {
throw {
name: 'StropheSessionError',
message: 'The "attach" method can only be used with a BOSH connection.'
};
}
},
/** Function: restore
* Attempt to restore a cached BOSH session.
*
* This function is only useful in conjunction with providing the
* "keepalive":true option when instantiating a new Strophe.Connection.
*
* When "keepalive" is set to true, Strophe will cache the BOSH tokens
* RID (Request ID) and SID (Session ID) and then when this function is
* called, it will attempt to restore the session from those cached
* tokens.
*
* This function must therefore be called instead of connect or attach.
*
* For an example on how to use it, please see examples/restore.js
*
* Parameters:
* (String) jid - The user's JID. This may be a bare JID or a full JID.
* (Function) callback - The connect callback function.
* (Integer) wait - The optional HTTPBIND wait value. This is the
* time the server will wait before returning an empty result for
* a request. The default setting of 60 seconds is recommended.
* (Integer) hold - The optional HTTPBIND hold value. This is the
* number of connections the server will hold at one time. This
* should almost always be set to 1 (the default).
* (Integer) wind - The optional HTTBIND window value. This is the
* allowed range of request ids that are valid. The default is 5.
*/
restore: function (jid, callback, wait, hold, wind) {
if (this._sessionCachingSupported()) {
this._proto._restore(jid, callback, wait, hold, wind);
} else {
throw {
name: 'StropheSessionError',
message: 'The "restore" method can only be used with a BOSH connection.'
};
}
},
/** PrivateFunction: _sessionCachingSupported
* Checks whether sessionStorage and JSON are supported and whether we're
* using BOSH.
*/
_sessionCachingSupported: function () {
if (this._proto instanceof Strophe.Bosh) {
if (!JSON) { return false; }
try {
sessionStorage.setItem('_strophe_', '_strophe_');
sessionStorage.removeItem('_strophe_');
} catch (e) {
return false;
}
return true;
}
return false;
},
/** Function: xmlInput
* User overrideable function that receives XML data coming into the
* connection.
*
* The default function does nothing. User code can override this with
* > Strophe.Connection.xmlInput = function (elem) {
* > (user code)
* > };
*
* Due to limitations of current Browsers' XML-Parsers the opening and closing
* <stream> tag for WebSocket-Connoctions will be passed as selfclosing here.
*
* BOSH-Connections will have all stanzas wrapped in a <body> tag. See
* <Strophe.Bosh.strip> if you want to strip this tag.
*
* Parameters:
* (XMLElement) elem - The XML data received by the connection.
*/
/* jshint unused:false */
xmlInput: function (elem) {
return;
},
/* jshint unused:true */
/** Function: xmlOutput
* User overrideable function that receives XML data sent to the
* connection.
*
* The default function does nothing. User code can override this with
* > Strophe.Connection.xmlOutput = function (elem) {
* > (user code)
* > };
*
* Due to limitations of current Browsers' XML-Parsers the opening and closing
* <stream> tag for WebSocket-Connoctions will be passed as selfclosing here.
*
* BOSH-Connections will have all stanzas wrapped in a <body> tag. See
* <Strophe.Bosh.strip> if you want to strip this tag.
*
* Parameters:
* (XMLElement) elem - The XMLdata sent by the connection.
*/
/* jshint unused:false */
xmlOutput: function (elem) {
return;
},
/* jshint unused:true */
/** Function: rawInput
* User overrideable function that receives raw data coming into the
* connection.
*
* The default function does nothing. User code can override this with
* > Strophe.Connection.rawInput = function (data) {
* > (user code)
* > };
*
* Parameters:
* (String) data - The data received by the connection.
*/
/* jshint unused:false */
rawInput: function (data) {
return;
},
/* jshint unused:true */
/** Function: rawOutput
* User overrideable function that receives raw data sent to the
* connection.
*
* The default function does nothing. User code can override this with
* > Strophe.Connection.rawOutput = function (data) {
* > (user code)
* > };
*
* Parameters:
* (String) data - The data sent by the connection.
*/
/* jshint unused:false */
rawOutput: function (data) {
return;
},
/* jshint unused:true */
/** Function: nextValidRid
* User overrideable function that receives the new valid rid.
*
* The default function does nothing. User code can override this with
* > Strophe.Connection.nextValidRid = function (rid) {
* > (user code)
* > };
*
* Parameters:
* (Number) rid - The next valid rid
*/
/* jshint unused:false */
nextValidRid: function (rid) {
return;
},
/* jshint unused:true */
/** Function: send
* Send a stanza.
*
* This function is called to push data onto the send queue to
* go out over the wire. Whenever a request is sent to the BOSH
* server, all pending data is sent and the queue is flushed.
*
* Parameters:
* (XMLElement |
* [XMLElement] |
* Strophe.Builder) elem - The stanza to send.
*/
send: function (elem) {
if (elem === null) { return ; }
if (typeof(elem.sort) === "function") {
for (var i = 0; i < elem.length; i++) {
this._queueData(elem[i]);
}
} else if (typeof(elem.tree) === "function") {
this._queueData(elem.tree());
} else {
this._queueData(elem);
}
this._proto._send();
},
/** Function: flush
* Immediately send any pending outgoing data.
*
* Normally send() queues outgoing data until the next idle period
* (100ms), which optimizes network use in the common cases when
* several send()s are called in succession. flush() can be used to
* immediately send all pending data.
*/
flush: function () {
// cancel the pending idle period and run the idle function
// immediately
clearTimeout(this._idleTimeout);
this._onIdle();
},
/** Function: sendPresence
* Helper function to send presence stanzas. The main benefit is for
* sending presence stanzas for which you expect a responding presence
* stanza with the same id (for example when leaving a chat room).
*
* Parameters:
* (XMLElement) elem - The stanza to send.
* (Function) callback - The callback function for a successful request.
* (Function) errback - The callback function for a failed or timed
* out request. On timeout, the stanza will be null.
* (Integer) timeout - The time specified in milliseconds for a
* timeout to occur.
*
* Returns:
* The id used to send the presence.
*/
sendPresence: function(elem, callback, errback, timeout) {
var timeoutHandler = null;
var that = this;
if (typeof(elem.tree) === "function") {
elem = elem.tree();
}
var id = elem.getAttribute('id');
if (!id) { // inject id if not found
id = this.getUniqueId("sendPresence");
elem.setAttribute("id", id);
}
if (typeof callback === "function" || typeof errback === "function") {
var handler = this.addHandler(function (stanza) {
// remove timeout handler if there is one
if (timeoutHandler) {
that.deleteTimedHandler(timeoutHandler);
}
var type = stanza.getAttribute('type');
if (type === 'error') {
if (errback) {
errback(stanza);
}
} else if (callback) {
callback(stanza);
}
}, null, 'presence', null, id);
// if timeout specified, set up a timeout handler.
if (timeout) {
timeoutHandler = this.addTimedHandler(timeout, function () {
// get rid of normal handler
that.deleteHandler(handler);
// call errback on timeout with null stanza
if (errback) {
errback(null);
}
return false;
});
}
}
this.send(elem);
return id;
},
/** Function: sendIQ
* Helper function to send IQ stanzas.
*
* Parameters:
* (XMLElement) elem - The stanza to send.
* (Function) callback - The callback function for a successful request.
* (Function) errback - The callback function for a failed or timed
* out request. On timeout, the stanza will be null.
* (Integer) timeout - The time specified in milliseconds for a
* timeout to occur.
*
* Returns:
* The id used to send the IQ.
*/
sendIQ: function(elem, callback, errback, timeout) {
var timeoutHandler = null;
var that = this;
if (typeof(elem.tree) === "function") {
elem = elem.tree();
}
var id = elem.getAttribute('id');
if (!id) { // inject id if not found
id = this.getUniqueId("sendIQ");
elem.setAttribute("id", id);
}
if (typeof callback === "function" || typeof errback === "function") {
var handler = this.addHandler(function (stanza) {
// remove timeout handler if there is one
if (timeoutHandler) {
that.deleteTimedHandler(timeoutHandler);
}
var iqtype = stanza.getAttribute('type');
if (iqtype === 'result') {
if (callback) {
callback(stanza);
}
} else if (iqtype === 'error') {
if (errback) {
errback(stanza);
}
} else {
throw {
name: "StropheError",
message: "Got bad IQ type of " + iqtype
};
}
}, null, 'iq', ['error', 'result'], id);
// if timeout specified, set up a timeout handler.
if (timeout) {
timeoutHandler = this.addTimedHandler(timeout, function () {
// get rid of normal handler
that.deleteHandler(handler);
// call errback on timeout with null stanza
if (errback) {
errback(null);
}
return false;
});
}
}
this.send(elem);
return id;
},
/** PrivateFunction: _queueData
* Queue outgoing data for later sending. Also ensures that the data
* is a DOMElement.
*/
_queueData: function (element) {
if (element === null ||
!element.tagName ||
!element.childNodes) {
throw {
name: "StropheError",
message: "Cannot queue non-DOMElement."
};
}
this._data.push(element);
},
/** PrivateFunction: _sendRestart
* Send an xmpp:restart stanza.
*/
_sendRestart: function () {
this._data.push("restart");
this._proto._sendRestart();
// XXX: setTimeout should be called only with function expressions (23974bc1)
this._idleTimeout = setTimeout(function() {
this._onIdle();
}.bind(this), 100);
},
/** Function: addTimedHandler
* Add a timed handler to the connection.
*
* This function adds a timed handler. The provided handler will
* be called every period milliseconds until it returns false,
* the connection is terminated, or the handler is removed. Handlers
* that wish to continue being invoked should return true.
*
* Because of method binding it is necessary to save the result of
* this function if you wish to remove a handler with
* deleteTimedHandler().
*
* Note that user handlers are not active until authentication is
* successful.
*
* Parameters:
* (Integer) period - The period of the handler.
* (Function) handler - The callback function.
*
* Returns:
* A reference to the handler that can be used to remove it.
*/
addTimedHandler: function (period, handler) {
var thand = new Strophe.TimedHandler(period, handler);
this.addTimeds.push(thand);
return thand;
},
/** Function: deleteTimedHandler
* Delete a timed handler for a connection.
*
* This function removes a timed handler from the connection. The
* handRef parameter is *not* the function passed to addTimedHandler(),
* but is the reference returned from addTimedHandler().
*
* Parameters:
* (Strophe.TimedHandler) handRef - The handler reference.
*/
deleteTimedHandler: function (handRef) {
// this must be done in the Idle loop so that we don't change
// the handlers during iteration
this.removeTimeds.push(handRef);
},
/** Function: addHandler
* Add a stanza handler for the connection.
*
* This function adds a stanza handler to the connection. The
* handler callback will be called for any stanza that matches
* the parameters. Note that if multiple parameters are supplied,
* they must all match for the handler to be invoked.
*
* The handler will receive the stanza that triggered it as its argument.
* *The handler should return true if it is to be invoked again;
* returning false will remove the handler after it returns.*
*
* As a convenience, the ns parameters applies to the top level element
* and also any of its immediate children. This is primarily to make
* matching /iq/query elements easy.
*
* Options
* ~~~~~~~
* With the options argument, you can specify boolean flags that affect how
* matches are being done.
*
* Currently two flags exist:
*
* - matchBareFromJid:
* When set to true, the from parameter and the
* from attribute on the stanza will be matched as bare JIDs instead
* of full JIDs. To use this, pass {matchBareFromJid: true} as the
* value of options. The default value for matchBareFromJid is false.
*
* - ignoreNamespaceFragment:
* When set to true, a fragment specified on the stanza's namespace
* URL will be ignored when it's matched with the one configured for
* the handler.
*
* This means that if you register like this:
* > connection.addHandler(
* > handler,
* > 'http://jabber.org/protocol/muc',
* > null, null, null, null,
* > {'ignoreNamespaceFragment': true}
* > );
*
* Then a stanza with XML namespace of
* 'http://jabber.org/protocol/muc#user' will also be matched. If
* 'ignoreNamespaceFragment' is false, then only stanzas with
* 'http://jabber.org/protocol/muc' will be matched.
*
* Deleting the handler
* ~~~~~~~~~~~~~~~~~~~~
* The return value should be saved if you wish to remove the handler
* with deleteHandler().
*
* Parameters:
* (Function) handler - The user callback.
* (String) ns - The namespace to match.
* (String) name - The stanza name to match.
* (String|Array) type - The stanza type (or types if an array) to match.
* (String) id - The stanza id attribute to match.
* (String) from - The stanza from attribute to match.
* (String) options - The handler options
*
* Returns:
* A reference to the handler that can be used to remove it.
*/
addHandler: function (handler, ns, name, type, id, from, options) {
var hand = new Strophe.Handler(handler, ns, name, type, id, from, options);
this.addHandlers.push(hand);
return hand;
},
/** Function: deleteHandler
* Delete a stanza handler for a connection.
*
* This function removes a stanza handler from the connection. The
* handRef parameter is *not* the function passed to addHandler(),
* but is the reference returned from addHandler().
*
* Parameters:
* (Strophe.Handler) handRef - The handler reference.
*/
deleteHandler: function (handRef) {
// this must be done in the Idle loop so that we don't change
// the handlers during iteration
this.removeHandlers.push(handRef);
// If a handler is being deleted while it is being added,
// prevent it from getting added
var i = this.addHandlers.indexOf(handRef);
if (i >= 0) {
this.addHandlers.splice(i, 1);
}
},
/** Function: registerSASLMechanisms
*
* Register the SASL mechanisms which will be supported by this instance of
* Strophe.Connection (i.e. which this XMPP client will support).
*
* Parameters:
* (Array) mechanisms - Array of objects with Strophe.SASLMechanism prototypes
*
*/
registerSASLMechanisms: function (mechanisms) {
this.mechanisms = {};
mechanisms = mechanisms || [
Strophe.SASLAnonymous,
Strophe.SASLExternal,
Strophe.SASLMD5,
Strophe.SASLOAuthBearer,
Strophe.SASLPlain,
Strophe.SASLSHA1
];
mechanisms.forEach(this.registerSASLMechanism.bind(this));
},
/** Function: registerSASLMechanism
*
* Register a single SASL mechanism, to be supported by this client.
*
* Parameters:
* (Object) mechanism - Object with a Strophe.SASLMechanism prototype
*
*/
registerSASLMechanism: function (mechanism) {
this.mechanisms[mechanism.prototype.name] = mechanism;
},
/** Function: disconnect
* Start the graceful disconnection process.
*
* This function starts the disconnection process. This process starts
* by sending unavailable presence and sending BOSH body of type
* terminate. A timeout handler makes sure that disconnection happens
* even if the BOSH server does not respond.
* If the Connection object isn't connected, at least tries to abort all pending requests
* so the connection object won't generate successful requests (which were already opened).
*
* The user supplied connection callback will be notified of the
* progress as this process happens.
*
* Parameters:
* (String) reason - The reason the disconnect is occuring.
*/
disconnect: function (reason) {
this._changeConnectStatus(Strophe.Status.DISCONNECTING, reason);
Strophe.info("Disconnect was called because: " + reason);
if (this.connected) {
var pres = false;
this.disconnecting = true;
if (this.authenticated) {
pres = $pres({
xmlns: Strophe.NS.CLIENT,
type: 'unavailable'
});
}
// setup timeout handler
this._disconnectTimeout = this._addSysTimedHandler(
3000, this._onDisconnectTimeout.bind(this));
this._proto._disconnect(pres);
} else {
Strophe.info("Disconnect was called before Strophe connected to the server");
this._proto._abortAllRequests();
this._doDisconnect();
}
},
/** PrivateFunction: _changeConnectStatus
* _Private_ helper function that makes sure plugins and the user's
* callback are notified of connection status changes.
*
* Parameters:
* (Integer) status - the new connection status, one of the values
* in Strophe.Status
* (String) condition - the error condition or null
*/
_changeConnectStatus: function (status, condition) {
// notify all plugins listening for status changes
for (var k in Strophe._connectionPlugins) {
if (Strophe._connectionPlugins.hasOwnProperty(k)) {
var plugin = this[k];
if (plugin.statusChanged) {
try {
plugin.statusChanged(status, condition);
} catch (err) {
Strophe.error("" + k + " plugin caused an exception " +
"changing status: " + err);
}
}
}
}
// notify the user's callback
if (this.connect_callback) {
try {
this.connect_callback(status, condition);
} catch (e) {
Strophe._handleError(e);
Strophe.error(
"User connection callback caused an "+"exception: "+e);
}
}
},
/** PrivateFunction: _doDisconnect
* _Private_ function to disconnect.
*
* This is the last piece of the disconnection logic. This resets the
* connection and alerts the user's connection callback.
*/
_doDisconnect: function (condition) {
if (typeof this._idleTimeout === "number") {
clearTimeout(this._idleTimeout);
}
// Cancel Disconnect Timeout
if (this._disconnectTimeout !== null) {
this.deleteTimedHandler(this._disconnectTimeout);
this._disconnectTimeout = null;
}
Strophe.info("_doDisconnect was called");
this._proto._doDisconnect();
this.authenticated = false;
this.disconnecting = false;
this.restored = false;
// delete handlers
this.handlers = [];
this.timedHandlers = [];
this.removeTimeds = [];
this.removeHandlers = [];
this.addTimeds = [];
this.addHandlers = [];
// tell the parent we disconnected
this._changeConnectStatus(Strophe.Status.DISCONNECTED, condition);
this.connected = false;
},
/** PrivateFunction: _dataRecv
* _Private_ handler to processes incoming data from the the connection.
*
* Except for _connect_cb handling the initial connection request,
* this function handles the incoming data for all requests. This
* function also fires stanza handlers that match each incoming
* stanza.
*
* Parameters:
* (Strophe.Request) req - The request that has data ready.
* (string) req - The stanza a raw string (optiona).
*/
_dataRecv: function (req, raw) {
Strophe.info("_dataRecv called");
var elem = this._proto._reqToData(req);
if (elem === null) { return; }
if (this.xmlInput !== Strophe.Connection.prototype.xmlInput) {
if (elem.nodeName === this._proto.strip && elem.childNodes.length) {
this.xmlInput(elem.childNodes[0]);
} else {
this.xmlInput(elem);
}
}
if (this.rawInput !== Strophe.Connection.prototype.rawInput) {
if (raw) {
this.rawInput(raw);
} else {
this.rawInput(Strophe.serialize(elem));
}
}
// remove handlers scheduled for deletion
var i, hand;
while (this.removeHandlers.length > 0) {
hand = this.removeHandlers.pop();
i = this.handlers.indexOf(hand);
if (i >= 0) {
this.handlers.splice(i, 1);
}
}
// add handlers scheduled for addition
while (this.addHandlers.length > 0) {
this.handlers.push(this.addHandlers.pop());
}
// handle graceful disconnect
if (this.disconnecting && this._proto._emptyQueue()) {
this._doDisconnect();
return;
}
var type = elem.getAttribute("type");
var cond, conflict;
if (type !== null && type === "terminate") {
// Don't process stanzas that come in after disconnect
if (this.disconnecting) {
return;
}
// an error occurred
cond = elem.getAttribute("condition");
conflict = elem.getElementsByTagName("conflict");
if (cond !== null) {
if (cond === "remote-stream-error" && conflict.length > 0) {
cond = "conflict";
}
this._changeConnectStatus(Strophe.Status.CONNFAIL, cond);
} else {
this._changeConnectStatus(Strophe.Status.CONNFAIL, "unknown");
}
this._doDisconnect(cond);
return;
}
// send each incoming stanza through the handler chain
var that = this;
Strophe.forEachChild(elem, null, function (child) {
var i, newList;
// process handlers
newList = that.handlers;
that.handlers = [];
for (i = 0; i < newList.length; i++) {
var hand = newList[i];
// encapsulate 'handler.run' not to lose the whole handler list if
// one of the handlers throws an exception
try {
if (hand.isMatch(child) &&
(that.authenticated || !hand.user)) {
if (hand.run(child)) {
that.handlers.push(hand);
}
} else {
that.handlers.push(hand);
}
} catch(e) {
// if the handler throws an exception, we consider it as false
Strophe.warn('Removing Strophe handlers due to uncaught exception: '+e.message);
}
}
});
},
/** Attribute: mechanisms
* SASL Mechanisms available for Connection.
*/
mechanisms: {},
/** PrivateFunction: _connect_cb
* _Private_ handler for initial connection request.
*
* This handler is used to process the initial connection request
* response from the BOSH server. It is used to set up authentication
* handlers and start the authentication process.
*
* SASL authentication will be attempted if available, otherwise
* the code will fall back to legacy authentication.
*
* Parameters:
* (Strophe.Request) req - The current request.
* (Function) _callback - low level (xmpp) connect callback function.
* Useful for plugins with their own xmpp connect callback (when their)
* want to do something special).
*/
_connect_cb: function (req, _callback, raw) {
Strophe.info("_connect_cb was called");
this.connected = true;
var bodyWrap;
try {
bodyWrap = this._proto._reqToData(req);
} catch (e) {
if (e !== "badformat") { throw e; }
this._changeConnectStatus(Strophe.Status.CONNFAIL, 'bad-format');
this._doDisconnect('bad-format');
}
if (!bodyWrap) { return; }
if (this.xmlInput !== Strophe.Connection.prototype.xmlInput) {
if (bodyWrap.nodeName === this._proto.strip && bodyWrap.childNodes.length) {
this.xmlInput(bodyWrap.childNodes[0]);
} else {
this.xmlInput(bodyWrap);
}
}
if (this.rawInput !== Strophe.Connection.prototype.rawInput) {
if (raw) {
this.rawInput(raw);
} else {
this.rawInput(Strophe.serialize(bodyWrap));
}
}
var conncheck = this._proto._connect_cb(bodyWrap);
if (conncheck === Strophe.Status.CONNFAIL) {
return;
}
// Check for the stream:features tag
var hasFeatures;
if (bodyWrap.getElementsByTagNameNS) {
hasFeatures = bodyWrap.getElementsByTagNameNS(Strophe.NS.STREAM, "features").length > 0;
} else {
hasFeatures = bodyWrap.getElementsByTagName("stream:features").length > 0 ||
bodyWrap.getElementsByTagName("features").length > 0;
}
if (!hasFeatures) {
this._proto._no_auth_received(_callback);
return;
}
var matched = [], i, mech;
var mechanisms = bodyWrap.getElementsByTagName("mechanism");
if (mechanisms.length > 0) {
for (i = 0; i < mechanisms.length; i++) {
mech = Strophe.getText(mechanisms[i]);
if (this.mechanisms[mech]) matched.push(this.mechanisms[mech]);
}
}
if (matched.length === 0) {
if (bodyWrap.getElementsByTagName("auth").length === 0) {
// There are no matching SASL mechanisms and also no legacy
// auth available.
this._proto._no_auth_received(_callback);
return;
}
}
if (this.do_authentication !== false) {
this.authenticate(matched);
}
},
/** Function: sortMechanismsByPriority
*
* Sorts an array of objects with prototype SASLMechanism according to
* their priorities.
*
* Parameters:
* (Array) mechanisms - Array of SASL mechanisms.
*
*/
sortMechanismsByPriority: function (mechanisms) {
// Sorting mechanisms according to priority.
var i, j, higher, swap;
for (i = 0; i < mechanisms.length - 1; ++i) {
higher = i;
for (j = i + 1; j < mechanisms.length; ++j) {
if (mechanisms[j].prototype.priority > mechanisms[higher].prototype.priority) {
higher = j;
}
}
if (higher !== i) {
swap = mechanisms[i];
mechanisms[i] = mechanisms[higher];
mechanisms[higher] = swap;
}
}
return mechanisms;
},
/** PrivateFunction: _attemptSASLAuth
*
* Iterate through an array of SASL mechanisms and attempt authentication
* with the highest priority (enabled) mechanism.
*
* Parameters:
* (Array) mechanisms - Array of SASL mechanisms.
*
* Returns:
* (Boolean) mechanism_found - true or false, depending on whether a
* valid SASL mechanism was found with which authentication could be
* started.
*/
_attemptSASLAuth: function (mechanisms) {
mechanisms = this.sortMechanismsByPriority(mechanisms || []);
var i = 0, mechanism_found = false;
for (i = 0; i < mechanisms.length; ++i) {
if (!mechanisms[i].prototype.test(this)) {
continue;
}
this._sasl_success_handler = this._addSysHandler(
this._sasl_success_cb.bind(this), null,
"success", null, null);
this._sasl_failure_handler = this._addSysHandler(
this._sasl_failure_cb.bind(this), null,
"failure", null, null);
this._sasl_challenge_handler = this._addSysHandler(
this._sasl_challenge_cb.bind(this), null,
"challenge", null, null);
this._sasl_mechanism = new mechanisms[i]();
this._sasl_mechanism.onStart(this);
var request_auth_exchange = $build("auth", {
xmlns: Strophe.NS.SASL,
mechanism: this._sasl_mechanism.name
});
if (this._sasl_mechanism.isClientFirst) {
var response = this._sasl_mechanism.onChallenge(this, null);
request_auth_exchange.t(btoa(response));
}
this.send(request_auth_exchange.tree());
mechanism_found = true;
break;
}
return mechanism_found;
},
/** PrivateFunction: _attemptLegacyAuth
*
* Attempt legacy (i.e. non-SASL) authentication.
*
*/
_attemptLegacyAuth: function () {
if (Strophe.getNodeFromJid(this.jid) === null) {
// we don't have a node, which is required for non-anonymous
// client connections
this._changeConnectStatus(
Strophe.Status.CONNFAIL,
'x-strophe-bad-non-anon-jid'
);
this.disconnect('x-strophe-bad-non-anon-jid');
} else {
// Fall back to legacy authentication
this._changeConnectStatus(Strophe.Status.AUTHENTICATING, null);
this._addSysHandler(
this._auth1_cb.bind(this),
null, null, null, "_auth_1"
);
this.send($iq({
'type': "get",
'to': this.domain,
'id': "_auth_1"
}).c("query", {xmlns: Strophe.NS.AUTH})
.c("username", {}).t(Strophe.getNodeFromJid(this.jid))
.tree());
}
},
/** Function: authenticate
* Set up authentication
*
* Continues the initial connection request by setting up authentication
* handlers and starting the authentication process.
*
* SASL authentication will be attempted if available, otherwise
* the code will fall back to legacy authentication.
*
* Parameters:
* (Array) matched - Array of SASL mechanisms supported.
*
*/
authenticate: function (matched) {
if (!this._attemptSASLAuth(matched)) {
this._attemptLegacyAuth();
}
},
/** PrivateFunction: _sasl_challenge_cb
* _Private_ handler for the SASL challenge
*
*/
_sasl_challenge_cb: function(elem) {
var challenge = atob(Strophe.getText(elem));
var response = this._sasl_mechanism.onChallenge(this, challenge);
var stanza = $build('response', {
'xmlns': Strophe.NS.SASL
});
if (response !== "") {
stanza.t(btoa(response));
}
this.send(stanza.tree());
return true;
},
/** PrivateFunction: _auth1_cb
* _Private_ handler for legacy authentication.
*
* This handler is called in response to the initial <iq type='get'/>
* for legacy authentication. It builds an authentication <iq/> and
* sends it, creating a handler (calling back to _auth2_cb()) to
* handle the result
*
* Parameters:
* (XMLElement) elem - The stanza that triggered the callback.
*
* Returns:
* false to remove the handler.
*/
/* jshint unused:false */
_auth1_cb: function (elem) {
// build plaintext auth iq
var iq = $iq({type: "set", id: "_auth_2"})
.c('query', {xmlns: Strophe.NS.AUTH})
.c('username', {}).t(Strophe.getNodeFromJid(this.jid))
.up()
.c('password').t(this.pass);
if (!Strophe.getResourceFromJid(this.jid)) {
// since the user has not supplied a resource, we pick
// a default one here. unlike other auth methods, the server
// cannot do this for us.
this.jid = Strophe.getBareJidFromJid(this.jid) + '/strophe';
}
iq.up().c('resource', {}).t(Strophe.getResourceFromJid(this.jid));
this._addSysHandler(this._auth2_cb.bind(this), null,
null, null, "_auth_2");
this.send(iq.tree());
return false;
},
/* jshint unused:true */
/** PrivateFunction: _sasl_success_cb
* _Private_ handler for succesful SASL authentication.
*
* Parameters:
* (XMLElement) elem - The matching stanza.
*
* Returns:
* false to remove the handler.
*/
_sasl_success_cb: function (elem) {
if (this._sasl_data["server-signature"]) {
var serverSignature;
var success = atob(Strophe.getText(elem));
var attribMatch = /([a-z]+)=([^,]+)(,|$)/;
var matches = success.match(attribMatch);
if (matches[1] === "v") {
serverSignature = matches[2];
}
if (serverSignature !== this._sasl_data["server-signature"]) {
// remove old handlers
this.deleteHandler(this._sasl_failure_handler);
this._sasl_failure_handler = null;
if (this._sasl_challenge_handler) {
this.deleteHandler(this._sasl_challenge_handler);
this._sasl_challenge_handler = null;
}
this._sasl_data = {};
return this._sasl_failure_cb(null);
}
}
Strophe.info("SASL authentication succeeded.");
if (this._sasl_mechanism) {
this._sasl_mechanism.onSuccess();
}
// remove old handlers
this.deleteHandler(this._sasl_failure_handler);
this._sasl_failure_handler = null;
if (this._sasl_challenge_handler) {
this.deleteHandler(this._sasl_challenge_handler);
this._sasl_challenge_handler = null;
}
var streamfeature_handlers = [];
var wrapper = function(handlers, elem) {
while (handlers.length) {
this.deleteHandler(handlers.pop());
}
this._sasl_auth1_cb.bind(this)(elem);
return false;
};
streamfeature_handlers.push(this._addSysHandler(function(elem) {
wrapper.bind(this)(streamfeature_handlers, elem);
}.bind(this), null, "stream:features", null, null));
streamfeature_handlers.push(this._addSysHandler(function(elem) {
wrapper.bind(this)(streamfeature_handlers, elem);
}.bind(this), Strophe.NS.STREAM, "features", null, null));
// we must send an xmpp:restart now
this._sendRestart();
return false;
},
/** PrivateFunction: _sasl_auth1_cb
* _Private_ handler to start stream binding.
*
* Parameters:
* (XMLElement) elem - The matching stanza.
*
* Returns:
* false to remove the handler.
*/
_sasl_auth1_cb: function (elem) {
// save stream:features for future usage
this.features = elem;
var i, child;
for (i = 0; i < elem.childNodes.length; i++) {
child = elem.childNodes[i];
if (child.nodeName === 'bind') {
this.do_bind = true;
}
if (child.nodeName === 'session') {
this.do_session = true;
}
}
if (!this.do_bind) {
this._changeConnectStatus(Strophe.Status.AUTHFAIL, null);
return false;
} else {
this._addSysHandler(this._sasl_bind_cb.bind(this), null, null,
null, "_bind_auth_2");
var resource = Strophe.getResourceFromJid(this.jid);
if (resource) {
this.send($iq({type: "set", id: "_bind_auth_2"})
.c('bind', {xmlns: Strophe.NS.BIND})
.c('resource', {}).t(resource).tree());
} else {
this.send($iq({type: "set", id: "_bind_auth_2"})
.c('bind', {xmlns: Strophe.NS.BIND})
.tree());
}
}
return false;
},
/** PrivateFunction: _sasl_bind_cb
* _Private_ handler for binding result and session start.
*
* Parameters:
* (XMLElement) elem - The matching stanza.
*
* Returns:
* false to remove the handler.
*/
_sasl_bind_cb: function (elem) {
if (elem.getAttribute("type") === "error") {
Strophe.info("SASL binding failed.");
var conflict = elem.getElementsByTagName("conflict"), condition;
if (conflict.length > 0) {
condition = 'conflict';
}
this._changeConnectStatus(Strophe.Status.AUTHFAIL, condition);
return false;
}
// TODO - need to grab errors
var bind = elem.getElementsByTagName("bind");
var jidNode;
if (bind.length > 0) {
// Grab jid
jidNode = bind[0].getElementsByTagName("jid");
if (jidNode.length > 0) {
this.jid = Strophe.getText(jidNode[0]);
if (this.do_session) {
this._addSysHandler(this._sasl_session_cb.bind(this),
null, null, null, "_session_auth_2");
this.send($iq({type: "set", id: "_session_auth_2"})
.c('session', {xmlns: Strophe.NS.SESSION})
.tree());
} else {
this.authenticated = true;
this._changeConnectStatus(Strophe.Status.CONNECTED, null);
}
}
} else {
Strophe.info("SASL binding failed.");
this._changeConnectStatus(Strophe.Status.AUTHFAIL, null);
return false;
}
},
/** PrivateFunction: _sasl_session_cb
* _Private_ handler to finish successful SASL connection.
*
* This sets Connection.authenticated to true on success, which
* starts the processing of user handlers.
*
* Parameters:
* (XMLElement) elem - The matching stanza.
*
* Returns:
* false to remove the handler.
*/
_sasl_session_cb: function (elem) {
if (elem.getAttribute("type") === "result") {
this.authenticated = true;
this._changeConnectStatus(Strophe.Status.CONNECTED, null);
} else if (elem.getAttribute("type") === "error") {
Strophe.info("Session creation failed.");
this._changeConnectStatus(Strophe.Status.AUTHFAIL, null);
return false;
}
return false;
},
/** PrivateFunction: _sasl_failure_cb
* _Private_ handler for SASL authentication failure.
*
* Parameters:
* (XMLElement) elem - The matching stanza.
*
* Returns:
* false to remove the handler.
*/
/* jshint unused:false */
_sasl_failure_cb: function (elem) {
// delete unneeded handlers
if (this._sasl_success_handler) {
this.deleteHandler(this._sasl_success_handler);
this._sasl_success_handler = null;
}
if (this._sasl_challenge_handler) {
this.deleteHandler(this._sasl_challenge_handler);
this._sasl_challenge_handler = null;
}
if(this._sasl_mechanism)
this._sasl_mechanism.onFailure();
this._changeConnectStatus(Strophe.Status.AUTHFAIL, null);
return false;
},
/* jshint unused:true */
/** PrivateFunction: _auth2_cb
* _Private_ handler to finish legacy authentication.
*
* This handler is called when the result from the jabber:iq:auth
* <iq/> stanza is returned.
*
* Parameters:
* (XMLElement) elem - The stanza that triggered the callback.
*
* Returns:
* false to remove the handler.
*/
_auth2_cb: function (elem) {
if (elem.getAttribute("type") === "result") {
this.authenticated = true;
this._changeConnectStatus(Strophe.Status.CONNECTED, null);
} else if (elem.getAttribute("type") === "error") {
this._changeConnectStatus(Strophe.Status.AUTHFAIL, null);
this.disconnect('authentication failed');
}
return false;
},
/** PrivateFunction: _addSysTimedHandler
* _Private_ function to add a system level timed handler.
*
* This function is used to add a Strophe.TimedHandler for the
* library code. System timed handlers are allowed to run before
* authentication is complete.
*
* Parameters:
* (Integer) period - The period of the handler.
* (Function) handler - The callback function.
*/
_addSysTimedHandler: function (period, handler) {
var thand = new Strophe.TimedHandler(period, handler);
thand.user = false;
this.addTimeds.push(thand);
return thand;
},
/** PrivateFunction: _addSysHandler
* _Private_ function to add a system level stanza handler.
*
* This function is used to add a Strophe.Handler for the
* library code. System stanza handlers are allowed to run before
* authentication is complete.
*
* Parameters:
* (Function) handler - The callback function.
* (String) ns - The namespace to match.
* (String) name - The stanza name to match.
* (String) type - The stanza type attribute to match.
* (String) id - The stanza id attribute to match.
*/
_addSysHandler: function (handler, ns, name, type, id) {
var hand = new Strophe.Handler(handler, ns, name, type, id);
hand.user = false;
this.addHandlers.push(hand);
return hand;
},
/** PrivateFunction: _onDisconnectTimeout
* _Private_ timeout handler for handling non-graceful disconnection.
*
* If the graceful disconnect process does not complete within the
* time allotted, this handler finishes the disconnect anyway.
*
* Returns:
* false to remove the handler.
*/
_onDisconnectTimeout: function () {
Strophe.info("_onDisconnectTimeout was called");
this._changeConnectStatus(Strophe.Status.CONNTIMEOUT, null);
this._proto._onDisconnectTimeout();
// actually disconnect
this._doDisconnect();
return false;
},
/** PrivateFunction: _onIdle
* _Private_ handler to process events during idle cycle.
*
* This handler is called every 100ms to fire timed handlers that
* are ready and keep poll requests going.
*/
_onIdle: function () {
var i, thand, since, newList;
// add timed handlers scheduled for addition
// NOTE: we add before remove in the case a timed handler is
// added and then deleted before the next _onIdle() call.
while (this.addTimeds.length > 0) {
this.timedHandlers.push(this.addTimeds.pop());
}
// remove timed handlers that have been scheduled for deletion
while (this.removeTimeds.length > 0) {
thand = this.removeTimeds.pop();
i = this.timedHandlers.indexOf(thand);
if (i >= 0) {
this.timedHandlers.splice(i, 1);
}
}
// call ready timed handlers
var now = new Date().getTime();
newList = [];
for (i = 0; i < this.timedHandlers.length; i++) {
thand = this.timedHandlers[i];
if (this.authenticated || !thand.user) {
since = thand.lastCalled + thand.period;
if (since - now <= 0) {
if (thand.run()) {
newList.push(thand);
}
} else {
newList.push(thand);
}
}
}
this.timedHandlers = newList;
clearTimeout(this._idleTimeout);
this._proto._onIdle();
// reactivate the timer only if connected
if (this.connected) {
// XXX: setTimeout should be called only with function expressions (23974bc1)
this._idleTimeout = setTimeout(function() {
this._onIdle();
}.bind(this), 100);
}
}
};
/** Class: Strophe.SASLMechanism
*
* encapsulates SASL authentication mechanisms.
*
* User code may override the priority for each mechanism or disable it completely.
* See <priority> for information about changing priority and <test> for informatian on
* how to disable a mechanism.
*
* By default, all mechanisms are enabled and the priorities are
*
* OAUTHBEARER - 60
* SCRAM-SHA1 - 50
* DIGEST-MD5 - 40
* PLAIN - 30
* ANONYMOUS - 20
* EXTERNAL - 10
*
* See: Strophe.Connection.addSupportedSASLMechanisms
*/
/**
* PrivateConstructor: Strophe.SASLMechanism
* SASL auth mechanism abstraction.
*
* Parameters:
* (String) name - SASL Mechanism name.
* (Boolean) isClientFirst - If client should send response first without challenge.
* (Number) priority - Priority.
*
* Returns:
* A new Strophe.SASLMechanism object.
*/
Strophe.SASLMechanism = function(name, isClientFirst, priority) {
/** PrivateVariable: name
* Mechanism name.
*/
this.name = name;
/** PrivateVariable: isClientFirst
* If client sends response without initial server challenge.
*/
this.isClientFirst = isClientFirst;
/** Variable: priority
* Determines which <SASLMechanism> is chosen for authentication (Higher is better).
* Users may override this to prioritize mechanisms differently.
*
* In the default configuration the priorities are
*
* SCRAM-SHA1 - 40
* DIGEST-MD5 - 30
* Plain - 20
*
* Example: (This will cause Strophe to choose the mechanism that the server sent first)
*
* > Strophe.SASLMD5.priority = Strophe.SASLSHA1.priority;
*
* See <SASL mechanisms> for a list of available mechanisms.
*
*/
this.priority = priority;
};
Strophe.SASLMechanism.prototype = {
/**
* Function: test
* Checks if mechanism able to run.
* To disable a mechanism, make this return false;
*
* To disable plain authentication run
* > Strophe.SASLPlain.test = function() {
* > return false;
* > }
*
* See <SASL mechanisms> for a list of available mechanisms.
*
* Parameters:
* (Strophe.Connection) connection - Target Connection.
*
* Returns:
* (Boolean) If mechanism was able to run.
*/
/* jshint unused:false */
test: function(connection) {
return true;
},
/* jshint unused:true */
/** PrivateFunction: onStart
* Called before starting mechanism on some connection.
*
* Parameters:
* (Strophe.Connection) connection - Target Connection.
*/
onStart: function(connection) {
this._connection = connection;
},
/** PrivateFunction: onChallenge
* Called by protocol implementation on incoming challenge. If client is
* first (isClientFirst === true) challenge will be null on the first call.
*
* Parameters:
* (Strophe.Connection) connection - Target Connection.
* (String) challenge - current challenge to handle.
*
* Returns:
* (String) Mechanism response.
*/
/* jshint unused:false */
onChallenge: function(connection, challenge) {
throw new Error("You should implement challenge handling!");
},
/* jshint unused:true */
/** PrivateFunction: onFailure
* Protocol informs mechanism implementation about SASL failure.
*/
onFailure: function() {
this._connection = null;
},
/** PrivateFunction: onSuccess
* Protocol informs mechanism implementation about SASL success.
*/
onSuccess: function() {
this._connection = null;
}
};
/** Constants: SASL mechanisms
* Available authentication mechanisms
*
* Strophe.SASLAnonymous - SASL ANONYMOUS authentication.
* Strophe.SASLPlain - SASL PLAIN authentication.
* Strophe.SASLMD5 - SASL DIGEST-MD5 authentication
* Strophe.SASLSHA1 - SASL SCRAM-SHA1 authentication
* Strophe.SASLOAuthBearer - SASL OAuth Bearer authentication
* Strophe.SASLExternal - SASL EXTERNAL authentication
*/
// Building SASL callbacks
/** PrivateConstructor: SASLAnonymous
* SASL ANONYMOUS authentication.
*/
Strophe.SASLAnonymous = function() {};
Strophe.SASLAnonymous.prototype = new Strophe.SASLMechanism("ANONYMOUS", false, 20);
Strophe.SASLAnonymous.prototype.test = function(connection) {
return connection.authcid === null;
};
/** PrivateConstructor: SASLPlain
* SASL PLAIN authentication.
*/
Strophe.SASLPlain = function() {};
Strophe.SASLPlain.prototype = new Strophe.SASLMechanism("PLAIN", true, 30);
Strophe.SASLPlain.prototype.test = function(connection) {
return connection.authcid !== null;
};
Strophe.SASLPlain.prototype.onChallenge = function(connection) {
var auth_str = connection.authzid;
auth_str = auth_str + "\u0000";
auth_str = auth_str + connection.authcid;
auth_str = auth_str + "\u0000";
auth_str = auth_str + connection.pass;
return utils.utf16to8(auth_str);
};
/** PrivateConstructor: SASLSHA1
* SASL SCRAM SHA 1 authentication.
*/
Strophe.SASLSHA1 = function() {};
Strophe.SASLSHA1.prototype = new Strophe.SASLMechanism("SCRAM-SHA-1", true, 50);
Strophe.SASLSHA1.prototype.test = function(connection) {
return connection.authcid !== null;
};
Strophe.SASLSHA1.prototype.onChallenge = function(connection, challenge, test_cnonce) {
var cnonce = test_cnonce || MD5.hexdigest(Math.random() * 1234567890);
var auth_str = "n=" + utils.utf16to8(connection.authcid);
auth_str += ",r=";
auth_str += cnonce;
connection._sasl_data.cnonce = cnonce;
connection._sasl_data["client-first-message-bare"] = auth_str;
auth_str = "n,," + auth_str;
this.onChallenge = function (connection, challenge) {
var nonce, salt, iter, Hi, U, U_old, i, k, pass;
var clientKey, serverKey, clientSignature;
var responseText = "c=biws,";
var authMessage = connection._sasl_data["client-first-message-bare"] + "," +
challenge + ",";
var cnonce = connection._sasl_data.cnonce;
var attribMatch = /([a-z]+)=([^,]+)(,|$)/;
while (challenge.match(attribMatch)) {
var matches = challenge.match(attribMatch);
challenge = challenge.replace(matches[0], "");
switch (matches[1]) {
case "r":
nonce = matches[2];
break;
case "s":
salt = matches[2];
break;
case "i":
iter = matches[2];
break;
}
}
if (nonce.substr(0, cnonce.length) !== cnonce) {
connection._sasl_data = {};
return connection._sasl_failure_cb();
}
responseText += "r=" + nonce;
authMessage += responseText;
salt = atob(salt);
salt += "\x00\x00\x00\x01";
pass = utils.utf16to8(connection.pass);
Hi = U_old = SHA1.core_hmac_sha1(pass, salt);
for (i = 1; i < iter; i++) {
U = SHA1.core_hmac_sha1(pass, SHA1.binb2str(U_old));
for (k = 0; k < 5; k++) {
Hi[k] ^= U[k];
}
U_old = U;
}
Hi = SHA1.binb2str(Hi);
clientKey = SHA1.core_hmac_sha1(Hi, "Client Key");
serverKey = SHA1.str_hmac_sha1(Hi, "Server Key");
clientSignature = SHA1.core_hmac_sha1(SHA1.str_sha1(SHA1.binb2str(clientKey)), authMessage);
connection._sasl_data["server-signature"] = SHA1.b64_hmac_sha1(serverKey, authMessage);
for (k = 0; k < 5; k++) {
clientKey[k] ^= clientSignature[k];
}
responseText += ",p=" + btoa(SHA1.binb2str(clientKey));
return responseText;
}.bind(this);
return auth_str;
};
/** PrivateConstructor: SASLMD5
* SASL DIGEST MD5 authentication.
*/
Strophe.SASLMD5 = function() {};
Strophe.SASLMD5.prototype = new Strophe.SASLMechanism("DIGEST-MD5", false, 40);
Strophe.SASLMD5.prototype.test = function(connection) {
return connection.authcid !== null;
};
/** PrivateFunction: _quote
* _Private_ utility function to backslash escape and quote strings.
*
* Parameters:
* (String) str - The string to be quoted.
*
* Returns:
* quoted string
*/
Strophe.SASLMD5.prototype._quote = function (str) {
return '"' + str.replace(/\\/g, "\\\\").replace(/"/g, '\\"') + '"';
//" end string workaround for emacs
};
Strophe.SASLMD5.prototype.onChallenge = function(connection, challenge, test_cnonce) {
var attribMatch = /([a-z]+)=("[^"]+"|[^,"]+)(?:,|$)/;
var cnonce = test_cnonce || MD5.hexdigest("" + (Math.random() * 1234567890));
var realm = "";
var host = null;
var nonce = "";
var qop = "";
var matches;
while (challenge.match(attribMatch)) {
matches = challenge.match(attribMatch);
challenge = challenge.replace(matches[0], "");
matches[2] = matches[2].replace(/^"(.+)"$/, "$1");
switch (matches[1]) {
case "realm":
realm = matches[2];
break;
case "nonce":
nonce = matches[2];
break;
case "qop":
qop = matches[2];
break;
case "host":
host = matches[2];
break;
}
}
var digest_uri = connection.servtype + "/" + connection.domain;
if (host !== null) {
digest_uri = digest_uri + "/" + host;
}
var cred = utils.utf16to8(connection.authcid + ":" + realm + ":" + this._connection.pass);
var A1 = MD5.hash(cred) + ":" + nonce + ":" + cnonce;
var A2 = 'AUTHENTICATE:' + digest_uri;
var responseText = "";
responseText += 'charset=utf-8,';
responseText += 'username=' + this._quote(utils.utf16to8(connection.authcid)) + ',';
responseText += 'realm=' + this._quote(realm) + ',';
responseText += 'nonce=' + this._quote(nonce) + ',';
responseText += 'nc=00000001,';
responseText += 'cnonce=' + this._quote(cnonce) + ',';
responseText += 'digest-uri=' + this._quote(digest_uri) + ',';
responseText += 'response=' + MD5.hexdigest(MD5.hexdigest(A1) + ":" +
nonce + ":00000001:" +
cnonce + ":auth:" +
MD5.hexdigest(A2)) + ",";
responseText += 'qop=auth';
this.onChallenge = function () {
return "";
};
return responseText;
};
/** PrivateConstructor: SASLOAuthBearer
* SASL OAuth Bearer authentication.
*/
Strophe.SASLOAuthBearer = function() {};
Strophe.SASLOAuthBearer.prototype = new Strophe.SASLMechanism("OAUTHBEARER", true, 60);
Strophe.SASLOAuthBearer.prototype.test = function(connection) {
return connection.pass !== null;
};
Strophe.SASLOAuthBearer.prototype.onChallenge = function(connection) {
var auth_str = 'n,';
if (connection.authcid !== null) {
auth_str = auth_str + 'a=' + connection.authzid;
}
auth_str = auth_str + ',';
auth_str = auth_str + "\u0001";
auth_str = auth_str + 'auth=Bearer ';
auth_str = auth_str + connection.pass;
auth_str = auth_str + "\u0001";
auth_str = auth_str + "\u0001";
return utils.utf16to8(auth_str);
};
/** PrivateConstructor: SASLExternal
* SASL EXTERNAL authentication.
*
* The EXTERNAL mechanism allows a client to request the server to use
* credentials established by means external to the mechanism to
* authenticate the client. The external means may be, for instance,
* TLS services.
*/
Strophe.SASLExternal = function() {};
Strophe.SASLExternal.prototype = new Strophe.SASLMechanism("EXTERNAL", true, 10);
Strophe.SASLExternal.prototype.onChallenge = function(connection) {
/** According to XEP-178, an authzid SHOULD NOT be presented when the
* authcid contained or implied in the client certificate is the JID (i.e.
* authzid) with which the user wants to log in as.
*
* To NOT send the authzid, the user should therefore set the authcid equal
* to the JID when instantiating a new Strophe.Connection object.
*/
return connection.authcid === connection.authzid ? '' : connection.authzid;
};
return {
'Strophe': Strophe,
'$build': $build,
'$iq': $iq,
'$msg': $msg,
'$pres': $pres,
'SHA1': SHA1,
'MD5': MD5,
'b64_hmac_sha1': SHA1.b64_hmac_sha1,
'b64_sha1': SHA1.b64_sha1,
'str_hmac_sha1': SHA1.str_hmac_sha1,
'str_sha1': SHA1.str_sha1
};
}));
/*
This program is distributed under the terms of the MIT license.
Please see the LICENSE file for details.
Copyright 2006-2008, OGG, LLC
*/
/* jshint undef: true, unused: true:, noarg: true, latedef: true */
/* global define, window, setTimeout, clearTimeout, XMLHttpRequest, ActiveXObject, Strophe, $build */
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define('strophe-bosh',['strophe-core'], function (core) {
return factory(
core.Strophe,
core.$build
);
});
} else {
// Browser globals
return factory(Strophe, $build);
}
}(this, function (Strophe, $build) {
/** PrivateClass: Strophe.Request
* _Private_ helper class that provides a cross implementation abstraction
* for a BOSH related XMLHttpRequest.
*
* The Strophe.Request class is used internally to encapsulate BOSH request
* information. It is not meant to be used from user's code.
*/
/** PrivateConstructor: Strophe.Request
* Create and initialize a new Strophe.Request object.
*
* Parameters:
* (XMLElement) elem - The XML data to be sent in the request.
* (Function) func - The function that will be called when the
* XMLHttpRequest readyState changes.
* (Integer) rid - The BOSH rid attribute associated with this request.
* (Integer) sends - The number of times this same request has been sent.
*/
Strophe.Request = function (elem, func, rid, sends) {
this.id = ++Strophe._requestId;
this.xmlData = elem;
this.data = Strophe.serialize(elem);
// save original function in case we need to make a new request
// from this one.
this.origFunc = func;
this.func = func;
this.rid = rid;
this.date = NaN;
this.sends = sends || 0;
this.abort = false;
this.dead = null;
this.age = function () {
if (!this.date) { return 0; }
var now = new Date();
return (now - this.date) / 1000;
};
this.timeDead = function () {
if (!this.dead) { return 0; }
var now = new Date();
return (now - this.dead) / 1000;
};
this.xhr = this._newXHR();
};
Strophe.Request.prototype = {
/** PrivateFunction: getResponse
* Get a response from the underlying XMLHttpRequest.
*
* This function attempts to get a response from the request and checks
* for errors.
*
* Throws:
* "parsererror" - A parser error occured.
* "badformat" - The entity has sent XML that cannot be processed.
*
* Returns:
* The DOM element tree of the response.
*/
getResponse: function () {
var node = null;
if (this.xhr.responseXML && this.xhr.responseXML.documentElement) {
node = this.xhr.responseXML.documentElement;
if (node.tagName === "parsererror") {
Strophe.error("invalid response received");
Strophe.error("responseText: " + this.xhr.responseText);
Strophe.error("responseXML: " +
Strophe.serialize(this.xhr.responseXML));
throw "parsererror";
}
} else if (this.xhr.responseText) {
Strophe.error("invalid response received");
Strophe.error("responseText: " + this.xhr.responseText);
throw "badformat";
}
return node;
},
/** PrivateFunction: _newXHR
* _Private_ helper function to create XMLHttpRequests.
*
* This function creates XMLHttpRequests across all implementations.
*
* Returns:
* A new XMLHttpRequest.
*/
_newXHR: function () {
var xhr = null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
if (xhr.overrideMimeType) {
xhr.overrideMimeType("text/xml; charset=utf-8");
}
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
// use Function.bind() to prepend ourselves as an argument
xhr.onreadystatechange = this.func.bind(null, this);
return xhr;
}
};
/** Class: Strophe.Bosh
* _Private_ helper class that handles BOSH Connections
*
* The Strophe.Bosh class is used internally by Strophe.Connection
* to encapsulate BOSH sessions. It is not meant to be used from user's code.
*/
/** File: bosh.js
* A JavaScript library to enable BOSH in Strophejs.
*
* this library uses Bidirectional-streams Over Synchronous HTTP (BOSH)
* to emulate a persistent, stateful, two-way connection to an XMPP server.
* More information on BOSH can be found in XEP 124.
*/
/** PrivateConstructor: Strophe.Bosh
* Create and initialize a Strophe.Bosh object.
*
* Parameters:
* (Strophe.Connection) connection - The Strophe.Connection that will use BOSH.
*
* Returns:
* A new Strophe.Bosh object.
*/
Strophe.Bosh = function(connection) {
this._conn = connection;
/* request id for body tags */
this.rid = Math.floor(Math.random() * 4294967295);
/* The current session ID. */
this.sid = null;
// default BOSH values
this.hold = 1;
this.wait = 60;
this.window = 5;
this.errors = 0;
this.inactivity = null;
this._requests = [];
};
Strophe.Bosh.prototype = {
/** Variable: strip
*
* BOSH-Connections will have all stanzas wrapped in a <body> tag when
* passed to <Strophe.Connection.xmlInput> or <Strophe.Connection.xmlOutput>.
* To strip this tag, User code can set <Strophe.Bosh.strip> to "body":
*
* > Strophe.Bosh.prototype.strip = "body";
*
* This will enable stripping of the body tag in both
* <Strophe.Connection.xmlInput> and <Strophe.Connection.xmlOutput>.
*/
strip: null,
/** PrivateFunction: _buildBody
* _Private_ helper function to generate the <body/> wrapper for BOSH.
*
* Returns:
* A Strophe.Builder with a <body/> element.
*/
_buildBody: function () {
var bodyWrap = $build('body', {
rid: this.rid++,
xmlns: Strophe.NS.HTTPBIND
});
if (this.sid !== null) {
bodyWrap.attrs({sid: this.sid});
}
if (this._conn.options.keepalive && this._conn._sessionCachingSupported()) {
this._cacheSession();
}
return bodyWrap;
},
/** PrivateFunction: _reset
* Reset the connection.
*
* This function is called by the reset function of the Strophe Connection
*/
_reset: function () {
this.rid = Math.floor(Math.random() * 4294967295);
this.sid = null;
this.errors = 0;
if (this._conn._sessionCachingSupported()) {
window.sessionStorage.removeItem('strophe-bosh-session');
}
this._conn.nextValidRid(this.rid);
},
/** PrivateFunction: _connect
* _Private_ function that initializes the BOSH connection.
*
* Creates and sends the Request that initializes the BOSH connection.
*/
_connect: function (wait, hold, route) {
this.wait = wait || this.wait;
this.hold = hold || this.hold;
this.errors = 0;
// build the body tag
var body = this._buildBody().attrs({
to: this._conn.domain,
"xml:lang": "en",
wait: this.wait,
hold: this.hold,
content: "text/xml; charset=utf-8",
ver: "1.6",
"xmpp:version": "1.0",
"xmlns:xmpp": Strophe.NS.BOSH
});
if(route){
body.attrs({
route: route
});
}
var _connect_cb = this._conn._connect_cb;
this._requests.push(
new Strophe.Request(body.tree(),
this._onRequestStateChange.bind(
this, _connect_cb.bind(this._conn)),
body.tree().getAttribute("rid")));
this._throttledRequestHandler();
},
/** PrivateFunction: _attach
* Attach to an already created and authenticated BOSH session.
*
* This function is provided to allow Strophe to attach to BOSH
* sessions which have been created externally, perhaps by a Web
* application. This is often used to support auto-login type features
* without putting user credentials into the page.
*
* Parameters:
* (String) jid - The full JID that is bound by the session.
* (String) sid - The SID of the BOSH session.
* (String) rid - The current RID of the BOSH session. This RID
* will be used by the next request.
* (Function) callback The connect callback function.
* (Integer) wait - The optional HTTPBIND wait value. This is the
* time the server will wait before returning an empty result for
* a request. The default setting of 60 seconds is recommended.
* Other settings will require tweaks to the Strophe.TIMEOUT value.
* (Integer) hold - The optional HTTPBIND hold value. This is the
* number of connections the server will hold at one time. This
* should almost always be set to 1 (the default).
* (Integer) wind - The optional HTTBIND window value. This is the
* allowed range of request ids that are valid. The default is 5.
*/
_attach: function (jid, sid, rid, callback, wait, hold, wind) {
this._conn.jid = jid;
this.sid = sid;
this.rid = rid;
this._conn.connect_callback = callback;
this._conn.domain = Strophe.getDomainFromJid(this._conn.jid);
this._conn.authenticated = true;
this._conn.connected = true;
this.wait = wait || this.wait;
this.hold = hold || this.hold;
this.window = wind || this.window;
this._conn._changeConnectStatus(Strophe.Status.ATTACHED, null);
},
/** PrivateFunction: _restore
* Attempt to restore a cached BOSH session
*
* Parameters:
* (String) jid - The full JID that is bound by the session.
* This parameter is optional but recommended, specifically in cases
* where prebinded BOSH sessions are used where it's important to know
* that the right session is being restored.
* (Function) callback The connect callback function.
* (Integer) wait - The optional HTTPBIND wait value. This is the
* time the server will wait before returning an empty result for
* a request. The default setting of 60 seconds is recommended.
* Other settings will require tweaks to the Strophe.TIMEOUT value.
* (Integer) hold - The optional HTTPBIND hold value. This is the
* number of connections the server will hold at one time. This
* should almost always be set to 1 (the default).
* (Integer) wind - The optional HTTBIND window value. This is the
* allowed range of request ids that are valid. The default is 5.
*/
_restore: function (jid, callback, wait, hold, wind) {
var session = JSON.parse(window.sessionStorage.getItem('strophe-bosh-session'));
if (typeof session !== "undefined" &&
session !== null &&
session.rid &&
session.sid &&
session.jid &&
( typeof jid === "undefined" ||
jid === null ||
Strophe.getBareJidFromJid(session.jid) === Strophe.getBareJidFromJid(jid) ||
// If authcid is null, then it's an anonymous login, so
// we compare only the domains:
((Strophe.getNodeFromJid(jid) === null) && (Strophe.getDomainFromJid(session.jid) === jid))
)
) {
this._conn.restored = true;
this._attach(session.jid, session.sid, session.rid, callback, wait, hold, wind);
} else {
throw { name: "StropheSessionError", message: "_restore: no restoreable session." };
}
},
/** PrivateFunction: _cacheSession
* _Private_ handler for the beforeunload event.
*
* This handler is used to process the Bosh-part of the initial request.
* Parameters:
* (Strophe.Request) bodyWrap - The received stanza.
*/
_cacheSession: function () {
if (this._conn.authenticated) {
if (this._conn.jid && this.rid && this.sid) {
window.sessionStorage.setItem('strophe-bosh-session', JSON.stringify({
'jid': this._conn.jid,
'rid': this.rid,
'sid': this.sid
}));
}
} else {
window.sessionStorage.removeItem('strophe-bosh-session');
}
},
/** PrivateFunction: _connect_cb
* _Private_ handler for initial connection request.
*
* This handler is used to process the Bosh-part of the initial request.
* Parameters:
* (Strophe.Request) bodyWrap - The received stanza.
*/
_connect_cb: function (bodyWrap) {
var typ = bodyWrap.getAttribute("type");
var cond, conflict;
if (typ !== null && typ === "terminate") {
// an error occurred
cond = bodyWrap.getAttribute("condition");
Strophe.error("BOSH-Connection failed: " + cond);
conflict = bodyWrap.getElementsByTagName("conflict");
if (cond !== null) {
if (cond === "remote-stream-error" && conflict.length > 0) {
cond = "conflict";
}
this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, cond);
} else {
this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, "unknown");
}
this._conn._doDisconnect(cond);
return Strophe.Status.CONNFAIL;
}
// check to make sure we don't overwrite these if _connect_cb is
// called multiple times in the case of missing stream:features
if (!this.sid) {
this.sid = bodyWrap.getAttribute("sid");
}
var wind = bodyWrap.getAttribute('requests');
if (wind) { this.window = parseInt(wind, 10); }
var hold = bodyWrap.getAttribute('hold');
if (hold) { this.hold = parseInt(hold, 10); }
var wait = bodyWrap.getAttribute('wait');
if (wait) { this.wait = parseInt(wait, 10); }
var inactivity = bodyWrap.getAttribute('inactivity');
if (inactivity) { this.inactivity = parseInt(inactivity, 10); }
},
/** PrivateFunction: _disconnect
* _Private_ part of Connection.disconnect for Bosh
*
* Parameters:
* (Request) pres - This stanza will be sent before disconnecting.
*/
_disconnect: function (pres) {
this._sendTerminate(pres);
},
/** PrivateFunction: _doDisconnect
* _Private_ function to disconnect.
*
* Resets the SID and RID.
*/
_doDisconnect: function () {
this.sid = null;
this.rid = Math.floor(Math.random() * 4294967295);
if (this._conn._sessionCachingSupported()) {
window.sessionStorage.removeItem('strophe-bosh-session');
}
this._conn.nextValidRid(this.rid);
},
/** PrivateFunction: _emptyQueue
* _Private_ function to check if the Request queue is empty.
*
* Returns:
* True, if there are no Requests queued, False otherwise.
*/
_emptyQueue: function () {
return this._requests.length === 0;
},
/** PrivateFunction: _callProtocolErrorHandlers
* _Private_ function to call error handlers registered for HTTP errors.
*
* Parameters:
* (Strophe.Request) req - The request that is changing readyState.
*/
_callProtocolErrorHandlers: function (req) {
var reqStatus = this._getRequestStatus(req),
err_callback;
err_callback = this._conn.protocolErrorHandlers.HTTP[reqStatus];
if (err_callback) {
err_callback.call(this, reqStatus);
}
},
/** PrivateFunction: _hitError
* _Private_ function to handle the error count.
*
* Requests are resent automatically until their error count reaches
* 5. Each time an error is encountered, this function is called to
* increment the count and disconnect if the count is too high.
*
* Parameters:
* (Integer) reqStatus - The request status.
*/
_hitError: function (reqStatus) {
this.errors++;
Strophe.warn("request errored, status: " + reqStatus +
", number of errors: " + this.errors);
if (this.errors > 4) {
this._conn._onDisconnectTimeout();
}
},
/** PrivateFunction: _no_auth_received
*
* Called on stream start/restart when no stream:features
* has been received and sends a blank poll request.
*/
_no_auth_received: function (_callback) {
if (_callback) {
_callback = _callback.bind(this._conn);
} else {
_callback = this._conn._connect_cb.bind(this._conn);
}
var body = this._buildBody();
this._requests.push(
new Strophe.Request(body.tree(),
this._onRequestStateChange.bind(
this, _callback.bind(this._conn)),
body.tree().getAttribute("rid")));
this._throttledRequestHandler();
},
/** PrivateFunction: _onDisconnectTimeout
* _Private_ timeout handler for handling non-graceful disconnection.
*
* Cancels all remaining Requests and clears the queue.
*/
_onDisconnectTimeout: function () {
this._abortAllRequests();
},
/** PrivateFunction: _abortAllRequests
* _Private_ helper function that makes sure all pending requests are aborted.
*/
_abortAllRequests: function _abortAllRequests() {
var req;
while (this._requests.length > 0) {
req = this._requests.pop();
req.abort = true;
req.xhr.abort();
// jslint complains, but this is fine. setting to empty func
// is necessary for IE6
req.xhr.onreadystatechange = function () {}; // jshint ignore:line
}
},
/** PrivateFunction: _onIdle
* _Private_ handler called by Strophe.Connection._onIdle
*
* Sends all queued Requests or polls with empty Request if there are none.
*/
_onIdle: function () {
var data = this._conn._data;
// if no requests are in progress, poll
if (this._conn.authenticated && this._requests.length === 0 &&
data.length === 0 && !this._conn.disconnecting) {
Strophe.info("no requests during idle cycle, sending " +
"blank request");
data.push(null);
}
if (this._conn.paused) {
return;
}
if (this._requests.length < 2 && data.length > 0) {
var body = this._buildBody();
for (var i = 0; i < data.length; i++) {
if (data[i] !== null) {
if (data[i] === "restart") {
body.attrs({
to: this._conn.domain,
"xml:lang": "en",
"xmpp:restart": "true",
"xmlns:xmpp": Strophe.NS.BOSH
});
} else {
body.cnode(data[i]).up();
}
}
}
delete this._conn._data;
this._conn._data = [];
this._requests.push(
new Strophe.Request(body.tree(),
this._onRequestStateChange.bind(
this, this._conn._dataRecv.bind(this._conn)),
body.tree().getAttribute("rid")));
this._throttledRequestHandler();
}
if (this._requests.length > 0) {
var time_elapsed = this._requests[0].age();
if (this._requests[0].dead !== null) {
if (this._requests[0].timeDead() >
Math.floor(Strophe.SECONDARY_TIMEOUT * this.wait)) {
this._throttledRequestHandler();
}
}
if (time_elapsed > Math.floor(Strophe.TIMEOUT * this.wait)) {
Strophe.warn("Request " +
this._requests[0].id +
" timed out, over " + Math.floor(Strophe.TIMEOUT * this.wait) +
" seconds since last activity");
this._throttledRequestHandler();
}
}
},
/** PrivateFunction: _getRequestStatus
*
* Returns the HTTP status code from a Strophe.Request
*
* Parameters:
* (Strophe.Request) req - The Strophe.Request instance.
* (Integer) def - The default value that should be returned if no
* status value was found.
*/
_getRequestStatus: function (req, def) {
var reqStatus;
if (req.xhr.readyState === 4) {
try {
reqStatus = req.xhr.status;
} catch (e) {
// ignore errors from undefined status attribute. Works
// around a browser bug
Strophe.error(
"Caught an error while retrieving a request's status, " +
"reqStatus: " + reqStatus);
}
}
if (typeof(reqStatus) === "undefined") {
reqStatus = typeof def === 'number' ? def : 0;
}
return reqStatus;
},
/** PrivateFunction: _onRequestStateChange
* _Private_ handler for Strophe.Request state changes.
*
* This function is called when the XMLHttpRequest readyState changes.
* It contains a lot of error handling logic for the many ways that
* requests can fail, and calls the request callback when requests
* succeed.
*
* Parameters:
* (Function) func - The handler for the request.
* (Strophe.Request) req - The request that is changing readyState.
*/
_onRequestStateChange: function (func, req) {
Strophe.debug("request id "+req.id+"."+req.sends+
" state changed to "+req.xhr.readyState);
if (req.abort) {
req.abort = false;
return;
}
if (req.xhr.readyState !== 4) {
// The request is not yet complete
return;
}
var reqStatus = this._getRequestStatus(req);
if (this.disconnecting && reqStatus >= 400) {
this._hitError(reqStatus);
this._callProtocolErrorHandlers(req);
return;
}
var valid_request = reqStatus > 0 && reqStatus < 500;
var too_many_retries = req.sends > this._conn.maxRetries;
if (valid_request || too_many_retries) {
// remove from internal queue
this._removeRequest(req);
Strophe.debug("request id "+req.id+" should now be removed");
}
if (reqStatus === 200) {
// request succeeded
var reqIs0 = (this._requests[0] === req);
var reqIs1 = (this._requests[1] === req);
// if request 1 finished, or request 0 finished and request
// 1 is over Strophe.SECONDARY_TIMEOUT seconds old, we need to
// restart the other - both will be in the first spot, as the
// completed request has been removed from the queue already
if (reqIs1 ||
(reqIs0 && this._requests.length > 0 &&
this._requests[0].age() > Math.floor(Strophe.SECONDARY_TIMEOUT * this.wait))) {
this._restartRequest(0);
}
this._conn.nextValidRid(Number(req.rid) + 1);
Strophe.debug("request id "+req.id+"."+req.sends+" got 200");
func(req); // call handler
this.errors = 0;
} else if (reqStatus === 0 ||
(reqStatus >= 400 && reqStatus < 600) ||
reqStatus >= 12000) {
// request failed
Strophe.error("request id "+req.id+"."+req.sends+" error "+reqStatus+" happened");
this._hitError(reqStatus);
this._callProtocolErrorHandlers(req);
if (reqStatus >= 400 && reqStatus < 500) {
this._conn._changeConnectStatus(Strophe.Status.DISCONNECTING, null);
this._conn._doDisconnect();
}
} else {
Strophe.error("request id "+req.id+"."+req.sends+" error "+reqStatus+" happened");
}
if (!valid_request && !too_many_retries) {
this._throttledRequestHandler();
} else if (too_many_retries && !this._conn.connected) {
this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, "giving-up");
}
},
/** PrivateFunction: _processRequest
* _Private_ function to process a request in the queue.
*
* This function takes requests off the queue and sends them and
* restarts dead requests.
*
* Parameters:
* (Integer) i - The index of the request in the queue.
*/
_processRequest: function (i) {
var self = this;
var req = this._requests[i];
var reqStatus = this._getRequestStatus(req, -1);
// make sure we limit the number of retries
if (req.sends > this._conn.maxRetries) {
this._conn._onDisconnectTimeout();
return;
}
var time_elapsed = req.age();
var primaryTimeout = (!isNaN(time_elapsed) &&
time_elapsed > Math.floor(Strophe.TIMEOUT * this.wait));
var secondaryTimeout = (req.dead !== null &&
req.timeDead() > Math.floor(Strophe.SECONDARY_TIMEOUT * this.wait));
var requestCompletedWithServerError = (req.xhr.readyState === 4 &&
(reqStatus < 1 || reqStatus >= 500));
if (primaryTimeout || secondaryTimeout ||
requestCompletedWithServerError) {
if (secondaryTimeout) {
Strophe.error("Request " + this._requests[i].id +
" timed out (secondary), restarting");
}
req.abort = true;
req.xhr.abort();
// setting to null fails on IE6, so set to empty function
req.xhr.onreadystatechange = function () {};
this._requests[i] = new Strophe.Request(req.xmlData,
req.origFunc,
req.rid,
req.sends);
req = this._requests[i];
}
if (req.xhr.readyState === 0) {
Strophe.debug("request id "+req.id+"."+req.sends+" posting");
try {
var contentType = this._conn.options.contentType || "text/xml; charset=utf-8";
req.xhr.open("POST", this._conn.service, this._conn.options.sync ? false : true);
if (typeof req.xhr.setRequestHeader !== 'undefined') {
// IE9 doesn't have setRequestHeader
req.xhr.setRequestHeader("Content-Type", contentType);
}
if (this._conn.options.withCredentials) {
req.xhr.withCredentials = true;
}
} catch (e2) {
Strophe.error("XHR open failed: " + e2.toString());
if (!this._conn.connected) {
this._conn._changeConnectStatus(
Strophe.Status.CONNFAIL, "bad-service");
}
this._conn.disconnect();
return;
}
// Fires the XHR request -- may be invoked immediately
// or on a gradually expanding retry window for reconnects
var sendFunc = function () {
req.date = new Date();
if (self._conn.options.customHeaders){
var headers = self._conn.options.customHeaders;
for (var header in headers) {
if (headers.hasOwnProperty(header)) {
req.xhr.setRequestHeader(header, headers[header]);
}
}
}
req.xhr.send(req.data);
};
// Implement progressive backoff for reconnects --
// First retry (send === 1) should also be instantaneous
if (req.sends > 1) {
// Using a cube of the retry number creates a nicely
// expanding retry window
var backoff = Math.min(Math.floor(Strophe.TIMEOUT * this.wait),
Math.pow(req.sends, 3)) * 1000;
setTimeout(function() {
// XXX: setTimeout should be called only with function expressions (23974bc1)
sendFunc();
}, backoff);
} else {
sendFunc();
}
req.sends++;
if (this._conn.xmlOutput !== Strophe.Connection.prototype.xmlOutput) {
if (req.xmlData.nodeName === this.strip && req.xmlData.childNodes.length) {
this._conn.xmlOutput(req.xmlData.childNodes[0]);
} else {
this._conn.xmlOutput(req.xmlData);
}
}
if (this._conn.rawOutput !== Strophe.Connection.prototype.rawOutput) {
this._conn.rawOutput(req.data);
}
} else {
Strophe.debug("_processRequest: " +
(i === 0 ? "first" : "second") +
" request has readyState of " +
req.xhr.readyState);
}
},
/** PrivateFunction: _removeRequest
* _Private_ function to remove a request from the queue.
*
* Parameters:
* (Strophe.Request) req - The request to remove.
*/
_removeRequest: function (req) {
Strophe.debug("removing request");
var i;
for (i = this._requests.length - 1; i >= 0; i--) {
if (req === this._requests[i]) {
this._requests.splice(i, 1);
}
}
// IE6 fails on setting to null, so set to empty function
req.xhr.onreadystatechange = function () {};
this._throttledRequestHandler();
},
/** PrivateFunction: _restartRequest
* _Private_ function to restart a request that is presumed dead.
*
* Parameters:
* (Integer) i - The index of the request in the queue.
*/
_restartRequest: function (i) {
var req = this._requests[i];
if (req.dead === null) {
req.dead = new Date();
}
this._processRequest(i);
},
/** PrivateFunction: _reqToData
* _Private_ function to get a stanza out of a request.
*
* Tries to extract a stanza out of a Request Object.
* When this fails the current connection will be disconnected.
*
* Parameters:
* (Object) req - The Request.
*
* Returns:
* The stanza that was passed.
*/
_reqToData: function (req) {
try {
return req.getResponse();
} catch (e) {
if (e !== "parsererror") { throw e; }
this._conn.disconnect("strophe-parsererror");
}
},
/** PrivateFunction: _sendTerminate
* _Private_ function to send initial disconnect sequence.
*
* This is the first step in a graceful disconnect. It sends
* the BOSH server a terminate body and includes an unavailable
* presence if authentication has completed.
*/
_sendTerminate: function (pres) {
Strophe.info("_sendTerminate was called");
var body = this._buildBody().attrs({type: "terminate"});
if (pres) {
body.cnode(pres.tree());
}
var req = new Strophe.Request(
body.tree(),
this._onRequestStateChange.bind(
this, this._conn._dataRecv.bind(this._conn)),
body.tree().getAttribute("rid")
);
this._requests.push(req);
this._throttledRequestHandler();
},
/** PrivateFunction: _send
* _Private_ part of the Connection.send function for BOSH
*
* Just triggers the RequestHandler to send the messages that are in the queue
*/
_send: function () {
clearTimeout(this._conn._idleTimeout);
this._throttledRequestHandler();
// XXX: setTimeout should be called only with function expressions (23974bc1)
this._conn._idleTimeout = setTimeout(function() {
this._onIdle();
}.bind(this._conn), 100);
},
/** PrivateFunction: _sendRestart
*
* Send an xmpp:restart stanza.
*/
_sendRestart: function () {
this._throttledRequestHandler();
clearTimeout(this._conn._idleTimeout);
},
/** PrivateFunction: _throttledRequestHandler
* _Private_ function to throttle requests to the connection window.
*
* This function makes sure we don't send requests so fast that the
* request ids overflow the connection window in the case that one
* request died.
*/
_throttledRequestHandler: function () {
if (!this._requests) {
Strophe.debug("_throttledRequestHandler called with " +
"undefined requests");
} else {
Strophe.debug("_throttledRequestHandler called with " +
this._requests.length + " requests");
}
if (!this._requests || this._requests.length === 0) {
return;
}
if (this._requests.length > 0) {
this._processRequest(0);
}
if (this._requests.length > 1 &&
Math.abs(this._requests[0].rid -
this._requests[1].rid) < this.window) {
this._processRequest(1);
}
}
};
return Strophe;
}));
/*
This program is distributed under the terms of the MIT license.
Please see the LICENSE file for details.
Copyright 2006-2008, OGG, LLC
*/
/* jshint undef: true, unused: true:, noarg: true, latedef: true */
/* global define, window, clearTimeout, WebSocket, DOMParser, Strophe, $build */
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define('strophe-websocket',['strophe-core'], function (core) {
return factory(
core.Strophe,
core.$build
);
});
} else {
// Browser globals
return factory(Strophe, $build);
}
}(this, function (Strophe, $build) {
/** Class: Strophe.WebSocket
* _Private_ helper class that handles WebSocket Connections
*
* The Strophe.WebSocket class is used internally by Strophe.Connection
* to encapsulate WebSocket sessions. It is not meant to be used from user's code.
*/
/** File: websocket.js
* A JavaScript library to enable XMPP over Websocket in Strophejs.
*
* This file implements XMPP over WebSockets for Strophejs.
* If a Connection is established with a Websocket url (ws://...)
* Strophe will use WebSockets.
* For more information on XMPP-over-WebSocket see RFC 7395:
* http://tools.ietf.org/html/rfc7395
*
* WebSocket support implemented by Andreas Guth (andreas.guth@rwth-aachen.de)
*/
/** PrivateConstructor: Strophe.Websocket
* Create and initialize a Strophe.WebSocket object.
* Currently only sets the connection Object.
*
* Parameters:
* (Strophe.Connection) connection - The Strophe.Connection that will use WebSockets.
*
* Returns:
* A new Strophe.WebSocket object.
*/
Strophe.Websocket = function(connection) {
this._conn = connection;
this.strip = "wrapper";
var service = connection.service;
if (service.indexOf("ws:") !== 0 && service.indexOf("wss:") !== 0) {
// If the service is not an absolute URL, assume it is a path and put the absolute
// URL together from options, current URL and the path.
var new_service = "";
if (connection.options.protocol === "ws" && window.location.protocol !== "https:") {
new_service += "ws";
} else {
new_service += "wss";
}
new_service += "://" + window.location.host;
if (service.indexOf("/") !== 0) {
new_service += window.location.pathname + service;
} else {
new_service += service;
}
connection.service = new_service;
}
};
Strophe.Websocket.prototype = {
/** PrivateFunction: _buildStream
* _Private_ helper function to generate the <stream> start tag for WebSockets
*
* Returns:
* A Strophe.Builder with a <stream> element.
*/
_buildStream: function () {
return $build("open", {
"xmlns": Strophe.NS.FRAMING,
"to": this._conn.domain,
"version": '1.0'
});
},
/** PrivateFunction: _check_streamerror
* _Private_ checks a message for stream:error
*
* Parameters:
* (Strophe.Request) bodyWrap - The received stanza.
* connectstatus - The ConnectStatus that will be set on error.
* Returns:
* true if there was a streamerror, false otherwise.
*/
_check_streamerror: function (bodyWrap, connectstatus) {
var errors;
if (bodyWrap.getElementsByTagNameNS) {
errors = bodyWrap.getElementsByTagNameNS(Strophe.NS.STREAM, "error");
} else {
errors = bodyWrap.getElementsByTagName("stream:error");
}
if (errors.length === 0) {
return false;
}
var error = errors[0];
var condition = "";
var text = "";
var ns = "urn:ietf:params:xml:ns:xmpp-streams";
for (var i = 0; i < error.childNodes.length; i++) {
var e = error.childNodes[i];
if (e.getAttribute("xmlns") !== ns) {
break;
} if (e.nodeName === "text") {
text = e.textContent;
} else {
condition = e.nodeName;
}
}
var errorString = "WebSocket stream error: ";
if (condition) {
errorString += condition;
} else {
errorString += "unknown";
}
if (text) {
errorString += " - " + text;
}
Strophe.error(errorString);
// close the connection on stream_error
this._conn._changeConnectStatus(connectstatus, condition);
this._conn._doDisconnect();
return true;
},
/** PrivateFunction: _reset
* Reset the connection.
*
* This function is called by the reset function of the Strophe Connection.
* Is not needed by WebSockets.
*/
_reset: function () {
return;
},
/** PrivateFunction: _connect
* _Private_ function called by Strophe.Connection.connect
*
* Creates a WebSocket for a connection and assigns Callbacks to it.
* Does nothing if there already is a WebSocket.
*/
_connect: function () {
// Ensure that there is no open WebSocket from a previous Connection.
this._closeSocket();
// Create the new WobSocket
this.socket = new WebSocket(this._conn.service, "xmpp");
this.socket.onopen = this._onOpen.bind(this);
this.socket.onerror = this._onError.bind(this);
this.socket.onclose = this._onClose.bind(this);
this.socket.onmessage = this._connect_cb_wrapper.bind(this);
},
/** PrivateFunction: _connect_cb
* _Private_ function called by Strophe.Connection._connect_cb
*
* checks for stream:error
*
* Parameters:
* (Strophe.Request) bodyWrap - The received stanza.
*/
_connect_cb: function(bodyWrap) {
var error = this._check_streamerror(bodyWrap, Strophe.Status.CONNFAIL);
if (error) {
return Strophe.Status.CONNFAIL;
}
},
/** PrivateFunction: _handleStreamStart
* _Private_ function that checks the opening <open /> tag for errors.
*
* Disconnects if there is an error and returns false, true otherwise.
*
* Parameters:
* (Node) message - Stanza containing the <open /> tag.
*/
_handleStreamStart: function(message) {
var error = false;
// Check for errors in the <open /> tag
var ns = message.getAttribute("xmlns");
if (typeof ns !== "string") {
error = "Missing xmlns in <open />";
} else if (ns !== Strophe.NS.FRAMING) {
error = "Wrong xmlns in <open />: " + ns;
}
var ver = message.getAttribute("version");
if (typeof ver !== "string") {
error = "Missing version in <open />";
} else if (ver !== "1.0") {
error = "Wrong version in <open />: " + ver;
}
if (error) {
this._conn._changeConnectStatus(Strophe.Status.CONNFAIL, error);
this._conn._doDisconnect();
return false;
}
return true;
},
/** PrivateFunction: _connect_cb_wrapper
* _Private_ function that handles the first connection messages.
*
* On receiving an opening stream tag this callback replaces itself with the real
* message handler. On receiving a stream error the connection is terminated.
*/
_connect_cb_wrapper: function(message) {
if (message.data.indexOf("<open ") === 0 || message.data.indexOf("<?xml") === 0) {
// Strip the XML Declaration, if there is one
var data = message.data.replace(/^(<\?.*?\?>\s*)*/, "");
if (data === '') return;
var streamStart = new DOMParser().parseFromString(data, "text/xml").documentElement;
this._conn.xmlInput(streamStart);
this._conn.rawInput(message.data);
//_handleStreamSteart will check for XML errors and disconnect on error
if (this._handleStreamStart(streamStart)) {
//_connect_cb will check for stream:error and disconnect on error
this._connect_cb(streamStart);
}
} else if (message.data.indexOf("<close ") === 0) { // <close xmlns="urn:ietf:params:xml:ns:xmpp-framing />
this._conn.rawInput(message.data);
this._conn.xmlInput(message);
var see_uri = message.getAttribute("see-other-uri");
if (see_uri) {
this._conn._changeConnectStatus(
Strophe.Status.REDIRECT,
"Received see-other-uri, resetting connection"
);
this._conn.reset();
this._conn.service = see_uri;
this._connect();
} else {
this._conn._changeConnectStatus(
Strophe.Status.CONNFAIL,
"Received closing stream"
);
this._conn._doDisconnect();
}
} else {
var string = this._streamWrap(message.data);
var elem = new DOMParser().parseFromString(string, "text/xml").documentElement;
this.socket.onmessage = this._onMessage.bind(this);
this._conn._connect_cb(elem, null, message.data);
}
},
/** PrivateFunction: _disconnect
* _Private_ function called by Strophe.Connection.disconnect
*
* Disconnects and sends a last stanza if one is given
*
* Parameters:
* (Request) pres - This stanza will be sent before disconnecting.
*/
_disconnect: function (pres) {
if (this.socket && this.socket.readyState !== WebSocket.CLOSED) {
if (pres) {
this._conn.send(pres);
}
var close = $build("close", { "xmlns": Strophe.NS.FRAMING });
this._conn.xmlOutput(close);
var closeString = Strophe.serialize(close);
this._conn.rawOutput(closeString);
try {
this.socket.send(closeString);
} catch (e) {
Strophe.info("Couldn't send <close /> tag.");
}
}
this._conn._doDisconnect();
},
/** PrivateFunction: _doDisconnect
* _Private_ function to disconnect.
*
* Just closes the Socket for WebSockets
*/
_doDisconnect: function () {
Strophe.info("WebSockets _doDisconnect was called");
this._closeSocket();
},
/** PrivateFunction _streamWrap
* _Private_ helper function to wrap a stanza in a <stream> tag.
* This is used so Strophe can process stanzas from WebSockets like BOSH
*/
_streamWrap: function (stanza) {
return "<wrapper>" + stanza + '</wrapper>';
},
/** PrivateFunction: _closeSocket
* _Private_ function to close the WebSocket.
*
* Closes the socket if it is still open and deletes it
*/
_closeSocket: function () {
if (this.socket) { try {
this.socket.close();
} catch (e) {} }
this.socket = null;
},
/** PrivateFunction: _emptyQueue
* _Private_ function to check if the message queue is empty.
*
* Returns:
* True, because WebSocket messages are send immediately after queueing.
*/
_emptyQueue: function () {
return true;
},
/** PrivateFunction: _onClose
* _Private_ function to handle websockets closing.
*
* Nothing to do here for WebSockets
*/
_onClose: function(e) {
if(this._conn.connected && !this._conn.disconnecting) {
Strophe.error("Websocket closed unexpectedly");
this._conn._doDisconnect();
} else if (e && e.code === 1006 && !this._conn.connected && this.socket) {
// in case the onError callback was not called (Safari 10 does not
// call onerror when the initial connection fails) we need to
// dispatch a CONNFAIL status update to be consistent with the
// behavior on other browsers.
Strophe.error("Websocket closed unexcectedly");
this._conn._changeConnectStatus(
Strophe.Status.CONNFAIL,
"The WebSocket connection could not be established or was disconnected."
);
this._conn._doDisconnect();
} else {
Strophe.info("Websocket closed");
}
},
/** PrivateFunction: _no_auth_received
*
* Called on stream start/restart when no stream:features
* has been received.
*/
_no_auth_received: function (_callback) {
Strophe.error("Server did not send any auth methods");
this._conn._changeConnectStatus(
Strophe.Status.CONNFAIL,
"Server did not send any auth methods"
);
if (_callback) {
_callback = _callback.bind(this._conn);
_callback();
}
this._conn._doDisconnect();
},
/** PrivateFunction: _onDisconnectTimeout
* _Private_ timeout handler for handling non-graceful disconnection.
*
* This does nothing for WebSockets
*/
_onDisconnectTimeout: function () {},
/** PrivateFunction: _abortAllRequests
* _Private_ helper function that makes sure all pending requests are aborted.
*/
_abortAllRequests: function () {},
/** PrivateFunction: _onError
* _Private_ function to handle websockets errors.
*
* Parameters:
* (Object) error - The websocket error.
*/
_onError: function(error) {
Strophe.error("Websocket error " + error);
this._conn._changeConnectStatus(
Strophe.Status.CONNFAIL,
"The WebSocket connection could not be established or was disconnected."
);
this._disconnect();
},
/** PrivateFunction: _onIdle
* _Private_ function called by Strophe.Connection._onIdle
*
* sends all queued stanzas
*/
_onIdle: function () {
var data = this._conn._data;
if (data.length > 0 && !this._conn.paused) {
for (var i = 0; i < data.length; i++) {
if (data[i] !== null) {
var stanza, rawStanza;
if (data[i] === "restart") {
stanza = this._buildStream().tree();
} else {
stanza = data[i];
}
rawStanza = Strophe.serialize(stanza);
this._conn.xmlOutput(stanza);
this._conn.rawOutput(rawStanza);
this.socket.send(rawStanza);
}
}
this._conn._data = [];
}
},
/** PrivateFunction: _onMessage
* _Private_ function to handle websockets messages.
*
* This function parses each of the messages as if they are full documents.
* [TODO : We may actually want to use a SAX Push parser].
*
* Since all XMPP traffic starts with
* <stream:stream version='1.0'
* xml:lang='en'
* xmlns='jabber:client'
* xmlns:stream='http://etherx.jabber.org/streams'
* id='3697395463'
* from='SERVER'>
*
* The first stanza will always fail to be parsed.
*
* Additionally, the seconds stanza will always be <stream:features> with
* the stream NS defined in the previous stanza, so we need to 'force'
* the inclusion of the NS in this stanza.
*
* Parameters:
* (string) message - The websocket message.
*/
_onMessage: function(message) {
var elem, data;
// check for closing stream
var close = '<close xmlns="urn:ietf:params:xml:ns:xmpp-framing" />';
if (message.data === close) {
this._conn.rawInput(close);
this._conn.xmlInput(message);
if (!this._conn.disconnecting) {
this._conn._doDisconnect();
}
return;
} else if (message.data.search("<open ") === 0) {
// This handles stream restarts
elem = new DOMParser().parseFromString(message.data, "text/xml").documentElement;
if (!this._handleStreamStart(elem)) {
return;
}
} else {
data = this._streamWrap(message.data);
elem = new DOMParser().parseFromString(data, "text/xml").documentElement;
}
if (this._check_streamerror(elem, Strophe.Status.ERROR)) {
return;
}
//handle unavailable presence stanza before disconnecting
if (this._conn.disconnecting &&
elem.firstChild.nodeName === "presence" &&
elem.firstChild.getAttribute("type") === "unavailable") {
this._conn.xmlInput(elem);
this._conn.rawInput(Strophe.serialize(elem));
// if we are already disconnecting we will ignore the unavailable stanza and
// wait for the </stream:stream> tag before we close the connection
return;
}
this._conn._dataRecv(elem, message.data);
},
/** PrivateFunction: _onOpen
* _Private_ function to handle websockets connection setup.
*
* The opening stream tag is sent here.
*/
_onOpen: function() {
Strophe.info("Websocket open");
var start = this._buildStream();
this._conn.xmlOutput(start.tree());
var startString = Strophe.serialize(start);
this._conn.rawOutput(startString);
this.socket.send(startString);
},
/** PrivateFunction: _reqToData
* _Private_ function to get a stanza out of a request.
*
* WebSockets don't use requests, so the passed argument is just returned.
*
* Parameters:
* (Object) stanza - The stanza.
*
* Returns:
* The stanza that was passed.
*/
_reqToData: function (stanza) {
return stanza;
},
/** PrivateFunction: _send
* _Private_ part of the Connection.send function for WebSocket
*
* Just flushes the messages that are in the queue
*/
_send: function () {
this._conn.flush();
},
/** PrivateFunction: _sendRestart
*
* Send an xmpp:restart stanza.
*/
_sendRestart: function () {
clearTimeout(this._conn._idleTimeout);
this._conn._onIdle.bind(this._conn)();
}
};
return Strophe;
}));
(function(root){
if(typeof define === 'function' && define.amd){
define('strophe',[
"strophe-core",
"strophe-bosh",
"strophe-websocket"
], function (wrapper) {
return wrapper;
});
}
})(this);
require(["strophe-polyfill"]);
/* jshint ignore:start */
//The modules for your project will be inlined above
//this snippet. Ask almond to synchronously require the
//module value for 'main' here and return it as the
//value to use for the public API for the built file.
return require('strophe');
}));
/* jshint ignore:end */
|
module.exports = function (grunt) {
var nodeExec = require.resolve('.bin/babel-node' + (process.platform === 'win32' ? '.cmd' : ''));
grunt.initConfig({
mocha_istanbul: {
target: {
src: 'test/*.test.js',
options: {
//coverageFolder: 'lcov',
coverage: true,
noColors: true,
dryRun: false,
//root: './test',
//root: './tasks',
//print: 'detail',
check: {
lines: 1
},
require: ['test/*1.js'],
excludes: ['test/excluded*.js', '**/other.js'],
mochaOptions: ['--bail', '--debug-brk'],
reporter: 'spec',
reportFormats: ['html','lcovonly']
}
},
babel: {
src: 'test/*.es6.js',
options: {
nodeExec: nodeExec,
reportFormats: ['html'],
istanbulOptions: ['--verbose'],
root: 'es6',
mochaOptions: ['--compilers', 'js:babel-register']
}
},
isparta: {
src: 'test/*.es5.js',
options: {
nodeExec: nodeExec,
reportFormats: ['html'],
istanbulOptions: ['--verbose'],
root: 'es6',
scriptPath: require.resolve('isparta/lib/cli')
}
}
}
});
grunt.event.on('coverage', function (content, done) {
console.log(content.slice(0, 15) + '...');
done();
});
require('./tasks')(grunt);
grunt.registerTask('default', ['mocha_istanbul']);
};
|
loadIonicon('<svg width="1em" height="1em" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M32 136v144h357.7l-84.4 86.2 33.2 33.8L480 256 338.5 112l-33.2 33.8 84.4 86.2H79.2v-96H32z"/></svg>','md-return-right'); |
/*!
* jQuery Cycle Plugin (with Transition Definitions)
* Examples and documentation at: http://jquery.malsup.com/cycle/
* Copyright (c) 2007-2010 M. Alsup
* Version: 2.9998 (27-OCT-2011)
* Dual licensed under the MIT and GPL licenses.
* http://jquery.malsup.com/license.html
* Requires: jQuery v1.3.2 or later
*/
;(function($, undefined) {
var ver = '2.9998';
// if $.support is not defined (pre jQuery 1.3) add what I need
if ($.support == undefined) {
$.support = {
opacity: !($.browser.msie)
};
}
function debug(s) {
$.fn.cycle.debug && log(s);
}
function log() {
window.console && console.log && console.log('[cycle] ' + Array.prototype.join.call(arguments,' '));
}
$.expr[':'].paused = function(el) {
return el.cyclePause;
}
// the options arg can be...
// a number - indicates an immediate transition should occur to the given slide index
// a string - 'pause', 'resume', 'toggle', 'next', 'prev', 'stop', 'destroy' or the name of a transition effect (ie, 'fade', 'zoom', etc)
// an object - properties to control the slideshow
//
// the arg2 arg can be...
// the name of an fx (only used in conjunction with a numeric value for 'options')
// the value true (only used in first arg == 'resume') and indicates
// that the resume should occur immediately (not wait for next timeout)
$.fn.cycle = function(options, arg2) {
var o = { s: this.selector, c: this.context };
// in 1.3+ we can fix mistakes with the ready state
if (this.length === 0 && options != 'stop') {
if (!$.isReady && o.s) {
log('DOM not ready, queuing slideshow');
$(function() {
$(o.s,o.c).cycle(options,arg2);
});
return this;
}
// is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)'));
return this;
}
// iterate the matched nodeset
return this.each(function() {
var opts = handleArguments(this, options, arg2);
if (opts === false)
return;
opts.updateActivePagerLink = opts.updateActivePagerLink || $.fn.cycle.updateActivePagerLink;
// stop existing slideshow for this container (if there is one)
if (this.cycleTimeout)
clearTimeout(this.cycleTimeout);
this.cycleTimeout = this.cyclePause = 0;
var $cont = $(this);
var $slides = opts.slideExpr ? $(opts.slideExpr, this) : $cont.children();
var els = $slides.get();
var opts2 = buildOptions($cont, $slides, els, opts, o);
if (opts2 === false)
return;
if (els.length < 2) {
log('terminating; too few slides: ' + els.length);
return;
}
var startTime = opts2.continuous ? 10 : getTimeout(els[opts2.currSlide], els[opts2.nextSlide], opts2, !opts2.backwards);
// if it's an auto slideshow, kick it off
if (startTime) {
startTime += (opts2.delay || 0);
if (startTime < 10)
startTime = 10;
debug('first timeout: ' + startTime);
this.cycleTimeout = setTimeout(function(){go(els,opts2,0,!opts.backwards)}, startTime);
}
});
};
function triggerPause(cont, byHover, onPager) {
var opts = $(cont).data('cycle.opts');
var paused = !!cont.cyclePause;
if (paused && opts.paused)
opts.paused(cont, opts, byHover, onPager);
else if (!paused && opts.resumed)
opts.resumed(cont, opts, byHover, onPager);
}
// process the args that were passed to the plugin fn
function handleArguments(cont, options, arg2) {
if (cont.cycleStop == undefined)
cont.cycleStop = 0;
if (options === undefined || options === null)
options = {};
if (options.constructor == String) {
switch(options) {
case 'destroy':
case 'stop':
var opts = $(cont).data('cycle.opts');
if (!opts)
return false;
cont.cycleStop++; // callbacks look for change
if (cont.cycleTimeout)
clearTimeout(cont.cycleTimeout);
cont.cycleTimeout = 0;
opts.elements && $(opts.elements).stop();
$(cont).removeData('cycle.opts');
if (options == 'destroy')
destroy(opts);
return false;
case 'toggle':
cont.cyclePause = (cont.cyclePause === 1) ? 0 : 1;
checkInstantResume(cont.cyclePause, arg2, cont);
triggerPause(cont);
return false;
case 'pause':
cont.cyclePause = 1;
triggerPause(cont);
return false;
case 'resume':
cont.cyclePause = 0;
checkInstantResume(false, arg2, cont);
triggerPause(cont);
return false;
case 'prev':
case 'next':
var opts = $(cont).data('cycle.opts');
if (!opts) {
log('options not found, "prev/next" ignored');
return false;
}
$.fn.cycle[options](opts);
return false;
default:
options = { fx: options };
};
return options;
}
else if (options.constructor == Number) {
// go to the requested slide
var num = options;
options = $(cont).data('cycle.opts');
if (!options) {
log('options not found, can not advance slide');
return false;
}
if (num < 0 || num >= options.elements.length) {
log('invalid slide index: ' + num);
return false;
}
options.nextSlide = num;
if (cont.cycleTimeout) {
clearTimeout(cont.cycleTimeout);
cont.cycleTimeout = 0;
}
if (typeof arg2 == 'string')
options.oneTimeFx = arg2;
go(options.elements, options, 1, num >= options.currSlide);
return false;
}
return options;
function checkInstantResume(isPaused, arg2, cont) {
if (!isPaused && arg2 === true) { // resume now!
var options = $(cont).data('cycle.opts');
if (!options) {
log('options not found, can not resume');
return false;
}
if (cont.cycleTimeout) {
clearTimeout(cont.cycleTimeout);
cont.cycleTimeout = 0;
}
go(options.elements, options, 1, !options.backwards);
}
}
};
function removeFilter(el, opts) {
if (!$.support.opacity && opts.cleartype && el.style.filter) {
try { el.style.removeAttribute('filter'); }
catch(smother) {} // handle old opera versions
}
};
// unbind event handlers
function destroy(opts) {
if (opts.next)
$(opts.next).unbind(opts.prevNextEvent);
if (opts.prev)
$(opts.prev).unbind(opts.prevNextEvent);
if (opts.pager || opts.pagerAnchorBuilder)
$.each(opts.pagerAnchors || [], function() {
this.unbind().remove();
});
opts.pagerAnchors = null;
if (opts.destroy) // callback
opts.destroy(opts);
};
// one-time initialization
function buildOptions($cont, $slides, els, options, o) {
var startingSlideSpecified;
// support metadata plugin (v1.0 and v2.0)
var opts = $.extend({}, $.fn.cycle.defaults, options || {}, $.metadata ? $cont.metadata() : $.meta ? $cont.data() : {});
var meta = $.isFunction($cont.data) ? $cont.data(opts.metaAttr) : null;
if (meta)
opts = $.extend(opts, meta);
if (opts.autostop)
opts.countdown = opts.autostopCount || els.length;
var cont = $cont[0];
$cont.data('cycle.opts', opts);
opts.$cont = $cont;
opts.stopCount = cont.cycleStop;
opts.elements = els;
opts.before = opts.before ? [opts.before] : [];
opts.after = opts.after ? [opts.after] : [];
// push some after callbacks
if (!$.support.opacity && opts.cleartype)
opts.after.push(function() { removeFilter(this, opts); });
if (opts.continuous)
opts.after.push(function() { go(els,opts,0,!opts.backwards); });
saveOriginalOpts(opts);
// clearType corrections
if (!$.support.opacity && opts.cleartype && !opts.cleartypeNoBg)
clearTypeFix($slides);
// container requires non-static position so that slides can be position within
if ($cont.css('position') == 'static')
$cont.css('position', 'relative');
if (opts.width)
$cont.width(opts.width);
if (opts.height && opts.height != 'auto')
$cont.height(opts.height);
if (opts.startingSlide != undefined) {
opts.startingSlide = parseInt(opts.startingSlide,10);
if (opts.startingSlide >= els.length || opts.startSlide < 0)
opts.startingSlide = 0; // catch bogus input
else
startingSlideSpecified = true;
}
else if (opts.backwards)
opts.startingSlide = els.length - 1;
else
opts.startingSlide = 0;
// if random, mix up the slide array
if (opts.random) {
opts.randomMap = [];
for (var i = 0; i < els.length; i++)
opts.randomMap.push(i);
opts.randomMap.sort(function(a,b) {return Math.random() - 0.5;});
if (startingSlideSpecified) {
// try to find the specified starting slide and if found set start slide index in the map accordingly
for ( var cnt = 0; cnt < els.length; cnt++ ) {
if ( opts.startingSlide == opts.randomMap[cnt] ) {
opts.randomIndex = cnt;
}
}
}
else {
opts.randomIndex = 1;
opts.startingSlide = opts.randomMap[1];
}
}
else if (opts.startingSlide >= els.length)
opts.startingSlide = 0; // catch bogus input
opts.currSlide = opts.startingSlide || 0;
var first = opts.startingSlide;
// set position and zIndex on all the slides
$slides.css({position: 'absolute', top:0, left:0}).hide().each(function(i) {
var z;
if (opts.backwards)
z = first ? i <= first ? els.length + (i-first) : first-i : els.length-i;
else
z = first ? i >= first ? els.length - (i-first) : first-i : els.length-i;
$(this).css('z-index', z)
});
// make sure first slide is visible
$(els[first]).css('opacity',1).show(); // opacity bit needed to handle restart use case
removeFilter(els[first], opts);
// stretch slides
if (opts.fit) {
if (!opts.aspect) {
if (opts.width)
$slides.width(opts.width);
if (opts.height && opts.height != 'auto')
$slides.height(opts.height);
} else {
$slides.each(function(){
var $slide = $(this);
var ratio = (opts.aspect === true) ? $slide.width()/$slide.height() : opts.aspect;
if( opts.width && $slide.width() != opts.width ) {
$slide.width( opts.width );
$slide.height( opts.width / ratio );
}
if( opts.height && $slide.height() < opts.height ) {
$slide.height( opts.height );
$slide.width( opts.height * ratio );
}
});
}
}
if (opts.center && ((!opts.fit) || opts.aspect)) {
$slides.each(function(){
var $slide = $(this);
$slide.css({
"margin-left": opts.width ?
((opts.width - $slide.width()) / 2) + "px" :
0,
"margin-top": opts.height ?
((opts.height - $slide.height()) / 2) + "px" :
0
});
});
}
if (opts.center && !opts.fit && !opts.slideResize) {
$slides.each(function(){
var $slide = $(this);
$slide.css({
"margin-left": opts.width ? ((opts.width - $slide.width()) / 2) + "px" : 0,
"margin-top": opts.height ? ((opts.height - $slide.height()) / 2) + "px" : 0
});
});
}
// stretch container
var reshape = opts.containerResize && !$cont.innerHeight();
if (reshape) { // do this only if container has no size http://tinyurl.com/da2oa9
var maxw = 0, maxh = 0;
for(var j=0; j < els.length; j++) {
var $e = $(els[j]), e = $e[0], w = $e.outerWidth(), h = $e.outerHeight();
if (!w) w = e.offsetWidth || e.width || $e.attr('width');
if (!h) h = e.offsetHeight || e.height || $e.attr('height');
maxw = w > maxw ? w : maxw;
maxh = h > maxh ? h : maxh;
}
if (maxw > 0 && maxh > 0)
$cont.css({width:maxw+'px',height:maxh+'px'});
}
var pauseFlag = false; // https://github.com/malsup/cycle/issues/44
if (opts.pause)
$cont.hover(
function(){
pauseFlag = true;
this.cyclePause++;
triggerPause(cont, true);
},
function(){
pauseFlag && this.cyclePause--;
triggerPause(cont, true);
}
);
if (supportMultiTransitions(opts) === false)
return false;
// apparently a lot of people use image slideshows without height/width attributes on the images.
// Cycle 2.50+ requires the sizing info for every slide; this block tries to deal with that.
var requeue = false;
options.requeueAttempts = options.requeueAttempts || 0;
$slides.each(function() {
// try to get height/width of each slide
var $el = $(this);
this.cycleH = (opts.fit && opts.height) ? opts.height : ($el.height() || this.offsetHeight || this.height || $el.attr('height') || 0);
this.cycleW = (opts.fit && opts.width) ? opts.width : ($el.width() || this.offsetWidth || this.width || $el.attr('width') || 0);
if ( $el.is('img') ) {
// sigh.. sniffing, hacking, shrugging... this crappy hack tries to account for what browsers do when
// an image is being downloaded and the markup did not include sizing info (height/width attributes);
// there seems to be some "default" sizes used in this situation
var loadingIE = ($.browser.msie && this.cycleW == 28 && this.cycleH == 30 && !this.complete);
var loadingFF = ($.browser.mozilla && this.cycleW == 34 && this.cycleH == 19 && !this.complete);
var loadingOp = ($.browser.opera && ((this.cycleW == 42 && this.cycleH == 19) || (this.cycleW == 37 && this.cycleH == 17)) && !this.complete);
var loadingOther = (this.cycleH == 0 && this.cycleW == 0 && !this.complete);
// don't requeue for images that are still loading but have a valid size
if (loadingIE || loadingFF || loadingOp || loadingOther) {
if (o.s && opts.requeueOnImageNotLoaded && ++options.requeueAttempts < 100) { // track retry count so we don't loop forever
log(options.requeueAttempts,' - img slide not loaded, requeuing slideshow: ', this.src, this.cycleW, this.cycleH);
setTimeout(function() {$(o.s,o.c).cycle(options)}, opts.requeueTimeout);
requeue = true;
return false; // break each loop
}
else {
log('could not determine size of image: '+this.src, this.cycleW, this.cycleH);
}
}
}
return true;
});
if (requeue)
return false;
opts.cssBefore = opts.cssBefore || {};
opts.cssAfter = opts.cssAfter || {};
opts.cssFirst = opts.cssFirst || {};
opts.animIn = opts.animIn || {};
opts.animOut = opts.animOut || {};
$slides.not(':eq('+first+')').css(opts.cssBefore);
$($slides[first]).css(opts.cssFirst);
if (opts.timeout) {
opts.timeout = parseInt(opts.timeout,10);
// ensure that timeout and speed settings are sane
if (opts.speed.constructor == String)
opts.speed = $.fx.speeds[opts.speed] || parseInt(opts.speed,10);
if (!opts.sync)
opts.speed = opts.speed / 2;
var buffer = opts.fx == 'none' ? 0 : opts.fx == 'shuffle' ? 500 : 250;
while((opts.timeout - opts.speed) < buffer) // sanitize timeout
opts.timeout += opts.speed;
}
if (opts.easing)
opts.easeIn = opts.easeOut = opts.easing;
if (!opts.speedIn)
opts.speedIn = opts.speed;
if (!opts.speedOut)
opts.speedOut = opts.speed;
opts.slideCount = els.length;
opts.currSlide = opts.lastSlide = first;
if (opts.random) {
if (++opts.randomIndex == els.length)
opts.randomIndex = 0;
opts.nextSlide = opts.randomMap[opts.randomIndex];
}
else if (opts.backwards)
opts.nextSlide = opts.startingSlide == 0 ? (els.length-1) : opts.startingSlide-1;
else
opts.nextSlide = opts.startingSlide >= (els.length-1) ? 0 : opts.startingSlide+1;
// run transition init fn
if (!opts.multiFx) {
var init = $.fn.cycle.transitions[opts.fx];
if ($.isFunction(init))
init($cont, $slides, opts);
else if (opts.fx != 'custom' && !opts.multiFx) {
log('unknown transition: ' + opts.fx,'; slideshow terminating');
return false;
}
}
// fire artificial events
var e0 = $slides[first];
if (!opts.skipInitializationCallbacks) {
if (opts.before.length)
opts.before[0].apply(e0, [e0, e0, opts, true]);
if (opts.after.length)
opts.after[0].apply(e0, [e0, e0, opts, true]);
}
if (opts.next)
$(opts.next).bind(opts.prevNextEvent,function(){return advance(opts,1)});
if (opts.prev)
$(opts.prev).bind(opts.prevNextEvent,function(){return advance(opts,0)});
if (opts.pager || opts.pagerAnchorBuilder)
buildPager(els,opts);
exposeAddSlide(opts, els);
return opts;
};
// save off original opts so we can restore after clearing state
function saveOriginalOpts(opts) {
opts.original = { before: [], after: [] };
opts.original.cssBefore = $.extend({}, opts.cssBefore);
opts.original.cssAfter = $.extend({}, opts.cssAfter);
opts.original.animIn = $.extend({}, opts.animIn);
opts.original.animOut = $.extend({}, opts.animOut);
$.each(opts.before, function() { opts.original.before.push(this); });
$.each(opts.after, function() { opts.original.after.push(this); });
};
function supportMultiTransitions(opts) {
var i, tx, txs = $.fn.cycle.transitions;
// look for multiple effects
if (opts.fx.indexOf(',') > 0) {
opts.multiFx = true;
opts.fxs = opts.fx.replace(/\s*/g,'').split(',');
// discard any bogus effect names
for (i=0; i < opts.fxs.length; i++) {
var fx = opts.fxs[i];
tx = txs[fx];
if (!tx || !txs.hasOwnProperty(fx) || !$.isFunction(tx)) {
log('discarding unknown transition: ',fx);
opts.fxs.splice(i,1);
i--;
}
}
// if we have an empty list then we threw everything away!
if (!opts.fxs.length) {
log('No valid transitions named; slideshow terminating.');
return false;
}
}
else if (opts.fx == 'all') { // auto-gen the list of transitions
opts.multiFx = true;
opts.fxs = [];
for (p in txs) {
tx = txs[p];
if (txs.hasOwnProperty(p) && $.isFunction(tx))
opts.fxs.push(p);
}
}
if (opts.multiFx && opts.randomizeEffects) {
// munge the fxs array to make effect selection random
var r1 = Math.floor(Math.random() * 20) + 30;
for (i = 0; i < r1; i++) {
var r2 = Math.floor(Math.random() * opts.fxs.length);
opts.fxs.push(opts.fxs.splice(r2,1)[0]);
}
debug('randomized fx sequence: ',opts.fxs);
}
return true;
};
// provide a mechanism for adding slides after the slideshow has started
function exposeAddSlide(opts, els) {
opts.addSlide = function(newSlide, prepend) {
var $s = $(newSlide), s = $s[0];
if (!opts.autostopCount)
opts.countdown++;
els[prepend?'unshift':'push'](s);
if (opts.els)
opts.els[prepend?'unshift':'push'](s); // shuffle needs this
opts.slideCount = els.length;
// add the slide to the random map and resort
if (opts.random) {
opts.randomMap.push(opts.slideCount-1);
opts.randomMap.sort(function(a,b) {return Math.random() - 0.5;});
}
$s.css('position','absolute');
$s[prepend?'prependTo':'appendTo'](opts.$cont);
if (prepend) {
opts.currSlide++;
opts.nextSlide++;
}
if (!$.support.opacity && opts.cleartype && !opts.cleartypeNoBg)
clearTypeFix($s);
if (opts.fit && opts.width)
$s.width(opts.width);
if (opts.fit && opts.height && opts.height != 'auto')
$s.height(opts.height);
s.cycleH = (opts.fit && opts.height) ? opts.height : $s.height();
s.cycleW = (opts.fit && opts.width) ? opts.width : $s.width();
$s.css(opts.cssBefore);
if (opts.pager || opts.pagerAnchorBuilder)
$.fn.cycle.createPagerAnchor(els.length-1, s, $(opts.pager), els, opts);
if ($.isFunction(opts.onAddSlide))
opts.onAddSlide($s);
else
$s.hide(); // default behavior
};
}
// reset internal state; we do this on every pass in order to support multiple effects
$.fn.cycle.resetState = function(opts, fx) {
fx = fx || opts.fx;
opts.before = []; opts.after = [];
opts.cssBefore = $.extend({}, opts.original.cssBefore);
opts.cssAfter = $.extend({}, opts.original.cssAfter);
opts.animIn = $.extend({}, opts.original.animIn);
opts.animOut = $.extend({}, opts.original.animOut);
opts.fxFn = null;
$.each(opts.original.before, function() { opts.before.push(this); });
$.each(opts.original.after, function() { opts.after.push(this); });
// re-init
var init = $.fn.cycle.transitions[fx];
if ($.isFunction(init))
init(opts.$cont, $(opts.elements), opts);
};
// this is the main engine fn, it handles the timeouts, callbacks and slide index mgmt
function go(els, opts, manual, fwd) {
// opts.busy is true if we're in the middle of an animation
if (manual && opts.busy && opts.manualTrump) {
// let manual transitions requests trump active ones
debug('manualTrump in go(), stopping active transition');
$(els).stop(true,true);
opts.busy = 0;
}
// don't begin another timeout-based transition if there is one active
if (opts.busy) {
debug('transition active, ignoring new tx request');
return;
}
var p = opts.$cont[0], curr = els[opts.currSlide], next = els[opts.nextSlide];
// stop cycling if we have an outstanding stop request
if (p.cycleStop != opts.stopCount || p.cycleTimeout === 0 && !manual)
return;
// check to see if we should stop cycling based on autostop options
if (!manual && !p.cyclePause && !opts.bounce &&
((opts.autostop && (--opts.countdown <= 0)) ||
(opts.nowrap && !opts.random && opts.nextSlide < opts.currSlide))) {
if (opts.end)
opts.end(opts);
return;
}
// if slideshow is paused, only transition on a manual trigger
var changed = false;
if ((manual || !p.cyclePause) && (opts.nextSlide != opts.currSlide)) {
changed = true;
var fx = opts.fx;
// keep trying to get the slide size if we don't have it yet
curr.cycleH = curr.cycleH || $(curr).height();
curr.cycleW = curr.cycleW || $(curr).width();
next.cycleH = next.cycleH || $(next).height();
next.cycleW = next.cycleW || $(next).width();
// support multiple transition types
if (opts.multiFx) {
if (fwd && (opts.lastFx == undefined || ++opts.lastFx >= opts.fxs.length))
opts.lastFx = 0;
else if (!fwd && (opts.lastFx == undefined || --opts.lastFx < 0))
opts.lastFx = opts.fxs.length - 1;
fx = opts.fxs[opts.lastFx];
}
// one-time fx overrides apply to: $('div').cycle(3,'zoom');
if (opts.oneTimeFx) {
fx = opts.oneTimeFx;
opts.oneTimeFx = null;
}
$.fn.cycle.resetState(opts, fx);
// run the before callbacks
if (opts.before.length)
$.each(opts.before, function(i,o) {
if (p.cycleStop != opts.stopCount) return;
o.apply(next, [curr, next, opts, fwd]);
});
// stage the after callacks
var after = function() {
opts.busy = 0;
$.each(opts.after, function(i,o) {
if (p.cycleStop != opts.stopCount) return;
o.apply(next, [curr, next, opts, fwd]);
});
if (!p.cycleStop) {
// queue next transition
queueNext();
}
};
debug('tx firing('+fx+'); currSlide: ' + opts.currSlide + '; nextSlide: ' + opts.nextSlide);
// get ready to perform the transition
opts.busy = 1;
if (opts.fxFn) // fx function provided?
opts.fxFn(curr, next, opts, after, fwd, manual && opts.fastOnEvent);
else if ($.isFunction($.fn.cycle[opts.fx])) // fx plugin ?
$.fn.cycle[opts.fx](curr, next, opts, after, fwd, manual && opts.fastOnEvent);
else
$.fn.cycle.custom(curr, next, opts, after, fwd, manual && opts.fastOnEvent);
}
else {
queueNext();
}
if (changed || opts.nextSlide == opts.currSlide) {
// calculate the next slide
opts.lastSlide = opts.currSlide;
if (opts.random) {
opts.currSlide = opts.nextSlide;
if (++opts.randomIndex == els.length) {
opts.randomIndex = 0;
opts.randomMap.sort(function(a,b) {return Math.random() - 0.5;});
}
opts.nextSlide = opts.randomMap[opts.randomIndex];
if (opts.nextSlide == opts.currSlide)
opts.nextSlide = (opts.currSlide == opts.slideCount - 1) ? 0 : opts.currSlide + 1;
}
else if (opts.backwards) {
var roll = (opts.nextSlide - 1) < 0;
if (roll && opts.bounce) {
opts.backwards = !opts.backwards;
opts.nextSlide = 1;
opts.currSlide = 0;
}
else {
opts.nextSlide = roll ? (els.length-1) : opts.nextSlide-1;
opts.currSlide = roll ? 0 : opts.nextSlide+1;
}
}
else { // sequence
var roll = (opts.nextSlide + 1) == els.length;
if (roll && opts.bounce) {
opts.backwards = !opts.backwards;
opts.nextSlide = els.length-2;
opts.currSlide = els.length-1;
}
else {
opts.nextSlide = roll ? 0 : opts.nextSlide+1;
opts.currSlide = roll ? els.length-1 : opts.nextSlide-1;
}
}
}
if (changed && opts.pager)
opts.updateActivePagerLink(opts.pager, opts.currSlide, opts.activePagerClass);
function queueNext() {
// stage the next transition
var ms = 0, timeout = opts.timeout;
if (opts.timeout && !opts.continuous) {
ms = getTimeout(els[opts.currSlide], els[opts.nextSlide], opts, fwd);
if (opts.fx == 'shuffle')
ms -= opts.speedOut;
}
else if (opts.continuous && p.cyclePause) // continuous shows work off an after callback, not this timer logic
ms = 10;
if (ms > 0)
p.cycleTimeout = setTimeout(function(){ go(els, opts, 0, !opts.backwards) }, ms);
}
};
// invoked after transition
$.fn.cycle.updateActivePagerLink = function(pager, currSlide, clsName) {
$(pager).each(function() {
$(this).children().removeClass(clsName).eq(currSlide).addClass(clsName);
});
};
// calculate timeout value for current transition
function getTimeout(curr, next, opts, fwd) {
if (opts.timeoutFn) {
// call user provided calc fn
var t = opts.timeoutFn.call(curr,curr,next,opts,fwd);
while (opts.fx != 'none' && (t - opts.speed) < 250) // sanitize timeout
t += opts.speed;
debug('calculated timeout: ' + t + '; speed: ' + opts.speed);
if (t !== false)
return t;
}
return opts.timeout;
};
// expose next/prev function, caller must pass in state
$.fn.cycle.next = function(opts) { advance(opts,1); };
$.fn.cycle.prev = function(opts) { advance(opts,0);};
// advance slide forward or back
function advance(opts, moveForward) {
var val = moveForward ? 1 : -1;
var els = opts.elements;
var p = opts.$cont[0], timeout = p.cycleTimeout;
if (timeout) {
clearTimeout(timeout);
p.cycleTimeout = 0;
}
if (opts.random && val < 0) {
// move back to the previously display slide
opts.randomIndex--;
if (--opts.randomIndex == -2)
opts.randomIndex = els.length-2;
else if (opts.randomIndex == -1)
opts.randomIndex = els.length-1;
opts.nextSlide = opts.randomMap[opts.randomIndex];
}
else if (opts.random) {
opts.nextSlide = opts.randomMap[opts.randomIndex];
}
else {
opts.nextSlide = opts.currSlide + val;
if (opts.nextSlide < 0) {
if (opts.nowrap) return false;
opts.nextSlide = els.length - 1;
}
else if (opts.nextSlide >= els.length) {
if (opts.nowrap) return false;
opts.nextSlide = 0;
}
}
var cb = opts.onPrevNextEvent || opts.prevNextClick; // prevNextClick is deprecated
if ($.isFunction(cb))
cb(val > 0, opts.nextSlide, els[opts.nextSlide]);
go(els, opts, 1, moveForward);
return false;
};
function buildPager(els, opts) {
var $p = $(opts.pager);
$.each(els, function(i,o) {
$.fn.cycle.createPagerAnchor(i,o,$p,els,opts);
});
opts.updateActivePagerLink(opts.pager, opts.startingSlide, opts.activePagerClass);
};
$.fn.cycle.createPagerAnchor = function(i, el, $p, els, opts) {
var a;
if ($.isFunction(opts.pagerAnchorBuilder)) {
a = opts.pagerAnchorBuilder(i,el);
debug('pagerAnchorBuilder('+i+', el) returned: ' + a);
}
else
a = '<a href="#">'+(i+1)+'</a>';
if (!a)
return;
var $a = $(a);
// don't reparent if anchor is in the dom
if ($a.parents('body').length === 0) {
var arr = [];
if ($p.length > 1) {
$p.each(function() {
var $clone = $a.clone(true);
$(this).append($clone);
arr.push($clone[0]);
});
$a = $(arr);
}
else {
$a.appendTo($p);
}
}
opts.pagerAnchors = opts.pagerAnchors || [];
opts.pagerAnchors.push($a);
var pagerFn = function(e) {
e.preventDefault();
opts.nextSlide = i;
var p = opts.$cont[0], timeout = p.cycleTimeout;
if (timeout) {
clearTimeout(timeout);
p.cycleTimeout = 0;
}
var cb = opts.onPagerEvent || opts.pagerClick; // pagerClick is deprecated
if ($.isFunction(cb))
cb(opts.nextSlide, els[opts.nextSlide]);
go(els,opts,1,opts.currSlide < i); // trigger the trans
// return false; // <== allow bubble
}
if ( /mouseenter|mouseover/i.test(opts.pagerEvent) ) {
$a.hover(pagerFn, function(){/* no-op */} );
}
else {
$a.bind(opts.pagerEvent, pagerFn);
}
if ( ! /^click/.test(opts.pagerEvent) && !opts.allowPagerClickBubble)
$a.bind('click.cycle', function(){return false;}); // suppress click
var cont = opts.$cont[0];
var pauseFlag = false; // https://github.com/malsup/cycle/issues/44
if (opts.pauseOnPagerHover) {
$a.hover(
function() {
pauseFlag = true;
cont.cyclePause++;
triggerPause(cont,true,true);
}, function() {
pauseFlag && cont.cyclePause--;
triggerPause(cont,true,true);
}
);
}
};
// helper fn to calculate the number of slides between the current and the next
$.fn.cycle.hopsFromLast = function(opts, fwd) {
var hops, l = opts.lastSlide, c = opts.currSlide;
if (fwd)
hops = c > l ? c - l : opts.slideCount - l;
else
hops = c < l ? l - c : l + opts.slideCount - c;
return hops;
};
// fix clearType problems in ie6 by setting an explicit bg color
// (otherwise text slides look horrible during a fade transition)
function clearTypeFix($slides) {
debug('applying clearType background-color hack');
function hex(s) {
s = parseInt(s,10).toString(16);
return s.length < 2 ? '0'+s : s;
};
function getBg(e) {
for ( ; e && e.nodeName.toLowerCase() != 'html'; e = e.parentNode) {
var v = $.css(e,'background-color');
if (v && v.indexOf('rgb') >= 0 ) {
var rgb = v.match(/\d+/g);
return '#'+ hex(rgb[0]) + hex(rgb[1]) + hex(rgb[2]);
}
if (v && v != 'transparent')
return v;
}
return '#ffffff';
};
$slides.each(function() { $(this).css('background-color', getBg(this)); });
};
// reset common props before the next transition
$.fn.cycle.commonReset = function(curr,next,opts,w,h,rev) {
$(opts.elements).not(curr).hide();
if (typeof opts.cssBefore.opacity == 'undefined')
opts.cssBefore.opacity = 1;
opts.cssBefore.display = 'block';
if (opts.slideResize && w !== false && next.cycleW > 0)
opts.cssBefore.width = next.cycleW;
if (opts.slideResize && h !== false && next.cycleH > 0)
opts.cssBefore.height = next.cycleH;
opts.cssAfter = opts.cssAfter || {};
opts.cssAfter.display = 'none';
$(curr).css('zIndex',opts.slideCount + (rev === true ? 1 : 0));
$(next).css('zIndex',opts.slideCount + (rev === true ? 0 : 1));
};
// the actual fn for effecting a transition
$.fn.cycle.custom = function(curr, next, opts, cb, fwd, speedOverride) {
var $l = $(curr), $n = $(next);
var speedIn = opts.speedIn, speedOut = opts.speedOut, easeIn = opts.easeIn, easeOut = opts.easeOut;
$n.css(opts.cssBefore);
if (speedOverride) {
if (typeof speedOverride == 'number')
speedIn = speedOut = speedOverride;
else
speedIn = speedOut = 1;
easeIn = easeOut = null;
}
var fn = function() {
$n.animate(opts.animIn, speedIn, easeIn, function() {
cb();
});
};
$l.animate(opts.animOut, speedOut, easeOut, function() {
$l.css(opts.cssAfter);
if (!opts.sync)
fn();
});
if (opts.sync) fn();
};
// transition definitions - only fade is defined here, transition pack defines the rest
$.fn.cycle.transitions = {
fade: function($cont, $slides, opts) {
$slides.not(':eq('+opts.currSlide+')').css('opacity',0);
opts.before.push(function(curr,next,opts) {
$.fn.cycle.commonReset(curr,next,opts);
opts.cssBefore.opacity = 0;
});
opts.animIn = { opacity: 1 };
opts.animOut = { opacity: 0 };
opts.cssBefore = { top: 0, left: 0 };
}
};
$.fn.cycle.ver = function() { return ver; };
// override these globally if you like (they are all optional)
$.fn.cycle.defaults = {
activePagerClass: 'activeSlide', // class name used for the active pager link
after: null, // transition callback (scope set to element that was shown): function(currSlideElement, nextSlideElement, options, forwardFlag)
allowPagerClickBubble: false, // allows or prevents click event on pager anchors from bubbling
animIn: null, // properties that define how the slide animates in
animOut: null, // properties that define how the slide animates out
aspect: false, // preserve aspect ratio during fit resizing, cropping if necessary (must be used with fit option)
autostop: 0, // true to end slideshow after X transitions (where X == slide count)
autostopCount: 0, // number of transitions (optionally used with autostop to define X)
backwards: false, // true to start slideshow at last slide and move backwards through the stack
before: null, // transition callback (scope set to element to be shown): function(currSlideElement, nextSlideElement, options, forwardFlag)
center: null, // set to true to have cycle add top/left margin to each slide (use with width and height options)
cleartype: !$.support.opacity, // true if clearType corrections should be applied (for IE)
cleartypeNoBg: false, // set to true to disable extra cleartype fixing (leave false to force background color setting on slides)
containerResize: 1, // resize container to fit largest slide
continuous: 0, // true to start next transition immediately after current one completes
cssAfter: null, // properties that defined the state of the slide after transitioning out
cssBefore: null, // properties that define the initial state of the slide before transitioning in
delay: 0, // additional delay (in ms) for first transition (hint: can be negative)
easeIn: null, // easing for "in" transition
easeOut: null, // easing for "out" transition
easing: null, // easing method for both in and out transitions
end: null, // callback invoked when the slideshow terminates (use with autostop or nowrap options): function(options)
fastOnEvent: 0, // force fast transitions when triggered manually (via pager or prev/next); value == time in ms
fit: 0, // force slides to fit container
fx: 'fade', // name of transition effect (or comma separated names, ex: 'fade,scrollUp,shuffle')
fxFn: null, // function used to control the transition: function(currSlideElement, nextSlideElement, options, afterCalback, forwardFlag)
height: 'auto', // container height (if the 'fit' option is true, the slides will be set to this height as well)
manualTrump: true, // causes manual transition to stop an active transition instead of being ignored
metaAttr: 'cycle',// data- attribute that holds the option data for the slideshow
next: null, // element, jQuery object, or jQuery selector string for the element to use as event trigger for next slide
nowrap: 0, // true to prevent slideshow from wrapping
onPagerEvent: null, // callback fn for pager events: function(zeroBasedSlideIndex, slideElement)
onPrevNextEvent: null,// callback fn for prev/next events: function(isNext, zeroBasedSlideIndex, slideElement)
pager: null, // element, jQuery object, or jQuery selector string for the element to use as pager container
pagerAnchorBuilder: null, // callback fn for building anchor links: function(index, DOMelement)
pagerEvent: 'click.cycle', // name of event which drives the pager navigation
pause: 0, // true to enable "pause on hover"
pauseOnPagerHover: 0, // true to pause when hovering over pager link
prev: null, // element, jQuery object, or jQuery selector string for the element to use as event trigger for previous slide
prevNextEvent:'click.cycle',// event which drives the manual transition to the previous or next slide
random: 0, // true for random, false for sequence (not applicable to shuffle fx)
randomizeEffects: 1, // valid when multiple effects are used; true to make the effect sequence random
requeueOnImageNotLoaded: true, // requeue the slideshow if any image slides are not yet loaded
requeueTimeout: 250, // ms delay for requeue
rev: 0, // causes animations to transition in reverse (for effects that support it such as scrollHorz/scrollVert/shuffle)
shuffle: null, // coords for shuffle animation, ex: { top:15, left: 200 }
skipInitializationCallbacks: false, // set to true to disable the first before/after callback that occurs prior to any transition
slideExpr: null, // expression for selecting slides (if something other than all children is required)
slideResize: 1, // force slide width/height to fixed size before every transition
speed: 1000, // speed of the transition (any valid fx speed value)
speedIn: null, // speed of the 'in' transition
speedOut: null, // speed of the 'out' transition
startingSlide: 0, // zero-based index of the first slide to be displayed
sync: 1, // true if in/out transitions should occur simultaneously
timeout: 4000, // milliseconds between slide transitions (0 to disable auto advance)
timeoutFn: null, // callback for determining per-slide timeout value: function(currSlideElement, nextSlideElement, options, forwardFlag)
updateActivePagerLink: null, // callback fn invoked to update the active pager link (adds/removes activePagerClass style)
width: null // container width (if the 'fit' option is true, the slides will be set to this width as well)
};
})(jQuery);
/*!
* jQuery Cycle Plugin Transition Definitions
* This script is a plugin for the jQuery Cycle Plugin
* Examples and documentation at: http://malsup.com/jquery/cycle/
* Copyright (c) 2007-2010 M. Alsup
* Version: 2.73
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*/
(function($) {
//
// These functions define slide initialization and properties for the named
// transitions. To save file size feel free to remove any of these that you
// don't need.
//
$.fn.cycle.transitions.none = function($cont, $slides, opts) {
opts.fxFn = function(curr,next,opts,after){
$(next).show();
$(curr).hide();
after();
};
};
// not a cross-fade, fadeout only fades out the top slide
$.fn.cycle.transitions.fadeout = function($cont, $slides, opts) {
$slides.not(':eq('+opts.currSlide+')').css({ display: 'block', 'opacity': 1 });
opts.before.push(function(curr,next,opts,w,h,rev) {
$(curr).css('zIndex',opts.slideCount + (!rev === true ? 1 : 0));
$(next).css('zIndex',opts.slideCount + (!rev === true ? 0 : 1));
});
opts.animIn.opacity = 1;
opts.animOut.opacity = 0;
opts.cssBefore.opacity = 1;
opts.cssBefore.display = 'block';
opts.cssAfter.zIndex = 0;
};
// scrollUp/Down/Left/Right
$.fn.cycle.transitions.scrollUp = function($cont, $slides, opts) {
$cont.css('overflow','hidden');
opts.before.push($.fn.cycle.commonReset);
var h = $cont.height();
opts.cssBefore.top = h;
opts.cssBefore.left = 0;
opts.cssFirst.top = 0;
opts.animIn.top = 0;
opts.animOut.top = -h;
};
$.fn.cycle.transitions.scrollDown = function($cont, $slides, opts) {
$cont.css('overflow','hidden');
opts.before.push($.fn.cycle.commonReset);
var h = $cont.height();
opts.cssFirst.top = 0;
opts.cssBefore.top = -h;
opts.cssBefore.left = 0;
opts.animIn.top = 0;
opts.animOut.top = h;
};
$.fn.cycle.transitions.scrollLeft = function($cont, $slides, opts) {
$cont.css('overflow','hidden');
opts.before.push($.fn.cycle.commonReset);
var w = $cont.width();
opts.cssFirst.left = 0;
opts.cssBefore.left = w;
opts.cssBefore.top = 0;
opts.animIn.left = 0;
opts.animOut.left = 0-w;
};
$.fn.cycle.transitions.scrollRight = function($cont, $slides, opts) {
$cont.css('overflow','hidden');
opts.before.push($.fn.cycle.commonReset);
var w = $cont.width();
opts.cssFirst.left = 0;
opts.cssBefore.left = -w;
opts.cssBefore.top = 0;
opts.animIn.left = 0;
opts.animOut.left = w;
};
$.fn.cycle.transitions.scrollHorz = function($cont, $slides, opts) {
$cont.css('overflow','hidden').width();
opts.before.push(function(curr, next, opts, fwd) {
if (opts.rev)
fwd = !fwd;
$.fn.cycle.commonReset(curr,next,opts);
opts.cssBefore.left = fwd ? (next.cycleW-1) : (1-next.cycleW);
opts.animOut.left = fwd ? -curr.cycleW : curr.cycleW;
});
opts.cssFirst.left = 0;
opts.cssBefore.top = 0;
opts.animIn.left = 0;
opts.animOut.top = 0;
};
$.fn.cycle.transitions.scrollVert = function($cont, $slides, opts) {
$cont.css('overflow','hidden');
opts.before.push(function(curr, next, opts, fwd) {
if (opts.rev)
fwd = !fwd;
$.fn.cycle.commonReset(curr,next,opts);
opts.cssBefore.top = fwd ? (1-next.cycleH) : (next.cycleH-1);
opts.animOut.top = fwd ? curr.cycleH : -curr.cycleH;
});
opts.cssFirst.top = 0;
opts.cssBefore.left = 0;
opts.animIn.top = 0;
opts.animOut.left = 0;
};
// slideX/slideY
$.fn.cycle.transitions.slideX = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$(opts.elements).not(curr).hide();
$.fn.cycle.commonReset(curr,next,opts,false,true);
opts.animIn.width = next.cycleW;
});
opts.cssBefore.left = 0;
opts.cssBefore.top = 0;
opts.cssBefore.width = 0;
opts.animIn.width = 'show';
opts.animOut.width = 0;
};
$.fn.cycle.transitions.slideY = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$(opts.elements).not(curr).hide();
$.fn.cycle.commonReset(curr,next,opts,true,false);
opts.animIn.height = next.cycleH;
});
opts.cssBefore.left = 0;
opts.cssBefore.top = 0;
opts.cssBefore.height = 0;
opts.animIn.height = 'show';
opts.animOut.height = 0;
};
// shuffle
$.fn.cycle.transitions.shuffle = function($cont, $slides, opts) {
var i, w = $cont.css('overflow', 'visible').width();
$slides.css({left: 0, top: 0});
opts.before.push(function(curr,next,opts) {
$.fn.cycle.commonReset(curr,next,opts,true,true,true);
});
// only adjust speed once!
if (!opts.speedAdjusted) {
opts.speed = opts.speed / 2; // shuffle has 2 transitions
opts.speedAdjusted = true;
}
opts.random = 0;
opts.shuffle = opts.shuffle || {left:-w, top:15};
opts.els = [];
for (i=0; i < $slides.length; i++)
opts.els.push($slides[i]);
for (i=0; i < opts.currSlide; i++)
opts.els.push(opts.els.shift());
// custom transition fn (hat tip to Benjamin Sterling for this bit of sweetness!)
opts.fxFn = function(curr, next, opts, cb, fwd) {
if (opts.rev)
fwd = !fwd;
var $el = fwd ? $(curr) : $(next);
$(next).css(opts.cssBefore);
var count = opts.slideCount;
$el.animate(opts.shuffle, opts.speedIn, opts.easeIn, function() {
var hops = $.fn.cycle.hopsFromLast(opts, fwd);
for (var k=0; k < hops; k++)
fwd ? opts.els.push(opts.els.shift()) : opts.els.unshift(opts.els.pop());
if (fwd) {
for (var i=0, len=opts.els.length; i < len; i++)
$(opts.els[i]).css('z-index', len-i+count);
}
else {
var z = $(curr).css('z-index');
$el.css('z-index', parseInt(z,10)+1+count);
}
$el.animate({left:0, top:0}, opts.speedOut, opts.easeOut, function() {
$(fwd ? this : curr).hide();
if (cb) cb();
});
});
};
$.extend(opts.cssBefore, { display: 'block', opacity: 1, top: 0, left: 0 });
};
// turnUp/Down/Left/Right
$.fn.cycle.transitions.turnUp = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts,true,false);
opts.cssBefore.top = next.cycleH;
opts.animIn.height = next.cycleH;
opts.animOut.width = next.cycleW;
});
opts.cssFirst.top = 0;
opts.cssBefore.left = 0;
opts.cssBefore.height = 0;
opts.animIn.top = 0;
opts.animOut.height = 0;
};
$.fn.cycle.transitions.turnDown = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts,true,false);
opts.animIn.height = next.cycleH;
opts.animOut.top = curr.cycleH;
});
opts.cssFirst.top = 0;
opts.cssBefore.left = 0;
opts.cssBefore.top = 0;
opts.cssBefore.height = 0;
opts.animOut.height = 0;
};
$.fn.cycle.transitions.turnLeft = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts,false,true);
opts.cssBefore.left = next.cycleW;
opts.animIn.width = next.cycleW;
});
opts.cssBefore.top = 0;
opts.cssBefore.width = 0;
opts.animIn.left = 0;
opts.animOut.width = 0;
};
$.fn.cycle.transitions.turnRight = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts,false,true);
opts.animIn.width = next.cycleW;
opts.animOut.left = curr.cycleW;
});
$.extend(opts.cssBefore, { top: 0, left: 0, width: 0 });
opts.animIn.left = 0;
opts.animOut.width = 0;
};
// zoom
$.fn.cycle.transitions.zoom = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts,false,false,true);
opts.cssBefore.top = next.cycleH/2;
opts.cssBefore.left = next.cycleW/2;
$.extend(opts.animIn, { top: 0, left: 0, width: next.cycleW, height: next.cycleH });
$.extend(opts.animOut, { width: 0, height: 0, top: curr.cycleH/2, left: curr.cycleW/2 });
});
opts.cssFirst.top = 0;
opts.cssFirst.left = 0;
opts.cssBefore.width = 0;
opts.cssBefore.height = 0;
};
// fadeZoom
$.fn.cycle.transitions.fadeZoom = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts,false,false);
opts.cssBefore.left = next.cycleW/2;
opts.cssBefore.top = next.cycleH/2;
$.extend(opts.animIn, { top: 0, left: 0, width: next.cycleW, height: next.cycleH });
});
opts.cssBefore.width = 0;
opts.cssBefore.height = 0;
opts.animOut.opacity = 0;
};
// blindX
$.fn.cycle.transitions.blindX = function($cont, $slides, opts) {
var w = $cont.css('overflow','hidden').width();
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts);
opts.animIn.width = next.cycleW;
opts.animOut.left = curr.cycleW;
});
opts.cssBefore.left = w;
opts.cssBefore.top = 0;
opts.animIn.left = 0;
opts.animOut.left = w;
};
// blindY
$.fn.cycle.transitions.blindY = function($cont, $slides, opts) {
var h = $cont.css('overflow','hidden').height();
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts);
opts.animIn.height = next.cycleH;
opts.animOut.top = curr.cycleH;
});
opts.cssBefore.top = h;
opts.cssBefore.left = 0;
opts.animIn.top = 0;
opts.animOut.top = h;
};
// blindZ
$.fn.cycle.transitions.blindZ = function($cont, $slides, opts) {
var h = $cont.css('overflow','hidden').height();
var w = $cont.width();
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts);
opts.animIn.height = next.cycleH;
opts.animOut.top = curr.cycleH;
});
opts.cssBefore.top = h;
opts.cssBefore.left = w;
opts.animIn.top = 0;
opts.animIn.left = 0;
opts.animOut.top = h;
opts.animOut.left = w;
};
// growX - grow horizontally from centered 0 width
$.fn.cycle.transitions.growX = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts,false,true);
opts.cssBefore.left = this.cycleW/2;
opts.animIn.left = 0;
opts.animIn.width = this.cycleW;
opts.animOut.left = 0;
});
opts.cssBefore.top = 0;
opts.cssBefore.width = 0;
};
// growY - grow vertically from centered 0 height
$.fn.cycle.transitions.growY = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts,true,false);
opts.cssBefore.top = this.cycleH/2;
opts.animIn.top = 0;
opts.animIn.height = this.cycleH;
opts.animOut.top = 0;
});
opts.cssBefore.height = 0;
opts.cssBefore.left = 0;
};
// curtainX - squeeze in both edges horizontally
$.fn.cycle.transitions.curtainX = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts,false,true,true);
opts.cssBefore.left = next.cycleW/2;
opts.animIn.left = 0;
opts.animIn.width = this.cycleW;
opts.animOut.left = curr.cycleW/2;
opts.animOut.width = 0;
});
opts.cssBefore.top = 0;
opts.cssBefore.width = 0;
};
// curtainY - squeeze in both edges vertically
$.fn.cycle.transitions.curtainY = function($cont, $slides, opts) {
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts,true,false,true);
opts.cssBefore.top = next.cycleH/2;
opts.animIn.top = 0;
opts.animIn.height = next.cycleH;
opts.animOut.top = curr.cycleH/2;
opts.animOut.height = 0;
});
opts.cssBefore.height = 0;
opts.cssBefore.left = 0;
};
// cover - curr slide covered by next slide
$.fn.cycle.transitions.cover = function($cont, $slides, opts) {
var d = opts.direction || 'left';
var w = $cont.css('overflow','hidden').width();
var h = $cont.height();
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts);
if (d == 'right')
opts.cssBefore.left = -w;
else if (d == 'up')
opts.cssBefore.top = h;
else if (d == 'down')
opts.cssBefore.top = -h;
else
opts.cssBefore.left = w;
});
opts.animIn.left = 0;
opts.animIn.top = 0;
opts.cssBefore.top = 0;
opts.cssBefore.left = 0;
};
// uncover - curr slide moves off next slide
$.fn.cycle.transitions.uncover = function($cont, $slides, opts) {
var d = opts.direction || 'left';
var w = $cont.css('overflow','hidden').width();
var h = $cont.height();
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts,true,true,true);
if (d == 'right')
opts.animOut.left = w;
else if (d == 'up')
opts.animOut.top = -h;
else if (d == 'down')
opts.animOut.top = h;
else
opts.animOut.left = -w;
});
opts.animIn.left = 0;
opts.animIn.top = 0;
opts.cssBefore.top = 0;
opts.cssBefore.left = 0;
};
// toss - move top slide and fade away
$.fn.cycle.transitions.toss = function($cont, $slides, opts) {
var w = $cont.css('overflow','visible').width();
var h = $cont.height();
opts.before.push(function(curr, next, opts) {
$.fn.cycle.commonReset(curr,next,opts,true,true,true);
// provide default toss settings if animOut not provided
if (!opts.animOut.left && !opts.animOut.top)
$.extend(opts.animOut, { left: w*2, top: -h/2, opacity: 0 });
else
opts.animOut.opacity = 0;
});
opts.cssBefore.left = 0;
opts.cssBefore.top = 0;
opts.animIn.left = 0;
};
// wipe - clip animation
$.fn.cycle.transitions.wipe = function($cont, $slides, opts) {
var w = $cont.css('overflow','hidden').width();
var h = $cont.height();
opts.cssBefore = opts.cssBefore || {};
var clip;
if (opts.clip) {
if (/l2r/.test(opts.clip))
clip = 'rect(0px 0px '+h+'px 0px)';
else if (/r2l/.test(opts.clip))
clip = 'rect(0px '+w+'px '+h+'px '+w+'px)';
else if (/t2b/.test(opts.clip))
clip = 'rect(0px '+w+'px 0px 0px)';
else if (/b2t/.test(opts.clip))
clip = 'rect('+h+'px '+w+'px '+h+'px 0px)';
else if (/zoom/.test(opts.clip)) {
var top = parseInt(h/2,10);
var left = parseInt(w/2,10);
clip = 'rect('+top+'px '+left+'px '+top+'px '+left+'px)';
}
}
opts.cssBefore.clip = opts.cssBefore.clip || clip || 'rect(0px 0px 0px 0px)';
var d = opts.cssBefore.clip.match(/(\d+)/g);
var t = parseInt(d[0],10), r = parseInt(d[1],10), b = parseInt(d[2],10), l = parseInt(d[3],10);
opts.before.push(function(curr, next, opts) {
if (curr == next) return;
var $curr = $(curr), $next = $(next);
$.fn.cycle.commonReset(curr,next,opts,true,true,false);
opts.cssAfter.display = 'block';
var step = 1, count = parseInt((opts.speedIn / 13),10) - 1;
(function f() {
var tt = t ? t - parseInt(step * (t/count),10) : 0;
var ll = l ? l - parseInt(step * (l/count),10) : 0;
var bb = b < h ? b + parseInt(step * ((h-b)/count || 1),10) : h;
var rr = r < w ? r + parseInt(step * ((w-r)/count || 1),10) : w;
$next.css({ clip: 'rect('+tt+'px '+rr+'px '+bb+'px '+ll+'px)' });
(step++ <= count) ? setTimeout(f, 13) : $curr.css('display', 'none');
})();
});
$.extend(opts.cssBefore, { display: 'block', opacity: 1, top: 0, left: 0 });
opts.animIn = { left: 0 };
opts.animOut = { left: 0 };
};
})(jQuery); |
var resolveKeyword = require('css-tree').keyword;
var walk = require('css-tree').walk;
var generate = require('css-tree').generate;
var createDeclarationIndexer = require('./createDeclarationIndexer');
var processSelector = require('./processSelector');
module.exports = function prepare(ast, options) {
var markDeclaration = createDeclarationIndexer();
walk(ast, {
visit: 'Rule',
enter: function processRule(node) {
node.block.children.each(markDeclaration);
processSelector(node, options.usage);
}
});
walk(ast, {
visit: 'Atrule',
enter: function(node) {
if (node.prelude) {
node.prelude.id = null; // pre-init property to avoid multiple hidden class for generate
node.prelude.id = generate(node.prelude);
}
// compare keyframe selectors by its values
// NOTE: still no clarification about problems with keyframes selector grouping (issue #197)
if (resolveKeyword(node.name).basename === 'keyframes') {
node.block.avoidRulesMerge = true; /* probably we don't need to prevent those merges for @keyframes
TODO: need to be checked */
node.block.children.each(function(rule) {
rule.prelude.children.each(function(simpleselector) {
simpleselector.compareMarker = simpleselector.id;
});
});
}
}
});
return {
declaration: markDeclaration
};
};
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceUsb = (props) => (
<SvgIcon {...props}>
<path d="M15 7v4h1v2h-3V5h2l-3-4-3 4h2v8H8v-2.07c.7-.37 1.2-1.08 1.2-1.93 0-1.21-.99-2.2-2.2-2.2-1.21 0-2.2.99-2.2 2.2 0 .85.5 1.56 1.2 1.93V13c0 1.11.89 2 2 2h3v3.05c-.71.37-1.2 1.1-1.2 1.95 0 1.22.99 2.2 2.2 2.2 1.21 0 2.2-.98 2.2-2.2 0-.85-.49-1.58-1.2-1.95V15h3c1.11 0 2-.89 2-2v-2h1V7h-4z"/>
</SvgIcon>
);
DeviceUsb = pure(DeviceUsb);
DeviceUsb.displayName = 'DeviceUsb';
DeviceUsb.muiName = 'SvgIcon';
export default DeviceUsb;
|
/*!
* jquery-sheetrock v0.2.3
* Quickly connect to, query, and lazy-load data from Google Spreadsheets.
* http://chriszarate.github.io/sheetrock/
* License: MIT
*/
(function(sheetrock) {
'use strict';
/* global define, module */
if(typeof define === 'function' && define.amd) {
define('jquery.sheetrock', ['jquery'], sheetrock);
} else if (typeof module === 'object' && module.exports) {
module.exports = sheetrock;
} else {
sheetrock(window.jQuery);
}
})(function($) {
'use strict';
$.fn.sheetrock = function(options, bootstrappedData) {
// Store reference to `this`.
options.target = this;
// Load and validate options.
options = _validateOptions(options);
// Proceed if options are valid.
if(options) {
// Check for bootstrapped data.
if(_defined(bootstrappedData) && bootstrappedData !== null) {
// Load bootstrapped data.
_loadBootstrappedData(options, bootstrappedData);
} else {
// Initialize request for external data.
_initializeRequest(options);
}
}
// Return `this` to allow jQuery object chaining.
return this;
};
/* Setup */
// Google API endpoints and key formats
var _spreadsheetTypes = {
'new': {
'endpoint': 'https://docs.google.com/spreadsheets/d/%key%/gviz/tq',
'keyFormat': new RegExp('spreadsheets/d/([^/#]+)','i')
},
'legacy': {
'endpoint': 'https://spreadsheets.google.com/tq?key=%key%',
'keyFormat': new RegExp('key=([^&#]+)','i')
}
},
// Placeholder for request status cache
_requestStatusCache = {
loaded: {},
failed: {},
offset: {}
},
// Placeholder for column labels cache
_columnLabelsCache = {},
// Callback function index
_callbackIndex = 0,
/* Task runners */
// Initiate request to Google Spreadsheets API. Use jQuery deferreds to make
// sure requests are processed synchronously.
_initializeRequest = function(options) {
// Chain off of previous promise.
$.fn.sheetrock.promise = $.fn.sheetrock.promise
// Prefetch column labels (if necessary).
.pipe(function() {
return _prefetchColumnLabels(options);
})
// Fetch request.
.pipe(function() {
return _fetchRequest(options);
});
},
// Load bootstrapped data (no request to API).
_loadBootstrappedData = function(options, data) {
// Spin up user-facing indicators.
_beforeRequest(options);
// Process the data as though it were a real response from the API.
_processResponse.call(options, data);
// Wind down user-facing indicators.
_afterRequest.call(options);
},
/* Data fetchers */
// Prefetch column labels (if necessary).
_prefetchColumnLabels = function(options) {
// Options for prefetching column labels
var prefetchOptions = {
sql: 'select * limit 1',
dataHandler: _cacheColumnLabels,
userCallback: $.noop,
target: false
};
// Proceed if column labels are not present (either in the SQL query via
// the '%label%' technique or in the passed options).
if(options.sql.indexOf('%') !== -1 && !_getColumnLabels(options)) {
// Make a special request for just the column labels.
_console('Prefetching column labels.');
return _fetchRequest($.extend({}, options, prefetchOptions));
} else {
// Return a resolved deferred object so that the next request fires
// immediately.
return $.Deferred().resolve();
}
},
// Fetch the requested data using the user's options.
_fetchRequest = function(options) {
// Spin up user-facing indicators.
_beforeRequest(options);
// Specify a custom callback function since Google doesn't use the
// default implementation favored by jQuery.
options.callback = 'sheetrock_callback_' + _callbackIndex;
_callbackIndex = _callbackIndex + 1;
// AJAX request options
var request = {
// Convert user options into AJAX request parameters.
data: _makeParameters(options),
// Use user options object as context (`this`) for data handler.
context: options,
url: options.server,
dataType: 'jsonp',
cache: true,
// Use custom callback function (see above).
jsonp: false,
jsonpCallback: options.callback
};
// If debugging is enabled, log request details to the console.
_console(request, options.debug);
// Send the request.
return $.ajax(request)
// Not sure this is necessary.
.promise()
// Validate the response data.
.done(_processResponse)
// Handle error.
.fail(_error)
// Wind down user-facing indicators.
.always(_afterRequest);
},
// Convert user options into AJAX request parameters.
_makeParameters = function(options) {
// Create new paramters object.
var parameters = {
// Google Spreadsheet identifiers
//key: options.key,
gid: options.gid,
// Conform to Google's nonstandard callback syntax.
tqx: 'responseHandler:' + options.callback
};
// Swap column labels for column letters, if applicable.
if(options.sql) {
parameters.tq = _swapLabels(options.sql, _getColumnLabels(options));
}
return parameters;
},
/* UI and AJAX helpers. */
// Spin up user-facing indicators.
_beforeRequest = function(options) {
// Show loading indicator.
options.loading.show();
// Turn on the `working` flag.
$.fn.sheetrock.working = true;
},
// Wind down user-facing indicators and call user callback function.
_afterRequest = function() {
// Hide the loading indicator.
this.loading.hide();
// Turn off the `working` flag.
$.fn.sheetrock.working = false;
// Call the user's callback function.
this.userCallback(this);
},
// Enumerate any messages embedded in the API response.
_enumerateMessages = function(data, state) {
// Look for the specified property at the root of the response object.
if(_has(data, state)) {
// Look for the kinds of messages we know about.
$.each(data[state], function(i, status) {
if(_has(status, 'detailed_message')) {
/* jshint camelcase: false */
_console(status.detailed_message);
} else if(_has(status, 'message')) {
_console(status.message);
}
});
}
},
/* Data validators */
// Validate API response.
_processResponse = function(data) {
// Enumerate any returned warning messages.
_enumerateMessages(data, 'warnings');
// Enumerate any returned error messages.
_enumerateMessages(data, 'errors');
// Log the API response to the console, if requested.
_console(data, this.debug);
// Make sure the response is populated with actual data.
if(_has(data, 'status', 'table') && _has(data.table, 'cols', 'rows')) {
// Extend the options hash with useful information about the response.
var parsedOptions = _extendOptions.call(this, data);
// Pass the API response to the data handler.
this.dataHandler.call(parsedOptions, data);
} else {
// The response seems empty; call the error handler.
_error.call(this, data);
}
},
// Extend the options hash with useful information about the response.
_extendOptions = function(data) {
// Store reference to the options hash.
var options = this;
// Initialize a hash for parsed options.
options.parsed = {};
// The Google API generates an unrecoverable error when the 'offset' is
// larger than the number of available rows, which is problematic for
// chunked requests. As a workaround, we request one more row than we need
// and stop when we see less rows than we requested.
// Calculate the last returned row.
options.parsed.last =
(options.chunkSize) ? Math.min(data.table.rows.length, options.chunkSize) : data.table.rows.length;
// Remember whether this request has been fully loaded.
_requestStatusCache.loaded[options.requestID] =
!options.chunkSize || options.parsed.last < options.chunkSize;
// Determine if Google has extracted column labels from a header row.
options.parsed.header =
($.map(data.table.cols, _getColumnLabel).length) ? 1 : 0;
// If no column labels are provided or if there are too many or too few
// compared to the returned data, use the returned column labels.
options.parsed.labels =
(options.labels && options.labels.length === data.table.cols.length) ? options.labels : $.map(data.table.cols, _getColumnLabelOrLetter);
// Return extended options.
return options;
},
/* Data parsers */
// Parse data, row by row.
_parseData = function(data) {
// Store reference to the options hash and target.
var options = this,
target = options.target;
// Add row group tags (<thead>, <tbody>), if requested.
$.extend(options, {
thead: (options.rowGroups) ? $('<thead/>').appendTo(target) : target,
tbody: (options.rowGroups) ? $('<tbody/>').appendTo(target) : target
});
// Output a header row, if needed.
if(!options.offset && !options.headersOff) {
if(options.parsed.header || !options.headers) {
options.thead.append(options.rowHandler({
num: 0,
cells: _arrayToObject(options.parsed.labels)
}));
}
}
// Each table cell ('c') can contain two properties: 'p' contains
// formatting and 'v' contains the actual cell value.
// Loop through each table row.
$.each(data.table.rows, function(i, obj) {
// Proceed if the row has cells and the row index is within the targeted
// range. (This avoids displaying too many rows when chunking data.)
if(_has(obj, 'c') && i < options.parsed.last) {
// Get the "real" row index (not counting header rows).
var counter = _stringToNaturalNumber(options.offset + i + 1 + options.parsed.header - options.headers),
// Initialize a row object, which will be passed to the row handler.
rowObject = {
num: counter,
cells: {}
};
// Suppress header row, if requested.
if(counter || !options.headersOff) {
// Loop through each cell in the row.
$.each(obj.c, function(x, cell) {
// Process cell formatting, if requested.
var style = (options.formatting) ? _getFormatting(cell) : false,
// Extract cell value.
value = (cell && _has(cell, 'v') && cell.v) ? cell.v : '';
// Avoid array cell values.
if(value instanceof Array) {
value = (_has(cell, 'f')) ? cell.f : value.join('');
}
// Process cell value with cell handler function.
value = options.cellHandler(value);
// Add the cell to the row object, using the desired column label
// as the key.
rowObject.cells[options.parsed.labels[x]] = (style) ? _wrapTag(value, 'span', style) : value;
});
// Pass the row object to the row handler and append the output to
// the target element.
if(rowObject.num) {
// Append to table body.
options.tbody.append(options.rowHandler(rowObject));
} else {
// Append to table header.
options.thead.append(options.rowHandler(rowObject));
}
}
}
});
},
// Cache column labels (indexed by key_gid) in the plugin scope. This way
// column labels will only be prefetched once.
_cacheColumnLabels = function(data) {
var labels = {};
$.each(data.table.cols, function(i, col) {
labels[col.id] = _getColumnLabelOrLetter(col);
});
_columnLabelsCache[this.key + '_' + this.gid] = labels;
},
// Look for acceptable column labels first in the passed options, then in
// the column label cache. Fallback to `false`, which triggers a prefetch.
_getColumnLabels = function(options) {
if($.isEmptyObject(options.columns)) {
return _columnLabelsCache[options.key + '_' + options.gid] || false;
} else {
return options.columns;
}
},
/* User input validator */
// Validate user-passed options.
_validateOptions = function(options) {
// Extend default options.
options = $.extend({}, $.fn.sheetrock.options, options);
// Get spreadsheet type ("new" or "legacy").
options.type = _getSpreadsheetType(options.url);
// Get spreadsheet key and gid.
options.key = _extractKey(options.url, options.type);
options.gid = _extractGID(options.url);
// Set API endpoint.
options.server = (options.server.length) ? options.server : options.type.endpoint;
options.server = options.server.replace('%key%', options.key);
// Set request ID (key_gid_sql).
if(options.key && options.gid) {
options.requestID = options.key + '_' + options.gid + '_' + options.sql;
}
// Validate chunk size.
options.chunkSize = (options.target.length) ? _stringToNaturalNumber(options.chunkSize) : 0;
// Validate number of header rows.
options.headers = _stringToNaturalNumber(options.headers);
// Make sure `loading` is a jQuery object.
options.loading = _validatejQueryObject(options.loading);
// If requested, reset request status.
if(options.resetStatus && options.requestID) {
_requestStatusCache.loaded[options.requestID] = false;
_requestStatusCache.failed[options.requestID] = false;
_requestStatusCache.offset[options.requestID] = 0;
_console('Resetting request status.');
}
// Retrieve current row offset.
options.offset = _requestStatusCache.offset[options.requestID] || 0;
// If requested, make a request for chunked data.
if(options.chunkSize && options.target && options.requestID) {
// Append a limit and row offest to the query to target the next chunk.
options.sql += ' limit ' + (options.chunkSize + 1);
options.sql += ' offset ' + options.offset;
// Remember the new row offset.
_requestStatusCache.offset[options.requestID] = options.offset + options.chunkSize;
}
// Require `this` or a data handler. Otherwise, the data has nowhere to go.
if(!options.target.length && options.dataHandler === _parseData) {
return _error.call(options, null, 'No element targeted or data handler provided.');
}
// Require a spreadsheet URL.
if(!options.url) {
return _error.call(options, null, 'No spreadsheet URL provided.');
}
// Require a spreadsheet key.
if(!options.key) {
return _error.call(options, null, 'Could not find a key in the provided URL.');
}
// Require a spreadsheet gid.
if(!options.gid) {
return _error.call(options, null, 'Could not find a gid in the provided URL.');
}
// Abandon requests that have previously generated an error.
if(_requestStatusCache.failed[options.requestID]) {
return _error.call(options, null, 'A previous request for this resource failed.');
}
// Abandon requests that have already been loaded.
if(_requestStatusCache.loaded[options.requestID]) {
return _console('No more rows to load!');
}
// Log the validated options to the console, if requested.
_console(options, options.debug);
return options;
},
// General error handler.
_error = function(data, msg) {
// Set error message.
msg = msg || 'Request failed.';
// Remember that this request failed.
if(this && this.requestID) {
_requestStatusCache.failed[this.requestID] = true;
}
// Log the error to the console.
_console(msg);
// Call the user's error handler.
this.errorHandler.call(this, data, msg);
return false;
},
/* Miscellaneous functions */
// Trim a string of leading and trailing spaces.
_trim = function(str) {
return str.toString().replace(/^ +/, '').replace(/ +$/, '');
},
// Parse a string as a natural number (>=0).
_stringToNaturalNumber = function(str) {
return Math.max(0, parseInt(str, 10) || 0);
},
// Return true if an object has all of the passed arguments as properties.
_has = function(obj) {
for(var i = 1; i < arguments.length; i = i + 1) {
if(!_defined(obj[arguments[i]])) {
return false;
}
}
return true;
},
// Return true if all of the passed arguments are defined.
_defined = function() {
for(var i = 0; i < arguments.length; i = i + 1) {
if(typeof arguments[i] === 'undefined') {
return false;
}
}
return true;
},
// Log something to the browser console, if it exists. The argument "show"
// is a Boolean (default = true) that determines whether to proceed.
_console = function(msg, show) {
show = (_defined(show, console)) ? show : true;
if(show && console.log) {
console.log(msg);
}
return false;
},
// Get spreadsheet "type" from Google Spreadsheet URL (default is "new").
_getSpreadsheetType = function(url) {
var returnValue;
$.each(_spreadsheetTypes, function(key, spreadsheetType) {
if(spreadsheetType.keyFormat.test(url)) {
returnValue = spreadsheetType;
return false;
}
});
return returnValue || _spreadsheetTypes.new;
},
// Extract the "key" from a Google Spreadsheet URL.
_extractKey = function(url, spreadsheetType) {
return (spreadsheetType.keyFormat.test(url)) ? url.match(spreadsheetType.keyFormat)[1] : false;
},
// Extract the "gid" from a Google spreadsheet URL.
_extractGID = function(url) {
var gidRegExp = new RegExp('gid=([^/&#]+)','i');
return (gidRegExp.test(url)) ? url.match(gidRegExp)[1] : false;
},
// Extract the label, if present, from a column object, sans white space.
_getColumnLabel = function(col) {
return (_has(col, 'label')) ? col.label.replace(/\s/g, '') : null;
},
// Map function: Return the label or letter of a column object.
_getColumnLabelOrLetter = function(col) {
return _getColumnLabel(col) || col.id;
},
// Swap user-provided column labels (%label%) with column letters.
_swapLabels = function(sql, columns) {
$.each(columns, function(key, val) {
sql = sql.replace(new RegExp('%' + val + '%', 'g'), key);
});
return sql;
},
// Return true if the reference is a valid jQuery object or selector.
_validatejQueryObject = function(ref) {
return (ref && !(ref instanceof $)) ? $(ref) : ref;
},
// Convert an array to a object.
_arrayToObject = function(arr) {
var obj = {};
$.each(arr, function(i, str) { obj[str] = str; });
return obj;
},
// Extract formatting from a Google spreadsheet cell.
_getFormatting = function(cell) {
return (cell && _has(cell, 'p') && _has(cell.p, 'style')) ? cell.p.style : false;
},
// Default row handler: Output a row object as an HTML table row.
_toHTML = function(row) {
// Placeholders
var cell, html = '',
// Use "td" for table body row, "th" for table header rows.
tag = (row.num) ? 'td' : 'th';
// Loop through each cell in the row.
for(cell in row.cells) {
// Make sure `cell` is a real object property.
if(_has(row.cells, cell)) {
// Wrap the cell value in the cell tag.
html += _wrapTag(row.cells[cell], tag, '');
}
}
// Wrap the cells in a table row tag.
return _wrapTag(html, 'tr', '');
},
// Wrap a string in tag. The style argument, if present, is populated into
// an inline CSS style attribute. (Gross!)
_wrapTag = function(str, tag, style) {
var attribute = (style) ? ' style="' + style + '"' : '';
return '<' + tag + attribute + '>' + str + '</' + tag + '>';
};
/* Default options */
$.fn.sheetrock.options = {
// Documentation is available at:
// http://chriszarate.github.io/sheetrock/
url: '', // String -- Google spreadsheet URL
sql: '', // String -- Google Visualization API query
server: '', // String -- Google API endpoint
chunkSize: 0, // Integer -- Number of rows to fetch (0 = all)
columns: {}, // Object -- Hash of column letters and labels
labels: [], // Array -- Override *returned* column labels
rowHandler: _toHTML, // Function
cellHandler: _trim, // Function
dataHandler: _parseData, // Function
errorHandler: $.noop, // Function
userCallback: $.noop, // Function
loading: $(), // jQuery object or selector
headers: 0, // Integer -- Number of header rows
headersOff: false, // Boolean -- Suppress header row output
rowGroups: true, // Boolean -- Output <thead> and <tbody> tags
formatting: false, // Boolean -- Include Google HTML formatting
resetStatus: false, // Boolean -- Reset request status
debug: false // Boolean -- Output raw data to the console
};
// This property is set to `true` when there is an active AJAX request. This
// can be useful for infinite scroll bindings or other monitoring.
$.fn.sheetrock.working = false;
// This property contains a jQuery promise for the most recent request. If
// you chain off of this, be sure to return another jQuery promise so
// Sheetrock can continue to chain off of it.
$.fn.sheetrock.promise = $.Deferred().resolve();
// Version number.
$.fn.sheetrock.version = '0.2.3';
});
|
/**
* Application version
*
* @type String
**/
elFinder.prototype.version = '2.0.2';
|
(function (angular) {
"use strict";
// when $routeProvider.whenAuthenticated() is called, the path is stored in this list
// to be used by authRequired() in the services below
var securedRoutes = [];
angular.module('myApp.security', ['ngRoute', 'firebase.auth', 'myApp.config'])
.config(['$routeProvider', function ($routeProvider) {
// routes which are not in our map are redirected to /home
//$routeProvider.otherwise({redirectTo: '/home'});
}])
/**
* Adds a special `whenAuthenticated` method onto $routeProvider. This special method,
* when called, waits for auth status to be resolved asynchronously, and then fails/redirects
* if the user is not properly authenticated.
*
* The promise either resolves to the authenticated user object and makes it available to
* dependency injection (see AuthCtrl), or rejects the promise if user is not logged in,
* forcing a redirect to the /login page
*/
.config(['$routeProvider', function ($routeProvider) {
// credits for this idea: https://groups.google.com/forum/#!msg/angular/dPr9BpIZID0/MgWVluo_Tg8J
// unfortunately, a decorator cannot be use here because they are not applied until after
// the .config calls resolve, so they can't be used during route configuration, so we have
// to hack it directly onto the $routeProvider object
$routeProvider.whenAuthenticated = function (path, route) {
securedRoutes.push(path); // store all secured routes for use with authRequired() below
route.resolve = route.resolve || {};
route.resolve.user = ['Auth', function (Auth) {
return Auth.$requireAuth();
}];
$routeProvider.when(path, route);
return this;
}
}])
/**
* Apply some route security. Any route's resolve method can reject the promise with
* { authRequired: true } to force a redirect. This method enforces that and also watches
* for changes in auth status which might require us to navigate away from a path
* that we can no longer view.
*/
.run(['$rootScope', '$location', 'Auth', 'loginRedirectPath',
function ($rootScope, $location, Auth, loginRedirectPath) {
// watch for login status changes and redirect if appropriate
Auth.$onAuth(check);
// some of our routes may reject resolve promises with the special {authRequired: true} error
// this redirects to the login page whenever that is encountered
$rootScope.$on("$routeChangeError", function (e, next, prev, err) {
if (err === "AUTH_REQUIRED") {
$location.path(loginRedirectPath);
}
});
function check(user) {
if (!user && authRequired($location.path())) {
console.log('check failed', user, $location.path()); //debug
$location.path(loginRedirectPath);
}
}
function authRequired(path) {
console.log('authRequired?', path, securedRoutes.indexOf(path)); //debug
return securedRoutes.indexOf(path) !== -1;
}
}
]);
})(angular);
|
// Copyright 2011 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 Number formatting symbols.
*
* This file is autogenerated by script:
* http://go/generate_number_constants.py
* using the --for_closure flag.
*
* To reduce the file size (which may cause issues in some JS
* developing environments), this file will only contain locales
* that are frequently used by web applications. This is defined as
* closure_tier1_locales and will change (most likely addition)
* over time. Rest of the data can be found in another file named
* "numberformatsymbolsext.js", which will be generated at the
* same time together with this file.
*
* Before checkin, this file could have been manually edited. This is
* to incorporate changes before we could fix CLDR. All manual
* modification must be documented in this section, and should be
* removed after those changes land to CLDR.
*/
goog.provide('goog.i18n.NumberFormatSymbols');
goog.provide('goog.i18n.NumberFormatSymbols_af');
goog.provide('goog.i18n.NumberFormatSymbols_af_ZA');
goog.provide('goog.i18n.NumberFormatSymbols_am');
goog.provide('goog.i18n.NumberFormatSymbols_am_ET');
goog.provide('goog.i18n.NumberFormatSymbols_ar');
goog.provide('goog.i18n.NumberFormatSymbols_ar_001');
goog.provide('goog.i18n.NumberFormatSymbols_ar_EG');
goog.provide('goog.i18n.NumberFormatSymbols_bg');
goog.provide('goog.i18n.NumberFormatSymbols_bg_BG');
goog.provide('goog.i18n.NumberFormatSymbols_bn');
goog.provide('goog.i18n.NumberFormatSymbols_bn_BD');
goog.provide('goog.i18n.NumberFormatSymbols_ca');
goog.provide('goog.i18n.NumberFormatSymbols_ca_ES');
goog.provide('goog.i18n.NumberFormatSymbols_chr');
goog.provide('goog.i18n.NumberFormatSymbols_chr_US');
goog.provide('goog.i18n.NumberFormatSymbols_cs');
goog.provide('goog.i18n.NumberFormatSymbols_cs_CZ');
goog.provide('goog.i18n.NumberFormatSymbols_cy');
goog.provide('goog.i18n.NumberFormatSymbols_cy_GB');
goog.provide('goog.i18n.NumberFormatSymbols_da');
goog.provide('goog.i18n.NumberFormatSymbols_da_DK');
goog.provide('goog.i18n.NumberFormatSymbols_de');
goog.provide('goog.i18n.NumberFormatSymbols_de_AT');
goog.provide('goog.i18n.NumberFormatSymbols_de_BE');
goog.provide('goog.i18n.NumberFormatSymbols_de_CH');
goog.provide('goog.i18n.NumberFormatSymbols_de_DE');
goog.provide('goog.i18n.NumberFormatSymbols_de_LU');
goog.provide('goog.i18n.NumberFormatSymbols_el');
goog.provide('goog.i18n.NumberFormatSymbols_el_GR');
goog.provide('goog.i18n.NumberFormatSymbols_en');
goog.provide('goog.i18n.NumberFormatSymbols_en_AS');
goog.provide('goog.i18n.NumberFormatSymbols_en_AU');
goog.provide('goog.i18n.NumberFormatSymbols_en_Dsrt');
goog.provide('goog.i18n.NumberFormatSymbols_en_Dsrt_US');
goog.provide('goog.i18n.NumberFormatSymbols_en_GB');
goog.provide('goog.i18n.NumberFormatSymbols_en_GU');
goog.provide('goog.i18n.NumberFormatSymbols_en_IE');
goog.provide('goog.i18n.NumberFormatSymbols_en_IN');
goog.provide('goog.i18n.NumberFormatSymbols_en_MH');
goog.provide('goog.i18n.NumberFormatSymbols_en_MP');
goog.provide('goog.i18n.NumberFormatSymbols_en_SG');
goog.provide('goog.i18n.NumberFormatSymbols_en_UM');
goog.provide('goog.i18n.NumberFormatSymbols_en_US');
goog.provide('goog.i18n.NumberFormatSymbols_en_VI');
goog.provide('goog.i18n.NumberFormatSymbols_en_ZA');
goog.provide('goog.i18n.NumberFormatSymbols_es');
goog.provide('goog.i18n.NumberFormatSymbols_es_419');
goog.provide('goog.i18n.NumberFormatSymbols_es_ES');
goog.provide('goog.i18n.NumberFormatSymbols_et');
goog.provide('goog.i18n.NumberFormatSymbols_et_EE');
goog.provide('goog.i18n.NumberFormatSymbols_eu');
goog.provide('goog.i18n.NumberFormatSymbols_eu_ES');
goog.provide('goog.i18n.NumberFormatSymbols_fa');
goog.provide('goog.i18n.NumberFormatSymbols_fa_IR');
goog.provide('goog.i18n.NumberFormatSymbols_fi');
goog.provide('goog.i18n.NumberFormatSymbols_fi_FI');
goog.provide('goog.i18n.NumberFormatSymbols_fil');
goog.provide('goog.i18n.NumberFormatSymbols_fil_PH');
goog.provide('goog.i18n.NumberFormatSymbols_fr');
goog.provide('goog.i18n.NumberFormatSymbols_fr_BL');
goog.provide('goog.i18n.NumberFormatSymbols_fr_CA');
goog.provide('goog.i18n.NumberFormatSymbols_fr_FR');
goog.provide('goog.i18n.NumberFormatSymbols_fr_GF');
goog.provide('goog.i18n.NumberFormatSymbols_fr_GP');
goog.provide('goog.i18n.NumberFormatSymbols_fr_MC');
goog.provide('goog.i18n.NumberFormatSymbols_fr_MF');
goog.provide('goog.i18n.NumberFormatSymbols_fr_MQ');
goog.provide('goog.i18n.NumberFormatSymbols_fr_RE');
goog.provide('goog.i18n.NumberFormatSymbols_fr_YT');
goog.provide('goog.i18n.NumberFormatSymbols_gl');
goog.provide('goog.i18n.NumberFormatSymbols_gl_ES');
goog.provide('goog.i18n.NumberFormatSymbols_gsw');
goog.provide('goog.i18n.NumberFormatSymbols_gsw_CH');
goog.provide('goog.i18n.NumberFormatSymbols_gu');
goog.provide('goog.i18n.NumberFormatSymbols_gu_IN');
goog.provide('goog.i18n.NumberFormatSymbols_haw');
goog.provide('goog.i18n.NumberFormatSymbols_haw_US');
goog.provide('goog.i18n.NumberFormatSymbols_he');
goog.provide('goog.i18n.NumberFormatSymbols_he_IL');
goog.provide('goog.i18n.NumberFormatSymbols_hi');
goog.provide('goog.i18n.NumberFormatSymbols_hi_IN');
goog.provide('goog.i18n.NumberFormatSymbols_hr');
goog.provide('goog.i18n.NumberFormatSymbols_hr_HR');
goog.provide('goog.i18n.NumberFormatSymbols_hu');
goog.provide('goog.i18n.NumberFormatSymbols_hu_HU');
goog.provide('goog.i18n.NumberFormatSymbols_id');
goog.provide('goog.i18n.NumberFormatSymbols_id_ID');
goog.provide('goog.i18n.NumberFormatSymbols_in');
goog.provide('goog.i18n.NumberFormatSymbols_is');
goog.provide('goog.i18n.NumberFormatSymbols_is_IS');
goog.provide('goog.i18n.NumberFormatSymbols_it');
goog.provide('goog.i18n.NumberFormatSymbols_it_IT');
goog.provide('goog.i18n.NumberFormatSymbols_iw');
goog.provide('goog.i18n.NumberFormatSymbols_ja');
goog.provide('goog.i18n.NumberFormatSymbols_ja_JP');
goog.provide('goog.i18n.NumberFormatSymbols_kn');
goog.provide('goog.i18n.NumberFormatSymbols_kn_IN');
goog.provide('goog.i18n.NumberFormatSymbols_ko');
goog.provide('goog.i18n.NumberFormatSymbols_ko_KR');
goog.provide('goog.i18n.NumberFormatSymbols_ln');
goog.provide('goog.i18n.NumberFormatSymbols_ln_CD');
goog.provide('goog.i18n.NumberFormatSymbols_lt');
goog.provide('goog.i18n.NumberFormatSymbols_lt_LT');
goog.provide('goog.i18n.NumberFormatSymbols_lv');
goog.provide('goog.i18n.NumberFormatSymbols_lv_LV');
goog.provide('goog.i18n.NumberFormatSymbols_ml');
goog.provide('goog.i18n.NumberFormatSymbols_ml_IN');
goog.provide('goog.i18n.NumberFormatSymbols_mr');
goog.provide('goog.i18n.NumberFormatSymbols_mr_IN');
goog.provide('goog.i18n.NumberFormatSymbols_ms');
goog.provide('goog.i18n.NumberFormatSymbols_ms_MY');
goog.provide('goog.i18n.NumberFormatSymbols_mt');
goog.provide('goog.i18n.NumberFormatSymbols_mt_MT');
goog.provide('goog.i18n.NumberFormatSymbols_nl');
goog.provide('goog.i18n.NumberFormatSymbols_nl_NL');
goog.provide('goog.i18n.NumberFormatSymbols_no');
goog.provide('goog.i18n.NumberFormatSymbols_or');
goog.provide('goog.i18n.NumberFormatSymbols_or_IN');
goog.provide('goog.i18n.NumberFormatSymbols_pl');
goog.provide('goog.i18n.NumberFormatSymbols_pl_PL');
goog.provide('goog.i18n.NumberFormatSymbols_pt');
goog.provide('goog.i18n.NumberFormatSymbols_pt_BR');
goog.provide('goog.i18n.NumberFormatSymbols_pt_PT');
goog.provide('goog.i18n.NumberFormatSymbols_ro');
goog.provide('goog.i18n.NumberFormatSymbols_ro_RO');
goog.provide('goog.i18n.NumberFormatSymbols_ru');
goog.provide('goog.i18n.NumberFormatSymbols_ru_RU');
goog.provide('goog.i18n.NumberFormatSymbols_sk');
goog.provide('goog.i18n.NumberFormatSymbols_sk_SK');
goog.provide('goog.i18n.NumberFormatSymbols_sl');
goog.provide('goog.i18n.NumberFormatSymbols_sl_SI');
goog.provide('goog.i18n.NumberFormatSymbols_sq');
goog.provide('goog.i18n.NumberFormatSymbols_sq_AL');
goog.provide('goog.i18n.NumberFormatSymbols_sr');
goog.provide('goog.i18n.NumberFormatSymbols_sr_Cyrl_RS');
goog.provide('goog.i18n.NumberFormatSymbols_sr_Latn_RS');
goog.provide('goog.i18n.NumberFormatSymbols_sv');
goog.provide('goog.i18n.NumberFormatSymbols_sv_SE');
goog.provide('goog.i18n.NumberFormatSymbols_sw');
goog.provide('goog.i18n.NumberFormatSymbols_sw_TZ');
goog.provide('goog.i18n.NumberFormatSymbols_ta');
goog.provide('goog.i18n.NumberFormatSymbols_ta_IN');
goog.provide('goog.i18n.NumberFormatSymbols_te');
goog.provide('goog.i18n.NumberFormatSymbols_te_IN');
goog.provide('goog.i18n.NumberFormatSymbols_th');
goog.provide('goog.i18n.NumberFormatSymbols_th_TH');
goog.provide('goog.i18n.NumberFormatSymbols_tl');
goog.provide('goog.i18n.NumberFormatSymbols_tr');
goog.provide('goog.i18n.NumberFormatSymbols_tr_TR');
goog.provide('goog.i18n.NumberFormatSymbols_uk');
goog.provide('goog.i18n.NumberFormatSymbols_uk_UA');
goog.provide('goog.i18n.NumberFormatSymbols_ur');
goog.provide('goog.i18n.NumberFormatSymbols_ur_PK');
goog.provide('goog.i18n.NumberFormatSymbols_vi');
goog.provide('goog.i18n.NumberFormatSymbols_vi_VN');
goog.provide('goog.i18n.NumberFormatSymbols_zh');
goog.provide('goog.i18n.NumberFormatSymbols_zh_CN');
goog.provide('goog.i18n.NumberFormatSymbols_zh_HK');
goog.provide('goog.i18n.NumberFormatSymbols_zh_Hans');
goog.provide('goog.i18n.NumberFormatSymbols_zh_Hans_CN');
goog.provide('goog.i18n.NumberFormatSymbols_zh_TW');
goog.provide('goog.i18n.NumberFormatSymbols_zu');
goog.provide('goog.i18n.NumberFormatSymbols_zu_ZA');
/**
* Number formatting symbols for locale af.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_af = {
DECIMAL_SEP: ',',
GROUP_SEP: '\u00A0',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '\u00A4#,##0.00',
DEF_CURRENCY_CODE: 'ZAR'
};
/**
* Number formatting symbols for locale af_ZA.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_af_ZA = goog.i18n.NumberFormatSymbols_af;
/**
* Number formatting symbols for locale am.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_am = {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '\u00A4#,##0.00;(\u00A4#,##0.00)',
DEF_CURRENCY_CODE: 'ETB'
};
/**
* Number formatting symbols for locale am_ET.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_am_ET = goog.i18n.NumberFormatSymbols_am;
/**
* Number formatting symbols for locale ar.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_ar = {
DECIMAL_SEP: '\u066B',
GROUP_SEP: '\u066C',
PERCENT: '\u066A',
ZERO_DIGIT: '\u0660',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: '\u0627\u0633',
PERMILL: '\u0609',
INFINITY: '\u221E',
NAN: '\u0644\u064A\u0633 \u0631\u0642\u0645',
DECIMAL_PATTERN: '#0.###;#0.###-',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '\u00A4\u00A0#0.00;\u00A4\u00A0#0.00-',
DEF_CURRENCY_CODE: 'EGP'
};
/**
* Number formatting symbols for locale ar_001.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_ar_001 = goog.i18n.NumberFormatSymbols_ar;
/**
* Number formatting symbols for locale ar_EG.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_ar_EG = goog.i18n.NumberFormatSymbols_ar;
/**
* Number formatting symbols for locale bg.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_bg = {
DECIMAL_SEP: ',',
GROUP_SEP: '\u00A0',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '#,##0.00\u00A0\u00A4',
DEF_CURRENCY_CODE: 'BGN'
};
/**
* Number formatting symbols for locale bg_BG.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_bg_BG = goog.i18n.NumberFormatSymbols_bg;
/**
* Number formatting symbols for locale bn.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_bn = {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PERCENT: '%',
ZERO_DIGIT: '\u09e6',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: '\u09B8\u0982\u0996\u09CD\u09AF\u09BE \u09A8\u09BE',
DECIMAL_PATTERN: '#,##,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##,##0%',
CURRENCY_PATTERN: '#,##,##0.00\u00A4;(#,##,##0.00\u00A4)',
DEF_CURRENCY_CODE: 'BDT'
};
/**
* Number formatting symbols for locale bn_BD.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_bn_BD = goog.i18n.NumberFormatSymbols_bn;
/**
* Number formatting symbols for locale ca.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_ca = {
DECIMAL_SEP: ',',
GROUP_SEP: '.',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '#,##0.00\u00A0\u00A4',
DEF_CURRENCY_CODE: 'EUR'
};
/**
* Number formatting symbols for locale ca_ES.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_ca_ES = goog.i18n.NumberFormatSymbols_ca;
/**
* Number formatting symbols for locale chr.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_chr = {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '\u00A4#,##0.00;(\u00A4#,##0.00)',
DEF_CURRENCY_CODE: 'USD'
};
/**
* Number formatting symbols for locale chr_US.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_chr_US = goog.i18n.NumberFormatSymbols_chr;
/**
* Number formatting symbols for locale cs.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_cs = {
DECIMAL_SEP: ',',
GROUP_SEP: '\u00A0',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0\u00A0%',
CURRENCY_PATTERN: '#,##0.00\u00A0\u00A4',
DEF_CURRENCY_CODE: 'CZK'
};
/**
* Number formatting symbols for locale cs_CZ.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_cs_CZ = goog.i18n.NumberFormatSymbols_cs;
/**
* Number formatting symbols for locale cy.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_cy = {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '\u00A4#,##0.00',
DEF_CURRENCY_CODE: 'GBP'
};
/**
* Number formatting symbols for locale cy_GB.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_cy_GB = goog.i18n.NumberFormatSymbols_cy;
/**
* Number formatting symbols for locale da.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_da = {
DECIMAL_SEP: ',',
GROUP_SEP: '.',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0\u00A0%',
CURRENCY_PATTERN: '#,##0.00\u00A0\u00A4',
DEF_CURRENCY_CODE: 'DKK'
};
/**
* Number formatting symbols for locale da_DK.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_da_DK = goog.i18n.NumberFormatSymbols_da;
/**
* Number formatting symbols for locale de.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_de = {
DECIMAL_SEP: ',',
GROUP_SEP: '.',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0\u00A0%',
CURRENCY_PATTERN: '#,##0.00\u00A0\u00A4',
DEF_CURRENCY_CODE: 'EUR'
};
/**
* Number formatting symbols for locale de_AT.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_de_AT = {
DECIMAL_SEP: ',',
GROUP_SEP: '.',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0\u00A0%',
CURRENCY_PATTERN: '\u00A4\u00A0#,##0.00',
DEF_CURRENCY_CODE: 'EUR'
};
/**
* Number formatting symbols for locale de_BE.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_de_BE = goog.i18n.NumberFormatSymbols_de;
/**
* Number formatting symbols for locale de_CH.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_de_CH = {
DECIMAL_SEP: '.',
GROUP_SEP: '\'',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0\u00A0%',
CURRENCY_PATTERN: '\u00A4\u00A0#,##0.00;\u00A4-#,##0.00',
DEF_CURRENCY_CODE: 'CHF'
};
/**
* Number formatting symbols for locale de_DE.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_de_DE = goog.i18n.NumberFormatSymbols_de;
/**
* Number formatting symbols for locale de_LU.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_de_LU = goog.i18n.NumberFormatSymbols_de;
/**
* Number formatting symbols for locale el.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_el = {
DECIMAL_SEP: ',',
GROUP_SEP: '.',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'e',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '#,##0.00\u00A0\u00A4',
DEF_CURRENCY_CODE: 'EUR'
};
/**
* Number formatting symbols for locale el_GR.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_el_GR = goog.i18n.NumberFormatSymbols_el;
/**
* Number formatting symbols for locale en.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_en = {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '\u00A4#,##0.00;(\u00A4#,##0.00)',
DEF_CURRENCY_CODE: 'USD'
};
/**
* Number formatting symbols for locale en_AS.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_en_AS = goog.i18n.NumberFormatSymbols_en;
/**
* Number formatting symbols for locale en_AU.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_en_AU = {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '\u00A4#,##0.00;(\u00A4#,##0.00)',
DEF_CURRENCY_CODE: 'AUD'
};
/**
* Number formatting symbols for locale en_Dsrt.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_en_Dsrt = goog.i18n.NumberFormatSymbols_en;
/**
* Number formatting symbols for locale en_Dsrt_US.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_en_Dsrt_US = goog.i18n.NumberFormatSymbols_en;
/**
* Number formatting symbols for locale en_GB.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_en_GB = {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '\u00A4#,##0.00',
DEF_CURRENCY_CODE: 'GBP'
};
/**
* Number formatting symbols for locale en_GU.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_en_GU = goog.i18n.NumberFormatSymbols_en;
/**
* Number formatting symbols for locale en_IE.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_en_IE = {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '\u00A4#,##0.00;(\u00A4#,##0.00)',
DEF_CURRENCY_CODE: 'EUR'
};
/**
* Number formatting symbols for locale en_IN.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_en_IN = {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##,##0%',
CURRENCY_PATTERN: '\u00A4\u00A0#,##,##0.00',
DEF_CURRENCY_CODE: 'INR'
};
/**
* Number formatting symbols for locale en_MH.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_en_MH = goog.i18n.NumberFormatSymbols_en;
/**
* Number formatting symbols for locale en_MP.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_en_MP = goog.i18n.NumberFormatSymbols_en;
/**
* Number formatting symbols for locale en_SG.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_en_SG = {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '\u00A4#,##0.00;(\u00A4#,##0.00)',
DEF_CURRENCY_CODE: 'SGD'
};
/**
* Number formatting symbols for locale en_UM.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_en_UM = goog.i18n.NumberFormatSymbols_en;
/**
* Number formatting symbols for locale en_US.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_en_US = goog.i18n.NumberFormatSymbols_en;
/**
* Number formatting symbols for locale en_VI.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_en_VI = goog.i18n.NumberFormatSymbols_en;
/**
* Number formatting symbols for locale en_ZA.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_en_ZA = {
DECIMAL_SEP: ',',
GROUP_SEP: '\u00A0',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '\u00A4#,##0.00;(\u00A4#,##0.00)',
DEF_CURRENCY_CODE: 'ZAR'
};
/**
* Number formatting symbols for locale es.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_es = {
DECIMAL_SEP: ',',
GROUP_SEP: '.',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '#,##0.00\u00A0\u00A4',
DEF_CURRENCY_CODE: 'EUR'
};
/**
* Number formatting symbols for locale es_419.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_es_419 = {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '\u00A4#,##0.00',
DEF_CURRENCY_CODE: 'MXN'
};
/**
* Number formatting symbols for locale es_ES.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_es_ES = goog.i18n.NumberFormatSymbols_es;
/**
* Number formatting symbols for locale et.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_et = {
DECIMAL_SEP: ',',
GROUP_SEP: '\u00A0',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '#,##0.00\u00A0\u00A4',
DEF_CURRENCY_CODE: 'EUR'
};
/**
* Number formatting symbols for locale et_EE.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_et_EE = goog.i18n.NumberFormatSymbols_et;
/**
* Number formatting symbols for locale eu.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_eu = {
DECIMAL_SEP: ',',
GROUP_SEP: '.',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '#,##0.00\u00A0\u00A4',
DEF_CURRENCY_CODE: 'EUR'
};
/**
* Number formatting symbols for locale eu_ES.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_eu_ES = goog.i18n.NumberFormatSymbols_eu;
/**
* Number formatting symbols for locale fa.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_fa = {
DECIMAL_SEP: '\u066B',
GROUP_SEP: '\u066C',
PERCENT: '\u066A',
ZERO_DIGIT: '\u06F0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: '\u00D7\u06F1\u06F0^',
PERMILL: '\u0609',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '#,##0.00\u00A0\u00A4;\u2212#,##0.00\u00A0\u00A4',
DEF_CURRENCY_CODE: 'IRR'
};
/**
* Number formatting symbols for locale fa_IR.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_fa_IR = goog.i18n.NumberFormatSymbols_fa;
/**
* Number formatting symbols for locale fi.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_fi = {
DECIMAL_SEP: ',',
GROUP_SEP: '\u00A0',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'ep\u00E4luku',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0\u00A0%',
CURRENCY_PATTERN: '#,##0.00\u00A0\u00A4',
DEF_CURRENCY_CODE: 'EUR'
};
/**
* Number formatting symbols for locale fi_FI.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_fi_FI = goog.i18n.NumberFormatSymbols_fi;
/**
* Number formatting symbols for locale fil.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_fil = {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '\u00A4\u00A0#,##0.00',
DEF_CURRENCY_CODE: 'PHP'
};
/**
* Number formatting symbols for locale fil_PH.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_fil_PH = goog.i18n.NumberFormatSymbols_fil;
/**
* Number formatting symbols for locale fr.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_fr = {
DECIMAL_SEP: ',',
GROUP_SEP: '\u00A0',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0\u00A0%',
CURRENCY_PATTERN: '#,##0.00\u00A0\u00A4',
DEF_CURRENCY_CODE: 'EUR'
};
/**
* Number formatting symbols for locale fr_BL.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_fr_BL = goog.i18n.NumberFormatSymbols_fr;
/**
* Number formatting symbols for locale fr_CA.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_fr_CA = {
DECIMAL_SEP: ',',
GROUP_SEP: '\u00A0',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0\u00A0%',
CURRENCY_PATTERN: '#,##0.00\u00A0\u00A4;(#,##0.00\u00A0\u00A4)',
DEF_CURRENCY_CODE: 'CAD'
};
/**
* Number formatting symbols for locale fr_FR.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_fr_FR = goog.i18n.NumberFormatSymbols_fr;
/**
* Number formatting symbols for locale fr_GF.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_fr_GF = goog.i18n.NumberFormatSymbols_fr;
/**
* Number formatting symbols for locale fr_GP.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_fr_GP = goog.i18n.NumberFormatSymbols_fr;
/**
* Number formatting symbols for locale fr_MC.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_fr_MC = goog.i18n.NumberFormatSymbols_fr;
/**
* Number formatting symbols for locale fr_MF.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_fr_MF = goog.i18n.NumberFormatSymbols_fr;
/**
* Number formatting symbols for locale fr_MQ.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_fr_MQ = goog.i18n.NumberFormatSymbols_fr;
/**
* Number formatting symbols for locale fr_RE.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_fr_RE = goog.i18n.NumberFormatSymbols_fr;
/**
* Number formatting symbols for locale fr_YT.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_fr_YT = goog.i18n.NumberFormatSymbols_fr;
/**
* Number formatting symbols for locale gl.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_gl = {
DECIMAL_SEP: ',',
GROUP_SEP: '.',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '#,##0.00\u00A0\u00A4',
DEF_CURRENCY_CODE: 'EUR'
};
/**
* Number formatting symbols for locale gl_ES.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_gl_ES = goog.i18n.NumberFormatSymbols_gl;
/**
* Number formatting symbols for locale gsw.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_gsw = {
DECIMAL_SEP: '.',
GROUP_SEP: '\u2019',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '\u2212',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0\u00A0%',
CURRENCY_PATTERN: '#,##0.00\u00A0\u00A4',
DEF_CURRENCY_CODE: 'CHF'
};
/**
* Number formatting symbols for locale gsw_CH.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_gsw_CH = goog.i18n.NumberFormatSymbols_gsw;
/**
* Number formatting symbols for locale gu.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_gu = {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: '\u0AAA\u0AC2\u0AB0\u0ACD\u0AB5',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: '\u0AB8\u0A82\u0A96\u0ACD\u0AAF\u0ABE \u0AA8\u0AA5\u0AC0\u0A82',
DECIMAL_PATTERN: '#,##,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##,##0%',
CURRENCY_PATTERN: '\u00A4\u00A0#,##,##0.00',
DEF_CURRENCY_CODE: 'INR'
};
/**
* Number formatting symbols for locale gu_IN.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_gu_IN = goog.i18n.NumberFormatSymbols_gu;
/**
* Number formatting symbols for locale haw.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_haw = {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '\u00A4#,##0.00;(\u00A4#,##0.00)',
DEF_CURRENCY_CODE: 'USD'
};
/**
* Number formatting symbols for locale haw_US.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_haw_US = goog.i18n.NumberFormatSymbols_haw;
/**
* Number formatting symbols for locale he.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_he = {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '#,##0.00\u00A0\u00A4',
DEF_CURRENCY_CODE: 'ILS'
};
/**
* Number formatting symbols for locale he_IL.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_he_IL = goog.i18n.NumberFormatSymbols_he;
/**
* Number formatting symbols for locale hi.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_hi = {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##,##0%',
CURRENCY_PATTERN: '\u00A4\u00A0#,##,##0.00',
DEF_CURRENCY_CODE: 'INR'
};
/**
* Number formatting symbols for locale hi_IN.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_hi_IN = goog.i18n.NumberFormatSymbols_hi;
/**
* Number formatting symbols for locale hr.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_hr = {
DECIMAL_SEP: ',',
GROUP_SEP: '.',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '#,##0.00\u00A0\u00A4',
DEF_CURRENCY_CODE: 'HRK'
};
/**
* Number formatting symbols for locale hr_HR.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_hr_HR = goog.i18n.NumberFormatSymbols_hr;
/**
* Number formatting symbols for locale hu.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_hu = {
DECIMAL_SEP: ',',
GROUP_SEP: '\u00A0',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '#,##0.00\u00A0\u00A4',
DEF_CURRENCY_CODE: 'HUF'
};
/**
* Number formatting symbols for locale hu_HU.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_hu_HU = goog.i18n.NumberFormatSymbols_hu;
/**
* Number formatting symbols for locale id.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_id = {
DECIMAL_SEP: ',',
GROUP_SEP: '.',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '\u00A4#,##0.00',
DEF_CURRENCY_CODE: 'IDR'
};
/**
* Number formatting symbols for locale id_ID.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_id_ID = goog.i18n.NumberFormatSymbols_id;
/**
* Number formatting symbols for locale in.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_in = {
DECIMAL_SEP: ',',
GROUP_SEP: '.',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '\u00A4#,##0.00',
DEF_CURRENCY_CODE: 'IDR'
};
/**
* Number formatting symbols for locale is.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_is = {
DECIMAL_SEP: ',',
GROUP_SEP: '.',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '\u2212',
EXP_SYMBOL: '\u00D710^',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'EiTa',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '#,##0.00\u00A0\u00A4',
DEF_CURRENCY_CODE: 'ISK'
};
/**
* Number formatting symbols for locale is_IS.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_is_IS = goog.i18n.NumberFormatSymbols_is;
/**
* Number formatting symbols for locale it.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_it = {
DECIMAL_SEP: ',',
GROUP_SEP: '.',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '\u00A4\u00A0#,##0.00',
DEF_CURRENCY_CODE: 'EUR'
};
/**
* Number formatting symbols for locale it_IT.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_it_IT = goog.i18n.NumberFormatSymbols_it;
/**
* Number formatting symbols for locale iw.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_iw = {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '#,##0.00\u00A0\u00A4',
DEF_CURRENCY_CODE: 'ILS'
};
/**
* Number formatting symbols for locale ja.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_ja = {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN\uFF08\u975E\u6570\uFF09',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '\u00A4#,##0.00',
DEF_CURRENCY_CODE: 'JPY'
};
/**
* Number formatting symbols for locale ja_JP.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_ja_JP = goog.i18n.NumberFormatSymbols_ja;
/**
* Number formatting symbols for locale kn.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_kn = {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: '\u0CAA\u0CC2\u0CB0\u0CCD\u0CB5',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: '\u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6\u0CAF\u0CB2\u0CCD\u0CB2',
DECIMAL_PATTERN: '#,##,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##,##0%',
CURRENCY_PATTERN: '\u00A4\u00A0#,##,##0.00',
DEF_CURRENCY_CODE: 'INR'
};
/**
* Number formatting symbols for locale kn_IN.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_kn_IN = goog.i18n.NumberFormatSymbols_kn;
/**
* Number formatting symbols for locale ko.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_ko = {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '\u00A4#,##0.00',
DEF_CURRENCY_CODE: 'KRW'
};
/**
* Number formatting symbols for locale ko_KR.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_ko_KR = goog.i18n.NumberFormatSymbols_ko;
/**
* Number formatting symbols for locale ln.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_ln = {
DECIMAL_SEP: ',',
GROUP_SEP: '.',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '#,##0.00\u00A0\u00A4',
DEF_CURRENCY_CODE: 'CDF'
};
/**
* Number formatting symbols for locale ln_CD.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_ln_CD = goog.i18n.NumberFormatSymbols_ln;
/**
* Number formatting symbols for locale lt.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_lt = {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '\u2212',
EXP_SYMBOL: '\u00D710^',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: '\u00A4\u00A4\u00A4',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0\u00A0%',
CURRENCY_PATTERN: '#,##0.00\u00A0\u00A4',
DEF_CURRENCY_CODE: 'LTL'
};
/**
* Number formatting symbols for locale lt_LT.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_lt_LT = goog.i18n.NumberFormatSymbols_lt;
/**
* Number formatting symbols for locale lv.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_lv = {
DECIMAL_SEP: ',',
GROUP_SEP: '\u00A0',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '\u2212',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'nav\u00A0skaitlis',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '#,##0.00\u00A0\u00A4',
DEF_CURRENCY_CODE: 'LVL'
};
/**
* Number formatting symbols for locale lv_LV.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_lv_LV = goog.i18n.NumberFormatSymbols_lv;
/**
* Number formatting symbols for locale ml.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_ml = {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##,##0%',
CURRENCY_PATTERN: '#,##,##0.00\u00A4',
DEF_CURRENCY_CODE: 'INR'
};
/**
* Number formatting symbols for locale ml_IN.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_ml_IN = goog.i18n.NumberFormatSymbols_ml;
/**
* Number formatting symbols for locale mr.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_mr = {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: '\u092A\u0942',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: '\u0928\u093E\u0928',
DECIMAL_PATTERN: '#,##,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##,##0%',
CURRENCY_PATTERN: '\u00A4\u00A0#,##,##0.00',
DEF_CURRENCY_CODE: 'INR'
};
/**
* Number formatting symbols for locale mr_IN.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_mr_IN = goog.i18n.NumberFormatSymbols_mr;
/**
* Number formatting symbols for locale ms.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_ms = {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '\u00A4#,##0.00;(\u00A4#,##0.00)',
DEF_CURRENCY_CODE: 'MYR'
};
/**
* Number formatting symbols for locale ms_MY.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_ms_MY = goog.i18n.NumberFormatSymbols_ms;
/**
* Number formatting symbols for locale mt.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_mt = {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '\u00A4#,##0.00',
DEF_CURRENCY_CODE: 'MTL'
};
/**
* Number formatting symbols for locale mt_MT.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_mt_MT = goog.i18n.NumberFormatSymbols_mt;
/**
* Number formatting symbols for locale nl.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_nl = {
DECIMAL_SEP: ',',
GROUP_SEP: '.',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '\u00A4\u00A0#,##0.00;\u00A4\u00A0#,##0.00-',
DEF_CURRENCY_CODE: 'EUR'
};
/**
* Number formatting symbols for locale nl_NL.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_nl_NL = goog.i18n.NumberFormatSymbols_nl;
/**
* Number formatting symbols for locale no.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_no = {
DECIMAL_SEP: ',',
GROUP_SEP: '\u00A0',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0\u00A0%',
CURRENCY_PATTERN: '\u00A4\u00A0#,##0.00',
DEF_CURRENCY_CODE: 'NOK'
};
/**
* Number formatting symbols for locale or.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_or = {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##,##0%',
CURRENCY_PATTERN: '\u00A4\u00A0#,##,##0.00',
DEF_CURRENCY_CODE: 'INR'
};
/**
* Number formatting symbols for locale or_IN.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_or_IN = goog.i18n.NumberFormatSymbols_or;
/**
* Number formatting symbols for locale pl.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_pl = {
DECIMAL_SEP: ',',
GROUP_SEP: '\u00A0',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '#,##0.00\u00A0\u00A4',
DEF_CURRENCY_CODE: 'PLN'
};
/**
* Number formatting symbols for locale pl_PL.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_pl_PL = goog.i18n.NumberFormatSymbols_pl;
/**
* Number formatting symbols for locale pt.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_pt = {
DECIMAL_SEP: ',',
GROUP_SEP: '.',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '\u00A4#,##0.00;(\u00A4#,##0.00)',
DEF_CURRENCY_CODE: 'BRL'
};
/**
* Number formatting symbols for locale pt_BR.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_pt_BR = goog.i18n.NumberFormatSymbols_pt;
/**
* Number formatting symbols for locale pt_PT.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_pt_PT = {
DECIMAL_SEP: ',',
GROUP_SEP: '\u00A0',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '#,##0.00\u00A0\u00A4',
DEF_CURRENCY_CODE: 'EUR'
};
/**
* Number formatting symbols for locale ro.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_ro = {
DECIMAL_SEP: ',',
GROUP_SEP: '.',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '#,##0.00\u00A0\u00A4',
DEF_CURRENCY_CODE: 'RON'
};
/**
* Number formatting symbols for locale ro_RO.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_ro_RO = goog.i18n.NumberFormatSymbols_ro;
/**
* Number formatting symbols for locale ru.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_ru = {
DECIMAL_SEP: ',',
GROUP_SEP: '\u00A0',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: '\u043D\u0435 \u0447\u0438\u0441\u043B\u043E',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0\u00A0%',
CURRENCY_PATTERN: '#,##0.00\u00A0\u00A4',
DEF_CURRENCY_CODE: 'RUB'
};
/**
* Number formatting symbols for locale ru_RU.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_ru_RU = goog.i18n.NumberFormatSymbols_ru;
/**
* Number formatting symbols for locale sk.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_sk = {
DECIMAL_SEP: ',',
GROUP_SEP: '\u00A0',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0\u00A0%',
CURRENCY_PATTERN: '#,##0.00\u00A0\u00A4',
DEF_CURRENCY_CODE: 'SKK'
};
/**
* Number formatting symbols for locale sk_SK.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_sk_SK = goog.i18n.NumberFormatSymbols_sk;
/**
* Number formatting symbols for locale sl.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_sl = {
DECIMAL_SEP: ',',
GROUP_SEP: '.',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'e',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '#,##0.00\u00A0\u00A4',
DEF_CURRENCY_CODE: 'EUR'
};
/**
* Number formatting symbols for locale sl_SI.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_sl_SI = goog.i18n.NumberFormatSymbols_sl;
/**
* Number formatting symbols for locale sq.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_sq = {
DECIMAL_SEP: ',',
GROUP_SEP: '.',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '\u00A4#,##0.00',
DEF_CURRENCY_CODE: 'ALL'
};
/**
* Number formatting symbols for locale sq_AL.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_sq_AL = goog.i18n.NumberFormatSymbols_sq;
/**
* Number formatting symbols for locale sr.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_sr = {
DECIMAL_SEP: ',',
GROUP_SEP: '.',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '#,##0.00\u00A0\u00A4',
DEF_CURRENCY_CODE: 'RSD'
};
/**
* Number formatting symbols for locale sr_Cyrl_RS.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_sr_Cyrl_RS = goog.i18n.NumberFormatSymbols_sr;
/**
* Number formatting symbols for locale sr_Latn_RS.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_sr_Latn_RS = goog.i18n.NumberFormatSymbols_sr;
/**
* Number formatting symbols for locale sv.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_sv = {
DECIMAL_SEP: ',',
GROUP_SEP: '\u00A0',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '\u2212',
EXP_SYMBOL: '\u00D710^',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: '\u00A4\u00A4\u00A4',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0\u00A0%',
CURRENCY_PATTERN: '#,##0.00\u00A0\u00A4',
DEF_CURRENCY_CODE: 'SEK'
};
/**
* Number formatting symbols for locale sv_SE.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_sv_SE = goog.i18n.NumberFormatSymbols_sv;
/**
* Number formatting symbols for locale sw.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_sw = {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '#,##0.00\u00A0\u00A4',
DEF_CURRENCY_CODE: 'TZS'
};
/**
* Number formatting symbols for locale sw_TZ.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_sw_TZ = goog.i18n.NumberFormatSymbols_sw;
/**
* Number formatting symbols for locale ta.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_ta = {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: '\u0B8E\u0BA3\u0BCD \u0B87\u0BB2\u0BCD\u0BB2\u0BC8',
DECIMAL_PATTERN: '#,##,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##,##0%',
CURRENCY_PATTERN: '\u00A4\u00A0#,##,##0.00',
DEF_CURRENCY_CODE: 'INR'
};
/**
* Number formatting symbols for locale ta_IN.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_ta_IN = goog.i18n.NumberFormatSymbols_ta;
/**
* Number formatting symbols for locale te.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_te = {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: '\u0C24\u0C42',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##,##0%',
CURRENCY_PATTERN: '\u00A4\u00A0#,##,##0.00',
DEF_CURRENCY_CODE: 'INR'
};
/**
* Number formatting symbols for locale te_IN.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_te_IN = goog.i18n.NumberFormatSymbols_te;
/**
* Number formatting symbols for locale th.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_th = {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '\u00A4#,##0.00;\u00A4-#,##0.00',
DEF_CURRENCY_CODE: 'THB'
};
/**
* Number formatting symbols for locale th_TH.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_th_TH = goog.i18n.NumberFormatSymbols_th;
/**
* Number formatting symbols for locale tl.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_tl = {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '\u00A4\u00A0#,##0.00',
DEF_CURRENCY_CODE: 'PHP'
};
/**
* Number formatting symbols for locale tr.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_tr = {
DECIMAL_SEP: ',',
GROUP_SEP: '.',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '%#,##0',
CURRENCY_PATTERN: '#,##0.00\u00A0\u00A4',
DEF_CURRENCY_CODE: 'TRY'
};
/**
* Number formatting symbols for locale tr_TR.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_tr_TR = goog.i18n.NumberFormatSymbols_tr;
/**
* Number formatting symbols for locale uk.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_uk = {
DECIMAL_SEP: ',',
GROUP_SEP: '\u00A0',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: '\u0415',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: '\u041D\u0435 \u0447\u0438\u0441\u043B\u043E',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '#,##0.00\u00A0\u00A4',
DEF_CURRENCY_CODE: 'UAH'
};
/**
* Number formatting symbols for locale uk_UA.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_uk_UA = goog.i18n.NumberFormatSymbols_uk;
/**
* Number formatting symbols for locale ur.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_ur = {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '\u00A4#,##0.00',
DEF_CURRENCY_CODE: 'PKR'
};
/**
* Number formatting symbols for locale ur_PK.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_ur_PK = goog.i18n.NumberFormatSymbols_ur;
/**
* Number formatting symbols for locale vi.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_vi = {
DECIMAL_SEP: ',',
GROUP_SEP: '.',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '#,##0.00\u00A0\u00A4',
DEF_CURRENCY_CODE: 'VND'
};
/**
* Number formatting symbols for locale vi_VN.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_vi_VN = goog.i18n.NumberFormatSymbols_vi;
/**
* Number formatting symbols for locale zh.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_zh = {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '\u00A4#,##0.00',
DEF_CURRENCY_CODE: 'CNY'
};
/**
* Number formatting symbols for locale zh_CN.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_zh_CN = goog.i18n.NumberFormatSymbols_zh;
/**
* Number formatting symbols for locale zh_HK.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_zh_HK = {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: '\u975E\u6578\u503C',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '\u00A4#,##0.00;(\u00A4#,##0.00)',
DEF_CURRENCY_CODE: 'HKD'
};
/**
* Number formatting symbols for locale zh_Hans.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_zh_Hans = goog.i18n.NumberFormatSymbols_zh;
/**
* Number formatting symbols for locale zh_Hans_CN.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_zh_Hans_CN = goog.i18n.NumberFormatSymbols_zh;
/**
* Number formatting symbols for locale zh_TW.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_zh_TW = {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: '\u975E\u6578\u503C',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '\u00A4#,##0.00',
DEF_CURRENCY_CODE: 'TWD'
};
/**
* Number formatting symbols for locale zu.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_zu = {
DECIMAL_SEP: ',',
GROUP_SEP: '\u00A0',
PERCENT: '%',
ZERO_DIGIT: '0',
PLUS_SIGN: '+',
MINUS_SIGN: '-',
EXP_SYMBOL: 'E',
PERMILL: '\u2030',
INFINITY: '\u221E',
NAN: 'NaN',
DECIMAL_PATTERN: '#,##0.###',
SCIENTIFIC_PATTERN: '#E0',
PERCENT_PATTERN: '#,##0%',
CURRENCY_PATTERN: '\u00A4#,##0.00',
DEF_CURRENCY_CODE: 'ZAR'
};
/**
* Number formatting symbols for locale zu_ZA.
* @enum {string}
*/
goog.i18n.NumberFormatSymbols_zu_ZA = goog.i18n.NumberFormatSymbols_zu;
/**
* Selected number formatting symbols by locale.
*/
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_en;
if (goog.LOCALE == 'af') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_af;
}
if (goog.LOCALE == 'af_ZA' || goog.LOCALE == 'af-ZA') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_af;
}
if (goog.LOCALE == 'am') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_am;
}
if (goog.LOCALE == 'am_ET' || goog.LOCALE == 'am-ET') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_am;
}
if (goog.LOCALE == 'ar') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_ar;
}
if (goog.LOCALE == 'ar_001' || goog.LOCALE == 'ar-001') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_ar;
}
if (goog.LOCALE == 'ar_EG' || goog.LOCALE == 'ar-EG') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_ar;
}
if (goog.LOCALE == 'bg') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_bg;
}
if (goog.LOCALE == 'bg_BG' || goog.LOCALE == 'bg-BG') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_bg;
}
if (goog.LOCALE == 'bn') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_bn;
}
if (goog.LOCALE == 'bn_BD' || goog.LOCALE == 'bn-BD') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_bn;
}
if (goog.LOCALE == 'ca') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_ca;
}
if (goog.LOCALE == 'ca_ES' || goog.LOCALE == 'ca-ES') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_ca;
}
if (goog.LOCALE == 'chr') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_chr;
}
if (goog.LOCALE == 'chr_US' || goog.LOCALE == 'chr-US') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_chr;
}
if (goog.LOCALE == 'cs') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_cs;
}
if (goog.LOCALE == 'cs_CZ' || goog.LOCALE == 'cs-CZ') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_cs;
}
if (goog.LOCALE == 'cy') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_cy;
}
if (goog.LOCALE == 'cy_GB' || goog.LOCALE == 'cy-GB') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_cy;
}
if (goog.LOCALE == 'da') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_da;
}
if (goog.LOCALE == 'da_DK' || goog.LOCALE == 'da-DK') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_da;
}
if (goog.LOCALE == 'de') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_de;
}
if (goog.LOCALE == 'de_AT' || goog.LOCALE == 'de-AT') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_de_AT;
}
if (goog.LOCALE == 'de_BE' || goog.LOCALE == 'de-BE') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_de;
}
if (goog.LOCALE == 'de_CH' || goog.LOCALE == 'de-CH') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_de_CH;
}
if (goog.LOCALE == 'de_DE' || goog.LOCALE == 'de-DE') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_de;
}
if (goog.LOCALE == 'de_LU' || goog.LOCALE == 'de-LU') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_de;
}
if (goog.LOCALE == 'el') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_el;
}
if (goog.LOCALE == 'el_GR' || goog.LOCALE == 'el-GR') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_el;
}
if (goog.LOCALE == 'en') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_en;
}
if (goog.LOCALE == 'en_AS' || goog.LOCALE == 'en-AS') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_en;
}
if (goog.LOCALE == 'en_AU' || goog.LOCALE == 'en-AU') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_en_AU;
}
if (goog.LOCALE == 'en_Dsrt' || goog.LOCALE == 'en-Dsrt') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_en;
}
if (goog.LOCALE == 'en_Dsrt_US' || goog.LOCALE == 'en-Dsrt-US') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_en;
}
if (goog.LOCALE == 'en_GB' || goog.LOCALE == 'en-GB') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_en_GB;
}
if (goog.LOCALE == 'en_GU' || goog.LOCALE == 'en-GU') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_en;
}
if (goog.LOCALE == 'en_IE' || goog.LOCALE == 'en-IE') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_en_IE;
}
if (goog.LOCALE == 'en_IN' || goog.LOCALE == 'en-IN') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_en_IN;
}
if (goog.LOCALE == 'en_MH' || goog.LOCALE == 'en-MH') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_en;
}
if (goog.LOCALE == 'en_MP' || goog.LOCALE == 'en-MP') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_en;
}
if (goog.LOCALE == 'en_SG' || goog.LOCALE == 'en-SG') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_en_SG;
}
if (goog.LOCALE == 'en_UM' || goog.LOCALE == 'en-UM') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_en;
}
if (goog.LOCALE == 'en_US' || goog.LOCALE == 'en-US') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_en;
}
if (goog.LOCALE == 'en_VI' || goog.LOCALE == 'en-VI') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_en;
}
if (goog.LOCALE == 'en_ZA' || goog.LOCALE == 'en-ZA') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_en_ZA;
}
if (goog.LOCALE == 'es') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_es;
}
if (goog.LOCALE == 'es_419' || goog.LOCALE == 'es-419') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_es_419;
}
if (goog.LOCALE == 'es_ES' || goog.LOCALE == 'es-ES') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_es;
}
if (goog.LOCALE == 'et') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_et;
}
if (goog.LOCALE == 'et_EE' || goog.LOCALE == 'et-EE') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_et;
}
if (goog.LOCALE == 'eu') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_eu;
}
if (goog.LOCALE == 'eu_ES' || goog.LOCALE == 'eu-ES') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_eu;
}
if (goog.LOCALE == 'fa') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_fa;
}
if (goog.LOCALE == 'fa_IR' || goog.LOCALE == 'fa-IR') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_fa;
}
if (goog.LOCALE == 'fi') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_fi;
}
if (goog.LOCALE == 'fi_FI' || goog.LOCALE == 'fi-FI') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_fi;
}
if (goog.LOCALE == 'fil') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_fil;
}
if (goog.LOCALE == 'fil_PH' || goog.LOCALE == 'fil-PH') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_fil;
}
if (goog.LOCALE == 'fr') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_fr;
}
if (goog.LOCALE == 'fr_BL' || goog.LOCALE == 'fr-BL') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_fr;
}
if (goog.LOCALE == 'fr_CA' || goog.LOCALE == 'fr-CA') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_fr_CA;
}
if (goog.LOCALE == 'fr_FR' || goog.LOCALE == 'fr-FR') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_fr;
}
if (goog.LOCALE == 'fr_GF' || goog.LOCALE == 'fr-GF') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_fr;
}
if (goog.LOCALE == 'fr_GP' || goog.LOCALE == 'fr-GP') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_fr;
}
if (goog.LOCALE == 'fr_MC' || goog.LOCALE == 'fr-MC') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_fr;
}
if (goog.LOCALE == 'fr_MF' || goog.LOCALE == 'fr-MF') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_fr;
}
if (goog.LOCALE == 'fr_MQ' || goog.LOCALE == 'fr-MQ') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_fr;
}
if (goog.LOCALE == 'fr_RE' || goog.LOCALE == 'fr-RE') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_fr;
}
if (goog.LOCALE == 'fr_YT' || goog.LOCALE == 'fr-YT') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_fr;
}
if (goog.LOCALE == 'gl') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_gl;
}
if (goog.LOCALE == 'gl_ES' || goog.LOCALE == 'gl-ES') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_gl;
}
if (goog.LOCALE == 'gsw') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_gsw;
}
if (goog.LOCALE == 'gsw_CH' || goog.LOCALE == 'gsw-CH') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_gsw;
}
if (goog.LOCALE == 'gu') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_gu;
}
if (goog.LOCALE == 'gu_IN' || goog.LOCALE == 'gu-IN') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_gu;
}
if (goog.LOCALE == 'haw') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_haw;
}
if (goog.LOCALE == 'haw_US' || goog.LOCALE == 'haw-US') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_haw;
}
if (goog.LOCALE == 'he') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_he;
}
if (goog.LOCALE == 'he_IL' || goog.LOCALE == 'he-IL') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_he;
}
if (goog.LOCALE == 'hi') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_hi;
}
if (goog.LOCALE == 'hi_IN' || goog.LOCALE == 'hi-IN') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_hi;
}
if (goog.LOCALE == 'hr') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_hr;
}
if (goog.LOCALE == 'hr_HR' || goog.LOCALE == 'hr-HR') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_hr;
}
if (goog.LOCALE == 'hu') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_hu;
}
if (goog.LOCALE == 'hu_HU' || goog.LOCALE == 'hu-HU') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_hu;
}
if (goog.LOCALE == 'id') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_id;
}
if (goog.LOCALE == 'id_ID' || goog.LOCALE == 'id-ID') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_id;
}
if (goog.LOCALE == 'in') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_in;
}
if (goog.LOCALE == 'is') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_is;
}
if (goog.LOCALE == 'is_IS' || goog.LOCALE == 'is-IS') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_is;
}
if (goog.LOCALE == 'it') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_it;
}
if (goog.LOCALE == 'it_IT' || goog.LOCALE == 'it-IT') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_it;
}
if (goog.LOCALE == 'iw') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_iw;
}
if (goog.LOCALE == 'ja') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_ja;
}
if (goog.LOCALE == 'ja_JP' || goog.LOCALE == 'ja-JP') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_ja;
}
if (goog.LOCALE == 'kn') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_kn;
}
if (goog.LOCALE == 'kn_IN' || goog.LOCALE == 'kn-IN') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_kn;
}
if (goog.LOCALE == 'ko') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_ko;
}
if (goog.LOCALE == 'ko_KR' || goog.LOCALE == 'ko-KR') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_ko;
}
if (goog.LOCALE == 'ln') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_ln;
}
if (goog.LOCALE == 'ln_CD' || goog.LOCALE == 'ln-CD') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_ln;
}
if (goog.LOCALE == 'lt') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_lt;
}
if (goog.LOCALE == 'lt_LT' || goog.LOCALE == 'lt-LT') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_lt;
}
if (goog.LOCALE == 'lv') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_lv;
}
if (goog.LOCALE == 'lv_LV' || goog.LOCALE == 'lv-LV') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_lv;
}
if (goog.LOCALE == 'ml') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_ml;
}
if (goog.LOCALE == 'ml_IN' || goog.LOCALE == 'ml-IN') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_ml;
}
if (goog.LOCALE == 'mr') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_mr;
}
if (goog.LOCALE == 'mr_IN' || goog.LOCALE == 'mr-IN') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_mr;
}
if (goog.LOCALE == 'ms') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_ms;
}
if (goog.LOCALE == 'ms_MY' || goog.LOCALE == 'ms-MY') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_ms;
}
if (goog.LOCALE == 'mt') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_mt;
}
if (goog.LOCALE == 'mt_MT' || goog.LOCALE == 'mt-MT') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_mt;
}
if (goog.LOCALE == 'nl') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_nl;
}
if (goog.LOCALE == 'nl_NL' || goog.LOCALE == 'nl-NL') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_nl;
}
if (goog.LOCALE == 'no') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_no;
}
if (goog.LOCALE == 'or') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_or;
}
if (goog.LOCALE == 'or_IN' || goog.LOCALE == 'or-IN') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_or;
}
if (goog.LOCALE == 'pl') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_pl;
}
if (goog.LOCALE == 'pl_PL' || goog.LOCALE == 'pl-PL') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_pl;
}
if (goog.LOCALE == 'pt') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_pt;
}
if (goog.LOCALE == 'pt_BR' || goog.LOCALE == 'pt-BR') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_pt;
}
if (goog.LOCALE == 'pt_PT' || goog.LOCALE == 'pt-PT') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_pt_PT;
}
if (goog.LOCALE == 'ro') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_ro;
}
if (goog.LOCALE == 'ro_RO' || goog.LOCALE == 'ro-RO') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_ro;
}
if (goog.LOCALE == 'ru') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_ru;
}
if (goog.LOCALE == 'ru_RU' || goog.LOCALE == 'ru-RU') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_ru;
}
if (goog.LOCALE == 'sk') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_sk;
}
if (goog.LOCALE == 'sk_SK' || goog.LOCALE == 'sk-SK') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_sk;
}
if (goog.LOCALE == 'sl') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_sl;
}
if (goog.LOCALE == 'sl_SI' || goog.LOCALE == 'sl-SI') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_sl;
}
if (goog.LOCALE == 'sq') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_sq;
}
if (goog.LOCALE == 'sq_AL' || goog.LOCALE == 'sq-AL') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_sq;
}
if (goog.LOCALE == 'sr') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_sr;
}
if (goog.LOCALE == 'sr_Cyrl_RS' || goog.LOCALE == 'sr-Cyrl-RS') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_sr;
}
if (goog.LOCALE == 'sr_Latn_RS' || goog.LOCALE == 'sr-Latn-RS') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_sr;
}
if (goog.LOCALE == 'sv') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_sv;
}
if (goog.LOCALE == 'sv_SE' || goog.LOCALE == 'sv-SE') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_sv;
}
if (goog.LOCALE == 'sw') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_sw;
}
if (goog.LOCALE == 'sw_TZ' || goog.LOCALE == 'sw-TZ') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_sw;
}
if (goog.LOCALE == 'ta') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_ta;
}
if (goog.LOCALE == 'ta_IN' || goog.LOCALE == 'ta-IN') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_ta;
}
if (goog.LOCALE == 'te') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_te;
}
if (goog.LOCALE == 'te_IN' || goog.LOCALE == 'te-IN') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_te;
}
if (goog.LOCALE == 'th') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_th;
}
if (goog.LOCALE == 'th_TH' || goog.LOCALE == 'th-TH') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_th;
}
if (goog.LOCALE == 'tl') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_tl;
}
if (goog.LOCALE == 'tr') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_tr;
}
if (goog.LOCALE == 'tr_TR' || goog.LOCALE == 'tr-TR') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_tr;
}
if (goog.LOCALE == 'uk') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_uk;
}
if (goog.LOCALE == 'uk_UA' || goog.LOCALE == 'uk-UA') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_uk;
}
if (goog.LOCALE == 'ur') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_ur;
}
if (goog.LOCALE == 'ur_PK' || goog.LOCALE == 'ur-PK') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_ur;
}
if (goog.LOCALE == 'vi') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_vi;
}
if (goog.LOCALE == 'vi_VN' || goog.LOCALE == 'vi-VN') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_vi;
}
if (goog.LOCALE == 'zh') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_zh;
}
if (goog.LOCALE == 'zh_CN' || goog.LOCALE == 'zh-CN') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_zh;
}
if (goog.LOCALE == 'zh_HK' || goog.LOCALE == 'zh-HK') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_zh_HK;
}
if (goog.LOCALE == 'zh_Hans' || goog.LOCALE == 'zh-Hans') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_zh;
}
if (goog.LOCALE == 'zh_Hans_CN' || goog.LOCALE == 'zh-Hans-CN') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_zh;
}
if (goog.LOCALE == 'zh_TW' || goog.LOCALE == 'zh-TW') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_zh_TW;
}
if (goog.LOCALE == 'zu') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_zu;
}
if (goog.LOCALE == 'zu_ZA' || goog.LOCALE == 'zu-ZA') {
goog.i18n.NumberFormatSymbols = goog.i18n.NumberFormatSymbols_zu;
}
|
// Fine Uploader 5.11.7 - (c) 2013-present Widen Enterprises, Inc. MIT licensed. http://fineuploader.com
(function(global) {
var qq = function(element) {
"use strict";
return {
hide: function() {
element.style.display = "none";
return this;
},
attach: function(type, fn) {
if (element.addEventListener) {
element.addEventListener(type, fn, false);
} else if (element.attachEvent) {
element.attachEvent("on" + type, fn);
}
return function() {
qq(element).detach(type, fn);
};
},
detach: function(type, fn) {
if (element.removeEventListener) {
element.removeEventListener(type, fn, false);
} else if (element.attachEvent) {
element.detachEvent("on" + type, fn);
}
return this;
},
contains: function(descendant) {
if (!descendant) {
return false;
}
if (element === descendant) {
return true;
}
if (element.contains) {
return element.contains(descendant);
} else {
return !!(descendant.compareDocumentPosition(element) & 8);
}
},
insertBefore: function(elementB) {
elementB.parentNode.insertBefore(element, elementB);
return this;
},
remove: function() {
element.parentNode.removeChild(element);
return this;
},
css: function(styles) {
if (element.style == null) {
throw new qq.Error("Can't apply style to node as it is not on the HTMLElement prototype chain!");
}
if (styles.opacity != null) {
if (typeof element.style.opacity !== "string" && typeof element.filters !== "undefined") {
styles.filter = "alpha(opacity=" + Math.round(100 * styles.opacity) + ")";
}
}
qq.extend(element.style, styles);
return this;
},
hasClass: function(name, considerParent) {
var re = new RegExp("(^| )" + name + "( |$)");
return re.test(element.className) || !!(considerParent && re.test(element.parentNode.className));
},
addClass: function(name) {
if (!qq(element).hasClass(name)) {
element.className += " " + name;
}
return this;
},
removeClass: function(name) {
var re = new RegExp("(^| )" + name + "( |$)");
element.className = element.className.replace(re, " ").replace(/^\s+|\s+$/g, "");
return this;
},
getByClass: function(className, first) {
var candidates, result = [];
if (first && element.querySelector) {
return element.querySelector("." + className);
} else if (element.querySelectorAll) {
return element.querySelectorAll("." + className);
}
candidates = element.getElementsByTagName("*");
qq.each(candidates, function(idx, val) {
if (qq(val).hasClass(className)) {
result.push(val);
}
});
return first ? result[0] : result;
},
getFirstByClass: function(className) {
return qq(element).getByClass(className, true);
},
children: function() {
var children = [], child = element.firstChild;
while (child) {
if (child.nodeType === 1) {
children.push(child);
}
child = child.nextSibling;
}
return children;
},
setText: function(text) {
element.innerText = text;
element.textContent = text;
return this;
},
clearText: function() {
return qq(element).setText("");
},
hasAttribute: function(attrName) {
var attrVal;
if (element.hasAttribute) {
if (!element.hasAttribute(attrName)) {
return false;
}
return /^false$/i.exec(element.getAttribute(attrName)) == null;
} else {
attrVal = element[attrName];
if (attrVal === undefined) {
return false;
}
return /^false$/i.exec(attrVal) == null;
}
}
};
};
(function() {
"use strict";
qq.canvasToBlob = function(canvas, mime, quality) {
return qq.dataUriToBlob(canvas.toDataURL(mime, quality));
};
qq.dataUriToBlob = function(dataUri) {
var arrayBuffer, byteString, createBlob = function(data, mime) {
var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder, blobBuilder = BlobBuilder && new BlobBuilder();
if (blobBuilder) {
blobBuilder.append(data);
return blobBuilder.getBlob(mime);
} else {
return new Blob([ data ], {
type: mime
});
}
}, intArray, mimeString;
if (dataUri.split(",")[0].indexOf("base64") >= 0) {
byteString = atob(dataUri.split(",")[1]);
} else {
byteString = decodeURI(dataUri.split(",")[1]);
}
mimeString = dataUri.split(",")[0].split(":")[1].split(";")[0];
arrayBuffer = new ArrayBuffer(byteString.length);
intArray = new Uint8Array(arrayBuffer);
qq.each(byteString, function(idx, character) {
intArray[idx] = character.charCodeAt(0);
});
return createBlob(arrayBuffer, mimeString);
};
qq.log = function(message, level) {
if (window.console) {
if (!level || level === "info") {
window.console.log(message);
} else {
if (window.console[level]) {
window.console[level](message);
} else {
window.console.log("<" + level + "> " + message);
}
}
}
};
qq.isObject = function(variable) {
return variable && !variable.nodeType && Object.prototype.toString.call(variable) === "[object Object]";
};
qq.isFunction = function(variable) {
return typeof variable === "function";
};
qq.isArray = function(value) {
return Object.prototype.toString.call(value) === "[object Array]" || value && window.ArrayBuffer && value.buffer && value.buffer.constructor === ArrayBuffer;
};
qq.isItemList = function(maybeItemList) {
return Object.prototype.toString.call(maybeItemList) === "[object DataTransferItemList]";
};
qq.isNodeList = function(maybeNodeList) {
return Object.prototype.toString.call(maybeNodeList) === "[object NodeList]" || maybeNodeList.item && maybeNodeList.namedItem;
};
qq.isString = function(maybeString) {
return Object.prototype.toString.call(maybeString) === "[object String]";
};
qq.trimStr = function(string) {
if (String.prototype.trim) {
return string.trim();
}
return string.replace(/^\s+|\s+$/g, "");
};
qq.format = function(str) {
var args = Array.prototype.slice.call(arguments, 1), newStr = str, nextIdxToReplace = newStr.indexOf("{}");
qq.each(args, function(idx, val) {
var strBefore = newStr.substring(0, nextIdxToReplace), strAfter = newStr.substring(nextIdxToReplace + 2);
newStr = strBefore + val + strAfter;
nextIdxToReplace = newStr.indexOf("{}", nextIdxToReplace + val.length);
if (nextIdxToReplace < 0) {
return false;
}
});
return newStr;
};
qq.isFile = function(maybeFile) {
return window.File && Object.prototype.toString.call(maybeFile) === "[object File]";
};
qq.isFileList = function(maybeFileList) {
return window.FileList && Object.prototype.toString.call(maybeFileList) === "[object FileList]";
};
qq.isFileOrInput = function(maybeFileOrInput) {
return qq.isFile(maybeFileOrInput) || qq.isInput(maybeFileOrInput);
};
qq.isInput = function(maybeInput, notFile) {
var evaluateType = function(type) {
var normalizedType = type.toLowerCase();
if (notFile) {
return normalizedType !== "file";
}
return normalizedType === "file";
};
if (window.HTMLInputElement) {
if (Object.prototype.toString.call(maybeInput) === "[object HTMLInputElement]") {
if (maybeInput.type && evaluateType(maybeInput.type)) {
return true;
}
}
}
if (maybeInput.tagName) {
if (maybeInput.tagName.toLowerCase() === "input") {
if (maybeInput.type && evaluateType(maybeInput.type)) {
return true;
}
}
}
return false;
};
qq.isBlob = function(maybeBlob) {
if (window.Blob && Object.prototype.toString.call(maybeBlob) === "[object Blob]") {
return true;
}
};
qq.isXhrUploadSupported = function() {
var input = document.createElement("input");
input.type = "file";
return input.multiple !== undefined && typeof File !== "undefined" && typeof FormData !== "undefined" && typeof qq.createXhrInstance().upload !== "undefined";
};
qq.createXhrInstance = function() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
}
try {
return new ActiveXObject("MSXML2.XMLHTTP.3.0");
} catch (error) {
qq.log("Neither XHR or ActiveX are supported!", "error");
return null;
}
};
qq.isFolderDropSupported = function(dataTransfer) {
return dataTransfer.items && dataTransfer.items.length > 0 && dataTransfer.items[0].webkitGetAsEntry;
};
qq.isFileChunkingSupported = function() {
return !qq.androidStock() && qq.isXhrUploadSupported() && (File.prototype.slice !== undefined || File.prototype.webkitSlice !== undefined || File.prototype.mozSlice !== undefined);
};
qq.sliceBlob = function(fileOrBlob, start, end) {
var slicer = fileOrBlob.slice || fileOrBlob.mozSlice || fileOrBlob.webkitSlice;
return slicer.call(fileOrBlob, start, end);
};
qq.arrayBufferToHex = function(buffer) {
var bytesAsHex = "", bytes = new Uint8Array(buffer);
qq.each(bytes, function(idx, byt) {
var byteAsHexStr = byt.toString(16);
if (byteAsHexStr.length < 2) {
byteAsHexStr = "0" + byteAsHexStr;
}
bytesAsHex += byteAsHexStr;
});
return bytesAsHex;
};
qq.readBlobToHex = function(blob, startOffset, length) {
var initialBlob = qq.sliceBlob(blob, startOffset, startOffset + length), fileReader = new FileReader(), promise = new qq.Promise();
fileReader.onload = function() {
promise.success(qq.arrayBufferToHex(fileReader.result));
};
fileReader.onerror = promise.failure;
fileReader.readAsArrayBuffer(initialBlob);
return promise;
};
qq.extend = function(first, second, extendNested) {
qq.each(second, function(prop, val) {
if (extendNested && qq.isObject(val)) {
if (first[prop] === undefined) {
first[prop] = {};
}
qq.extend(first[prop], val, true);
} else {
first[prop] = val;
}
});
return first;
};
qq.override = function(target, sourceFn) {
var super_ = {}, source = sourceFn(super_);
qq.each(source, function(srcPropName, srcPropVal) {
if (target[srcPropName] !== undefined) {
super_[srcPropName] = target[srcPropName];
}
target[srcPropName] = srcPropVal;
});
return target;
};
qq.indexOf = function(arr, elt, from) {
if (arr.indexOf) {
return arr.indexOf(elt, from);
}
from = from || 0;
var len = arr.length;
if (from < 0) {
from += len;
}
for (;from < len; from += 1) {
if (arr.hasOwnProperty(from) && arr[from] === elt) {
return from;
}
}
return -1;
};
qq.getUniqueId = function() {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
return v.toString(16);
});
};
qq.ie = function() {
return navigator.userAgent.indexOf("MSIE") !== -1 || navigator.userAgent.indexOf("Trident") !== -1;
};
qq.ie7 = function() {
return navigator.userAgent.indexOf("MSIE 7") !== -1;
};
qq.ie8 = function() {
return navigator.userAgent.indexOf("MSIE 8") !== -1;
};
qq.ie10 = function() {
return navigator.userAgent.indexOf("MSIE 10") !== -1;
};
qq.ie11 = function() {
return qq.ie() && navigator.userAgent.indexOf("rv:11") !== -1;
};
qq.edge = function() {
return navigator.userAgent.indexOf("Edge") >= 0;
};
qq.safari = function() {
return navigator.vendor !== undefined && navigator.vendor.indexOf("Apple") !== -1;
};
qq.chrome = function() {
return navigator.vendor !== undefined && navigator.vendor.indexOf("Google") !== -1;
};
qq.opera = function() {
return navigator.vendor !== undefined && navigator.vendor.indexOf("Opera") !== -1;
};
qq.firefox = function() {
return !qq.edge() && !qq.ie11() && navigator.userAgent.indexOf("Mozilla") !== -1 && navigator.vendor !== undefined && navigator.vendor === "";
};
qq.windows = function() {
return navigator.platform === "Win32";
};
qq.android = function() {
return navigator.userAgent.toLowerCase().indexOf("android") !== -1;
};
qq.androidStock = function() {
return qq.android() && navigator.userAgent.toLowerCase().indexOf("chrome") < 0;
};
qq.ios6 = function() {
return qq.ios() && navigator.userAgent.indexOf(" OS 6_") !== -1;
};
qq.ios7 = function() {
return qq.ios() && navigator.userAgent.indexOf(" OS 7_") !== -1;
};
qq.ios8 = function() {
return qq.ios() && navigator.userAgent.indexOf(" OS 8_") !== -1;
};
qq.ios800 = function() {
return qq.ios() && navigator.userAgent.indexOf(" OS 8_0 ") !== -1;
};
qq.ios = function() {
return navigator.userAgent.indexOf("iPad") !== -1 || navigator.userAgent.indexOf("iPod") !== -1 || navigator.userAgent.indexOf("iPhone") !== -1;
};
qq.iosChrome = function() {
return qq.ios() && navigator.userAgent.indexOf("CriOS") !== -1;
};
qq.iosSafari = function() {
return qq.ios() && !qq.iosChrome() && navigator.userAgent.indexOf("Safari") !== -1;
};
qq.iosSafariWebView = function() {
return qq.ios() && !qq.iosChrome() && !qq.iosSafari();
};
qq.preventDefault = function(e) {
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
};
qq.toElement = function() {
var div = document.createElement("div");
return function(html) {
div.innerHTML = html;
var element = div.firstChild;
div.removeChild(element);
return element;
};
}();
qq.each = function(iterableItem, callback) {
var keyOrIndex, retVal;
if (iterableItem) {
if (window.Storage && iterableItem.constructor === window.Storage) {
for (keyOrIndex = 0; keyOrIndex < iterableItem.length; keyOrIndex++) {
retVal = callback(iterableItem.key(keyOrIndex), iterableItem.getItem(iterableItem.key(keyOrIndex)));
if (retVal === false) {
break;
}
}
} else if (qq.isArray(iterableItem) || qq.isItemList(iterableItem) || qq.isNodeList(iterableItem)) {
for (keyOrIndex = 0; keyOrIndex < iterableItem.length; keyOrIndex++) {
retVal = callback(keyOrIndex, iterableItem[keyOrIndex]);
if (retVal === false) {
break;
}
}
} else if (qq.isString(iterableItem)) {
for (keyOrIndex = 0; keyOrIndex < iterableItem.length; keyOrIndex++) {
retVal = callback(keyOrIndex, iterableItem.charAt(keyOrIndex));
if (retVal === false) {
break;
}
}
} else {
for (keyOrIndex in iterableItem) {
if (Object.prototype.hasOwnProperty.call(iterableItem, keyOrIndex)) {
retVal = callback(keyOrIndex, iterableItem[keyOrIndex]);
if (retVal === false) {
break;
}
}
}
}
}
};
qq.bind = function(oldFunc, context) {
if (qq.isFunction(oldFunc)) {
var args = Array.prototype.slice.call(arguments, 2);
return function() {
var newArgs = qq.extend([], args);
if (arguments.length) {
newArgs = newArgs.concat(Array.prototype.slice.call(arguments));
}
return oldFunc.apply(context, newArgs);
};
}
throw new Error("first parameter must be a function!");
};
qq.obj2url = function(obj, temp, prefixDone) {
var uristrings = [], prefix = "&", add = function(nextObj, i) {
var nextTemp = temp ? /\[\]$/.test(temp) ? temp : temp + "[" + i + "]" : i;
if (nextTemp !== "undefined" && i !== "undefined") {
uristrings.push(typeof nextObj === "object" ? qq.obj2url(nextObj, nextTemp, true) : Object.prototype.toString.call(nextObj) === "[object Function]" ? encodeURIComponent(nextTemp) + "=" + encodeURIComponent(nextObj()) : encodeURIComponent(nextTemp) + "=" + encodeURIComponent(nextObj));
}
};
if (!prefixDone && temp) {
prefix = /\?/.test(temp) ? /\?$/.test(temp) ? "" : "&" : "?";
uristrings.push(temp);
uristrings.push(qq.obj2url(obj));
} else if (Object.prototype.toString.call(obj) === "[object Array]" && typeof obj !== "undefined") {
qq.each(obj, function(idx, val) {
add(val, idx);
});
} else if (typeof obj !== "undefined" && obj !== null && typeof obj === "object") {
qq.each(obj, function(prop, val) {
add(val, prop);
});
} else {
uristrings.push(encodeURIComponent(temp) + "=" + encodeURIComponent(obj));
}
if (temp) {
return uristrings.join(prefix);
} else {
return uristrings.join(prefix).replace(/^&/, "").replace(/%20/g, "+");
}
};
qq.obj2FormData = function(obj, formData, arrayKeyName) {
if (!formData) {
formData = new FormData();
}
qq.each(obj, function(key, val) {
key = arrayKeyName ? arrayKeyName + "[" + key + "]" : key;
if (qq.isObject(val)) {
qq.obj2FormData(val, formData, key);
} else if (qq.isFunction(val)) {
formData.append(key, val());
} else {
formData.append(key, val);
}
});
return formData;
};
qq.obj2Inputs = function(obj, form) {
var input;
if (!form) {
form = document.createElement("form");
}
qq.obj2FormData(obj, {
append: function(key, val) {
input = document.createElement("input");
input.setAttribute("name", key);
input.setAttribute("value", val);
form.appendChild(input);
}
});
return form;
};
qq.parseJson = function(json) {
if (window.JSON && qq.isFunction(JSON.parse)) {
return JSON.parse(json);
} else {
return eval("(" + json + ")");
}
};
qq.getExtension = function(filename) {
var extIdx = filename.lastIndexOf(".") + 1;
if (extIdx > 0) {
return filename.substr(extIdx, filename.length - extIdx);
}
};
qq.getFilename = function(blobOrFileInput) {
if (qq.isInput(blobOrFileInput)) {
return blobOrFileInput.value.replace(/.*(\/|\\)/, "");
} else if (qq.isFile(blobOrFileInput)) {
if (blobOrFileInput.fileName !== null && blobOrFileInput.fileName !== undefined) {
return blobOrFileInput.fileName;
}
}
return blobOrFileInput.name;
};
qq.DisposeSupport = function() {
var disposers = [];
return {
dispose: function() {
var disposer;
do {
disposer = disposers.shift();
if (disposer) {
disposer();
}
} while (disposer);
},
attach: function() {
var args = arguments;
this.addDisposer(qq(args[0]).attach.apply(this, Array.prototype.slice.call(arguments, 1)));
},
addDisposer: function(disposeFunction) {
disposers.push(disposeFunction);
}
};
};
})();
(function() {
"use strict";
if (typeof define === "function" && define.amd) {
define(function() {
return qq;
});
} else if (typeof module !== "undefined" && module.exports) {
module.exports = qq;
} else {
global.qq = qq;
}
})();
(function() {
"use strict";
qq.Error = function(message) {
this.message = "[Fine Uploader " + qq.version + "] " + message;
};
qq.Error.prototype = new Error();
})();
qq.version = "5.11.7";
qq.supportedFeatures = function() {
"use strict";
var supportsUploading, supportsUploadingBlobs, supportsFileDrop, supportsAjaxFileUploading, supportsFolderDrop, supportsChunking, supportsResume, supportsUploadViaPaste, supportsUploadCors, supportsDeleteFileXdr, supportsDeleteFileCorsXhr, supportsDeleteFileCors, supportsFolderSelection, supportsImagePreviews, supportsUploadProgress;
function testSupportsFileInputElement() {
var supported = true, tempInput;
try {
tempInput = document.createElement("input");
tempInput.type = "file";
qq(tempInput).hide();
if (tempInput.disabled) {
supported = false;
}
} catch (ex) {
supported = false;
}
return supported;
}
function isChrome21OrHigher() {
return (qq.chrome() || qq.opera()) && navigator.userAgent.match(/Chrome\/[2][1-9]|Chrome\/[3-9][0-9]/) !== undefined;
}
function isChrome14OrHigher() {
return (qq.chrome() || qq.opera()) && navigator.userAgent.match(/Chrome\/[1][4-9]|Chrome\/[2-9][0-9]/) !== undefined;
}
function isCrossOriginXhrSupported() {
if (window.XMLHttpRequest) {
var xhr = qq.createXhrInstance();
return xhr.withCredentials !== undefined;
}
return false;
}
function isXdrSupported() {
return window.XDomainRequest !== undefined;
}
function isCrossOriginAjaxSupported() {
if (isCrossOriginXhrSupported()) {
return true;
}
return isXdrSupported();
}
function isFolderSelectionSupported() {
return document.createElement("input").webkitdirectory !== undefined;
}
function isLocalStorageSupported() {
try {
return !!window.localStorage && qq.isFunction(window.localStorage.setItem);
} catch (error) {
return false;
}
}
function isDragAndDropSupported() {
var span = document.createElement("span");
return ("draggable" in span || "ondragstart" in span && "ondrop" in span) && !qq.android() && !qq.ios();
}
supportsUploading = testSupportsFileInputElement();
supportsAjaxFileUploading = supportsUploading && qq.isXhrUploadSupported();
supportsUploadingBlobs = supportsAjaxFileUploading && !qq.androidStock();
supportsFileDrop = supportsAjaxFileUploading && isDragAndDropSupported();
supportsFolderDrop = supportsFileDrop && isChrome21OrHigher();
supportsChunking = supportsAjaxFileUploading && qq.isFileChunkingSupported();
supportsResume = supportsAjaxFileUploading && supportsChunking && isLocalStorageSupported();
supportsUploadViaPaste = supportsAjaxFileUploading && isChrome14OrHigher();
supportsUploadCors = supportsUploading && (window.postMessage !== undefined || supportsAjaxFileUploading);
supportsDeleteFileCorsXhr = isCrossOriginXhrSupported();
supportsDeleteFileXdr = isXdrSupported();
supportsDeleteFileCors = isCrossOriginAjaxSupported();
supportsFolderSelection = isFolderSelectionSupported();
supportsImagePreviews = supportsAjaxFileUploading && window.FileReader !== undefined;
supportsUploadProgress = function() {
if (supportsAjaxFileUploading) {
return !qq.androidStock() && !qq.iosChrome();
}
return false;
}();
return {
ajaxUploading: supportsAjaxFileUploading,
blobUploading: supportsUploadingBlobs,
canDetermineSize: supportsAjaxFileUploading,
chunking: supportsChunking,
deleteFileCors: supportsDeleteFileCors,
deleteFileCorsXdr: supportsDeleteFileXdr,
deleteFileCorsXhr: supportsDeleteFileCorsXhr,
dialogElement: !!window.HTMLDialogElement,
fileDrop: supportsFileDrop,
folderDrop: supportsFolderDrop,
folderSelection: supportsFolderSelection,
imagePreviews: supportsImagePreviews,
imageValidation: supportsImagePreviews,
itemSizeValidation: supportsAjaxFileUploading,
pause: supportsChunking,
progressBar: supportsUploadProgress,
resume: supportsResume,
scaling: supportsImagePreviews && supportsUploadingBlobs,
tiffPreviews: qq.safari(),
unlimitedScaledImageSize: !qq.ios(),
uploading: supportsUploading,
uploadCors: supportsUploadCors,
uploadCustomHeaders: supportsAjaxFileUploading,
uploadNonMultipart: supportsAjaxFileUploading,
uploadViaPaste: supportsUploadViaPaste
};
}();
qq.isGenericPromise = function(maybePromise) {
"use strict";
return !!(maybePromise && maybePromise.then && qq.isFunction(maybePromise.then));
};
qq.Promise = function() {
"use strict";
var successArgs, failureArgs, successCallbacks = [], failureCallbacks = [], doneCallbacks = [], state = 0;
qq.extend(this, {
then: function(onSuccess, onFailure) {
if (state === 0) {
if (onSuccess) {
successCallbacks.push(onSuccess);
}
if (onFailure) {
failureCallbacks.push(onFailure);
}
} else if (state === -1) {
onFailure && onFailure.apply(null, failureArgs);
} else if (onSuccess) {
onSuccess.apply(null, successArgs);
}
return this;
},
done: function(callback) {
if (state === 0) {
doneCallbacks.push(callback);
} else {
callback.apply(null, failureArgs === undefined ? successArgs : failureArgs);
}
return this;
},
success: function() {
state = 1;
successArgs = arguments;
if (successCallbacks.length) {
qq.each(successCallbacks, function(idx, callback) {
callback.apply(null, successArgs);
});
}
if (doneCallbacks.length) {
qq.each(doneCallbacks, function(idx, callback) {
callback.apply(null, successArgs);
});
}
return this;
},
failure: function() {
state = -1;
failureArgs = arguments;
if (failureCallbacks.length) {
qq.each(failureCallbacks, function(idx, callback) {
callback.apply(null, failureArgs);
});
}
if (doneCallbacks.length) {
qq.each(doneCallbacks, function(idx, callback) {
callback.apply(null, failureArgs);
});
}
return this;
}
});
};
qq.BlobProxy = function(referenceBlob, onCreate) {
"use strict";
qq.extend(this, {
referenceBlob: referenceBlob,
create: function() {
return onCreate(referenceBlob);
}
});
};
qq.UploadButton = function(o) {
"use strict";
var self = this, disposeSupport = new qq.DisposeSupport(), options = {
acceptFiles: null,
element: null,
focusClass: "qq-upload-button-focus",
folders: false,
hoverClass: "qq-upload-button-hover",
ios8BrowserCrashWorkaround: false,
multiple: false,
name: "qqfile",
onChange: function(input) {},
title: null
}, input, buttonId;
qq.extend(options, o);
buttonId = qq.getUniqueId();
function createInput() {
var input = document.createElement("input");
input.setAttribute(qq.UploadButton.BUTTON_ID_ATTR_NAME, buttonId);
input.setAttribute("title", options.title);
self.setMultiple(options.multiple, input);
if (options.folders && qq.supportedFeatures.folderSelection) {
input.setAttribute("webkitdirectory", "");
}
if (options.acceptFiles) {
input.setAttribute("accept", options.acceptFiles);
}
input.setAttribute("type", "file");
input.setAttribute("name", options.name);
qq(input).css({
position: "absolute",
right: 0,
top: 0,
fontFamily: "Arial",
fontSize: qq.ie() && !qq.ie8() ? "3500px" : "118px",
margin: 0,
padding: 0,
cursor: "pointer",
opacity: 0
});
!qq.ie7() && qq(input).css({
height: "100%"
});
options.element.appendChild(input);
disposeSupport.attach(input, "change", function() {
options.onChange(input);
});
disposeSupport.attach(input, "mouseover", function() {
qq(options.element).addClass(options.hoverClass);
});
disposeSupport.attach(input, "mouseout", function() {
qq(options.element).removeClass(options.hoverClass);
});
disposeSupport.attach(input, "focus", function() {
qq(options.element).addClass(options.focusClass);
});
disposeSupport.attach(input, "blur", function() {
qq(options.element).removeClass(options.focusClass);
});
return input;
}
qq(options.element).css({
position: "relative",
overflow: "hidden",
direction: "ltr"
});
qq.extend(this, {
getInput: function() {
return input;
},
getButtonId: function() {
return buttonId;
},
setMultiple: function(isMultiple, optInput) {
var input = optInput || this.getInput();
if (options.ios8BrowserCrashWorkaround && qq.ios8() && (qq.iosChrome() || qq.iosSafariWebView())) {
input.setAttribute("multiple", "");
} else {
if (isMultiple) {
input.setAttribute("multiple", "");
} else {
input.removeAttribute("multiple");
}
}
},
setAcceptFiles: function(acceptFiles) {
if (acceptFiles !== options.acceptFiles) {
input.setAttribute("accept", acceptFiles);
}
},
reset: function() {
if (input.parentNode) {
qq(input).remove();
}
qq(options.element).removeClass(options.focusClass);
input = null;
input = createInput();
}
});
input = createInput();
};
qq.UploadButton.BUTTON_ID_ATTR_NAME = "qq-button-id";
qq.UploadData = function(uploaderProxy) {
"use strict";
var data = [], byUuid = {}, byStatus = {}, byProxyGroupId = {}, byBatchId = {};
function getDataByIds(idOrIds) {
if (qq.isArray(idOrIds)) {
var entries = [];
qq.each(idOrIds, function(idx, id) {
entries.push(data[id]);
});
return entries;
}
return data[idOrIds];
}
function getDataByUuids(uuids) {
if (qq.isArray(uuids)) {
var entries = [];
qq.each(uuids, function(idx, uuid) {
entries.push(data[byUuid[uuid]]);
});
return entries;
}
return data[byUuid[uuids]];
}
function getDataByStatus(status) {
var statusResults = [], statuses = [].concat(status);
qq.each(statuses, function(index, statusEnum) {
var statusResultIndexes = byStatus[statusEnum];
if (statusResultIndexes !== undefined) {
qq.each(statusResultIndexes, function(i, dataIndex) {
statusResults.push(data[dataIndex]);
});
}
});
return statusResults;
}
qq.extend(this, {
addFile: function(spec) {
var status = spec.status || qq.status.SUBMITTING, id = data.push({
name: spec.name,
originalName: spec.name,
uuid: spec.uuid,
size: spec.size == null ? -1 : spec.size,
status: status
}) - 1;
if (spec.batchId) {
data[id].batchId = spec.batchId;
if (byBatchId[spec.batchId] === undefined) {
byBatchId[spec.batchId] = [];
}
byBatchId[spec.batchId].push(id);
}
if (spec.proxyGroupId) {
data[id].proxyGroupId = spec.proxyGroupId;
if (byProxyGroupId[spec.proxyGroupId] === undefined) {
byProxyGroupId[spec.proxyGroupId] = [];
}
byProxyGroupId[spec.proxyGroupId].push(id);
}
data[id].id = id;
byUuid[spec.uuid] = id;
if (byStatus[status] === undefined) {
byStatus[status] = [];
}
byStatus[status].push(id);
uploaderProxy.onStatusChange(id, null, status);
return id;
},
retrieve: function(optionalFilter) {
if (qq.isObject(optionalFilter) && data.length) {
if (optionalFilter.id !== undefined) {
return getDataByIds(optionalFilter.id);
} else if (optionalFilter.uuid !== undefined) {
return getDataByUuids(optionalFilter.uuid);
} else if (optionalFilter.status) {
return getDataByStatus(optionalFilter.status);
}
} else {
return qq.extend([], data, true);
}
},
reset: function() {
data = [];
byUuid = {};
byStatus = {};
byBatchId = {};
},
setStatus: function(id, newStatus) {
var oldStatus = data[id].status, byStatusOldStatusIndex = qq.indexOf(byStatus[oldStatus], id);
byStatus[oldStatus].splice(byStatusOldStatusIndex, 1);
data[id].status = newStatus;
if (byStatus[newStatus] === undefined) {
byStatus[newStatus] = [];
}
byStatus[newStatus].push(id);
uploaderProxy.onStatusChange(id, oldStatus, newStatus);
},
uuidChanged: function(id, newUuid) {
var oldUuid = data[id].uuid;
data[id].uuid = newUuid;
byUuid[newUuid] = id;
delete byUuid[oldUuid];
},
updateName: function(id, newName) {
data[id].name = newName;
},
updateSize: function(id, newSize) {
data[id].size = newSize;
},
setParentId: function(targetId, parentId) {
data[targetId].parentId = parentId;
},
getIdsInProxyGroup: function(id) {
var proxyGroupId = data[id].proxyGroupId;
if (proxyGroupId) {
return byProxyGroupId[proxyGroupId];
}
return [];
},
getIdsInBatch: function(id) {
var batchId = data[id].batchId;
return byBatchId[batchId];
}
});
};
qq.status = {
SUBMITTING: "submitting",
SUBMITTED: "submitted",
REJECTED: "rejected",
QUEUED: "queued",
CANCELED: "canceled",
PAUSED: "paused",
UPLOADING: "uploading",
UPLOAD_RETRYING: "retrying upload",
UPLOAD_SUCCESSFUL: "upload successful",
UPLOAD_FAILED: "upload failed",
DELETE_FAILED: "delete failed",
DELETING: "deleting",
DELETED: "deleted"
};
(function() {
"use strict";
qq.basePublicApi = {
addBlobs: function(blobDataOrArray, params, endpoint) {
this.addFiles(blobDataOrArray, params, endpoint);
},
addInitialFiles: function(cannedFileList) {
var self = this;
qq.each(cannedFileList, function(index, cannedFile) {
self._addCannedFile(cannedFile);
});
},
addFiles: function(data, params, endpoint) {
this._maybeHandleIos8SafariWorkaround();
var batchId = this._storedIds.length === 0 ? qq.getUniqueId() : this._currentBatchId, processBlob = qq.bind(function(blob) {
this._handleNewFile({
blob: blob,
name: this._options.blobs.defaultName
}, batchId, verifiedFiles);
}, this), processBlobData = qq.bind(function(blobData) {
this._handleNewFile(blobData, batchId, verifiedFiles);
}, this), processCanvas = qq.bind(function(canvas) {
var blob = qq.canvasToBlob(canvas);
this._handleNewFile({
blob: blob,
name: this._options.blobs.defaultName + ".png"
}, batchId, verifiedFiles);
}, this), processCanvasData = qq.bind(function(canvasData) {
var normalizedQuality = canvasData.quality && canvasData.quality / 100, blob = qq.canvasToBlob(canvasData.canvas, canvasData.type, normalizedQuality);
this._handleNewFile({
blob: blob,
name: canvasData.name
}, batchId, verifiedFiles);
}, this), processFileOrInput = qq.bind(function(fileOrInput) {
if (qq.isInput(fileOrInput) && qq.supportedFeatures.ajaxUploading) {
var files = Array.prototype.slice.call(fileOrInput.files), self = this;
qq.each(files, function(idx, file) {
self._handleNewFile(file, batchId, verifiedFiles);
});
} else {
this._handleNewFile(fileOrInput, batchId, verifiedFiles);
}
}, this), normalizeData = function() {
if (qq.isFileList(data)) {
data = Array.prototype.slice.call(data);
}
data = [].concat(data);
}, self = this, verifiedFiles = [];
this._currentBatchId = batchId;
if (data) {
normalizeData();
qq.each(data, function(idx, fileContainer) {
if (qq.isFileOrInput(fileContainer)) {
processFileOrInput(fileContainer);
} else if (qq.isBlob(fileContainer)) {
processBlob(fileContainer);
} else if (qq.isObject(fileContainer)) {
if (fileContainer.blob && fileContainer.name) {
processBlobData(fileContainer);
} else if (fileContainer.canvas && fileContainer.name) {
processCanvasData(fileContainer);
}
} else if (fileContainer.tagName && fileContainer.tagName.toLowerCase() === "canvas") {
processCanvas(fileContainer);
} else {
self.log(fileContainer + " is not a valid file container! Ignoring!", "warn");
}
});
this.log("Received " + verifiedFiles.length + " files.");
this._prepareItemsForUpload(verifiedFiles, params, endpoint);
}
},
cancel: function(id) {
this._handler.cancel(id);
},
cancelAll: function() {
var storedIdsCopy = [], self = this;
qq.extend(storedIdsCopy, this._storedIds);
qq.each(storedIdsCopy, function(idx, storedFileId) {
self.cancel(storedFileId);
});
this._handler.cancelAll();
},
clearStoredFiles: function() {
this._storedIds = [];
},
continueUpload: function(id) {
var uploadData = this._uploadData.retrieve({
id: id
});
if (!qq.supportedFeatures.pause || !this._options.chunking.enabled) {
return false;
}
if (uploadData.status === qq.status.PAUSED) {
this.log(qq.format("Paused file ID {} ({}) will be continued. Not paused.", id, this.getName(id)));
this._uploadFile(id);
return true;
} else {
this.log(qq.format("Ignoring continue for file ID {} ({}). Not paused.", id, this.getName(id)), "error");
}
return false;
},
deleteFile: function(id) {
return this._onSubmitDelete(id);
},
doesExist: function(fileOrBlobId) {
return this._handler.isValid(fileOrBlobId);
},
drawThumbnail: function(fileId, imgOrCanvas, maxSize, fromServer, customResizeFunction) {
var promiseToReturn = new qq.Promise(), fileOrUrl, options;
if (this._imageGenerator) {
fileOrUrl = this._thumbnailUrls[fileId];
options = {
customResizeFunction: customResizeFunction,
maxSize: maxSize > 0 ? maxSize : null,
scale: maxSize > 0
};
if (!fromServer && qq.supportedFeatures.imagePreviews) {
fileOrUrl = this.getFile(fileId);
}
if (fileOrUrl == null) {
promiseToReturn.failure({
container: imgOrCanvas,
error: "File or URL not found."
});
} else {
this._imageGenerator.generate(fileOrUrl, imgOrCanvas, options).then(function success(modifiedContainer) {
promiseToReturn.success(modifiedContainer);
}, function failure(container, reason) {
promiseToReturn.failure({
container: container,
error: reason || "Problem generating thumbnail"
});
});
}
} else {
promiseToReturn.failure({
container: imgOrCanvas,
error: "Missing image generator module"
});
}
return promiseToReturn;
},
getButton: function(fileId) {
return this._getButton(this._buttonIdsForFileIds[fileId]);
},
getEndpoint: function(fileId) {
return this._endpointStore.get(fileId);
},
getFile: function(fileOrBlobId) {
return this._handler.getFile(fileOrBlobId) || null;
},
getInProgress: function() {
return this._uploadData.retrieve({
status: [ qq.status.UPLOADING, qq.status.UPLOAD_RETRYING, qq.status.QUEUED ]
}).length;
},
getName: function(id) {
return this._uploadData.retrieve({
id: id
}).name;
},
getParentId: function(id) {
var uploadDataEntry = this.getUploads({
id: id
}), parentId = null;
if (uploadDataEntry) {
if (uploadDataEntry.parentId !== undefined) {
parentId = uploadDataEntry.parentId;
}
}
return parentId;
},
getResumableFilesData: function() {
return this._handler.getResumableFilesData();
},
getSize: function(id) {
return this._uploadData.retrieve({
id: id
}).size;
},
getNetUploads: function() {
return this._netUploaded;
},
getRemainingAllowedItems: function() {
var allowedItems = this._currentItemLimit;
if (allowedItems > 0) {
return allowedItems - this._netUploadedOrQueued;
}
return null;
},
getUploads: function(optionalFilter) {
return this._uploadData.retrieve(optionalFilter);
},
getUuid: function(id) {
return this._uploadData.retrieve({
id: id
}).uuid;
},
log: function(str, level) {
if (this._options.debug && (!level || level === "info")) {
qq.log("[Fine Uploader " + qq.version + "] " + str);
} else if (level && level !== "info") {
qq.log("[Fine Uploader " + qq.version + "] " + str, level);
}
},
pauseUpload: function(id) {
var uploadData = this._uploadData.retrieve({
id: id
});
if (!qq.supportedFeatures.pause || !this._options.chunking.enabled) {
return false;
}
if (qq.indexOf([ qq.status.UPLOADING, qq.status.UPLOAD_RETRYING ], uploadData.status) >= 0) {
if (this._handler.pause(id)) {
this._uploadData.setStatus(id, qq.status.PAUSED);
return true;
} else {
this.log(qq.format("Unable to pause file ID {} ({}).", id, this.getName(id)), "error");
}
} else {
this.log(qq.format("Ignoring pause for file ID {} ({}). Not in progress.", id, this.getName(id)), "error");
}
return false;
},
reset: function() {
this.log("Resetting uploader...");
this._handler.reset();
this._storedIds = [];
this._autoRetries = [];
this._retryTimeouts = [];
this._preventRetries = [];
this._thumbnailUrls = [];
qq.each(this._buttons, function(idx, button) {
button.reset();
});
this._paramsStore.reset();
this._endpointStore.reset();
this._netUploadedOrQueued = 0;
this._netUploaded = 0;
this._uploadData.reset();
this._buttonIdsForFileIds = [];
this._pasteHandler && this._pasteHandler.reset();
this._options.session.refreshOnReset && this._refreshSessionData();
this._succeededSinceLastAllComplete = [];
this._failedSinceLastAllComplete = [];
this._totalProgress && this._totalProgress.reset();
},
retry: function(id) {
return this._manualRetry(id);
},
scaleImage: function(id, specs) {
var self = this;
return qq.Scaler.prototype.scaleImage(id, specs, {
log: qq.bind(self.log, self),
getFile: qq.bind(self.getFile, self),
uploadData: self._uploadData
});
},
setCustomHeaders: function(headers, id) {
this._customHeadersStore.set(headers, id);
},
setDeleteFileCustomHeaders: function(headers, id) {
this._deleteFileCustomHeadersStore.set(headers, id);
},
setDeleteFileEndpoint: function(endpoint, id) {
this._deleteFileEndpointStore.set(endpoint, id);
},
setDeleteFileParams: function(params, id) {
this._deleteFileParamsStore.set(params, id);
},
setEndpoint: function(endpoint, id) {
this._endpointStore.set(endpoint, id);
},
setForm: function(elementOrId) {
this._updateFormSupportAndParams(elementOrId);
},
setItemLimit: function(newItemLimit) {
this._currentItemLimit = newItemLimit;
},
setName: function(id, newName) {
this._uploadData.updateName(id, newName);
},
setParams: function(params, id) {
this._paramsStore.set(params, id);
},
setUuid: function(id, newUuid) {
return this._uploadData.uuidChanged(id, newUuid);
},
uploadStoredFiles: function() {
if (this._storedIds.length === 0) {
this._itemError("noFilesError");
} else {
this._uploadStoredFiles();
}
}
};
qq.basePrivateApi = {
_addCannedFile: function(sessionData) {
var id = this._uploadData.addFile({
uuid: sessionData.uuid,
name: sessionData.name,
size: sessionData.size,
status: qq.status.UPLOAD_SUCCESSFUL
});
sessionData.deleteFileEndpoint && this.setDeleteFileEndpoint(sessionData.deleteFileEndpoint, id);
sessionData.deleteFileParams && this.setDeleteFileParams(sessionData.deleteFileParams, id);
if (sessionData.thumbnailUrl) {
this._thumbnailUrls[id] = sessionData.thumbnailUrl;
}
this._netUploaded++;
this._netUploadedOrQueued++;
return id;
},
_annotateWithButtonId: function(file, associatedInput) {
if (qq.isFile(file)) {
file.qqButtonId = this._getButtonId(associatedInput);
}
},
_batchError: function(message) {
this._options.callbacks.onError(null, null, message, undefined);
},
_createDeleteHandler: function() {
var self = this;
return new qq.DeleteFileAjaxRequester({
method: this._options.deleteFile.method.toUpperCase(),
maxConnections: this._options.maxConnections,
uuidParamName: this._options.request.uuidName,
customHeaders: this._deleteFileCustomHeadersStore,
paramsStore: this._deleteFileParamsStore,
endpointStore: this._deleteFileEndpointStore,
cors: this._options.cors,
log: qq.bind(self.log, self),
onDelete: function(id) {
self._onDelete(id);
self._options.callbacks.onDelete(id);
},
onDeleteComplete: function(id, xhrOrXdr, isError) {
self._onDeleteComplete(id, xhrOrXdr, isError);
self._options.callbacks.onDeleteComplete(id, xhrOrXdr, isError);
}
});
},
_createPasteHandler: function() {
var self = this;
return new qq.PasteSupport({
targetElement: this._options.paste.targetElement,
callbacks: {
log: qq.bind(self.log, self),
pasteReceived: function(blob) {
self._handleCheckedCallback({
name: "onPasteReceived",
callback: qq.bind(self._options.callbacks.onPasteReceived, self, blob),
onSuccess: qq.bind(self._handlePasteSuccess, self, blob),
identifier: "pasted image"
});
}
}
});
},
_createStore: function(initialValue, _readOnlyValues_) {
var store = {}, catchall = initialValue, perIdReadOnlyValues = {}, readOnlyValues = _readOnlyValues_, copy = function(orig) {
if (qq.isObject(orig)) {
return qq.extend({}, orig);
}
return orig;
}, getReadOnlyValues = function() {
if (qq.isFunction(readOnlyValues)) {
return readOnlyValues();
}
return readOnlyValues;
}, includeReadOnlyValues = function(id, existing) {
if (readOnlyValues && qq.isObject(existing)) {
qq.extend(existing, getReadOnlyValues());
}
if (perIdReadOnlyValues[id]) {
qq.extend(existing, perIdReadOnlyValues[id]);
}
};
return {
set: function(val, id) {
if (id == null) {
store = {};
catchall = copy(val);
} else {
store[id] = copy(val);
}
},
get: function(id) {
var values;
if (id != null && store[id]) {
values = store[id];
} else {
values = copy(catchall);
}
includeReadOnlyValues(id, values);
return copy(values);
},
addReadOnly: function(id, values) {
if (qq.isObject(store)) {
if (id === null) {
if (qq.isFunction(values)) {
readOnlyValues = values;
} else {
readOnlyValues = readOnlyValues || {};
qq.extend(readOnlyValues, values);
}
} else {
perIdReadOnlyValues[id] = perIdReadOnlyValues[id] || {};
qq.extend(perIdReadOnlyValues[id], values);
}
}
},
remove: function(fileId) {
return delete store[fileId];
},
reset: function() {
store = {};
perIdReadOnlyValues = {};
catchall = initialValue;
}
};
},
_createUploadDataTracker: function() {
var self = this;
return new qq.UploadData({
getName: function(id) {
return self.getName(id);
},
getUuid: function(id) {
return self.getUuid(id);
},
getSize: function(id) {
return self.getSize(id);
},
onStatusChange: function(id, oldStatus, newStatus) {
self._onUploadStatusChange(id, oldStatus, newStatus);
self._options.callbacks.onStatusChange(id, oldStatus, newStatus);
self._maybeAllComplete(id, newStatus);
if (self._totalProgress) {
setTimeout(function() {
self._totalProgress.onStatusChange(id, oldStatus, newStatus);
}, 0);
}
}
});
},
_createUploadButton: function(spec) {
var self = this, acceptFiles = spec.accept || this._options.validation.acceptFiles, allowedExtensions = spec.allowedExtensions || this._options.validation.allowedExtensions, button;
function allowMultiple() {
if (qq.supportedFeatures.ajaxUploading) {
if (self._options.workarounds.iosEmptyVideos && qq.ios() && !qq.ios6() && self._isAllowedExtension(allowedExtensions, ".mov")) {
return false;
}
if (spec.multiple === undefined) {
return self._options.multiple;
}
return spec.multiple;
}
return false;
}
button = new qq.UploadButton({
acceptFiles: acceptFiles,
element: spec.element,
focusClass: this._options.classes.buttonFocus,
folders: spec.folders,
hoverClass: this._options.classes.buttonHover,
ios8BrowserCrashWorkaround: this._options.workarounds.ios8BrowserCrash,
multiple: allowMultiple(),
name: this._options.request.inputName,
onChange: function(input) {
self._onInputChange(input);
},
title: spec.title == null ? this._options.text.fileInputTitle : spec.title
});
this._disposeSupport.addDisposer(function() {
button.dispose();
});
self._buttons.push(button);
return button;
},
_createUploadHandler: function(additionalOptions, namespace) {
var self = this, lastOnProgress = {}, options = {
debug: this._options.debug,
maxConnections: this._options.maxConnections,
cors: this._options.cors,
paramsStore: this._paramsStore,
endpointStore: this._endpointStore,
chunking: this._options.chunking,
resume: this._options.resume,
blobs: this._options.blobs,
log: qq.bind(self.log, self),
preventRetryParam: this._options.retry.preventRetryResponseProperty,
onProgress: function(id, name, loaded, total) {
if (loaded < 0 || total < 0) {
return;
}
if (lastOnProgress[id]) {
if (lastOnProgress[id].loaded !== loaded || lastOnProgress[id].total !== total) {
self._onProgress(id, name, loaded, total);
self._options.callbacks.onProgress(id, name, loaded, total);
}
} else {
self._onProgress(id, name, loaded, total);
self._options.callbacks.onProgress(id, name, loaded, total);
}
lastOnProgress[id] = {
loaded: loaded,
total: total
};
},
onComplete: function(id, name, result, xhr) {
delete lastOnProgress[id];
var status = self.getUploads({
id: id
}).status, retVal;
if (status === qq.status.UPLOAD_SUCCESSFUL || status === qq.status.UPLOAD_FAILED) {
return;
}
retVal = self._onComplete(id, name, result, xhr);
if (retVal instanceof qq.Promise) {
retVal.done(function() {
self._options.callbacks.onComplete(id, name, result, xhr);
});
} else {
self._options.callbacks.onComplete(id, name, result, xhr);
}
},
onCancel: function(id, name, cancelFinalizationEffort) {
var promise = new qq.Promise();
self._handleCheckedCallback({
name: "onCancel",
callback: qq.bind(self._options.callbacks.onCancel, self, id, name),
onFailure: promise.failure,
onSuccess: function() {
cancelFinalizationEffort.then(function() {
self._onCancel(id, name);
});
promise.success();
},
identifier: id
});
return promise;
},
onUploadPrep: qq.bind(this._onUploadPrep, this),
onUpload: function(id, name) {
self._onUpload(id, name);
self._options.callbacks.onUpload(id, name);
},
onUploadChunk: function(id, name, chunkData) {
self._onUploadChunk(id, chunkData);
self._options.callbacks.onUploadChunk(id, name, chunkData);
},
onUploadChunkSuccess: function(id, chunkData, result, xhr) {
self._options.callbacks.onUploadChunkSuccess.apply(self, arguments);
},
onResume: function(id, name, chunkData) {
return self._options.callbacks.onResume(id, name, chunkData);
},
onAutoRetry: function(id, name, responseJSON, xhr) {
return self._onAutoRetry.apply(self, arguments);
},
onUuidChanged: function(id, newUuid) {
self.log("Server requested UUID change from '" + self.getUuid(id) + "' to '" + newUuid + "'");
self.setUuid(id, newUuid);
},
getName: qq.bind(self.getName, self),
getUuid: qq.bind(self.getUuid, self),
getSize: qq.bind(self.getSize, self),
setSize: qq.bind(self._setSize, self),
getDataByUuid: function(uuid) {
return self.getUploads({
uuid: uuid
});
},
isQueued: function(id) {
var status = self.getUploads({
id: id
}).status;
return status === qq.status.QUEUED || status === qq.status.SUBMITTED || status === qq.status.UPLOAD_RETRYING || status === qq.status.PAUSED;
},
getIdsInProxyGroup: self._uploadData.getIdsInProxyGroup,
getIdsInBatch: self._uploadData.getIdsInBatch
};
qq.each(this._options.request, function(prop, val) {
options[prop] = val;
});
options.customHeaders = this._customHeadersStore;
if (additionalOptions) {
qq.each(additionalOptions, function(key, val) {
options[key] = val;
});
}
return new qq.UploadHandlerController(options, namespace);
},
_fileOrBlobRejected: function(id) {
this._netUploadedOrQueued--;
this._uploadData.setStatus(id, qq.status.REJECTED);
},
_formatSize: function(bytes) {
var i = -1;
do {
bytes = bytes / 1e3;
i++;
} while (bytes > 999);
return Math.max(bytes, .1).toFixed(1) + this._options.text.sizeSymbols[i];
},
_generateExtraButtonSpecs: function() {
var self = this;
this._extraButtonSpecs = {};
qq.each(this._options.extraButtons, function(idx, extraButtonOptionEntry) {
var multiple = extraButtonOptionEntry.multiple, validation = qq.extend({}, self._options.validation, true), extraButtonSpec = qq.extend({}, extraButtonOptionEntry);
if (multiple === undefined) {
multiple = self._options.multiple;
}
if (extraButtonSpec.validation) {
qq.extend(validation, extraButtonOptionEntry.validation, true);
}
qq.extend(extraButtonSpec, {
multiple: multiple,
validation: validation
}, true);
self._initExtraButton(extraButtonSpec);
});
},
_getButton: function(buttonId) {
var extraButtonsSpec = this._extraButtonSpecs[buttonId];
if (extraButtonsSpec) {
return extraButtonsSpec.element;
} else if (buttonId === this._defaultButtonId) {
return this._options.button;
}
},
_getButtonId: function(buttonOrFileInputOrFile) {
var inputs, fileInput, fileBlobOrInput = buttonOrFileInputOrFile;
if (fileBlobOrInput instanceof qq.BlobProxy) {
fileBlobOrInput = fileBlobOrInput.referenceBlob;
}
if (fileBlobOrInput && !qq.isBlob(fileBlobOrInput)) {
if (qq.isFile(fileBlobOrInput)) {
return fileBlobOrInput.qqButtonId;
} else if (fileBlobOrInput.tagName.toLowerCase() === "input" && fileBlobOrInput.type.toLowerCase() === "file") {
return fileBlobOrInput.getAttribute(qq.UploadButton.BUTTON_ID_ATTR_NAME);
}
inputs = fileBlobOrInput.getElementsByTagName("input");
qq.each(inputs, function(idx, input) {
if (input.getAttribute("type") === "file") {
fileInput = input;
return false;
}
});
if (fileInput) {
return fileInput.getAttribute(qq.UploadButton.BUTTON_ID_ATTR_NAME);
}
}
},
_getNotFinished: function() {
return this._uploadData.retrieve({
status: [ qq.status.UPLOADING, qq.status.UPLOAD_RETRYING, qq.status.QUEUED, qq.status.SUBMITTING, qq.status.SUBMITTED, qq.status.PAUSED ]
}).length;
},
_getValidationBase: function(buttonId) {
var extraButtonSpec = this._extraButtonSpecs[buttonId];
return extraButtonSpec ? extraButtonSpec.validation : this._options.validation;
},
_getValidationDescriptor: function(fileWrapper) {
if (fileWrapper.file instanceof qq.BlobProxy) {
return {
name: qq.getFilename(fileWrapper.file.referenceBlob),
size: fileWrapper.file.referenceBlob.size
};
}
return {
name: this.getUploads({
id: fileWrapper.id
}).name,
size: this.getUploads({
id: fileWrapper.id
}).size
};
},
_getValidationDescriptors: function(fileWrappers) {
var self = this, fileDescriptors = [];
qq.each(fileWrappers, function(idx, fileWrapper) {
fileDescriptors.push(self._getValidationDescriptor(fileWrapper));
});
return fileDescriptors;
},
_handleCameraAccess: function() {
if (this._options.camera.ios && qq.ios()) {
var acceptIosCamera = "image/*;capture=camera", button = this._options.camera.button, buttonId = button ? this._getButtonId(button) : this._defaultButtonId, optionRoot = this._options;
if (buttonId && buttonId !== this._defaultButtonId) {
optionRoot = this._extraButtonSpecs[buttonId];
}
optionRoot.multiple = false;
if (optionRoot.validation.acceptFiles === null) {
optionRoot.validation.acceptFiles = acceptIosCamera;
} else {
optionRoot.validation.acceptFiles += "," + acceptIosCamera;
}
qq.each(this._buttons, function(idx, button) {
if (button.getButtonId() === buttonId) {
button.setMultiple(optionRoot.multiple);
button.setAcceptFiles(optionRoot.acceptFiles);
return false;
}
});
}
},
_handleCheckedCallback: function(details) {
var self = this, callbackRetVal = details.callback();
if (qq.isGenericPromise(callbackRetVal)) {
this.log(details.name + " - waiting for " + details.name + " promise to be fulfilled for " + details.identifier);
return callbackRetVal.then(function(successParam) {
self.log(details.name + " promise success for " + details.identifier);
details.onSuccess(successParam);
}, function() {
if (details.onFailure) {
self.log(details.name + " promise failure for " + details.identifier);
details.onFailure();
} else {
self.log(details.name + " promise failure for " + details.identifier);
}
});
}
if (callbackRetVal !== false) {
details.onSuccess(callbackRetVal);
} else {
if (details.onFailure) {
this.log(details.name + " - return value was 'false' for " + details.identifier + ". Invoking failure callback.");
details.onFailure();
} else {
this.log(details.name + " - return value was 'false' for " + details.identifier + ". Will not proceed.");
}
}
return callbackRetVal;
},
_handleNewFile: function(file, batchId, newFileWrapperList) {
var self = this, uuid = qq.getUniqueId(), size = -1, name = qq.getFilename(file), actualFile = file.blob || file, handler = this._customNewFileHandler ? this._customNewFileHandler : qq.bind(self._handleNewFileGeneric, self);
if (!qq.isInput(actualFile) && actualFile.size >= 0) {
size = actualFile.size;
}
handler(actualFile, name, uuid, size, newFileWrapperList, batchId, this._options.request.uuidName, {
uploadData: self._uploadData,
paramsStore: self._paramsStore,
addFileToHandler: function(id, file) {
self._handler.add(id, file);
self._netUploadedOrQueued++;
self._trackButton(id);
}
});
},
_handleNewFileGeneric: function(file, name, uuid, size, fileList, batchId) {
var id = this._uploadData.addFile({
uuid: uuid,
name: name,
size: size,
batchId: batchId
});
this._handler.add(id, file);
this._trackButton(id);
this._netUploadedOrQueued++;
fileList.push({
id: id,
file: file
});
},
_handlePasteSuccess: function(blob, extSuppliedName) {
var extension = blob.type.split("/")[1], name = extSuppliedName;
if (name == null) {
name = this._options.paste.defaultName;
}
name += "." + extension;
this.addFiles({
name: name,
blob: blob
});
},
_initExtraButton: function(spec) {
var button = this._createUploadButton({
accept: spec.validation.acceptFiles,
allowedExtensions: spec.validation.allowedExtensions,
element: spec.element,
folders: spec.folders,
multiple: spec.multiple,
title: spec.fileInputTitle
});
this._extraButtonSpecs[button.getButtonId()] = spec;
},
_initFormSupportAndParams: function() {
this._formSupport = qq.FormSupport && new qq.FormSupport(this._options.form, qq.bind(this.uploadStoredFiles, this), qq.bind(this.log, this));
if (this._formSupport && this._formSupport.attachedToForm) {
this._paramsStore = this._createStore(this._options.request.params, this._formSupport.getFormInputsAsObject);
this._options.autoUpload = this._formSupport.newAutoUpload;
if (this._formSupport.newEndpoint) {
this._options.request.endpoint = this._formSupport.newEndpoint;
}
} else {
this._paramsStore = this._createStore(this._options.request.params);
}
},
_isDeletePossible: function() {
if (!qq.DeleteFileAjaxRequester || !this._options.deleteFile.enabled) {
return false;
}
if (this._options.cors.expected) {
if (qq.supportedFeatures.deleteFileCorsXhr) {
return true;
}
if (qq.supportedFeatures.deleteFileCorsXdr && this._options.cors.allowXdr) {
return true;
}
return false;
}
return true;
},
_isAllowedExtension: function(allowed, fileName) {
var valid = false;
if (!allowed.length) {
return true;
}
qq.each(allowed, function(idx, allowedExt) {
if (qq.isString(allowedExt)) {
var extRegex = new RegExp("\\." + allowedExt + "$", "i");
if (fileName.match(extRegex) != null) {
valid = true;
return false;
}
}
});
return valid;
},
_itemError: function(code, maybeNameOrNames, item) {
var message = this._options.messages[code], allowedExtensions = [], names = [].concat(maybeNameOrNames), name = names[0], buttonId = this._getButtonId(item), validationBase = this._getValidationBase(buttonId), extensionsForMessage, placeholderMatch;
function r(name, replacement) {
message = message.replace(name, replacement);
}
qq.each(validationBase.allowedExtensions, function(idx, allowedExtension) {
if (qq.isString(allowedExtension)) {
allowedExtensions.push(allowedExtension);
}
});
extensionsForMessage = allowedExtensions.join(", ").toLowerCase();
r("{file}", this._options.formatFileName(name));
r("{extensions}", extensionsForMessage);
r("{sizeLimit}", this._formatSize(validationBase.sizeLimit));
r("{minSizeLimit}", this._formatSize(validationBase.minSizeLimit));
placeholderMatch = message.match(/(\{\w+\})/g);
if (placeholderMatch !== null) {
qq.each(placeholderMatch, function(idx, placeholder) {
r(placeholder, names[idx]);
});
}
this._options.callbacks.onError(null, name, message, undefined);
return message;
},
_manualRetry: function(id, callback) {
if (this._onBeforeManualRetry(id)) {
this._netUploadedOrQueued++;
this._uploadData.setStatus(id, qq.status.UPLOAD_RETRYING);
if (callback) {
callback(id);
} else {
this._handler.retry(id);
}
return true;
}
},
_maybeAllComplete: function(id, status) {
var self = this, notFinished = this._getNotFinished();
if (status === qq.status.UPLOAD_SUCCESSFUL) {
this._succeededSinceLastAllComplete.push(id);
} else if (status === qq.status.UPLOAD_FAILED) {
this._failedSinceLastAllComplete.push(id);
}
if (notFinished === 0 && (this._succeededSinceLastAllComplete.length || this._failedSinceLastAllComplete.length)) {
setTimeout(function() {
self._onAllComplete(self._succeededSinceLastAllComplete, self._failedSinceLastAllComplete);
}, 0);
}
},
_maybeHandleIos8SafariWorkaround: function() {
var self = this;
if (this._options.workarounds.ios8SafariUploads && qq.ios800() && qq.iosSafari()) {
setTimeout(function() {
window.alert(self._options.messages.unsupportedBrowserIos8Safari);
}, 0);
throw new qq.Error(this._options.messages.unsupportedBrowserIos8Safari);
}
},
_maybeParseAndSendUploadError: function(id, name, response, xhr) {
if (!response.success) {
if (xhr && xhr.status !== 200 && !response.error) {
this._options.callbacks.onError(id, name, "XHR returned response code " + xhr.status, xhr);
} else {
var errorReason = response.error ? response.error : this._options.text.defaultResponseError;
this._options.callbacks.onError(id, name, errorReason, xhr);
}
}
},
_maybeProcessNextItemAfterOnValidateCallback: function(validItem, items, index, params, endpoint) {
var self = this;
if (items.length > index) {
if (validItem || !this._options.validation.stopOnFirstInvalidFile) {
setTimeout(function() {
var validationDescriptor = self._getValidationDescriptor(items[index]), buttonId = self._getButtonId(items[index].file), button = self._getButton(buttonId);
self._handleCheckedCallback({
name: "onValidate",
callback: qq.bind(self._options.callbacks.onValidate, self, validationDescriptor, button),
onSuccess: qq.bind(self._onValidateCallbackSuccess, self, items, index, params, endpoint),
onFailure: qq.bind(self._onValidateCallbackFailure, self, items, index, params, endpoint),
identifier: "Item '" + validationDescriptor.name + "', size: " + validationDescriptor.size
});
}, 0);
} else if (!validItem) {
for (;index < items.length; index++) {
self._fileOrBlobRejected(items[index].id);
}
}
}
},
_onAllComplete: function(successful, failed) {
this._totalProgress && this._totalProgress.onAllComplete(successful, failed, this._preventRetries);
this._options.callbacks.onAllComplete(qq.extend([], successful), qq.extend([], failed));
this._succeededSinceLastAllComplete = [];
this._failedSinceLastAllComplete = [];
},
_onAutoRetry: function(id, name, responseJSON, xhr, callback) {
var self = this;
self._preventRetries[id] = responseJSON[self._options.retry.preventRetryResponseProperty];
if (self._shouldAutoRetry(id, name, responseJSON)) {
self._maybeParseAndSendUploadError.apply(self, arguments);
self._options.callbacks.onAutoRetry(id, name, self._autoRetries[id]);
self._onBeforeAutoRetry(id, name);
self._retryTimeouts[id] = setTimeout(function() {
self.log("Retrying " + name + "...");
self._uploadData.setStatus(id, qq.status.UPLOAD_RETRYING);
if (callback) {
callback(id);
} else {
self._handler.retry(id);
}
}, self._options.retry.autoAttemptDelay * 1e3);
return true;
}
},
_onBeforeAutoRetry: function(id, name) {
this.log("Waiting " + this._options.retry.autoAttemptDelay + " seconds before retrying " + name + "...");
},
_onBeforeManualRetry: function(id) {
var itemLimit = this._currentItemLimit, fileName;
if (this._preventRetries[id]) {
this.log("Retries are forbidden for id " + id, "warn");
return false;
} else if (this._handler.isValid(id)) {
fileName = this.getName(id);
if (this._options.callbacks.onManualRetry(id, fileName) === false) {
return false;
}
if (itemLimit > 0 && this._netUploadedOrQueued + 1 > itemLimit) {
this._itemError("retryFailTooManyItems");
return false;
}
this.log("Retrying upload for '" + fileName + "' (id: " + id + ")...");
return true;
} else {
this.log("'" + id + "' is not a valid file ID", "error");
return false;
}
},
_onCancel: function(id, name) {
this._netUploadedOrQueued--;
clearTimeout(this._retryTimeouts[id]);
var storedItemIndex = qq.indexOf(this._storedIds, id);
if (!this._options.autoUpload && storedItemIndex >= 0) {
this._storedIds.splice(storedItemIndex, 1);
}
this._uploadData.setStatus(id, qq.status.CANCELED);
},
_onComplete: function(id, name, result, xhr) {
if (!result.success) {
this._netUploadedOrQueued--;
this._uploadData.setStatus(id, qq.status.UPLOAD_FAILED);
if (result[this._options.retry.preventRetryResponseProperty] === true) {
this._preventRetries[id] = true;
}
} else {
if (result.thumbnailUrl) {
this._thumbnailUrls[id] = result.thumbnailUrl;
}
this._netUploaded++;
this._uploadData.setStatus(id, qq.status.UPLOAD_SUCCESSFUL);
}
this._maybeParseAndSendUploadError(id, name, result, xhr);
return result.success ? true : false;
},
_onDelete: function(id) {
this._uploadData.setStatus(id, qq.status.DELETING);
},
_onDeleteComplete: function(id, xhrOrXdr, isError) {
var name = this.getName(id);
if (isError) {
this._uploadData.setStatus(id, qq.status.DELETE_FAILED);
this.log("Delete request for '" + name + "' has failed.", "error");
if (xhrOrXdr.withCredentials === undefined) {
this._options.callbacks.onError(id, name, "Delete request failed", xhrOrXdr);
} else {
this._options.callbacks.onError(id, name, "Delete request failed with response code " + xhrOrXdr.status, xhrOrXdr);
}
} else {
this._netUploadedOrQueued--;
this._netUploaded--;
this._handler.expunge(id);
this._uploadData.setStatus(id, qq.status.DELETED);
this.log("Delete request for '" + name + "' has succeeded.");
}
},
_onInputChange: function(input) {
var fileIndex;
if (qq.supportedFeatures.ajaxUploading) {
for (fileIndex = 0; fileIndex < input.files.length; fileIndex++) {
this._annotateWithButtonId(input.files[fileIndex], input);
}
this.addFiles(input.files);
} else if (input.value.length > 0) {
this.addFiles(input);
}
qq.each(this._buttons, function(idx, button) {
button.reset();
});
},
_onProgress: function(id, name, loaded, total) {
this._totalProgress && this._totalProgress.onIndividualProgress(id, loaded, total);
},
_onSubmit: function(id, name) {},
_onSubmitCallbackSuccess: function(id, name) {
this._onSubmit.apply(this, arguments);
this._uploadData.setStatus(id, qq.status.SUBMITTED);
this._onSubmitted.apply(this, arguments);
if (this._options.autoUpload) {
this._options.callbacks.onSubmitted.apply(this, arguments);
this._uploadFile(id);
} else {
this._storeForLater(id);
this._options.callbacks.onSubmitted.apply(this, arguments);
}
},
_onSubmitDelete: function(id, onSuccessCallback, additionalMandatedParams) {
var uuid = this.getUuid(id), adjustedOnSuccessCallback;
if (onSuccessCallback) {
adjustedOnSuccessCallback = qq.bind(onSuccessCallback, this, id, uuid, additionalMandatedParams);
}
if (this._isDeletePossible()) {
this._handleCheckedCallback({
name: "onSubmitDelete",
callback: qq.bind(this._options.callbacks.onSubmitDelete, this, id),
onSuccess: adjustedOnSuccessCallback || qq.bind(this._deleteHandler.sendDelete, this, id, uuid, additionalMandatedParams),
identifier: id
});
return true;
} else {
this.log("Delete request ignored for ID " + id + ", delete feature is disabled or request not possible " + "due to CORS on a user agent that does not support pre-flighting.", "warn");
return false;
}
},
_onSubmitted: function(id) {},
_onTotalProgress: function(loaded, total) {
this._options.callbacks.onTotalProgress(loaded, total);
},
_onUploadPrep: function(id) {},
_onUpload: function(id, name) {
this._uploadData.setStatus(id, qq.status.UPLOADING);
},
_onUploadChunk: function(id, chunkData) {},
_onUploadStatusChange: function(id, oldStatus, newStatus) {
if (newStatus === qq.status.PAUSED) {
clearTimeout(this._retryTimeouts[id]);
}
},
_onValidateBatchCallbackFailure: function(fileWrappers) {
var self = this;
qq.each(fileWrappers, function(idx, fileWrapper) {
self._fileOrBlobRejected(fileWrapper.id);
});
},
_onValidateBatchCallbackSuccess: function(validationDescriptors, items, params, endpoint, button) {
var errorMessage, itemLimit = this._currentItemLimit, proposedNetFilesUploadedOrQueued = this._netUploadedOrQueued;
if (itemLimit === 0 || proposedNetFilesUploadedOrQueued <= itemLimit) {
if (items.length > 0) {
this._handleCheckedCallback({
name: "onValidate",
callback: qq.bind(this._options.callbacks.onValidate, this, validationDescriptors[0], button),
onSuccess: qq.bind(this._onValidateCallbackSuccess, this, items, 0, params, endpoint),
onFailure: qq.bind(this._onValidateCallbackFailure, this, items, 0, params, endpoint),
identifier: "Item '" + items[0].file.name + "', size: " + items[0].file.size
});
} else {
this._itemError("noFilesError");
}
} else {
this._onValidateBatchCallbackFailure(items);
errorMessage = this._options.messages.tooManyItemsError.replace(/\{netItems\}/g, proposedNetFilesUploadedOrQueued).replace(/\{itemLimit\}/g, itemLimit);
this._batchError(errorMessage);
}
},
_onValidateCallbackFailure: function(items, index, params, endpoint) {
var nextIndex = index + 1;
this._fileOrBlobRejected(items[index].id, items[index].file.name);
this._maybeProcessNextItemAfterOnValidateCallback(false, items, nextIndex, params, endpoint);
},
_onValidateCallbackSuccess: function(items, index, params, endpoint) {
var self = this, nextIndex = index + 1, validationDescriptor = this._getValidationDescriptor(items[index]);
this._validateFileOrBlobData(items[index], validationDescriptor).then(function() {
self._upload(items[index].id, params, endpoint);
self._maybeProcessNextItemAfterOnValidateCallback(true, items, nextIndex, params, endpoint);
}, function() {
self._maybeProcessNextItemAfterOnValidateCallback(false, items, nextIndex, params, endpoint);
});
},
_prepareItemsForUpload: function(items, params, endpoint) {
if (items.length === 0) {
this._itemError("noFilesError");
return;
}
var validationDescriptors = this._getValidationDescriptors(items), buttonId = this._getButtonId(items[0].file), button = this._getButton(buttonId);
this._handleCheckedCallback({
name: "onValidateBatch",
callback: qq.bind(this._options.callbacks.onValidateBatch, this, validationDescriptors, button),
onSuccess: qq.bind(this._onValidateBatchCallbackSuccess, this, validationDescriptors, items, params, endpoint, button),
onFailure: qq.bind(this._onValidateBatchCallbackFailure, this, items),
identifier: "batch validation"
});
},
_preventLeaveInProgress: function() {
var self = this;
this._disposeSupport.attach(window, "beforeunload", function(e) {
if (self.getInProgress()) {
e = e || window.event;
e.returnValue = self._options.messages.onLeave;
return self._options.messages.onLeave;
}
});
},
_refreshSessionData: function() {
var self = this, options = this._options.session;
if (qq.Session && this._options.session.endpoint != null) {
if (!this._session) {
qq.extend(options, {
cors: this._options.cors
});
options.log = qq.bind(this.log, this);
options.addFileRecord = qq.bind(this._addCannedFile, this);
this._session = new qq.Session(options);
}
setTimeout(function() {
self._session.refresh().then(function(response, xhrOrXdr) {
self._sessionRequestComplete();
self._options.callbacks.onSessionRequestComplete(response, true, xhrOrXdr);
}, function(response, xhrOrXdr) {
self._options.callbacks.onSessionRequestComplete(response, false, xhrOrXdr);
});
}, 0);
}
},
_sessionRequestComplete: function() {},
_setSize: function(id, newSize) {
this._uploadData.updateSize(id, newSize);
this._totalProgress && this._totalProgress.onNewSize(id);
},
_shouldAutoRetry: function(id, name, responseJSON) {
var uploadData = this._uploadData.retrieve({
id: id
});
if (!this._preventRetries[id] && this._options.retry.enableAuto && uploadData.status !== qq.status.PAUSED) {
if (this._autoRetries[id] === undefined) {
this._autoRetries[id] = 0;
}
if (this._autoRetries[id] < this._options.retry.maxAutoAttempts) {
this._autoRetries[id] += 1;
return true;
}
}
return false;
},
_storeForLater: function(id) {
this._storedIds.push(id);
},
_trackButton: function(id) {
var buttonId;
if (qq.supportedFeatures.ajaxUploading) {
buttonId = this._handler.getFile(id).qqButtonId;
} else {
buttonId = this._getButtonId(this._handler.getInput(id));
}
if (buttonId) {
this._buttonIdsForFileIds[id] = buttonId;
}
},
_updateFormSupportAndParams: function(formElementOrId) {
this._options.form.element = formElementOrId;
this._formSupport = qq.FormSupport && new qq.FormSupport(this._options.form, qq.bind(this.uploadStoredFiles, this), qq.bind(this.log, this));
if (this._formSupport && this._formSupport.attachedToForm) {
this._paramsStore.addReadOnly(null, this._formSupport.getFormInputsAsObject);
this._options.autoUpload = this._formSupport.newAutoUpload;
if (this._formSupport.newEndpoint) {
this.setEndpoint(this._formSupport.newEndpoint);
}
}
},
_upload: function(id, params, endpoint) {
var name = this.getName(id);
if (params) {
this.setParams(params, id);
}
if (endpoint) {
this.setEndpoint(endpoint, id);
}
this._handleCheckedCallback({
name: "onSubmit",
callback: qq.bind(this._options.callbacks.onSubmit, this, id, name),
onSuccess: qq.bind(this._onSubmitCallbackSuccess, this, id, name),
onFailure: qq.bind(this._fileOrBlobRejected, this, id, name),
identifier: id
});
},
_uploadFile: function(id) {
if (!this._handler.upload(id)) {
this._uploadData.setStatus(id, qq.status.QUEUED);
}
},
_uploadStoredFiles: function() {
var idToUpload, stillSubmitting, self = this;
while (this._storedIds.length) {
idToUpload = this._storedIds.shift();
this._uploadFile(idToUpload);
}
stillSubmitting = this.getUploads({
status: qq.status.SUBMITTING
}).length;
if (stillSubmitting) {
qq.log("Still waiting for " + stillSubmitting + " files to clear submit queue. Will re-parse stored IDs array shortly.");
setTimeout(function() {
self._uploadStoredFiles();
}, 1e3);
}
},
_validateFileOrBlobData: function(fileWrapper, validationDescriptor) {
var self = this, file = function() {
if (fileWrapper.file instanceof qq.BlobProxy) {
return fileWrapper.file.referenceBlob;
}
return fileWrapper.file;
}(), name = validationDescriptor.name, size = validationDescriptor.size, buttonId = this._getButtonId(fileWrapper.file), validationBase = this._getValidationBase(buttonId), validityChecker = new qq.Promise();
validityChecker.then(function() {}, function() {
self._fileOrBlobRejected(fileWrapper.id, name);
});
if (qq.isFileOrInput(file) && !this._isAllowedExtension(validationBase.allowedExtensions, name)) {
this._itemError("typeError", name, file);
return validityChecker.failure();
}
if (size === 0) {
this._itemError("emptyError", name, file);
return validityChecker.failure();
}
if (size > 0 && validationBase.sizeLimit && size > validationBase.sizeLimit) {
this._itemError("sizeError", name, file);
return validityChecker.failure();
}
if (size > 0 && size < validationBase.minSizeLimit) {
this._itemError("minSizeError", name, file);
return validityChecker.failure();
}
if (qq.ImageValidation && qq.supportedFeatures.imagePreviews && qq.isFile(file)) {
new qq.ImageValidation(file, qq.bind(self.log, self)).validate(validationBase.image).then(validityChecker.success, function(errorCode) {
self._itemError(errorCode + "ImageError", name, file);
validityChecker.failure();
});
} else {
validityChecker.success();
}
return validityChecker;
},
_wrapCallbacks: function() {
var self, safeCallback, prop;
self = this;
safeCallback = function(name, callback, args) {
var errorMsg;
try {
return callback.apply(self, args);
} catch (exception) {
errorMsg = exception.message || exception.toString();
self.log("Caught exception in '" + name + "' callback - " + errorMsg, "error");
}
};
for (prop in this._options.callbacks) {
(function() {
var callbackName, callbackFunc;
callbackName = prop;
callbackFunc = self._options.callbacks[callbackName];
self._options.callbacks[callbackName] = function() {
return safeCallback(callbackName, callbackFunc, arguments);
};
})();
}
}
};
})();
(function() {
"use strict";
qq.FineUploaderBasic = function(o) {
var self = this;
this._options = {
debug: false,
button: null,
multiple: true,
maxConnections: 3,
disableCancelForFormUploads: false,
autoUpload: true,
request: {
customHeaders: {},
endpoint: "/server/upload",
filenameParam: "qqfilename",
forceMultipart: true,
inputName: "qqfile",
method: "POST",
params: {},
paramsInBody: true,
totalFileSizeName: "qqtotalfilesize",
uuidName: "qquuid"
},
validation: {
allowedExtensions: [],
sizeLimit: 0,
minSizeLimit: 0,
itemLimit: 0,
stopOnFirstInvalidFile: true,
acceptFiles: null,
image: {
maxHeight: 0,
maxWidth: 0,
minHeight: 0,
minWidth: 0
}
},
callbacks: {
onSubmit: function(id, name) {},
onSubmitted: function(id, name) {},
onComplete: function(id, name, responseJSON, maybeXhr) {},
onAllComplete: function(successful, failed) {},
onCancel: function(id, name) {},
onUpload: function(id, name) {},
onUploadChunk: function(id, name, chunkData) {},
onUploadChunkSuccess: function(id, chunkData, responseJSON, xhr) {},
onResume: function(id, fileName, chunkData) {},
onProgress: function(id, name, loaded, total) {},
onTotalProgress: function(loaded, total) {},
onError: function(id, name, reason, maybeXhrOrXdr) {},
onAutoRetry: function(id, name, attemptNumber) {},
onManualRetry: function(id, name) {},
onValidateBatch: function(fileOrBlobData) {},
onValidate: function(fileOrBlobData) {},
onSubmitDelete: function(id) {},
onDelete: function(id) {},
onDeleteComplete: function(id, xhrOrXdr, isError) {},
onPasteReceived: function(blob) {},
onStatusChange: function(id, oldStatus, newStatus) {},
onSessionRequestComplete: function(response, success, xhrOrXdr) {}
},
messages: {
typeError: "{file} has an invalid extension. Valid extension(s): {extensions}.",
sizeError: "{file} is too large, maximum file size is {sizeLimit}.",
minSizeError: "{file} is too small, minimum file size is {minSizeLimit}.",
emptyError: "{file} is empty, please select files again without it.",
noFilesError: "No files to upload.",
tooManyItemsError: "Too many items ({netItems}) would be uploaded. Item limit is {itemLimit}.",
maxHeightImageError: "Image is too tall.",
maxWidthImageError: "Image is too wide.",
minHeightImageError: "Image is not tall enough.",
minWidthImageError: "Image is not wide enough.",
retryFailTooManyItems: "Retry failed - you have reached your file limit.",
onLeave: "The files are being uploaded, if you leave now the upload will be canceled.",
unsupportedBrowserIos8Safari: "Unrecoverable error - this browser does not permit file uploading of any kind due to serious bugs in iOS8 Safari. Please use iOS8 Chrome until Apple fixes these issues."
},
retry: {
enableAuto: false,
maxAutoAttempts: 3,
autoAttemptDelay: 5,
preventRetryResponseProperty: "preventRetry"
},
classes: {
buttonHover: "qq-upload-button-hover",
buttonFocus: "qq-upload-button-focus"
},
chunking: {
enabled: false,
concurrent: {
enabled: false
},
mandatory: false,
paramNames: {
partIndex: "qqpartindex",
partByteOffset: "qqpartbyteoffset",
chunkSize: "qqchunksize",
totalFileSize: "qqtotalfilesize",
totalParts: "qqtotalparts"
},
partSize: 2e6,
success: {
endpoint: null
}
},
resume: {
enabled: false,
recordsExpireIn: 7,
paramNames: {
resuming: "qqresume"
}
},
formatFileName: function(fileOrBlobName) {
return fileOrBlobName;
},
text: {
defaultResponseError: "Upload failure reason unknown",
fileInputTitle: "file input",
sizeSymbols: [ "kB", "MB", "GB", "TB", "PB", "EB" ]
},
deleteFile: {
enabled: false,
method: "DELETE",
endpoint: "/server/upload",
customHeaders: {},
params: {}
},
cors: {
expected: false,
sendCredentials: false,
allowXdr: false
},
blobs: {
defaultName: "misc_data"
},
paste: {
targetElement: null,
defaultName: "pasted_image"
},
camera: {
ios: false,
button: null
},
extraButtons: [],
session: {
endpoint: null,
params: {},
customHeaders: {},
refreshOnReset: true
},
form: {
element: "qq-form",
autoUpload: false,
interceptSubmit: true
},
scaling: {
customResizer: null,
sendOriginal: true,
orient: true,
defaultType: null,
defaultQuality: 80,
failureText: "Failed to scale",
includeExif: false,
sizes: []
},
workarounds: {
iosEmptyVideos: true,
ios8SafariUploads: true,
ios8BrowserCrash: false
}
};
qq.extend(this._options, o, true);
this._buttons = [];
this._extraButtonSpecs = {};
this._buttonIdsForFileIds = [];
this._wrapCallbacks();
this._disposeSupport = new qq.DisposeSupport();
this._storedIds = [];
this._autoRetries = [];
this._retryTimeouts = [];
this._preventRetries = [];
this._thumbnailUrls = [];
this._netUploadedOrQueued = 0;
this._netUploaded = 0;
this._uploadData = this._createUploadDataTracker();
this._initFormSupportAndParams();
this._customHeadersStore = this._createStore(this._options.request.customHeaders);
this._deleteFileCustomHeadersStore = this._createStore(this._options.deleteFile.customHeaders);
this._deleteFileParamsStore = this._createStore(this._options.deleteFile.params);
this._endpointStore = this._createStore(this._options.request.endpoint);
this._deleteFileEndpointStore = this._createStore(this._options.deleteFile.endpoint);
this._handler = this._createUploadHandler();
this._deleteHandler = qq.DeleteFileAjaxRequester && this._createDeleteHandler();
if (this._options.button) {
this._defaultButtonId = this._createUploadButton({
element: this._options.button,
title: this._options.text.fileInputTitle
}).getButtonId();
}
this._generateExtraButtonSpecs();
this._handleCameraAccess();
if (this._options.paste.targetElement) {
if (qq.PasteSupport) {
this._pasteHandler = this._createPasteHandler();
} else {
this.log("Paste support module not found", "error");
}
}
this._preventLeaveInProgress();
this._imageGenerator = qq.ImageGenerator && new qq.ImageGenerator(qq.bind(this.log, this));
this._refreshSessionData();
this._succeededSinceLastAllComplete = [];
this._failedSinceLastAllComplete = [];
this._scaler = qq.Scaler && new qq.Scaler(this._options.scaling, qq.bind(this.log, this)) || {};
if (this._scaler.enabled) {
this._customNewFileHandler = qq.bind(this._scaler.handleNewFile, this._scaler);
}
if (qq.TotalProgress && qq.supportedFeatures.progressBar) {
this._totalProgress = new qq.TotalProgress(qq.bind(this._onTotalProgress, this), function(id) {
var entry = self._uploadData.retrieve({
id: id
});
return entry && entry.size || 0;
});
}
this._currentItemLimit = this._options.validation.itemLimit;
};
qq.FineUploaderBasic.prototype = qq.basePublicApi;
qq.extend(qq.FineUploaderBasic.prototype, qq.basePrivateApi);
})();
qq.AjaxRequester = function(o) {
"use strict";
var log, shouldParamsBeInQueryString, queue = [], requestData = {}, options = {
acceptHeader: null,
validMethods: [ "PATCH", "POST", "PUT" ],
method: "POST",
contentType: "application/x-www-form-urlencoded",
maxConnections: 3,
customHeaders: {},
endpointStore: {},
paramsStore: {},
mandatedParams: {},
allowXRequestedWithAndCacheControl: true,
successfulResponseCodes: {
DELETE: [ 200, 202, 204 ],
PATCH: [ 200, 201, 202, 203, 204 ],
POST: [ 200, 201, 202, 203, 204 ],
PUT: [ 200, 201, 202, 203, 204 ],
GET: [ 200 ]
},
cors: {
expected: false,
sendCredentials: false
},
log: function(str, level) {},
onSend: function(id) {},
onComplete: function(id, xhrOrXdr, isError) {},
onProgress: null
};
qq.extend(options, o);
log = options.log;
if (qq.indexOf(options.validMethods, options.method) < 0) {
throw new Error("'" + options.method + "' is not a supported method for this type of request!");
}
function isSimpleMethod() {
return qq.indexOf([ "GET", "POST", "HEAD" ], options.method) >= 0;
}
function containsNonSimpleHeaders(headers) {
var containsNonSimple = false;
qq.each(containsNonSimple, function(idx, header) {
if (qq.indexOf([ "Accept", "Accept-Language", "Content-Language", "Content-Type" ], header) < 0) {
containsNonSimple = true;
return false;
}
});
return containsNonSimple;
}
function isXdr(xhr) {
return options.cors.expected && xhr.withCredentials === undefined;
}
function getCorsAjaxTransport() {
var xhrOrXdr;
if (window.XMLHttpRequest || window.ActiveXObject) {
xhrOrXdr = qq.createXhrInstance();
if (xhrOrXdr.withCredentials === undefined) {
xhrOrXdr = new XDomainRequest();
xhrOrXdr.onload = function() {};
xhrOrXdr.onerror = function() {};
xhrOrXdr.ontimeout = function() {};
xhrOrXdr.onprogress = function() {};
}
}
return xhrOrXdr;
}
function getXhrOrXdr(id, suppliedXhr) {
var xhrOrXdr = requestData[id].xhr;
if (!xhrOrXdr) {
if (suppliedXhr) {
xhrOrXdr = suppliedXhr;
} else {
if (options.cors.expected) {
xhrOrXdr = getCorsAjaxTransport();
} else {
xhrOrXdr = qq.createXhrInstance();
}
}
requestData[id].xhr = xhrOrXdr;
}
return xhrOrXdr;
}
function dequeue(id) {
var i = qq.indexOf(queue, id), max = options.maxConnections, nextId;
delete requestData[id];
queue.splice(i, 1);
if (queue.length >= max && i < max) {
nextId = queue[max - 1];
sendRequest(nextId);
}
}
function onComplete(id, xdrError) {
var xhr = getXhrOrXdr(id), method = options.method, isError = xdrError === true;
dequeue(id);
if (isError) {
log(method + " request for " + id + " has failed", "error");
} else if (!isXdr(xhr) && !isResponseSuccessful(xhr.status)) {
isError = true;
log(method + " request for " + id + " has failed - response code " + xhr.status, "error");
}
options.onComplete(id, xhr, isError);
}
function getParams(id) {
var onDemandParams = requestData[id].additionalParams, mandatedParams = options.mandatedParams, params;
if (options.paramsStore.get) {
params = options.paramsStore.get(id);
}
if (onDemandParams) {
qq.each(onDemandParams, function(name, val) {
params = params || {};
params[name] = val;
});
}
if (mandatedParams) {
qq.each(mandatedParams, function(name, val) {
params = params || {};
params[name] = val;
});
}
return params;
}
function sendRequest(id, optXhr) {
var xhr = getXhrOrXdr(id, optXhr), method = options.method, params = getParams(id), payload = requestData[id].payload, url;
options.onSend(id);
url = createUrl(id, params, requestData[id].additionalQueryParams);
if (isXdr(xhr)) {
xhr.onload = getXdrLoadHandler(id);
xhr.onerror = getXdrErrorHandler(id);
} else {
xhr.onreadystatechange = getXhrReadyStateChangeHandler(id);
}
registerForUploadProgress(id);
xhr.open(method, url, true);
if (options.cors.expected && options.cors.sendCredentials && !isXdr(xhr)) {
xhr.withCredentials = true;
}
setHeaders(id);
log("Sending " + method + " request for " + id);
if (payload) {
xhr.send(payload);
} else if (shouldParamsBeInQueryString || !params) {
xhr.send();
} else if (params && options.contentType && options.contentType.toLowerCase().indexOf("application/x-www-form-urlencoded") >= 0) {
xhr.send(qq.obj2url(params, ""));
} else if (params && options.contentType && options.contentType.toLowerCase().indexOf("application/json") >= 0) {
xhr.send(JSON.stringify(params));
} else {
xhr.send(params);
}
return xhr;
}
function createUrl(id, params, additionalQueryParams) {
var endpoint = options.endpointStore.get(id), addToPath = requestData[id].addToPath;
if (addToPath != undefined) {
endpoint += "/" + addToPath;
}
if (shouldParamsBeInQueryString && params) {
endpoint = qq.obj2url(params, endpoint);
}
if (additionalQueryParams) {
endpoint = qq.obj2url(additionalQueryParams, endpoint);
}
return endpoint;
}
function getXhrReadyStateChangeHandler(id) {
return function() {
if (getXhrOrXdr(id).readyState === 4) {
onComplete(id);
}
};
}
function registerForUploadProgress(id) {
var onProgress = options.onProgress;
if (onProgress) {
getXhrOrXdr(id).upload.onprogress = function(e) {
if (e.lengthComputable) {
onProgress(id, e.loaded, e.total);
}
};
}
}
function getXdrLoadHandler(id) {
return function() {
onComplete(id);
};
}
function getXdrErrorHandler(id) {
return function() {
onComplete(id, true);
};
}
function setHeaders(id) {
var xhr = getXhrOrXdr(id), customHeaders = options.customHeaders, onDemandHeaders = requestData[id].additionalHeaders || {}, method = options.method, allHeaders = {};
if (!isXdr(xhr)) {
options.acceptHeader && xhr.setRequestHeader("Accept", options.acceptHeader);
if (options.allowXRequestedWithAndCacheControl) {
if (!options.cors.expected || (!isSimpleMethod() || containsNonSimpleHeaders(customHeaders))) {
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("Cache-Control", "no-cache");
}
}
if (options.contentType && (method === "POST" || method === "PUT")) {
xhr.setRequestHeader("Content-Type", options.contentType);
}
qq.extend(allHeaders, qq.isFunction(customHeaders) ? customHeaders(id) : customHeaders);
qq.extend(allHeaders, onDemandHeaders);
qq.each(allHeaders, function(name, val) {
xhr.setRequestHeader(name, val);
});
}
}
function isResponseSuccessful(responseCode) {
return qq.indexOf(options.successfulResponseCodes[options.method], responseCode) >= 0;
}
function prepareToSend(id, optXhr, addToPath, additionalParams, additionalQueryParams, additionalHeaders, payload) {
requestData[id] = {
addToPath: addToPath,
additionalParams: additionalParams,
additionalQueryParams: additionalQueryParams,
additionalHeaders: additionalHeaders,
payload: payload
};
var len = queue.push(id);
if (len <= options.maxConnections) {
return sendRequest(id, optXhr);
}
}
shouldParamsBeInQueryString = options.method === "GET" || options.method === "DELETE";
qq.extend(this, {
initTransport: function(id) {
var path, params, headers, payload, cacheBuster, additionalQueryParams;
return {
withPath: function(appendToPath) {
path = appendToPath;
return this;
},
withParams: function(additionalParams) {
params = additionalParams;
return this;
},
withQueryParams: function(_additionalQueryParams_) {
additionalQueryParams = _additionalQueryParams_;
return this;
},
withHeaders: function(additionalHeaders) {
headers = additionalHeaders;
return this;
},
withPayload: function(thePayload) {
payload = thePayload;
return this;
},
withCacheBuster: function() {
cacheBuster = true;
return this;
},
send: function(optXhr) {
if (cacheBuster && qq.indexOf([ "GET", "DELETE" ], options.method) >= 0) {
params.qqtimestamp = new Date().getTime();
}
return prepareToSend(id, optXhr, path, params, additionalQueryParams, headers, payload);
}
};
},
canceled: function(id) {
dequeue(id);
}
});
};
qq.UploadHandler = function(spec) {
"use strict";
var proxy = spec.proxy, fileState = {}, onCancel = proxy.onCancel, getName = proxy.getName;
qq.extend(this, {
add: function(id, fileItem) {
fileState[id] = fileItem;
fileState[id].temp = {};
},
cancel: function(id) {
var self = this, cancelFinalizationEffort = new qq.Promise(), onCancelRetVal = onCancel(id, getName(id), cancelFinalizationEffort);
onCancelRetVal.then(function() {
if (self.isValid(id)) {
fileState[id].canceled = true;
self.expunge(id);
}
cancelFinalizationEffort.success();
});
},
expunge: function(id) {
delete fileState[id];
},
getThirdPartyFileId: function(id) {
return fileState[id].key;
},
isValid: function(id) {
return fileState[id] !== undefined;
},
reset: function() {
fileState = {};
},
_getFileState: function(id) {
return fileState[id];
},
_setThirdPartyFileId: function(id, thirdPartyFileId) {
fileState[id].key = thirdPartyFileId;
},
_wasCanceled: function(id) {
return !!fileState[id].canceled;
}
});
};
qq.UploadHandlerController = function(o, namespace) {
"use strict";
var controller = this, chunkingPossible = false, concurrentChunkingPossible = false, chunking, preventRetryResponse, log, handler, options = {
paramsStore: {},
maxConnections: 3,
chunking: {
enabled: false,
multiple: {
enabled: false
}
},
log: function(str, level) {},
onProgress: function(id, fileName, loaded, total) {},
onComplete: function(id, fileName, response, xhr) {},
onCancel: function(id, fileName) {},
onUploadPrep: function(id) {},
onUpload: function(id, fileName) {},
onUploadChunk: function(id, fileName, chunkData) {},
onUploadChunkSuccess: function(id, chunkData, response, xhr) {},
onAutoRetry: function(id, fileName, response, xhr) {},
onResume: function(id, fileName, chunkData) {},
onUuidChanged: function(id, newUuid) {},
getName: function(id) {},
setSize: function(id, newSize) {},
isQueued: function(id) {},
getIdsInProxyGroup: function(id) {},
getIdsInBatch: function(id) {}
}, chunked = {
done: function(id, chunkIdx, response, xhr) {
var chunkData = handler._getChunkData(id, chunkIdx);
handler._getFileState(id).attemptingResume = false;
delete handler._getFileState(id).temp.chunkProgress[chunkIdx];
handler._getFileState(id).loaded += chunkData.size;
options.onUploadChunkSuccess(id, handler._getChunkDataForCallback(chunkData), response, xhr);
},
finalize: function(id) {
var size = options.getSize(id), name = options.getName(id);
log("All chunks have been uploaded for " + id + " - finalizing....");
handler.finalizeChunks(id).then(function(response, xhr) {
log("Finalize successful for " + id);
var normaizedResponse = upload.normalizeResponse(response, true);
options.onProgress(id, name, size, size);
handler._maybeDeletePersistedChunkData(id);
upload.cleanup(id, normaizedResponse, xhr);
}, function(response, xhr) {
var normaizedResponse = upload.normalizeResponse(response, false);
log("Problem finalizing chunks for file ID " + id + " - " + normaizedResponse.error, "error");
if (normaizedResponse.reset) {
chunked.reset(id);
}
if (!options.onAutoRetry(id, name, normaizedResponse, xhr)) {
upload.cleanup(id, normaizedResponse, xhr);
}
});
},
hasMoreParts: function(id) {
return !!handler._getFileState(id).chunking.remaining.length;
},
nextPart: function(id) {
var nextIdx = handler._getFileState(id).chunking.remaining.shift();
if (nextIdx >= handler._getTotalChunks(id)) {
nextIdx = null;
}
return nextIdx;
},
reset: function(id) {
log("Server or callback has ordered chunking effort to be restarted on next attempt for item ID " + id, "error");
handler._maybeDeletePersistedChunkData(id);
handler.reevaluateChunking(id);
handler._getFileState(id).loaded = 0;
},
sendNext: function(id) {
var size = options.getSize(id), name = options.getName(id), chunkIdx = chunked.nextPart(id), chunkData = handler._getChunkData(id, chunkIdx), resuming = handler._getFileState(id).attemptingResume, inProgressChunks = handler._getFileState(id).chunking.inProgress || [];
if (handler._getFileState(id).loaded == null) {
handler._getFileState(id).loaded = 0;
}
if (resuming && options.onResume(id, name, chunkData) === false) {
chunked.reset(id);
chunkIdx = chunked.nextPart(id);
chunkData = handler._getChunkData(id, chunkIdx);
resuming = false;
}
if (chunkIdx == null && inProgressChunks.length === 0) {
chunked.finalize(id);
} else {
log(qq.format("Sending chunked upload request for item {}.{}, bytes {}-{} of {}.", id, chunkIdx, chunkData.start + 1, chunkData.end, size));
options.onUploadChunk(id, name, handler._getChunkDataForCallback(chunkData));
inProgressChunks.push(chunkIdx);
handler._getFileState(id).chunking.inProgress = inProgressChunks;
if (concurrentChunkingPossible) {
connectionManager.open(id, chunkIdx);
}
if (concurrentChunkingPossible && connectionManager.available() && handler._getFileState(id).chunking.remaining.length) {
chunked.sendNext(id);
}
handler.uploadChunk(id, chunkIdx, resuming).then(function success(response, xhr) {
log("Chunked upload request succeeded for " + id + ", chunk " + chunkIdx);
handler.clearCachedChunk(id, chunkIdx);
var inProgressChunks = handler._getFileState(id).chunking.inProgress || [], responseToReport = upload.normalizeResponse(response, true), inProgressChunkIdx = qq.indexOf(inProgressChunks, chunkIdx);
log(qq.format("Chunk {} for file {} uploaded successfully.", chunkIdx, id));
chunked.done(id, chunkIdx, responseToReport, xhr);
if (inProgressChunkIdx >= 0) {
inProgressChunks.splice(inProgressChunkIdx, 1);
}
handler._maybePersistChunkedState(id);
if (!chunked.hasMoreParts(id) && inProgressChunks.length === 0) {
chunked.finalize(id);
} else if (chunked.hasMoreParts(id)) {
chunked.sendNext(id);
} else {
log(qq.format("File ID {} has no more chunks to send and these chunk indexes are still marked as in-progress: {}", id, JSON.stringify(inProgressChunks)));
}
}, function failure(response, xhr) {
log("Chunked upload request failed for " + id + ", chunk " + chunkIdx);
handler.clearCachedChunk(id, chunkIdx);
var responseToReport = upload.normalizeResponse(response, false), inProgressIdx;
if (responseToReport.reset) {
chunked.reset(id);
} else {
inProgressIdx = qq.indexOf(handler._getFileState(id).chunking.inProgress, chunkIdx);
if (inProgressIdx >= 0) {
handler._getFileState(id).chunking.inProgress.splice(inProgressIdx, 1);
handler._getFileState(id).chunking.remaining.unshift(chunkIdx);
}
}
if (!handler._getFileState(id).temp.ignoreFailure) {
if (concurrentChunkingPossible) {
handler._getFileState(id).temp.ignoreFailure = true;
log(qq.format("Going to attempt to abort these chunks: {}. These are currently in-progress: {}.", JSON.stringify(Object.keys(handler._getXhrs(id))), JSON.stringify(handler._getFileState(id).chunking.inProgress)));
qq.each(handler._getXhrs(id), function(ckid, ckXhr) {
log(qq.format("Attempting to abort file {}.{}. XHR readyState {}. ", id, ckid, ckXhr.readyState));
ckXhr.abort();
ckXhr._cancelled = true;
});
handler.moveInProgressToRemaining(id);
connectionManager.free(id, true);
}
if (!options.onAutoRetry(id, name, responseToReport, xhr)) {
upload.cleanup(id, responseToReport, xhr);
}
}
}).done(function() {
handler.clearXhr(id, chunkIdx);
});
}
}
}, connectionManager = {
_open: [],
_openChunks: {},
_waiting: [],
available: function() {
var max = options.maxConnections, openChunkEntriesCount = 0, openChunksCount = 0;
qq.each(connectionManager._openChunks, function(fileId, openChunkIndexes) {
openChunkEntriesCount++;
openChunksCount += openChunkIndexes.length;
});
return max - (connectionManager._open.length - openChunkEntriesCount + openChunksCount);
},
free: function(id, dontAllowNext) {
var allowNext = !dontAllowNext, waitingIndex = qq.indexOf(connectionManager._waiting, id), connectionsIndex = qq.indexOf(connectionManager._open, id), nextId;
delete connectionManager._openChunks[id];
if (upload.getProxyOrBlob(id) instanceof qq.BlobProxy) {
log("Generated blob upload has ended for " + id + ", disposing generated blob.");
delete handler._getFileState(id).file;
}
if (waitingIndex >= 0) {
connectionManager._waiting.splice(waitingIndex, 1);
} else if (allowNext && connectionsIndex >= 0) {
connectionManager._open.splice(connectionsIndex, 1);
nextId = connectionManager._waiting.shift();
if (nextId >= 0) {
connectionManager._open.push(nextId);
upload.start(nextId);
}
}
},
getWaitingOrConnected: function() {
var waitingOrConnected = [];
qq.each(connectionManager._openChunks, function(fileId, chunks) {
if (chunks && chunks.length) {
waitingOrConnected.push(parseInt(fileId));
}
});
qq.each(connectionManager._open, function(idx, fileId) {
if (!connectionManager._openChunks[fileId]) {
waitingOrConnected.push(parseInt(fileId));
}
});
waitingOrConnected = waitingOrConnected.concat(connectionManager._waiting);
return waitingOrConnected;
},
isUsingConnection: function(id) {
return qq.indexOf(connectionManager._open, id) >= 0;
},
open: function(id, chunkIdx) {
if (chunkIdx == null) {
connectionManager._waiting.push(id);
}
if (connectionManager.available()) {
if (chunkIdx == null) {
connectionManager._waiting.pop();
connectionManager._open.push(id);
} else {
(function() {
var openChunksEntry = connectionManager._openChunks[id] || [];
openChunksEntry.push(chunkIdx);
connectionManager._openChunks[id] = openChunksEntry;
})();
}
return true;
}
return false;
},
reset: function() {
connectionManager._waiting = [];
connectionManager._open = [];
}
}, simple = {
send: function(id, name) {
handler._getFileState(id).loaded = 0;
log("Sending simple upload request for " + id);
handler.uploadFile(id).then(function(response, optXhr) {
log("Simple upload request succeeded for " + id);
var responseToReport = upload.normalizeResponse(response, true), size = options.getSize(id);
options.onProgress(id, name, size, size);
upload.maybeNewUuid(id, responseToReport);
upload.cleanup(id, responseToReport, optXhr);
}, function(response, optXhr) {
log("Simple upload request failed for " + id);
var responseToReport = upload.normalizeResponse(response, false);
if (!options.onAutoRetry(id, name, responseToReport, optXhr)) {
upload.cleanup(id, responseToReport, optXhr);
}
});
}
}, upload = {
cancel: function(id) {
log("Cancelling " + id);
options.paramsStore.remove(id);
connectionManager.free(id);
},
cleanup: function(id, response, optXhr) {
var name = options.getName(id);
options.onComplete(id, name, response, optXhr);
if (handler._getFileState(id)) {
handler._clearXhrs && handler._clearXhrs(id);
}
connectionManager.free(id);
},
getProxyOrBlob: function(id) {
return handler.getProxy && handler.getProxy(id) || handler.getFile && handler.getFile(id);
},
initHandler: function() {
var handlerType = namespace ? qq[namespace] : qq.traditional, handlerModuleSubtype = qq.supportedFeatures.ajaxUploading ? "Xhr" : "Form";
handler = new handlerType[handlerModuleSubtype + "UploadHandler"](options, {
getDataByUuid: options.getDataByUuid,
getName: options.getName,
getSize: options.getSize,
getUuid: options.getUuid,
log: log,
onCancel: options.onCancel,
onProgress: options.onProgress,
onUuidChanged: options.onUuidChanged
});
if (handler._removeExpiredChunkingRecords) {
handler._removeExpiredChunkingRecords();
}
},
isDeferredEligibleForUpload: function(id) {
return options.isQueued(id);
},
maybeDefer: function(id, blob) {
if (blob && !handler.getFile(id) && blob instanceof qq.BlobProxy) {
options.onUploadPrep(id);
log("Attempting to generate a blob on-demand for " + id);
blob.create().then(function(generatedBlob) {
log("Generated an on-demand blob for " + id);
handler.updateBlob(id, generatedBlob);
options.setSize(id, generatedBlob.size);
handler.reevaluateChunking(id);
upload.maybeSendDeferredFiles(id);
}, function(errorMessage) {
var errorResponse = {};
if (errorMessage) {
errorResponse.error = errorMessage;
}
log(qq.format("Failed to generate blob for ID {}. Error message: {}.", id, errorMessage), "error");
options.onComplete(id, options.getName(id), qq.extend(errorResponse, preventRetryResponse), null);
upload.maybeSendDeferredFiles(id);
connectionManager.free(id);
});
} else {
return upload.maybeSendDeferredFiles(id);
}
return false;
},
maybeSendDeferredFiles: function(id) {
var idsInGroup = options.getIdsInProxyGroup(id), uploadedThisId = false;
if (idsInGroup && idsInGroup.length) {
log("Maybe ready to upload proxy group file " + id);
qq.each(idsInGroup, function(idx, idInGroup) {
if (upload.isDeferredEligibleForUpload(idInGroup) && !!handler.getFile(idInGroup)) {
uploadedThisId = idInGroup === id;
upload.now(idInGroup);
} else if (upload.isDeferredEligibleForUpload(idInGroup)) {
return false;
}
});
} else {
uploadedThisId = true;
upload.now(id);
}
return uploadedThisId;
},
maybeNewUuid: function(id, response) {
if (response.newUuid !== undefined) {
options.onUuidChanged(id, response.newUuid);
}
},
normalizeResponse: function(originalResponse, successful) {
var response = originalResponse;
if (!qq.isObject(originalResponse)) {
response = {};
if (qq.isString(originalResponse) && !successful) {
response.error = originalResponse;
}
}
response.success = successful;
return response;
},
now: function(id) {
var name = options.getName(id);
if (!controller.isValid(id)) {
throw new qq.Error(id + " is not a valid file ID to upload!");
}
options.onUpload(id, name);
if (chunkingPossible && handler._shouldChunkThisFile(id)) {
chunked.sendNext(id);
} else {
simple.send(id, name);
}
},
start: function(id) {
var blobToUpload = upload.getProxyOrBlob(id);
if (blobToUpload) {
return upload.maybeDefer(id, blobToUpload);
} else {
upload.now(id);
return true;
}
}
};
qq.extend(this, {
add: function(id, file) {
handler.add.apply(this, arguments);
},
upload: function(id) {
if (connectionManager.open(id)) {
return upload.start(id);
}
return false;
},
retry: function(id) {
if (concurrentChunkingPossible) {
handler._getFileState(id).temp.ignoreFailure = false;
}
if (connectionManager.isUsingConnection(id)) {
return upload.start(id);
} else {
return controller.upload(id);
}
},
cancel: function(id) {
var cancelRetVal = handler.cancel(id);
if (qq.isGenericPromise(cancelRetVal)) {
cancelRetVal.then(function() {
upload.cancel(id);
});
} else if (cancelRetVal !== false) {
upload.cancel(id);
}
},
cancelAll: function() {
var waitingOrConnected = connectionManager.getWaitingOrConnected(), i;
if (waitingOrConnected.length) {
for (i = waitingOrConnected.length - 1; i >= 0; i--) {
controller.cancel(waitingOrConnected[i]);
}
}
connectionManager.reset();
},
getFile: function(id) {
if (handler.getProxy && handler.getProxy(id)) {
return handler.getProxy(id).referenceBlob;
}
return handler.getFile && handler.getFile(id);
},
isProxied: function(id) {
return !!(handler.getProxy && handler.getProxy(id));
},
getInput: function(id) {
if (handler.getInput) {
return handler.getInput(id);
}
},
reset: function() {
log("Resetting upload handler");
controller.cancelAll();
connectionManager.reset();
handler.reset();
},
expunge: function(id) {
if (controller.isValid(id)) {
return handler.expunge(id);
}
},
isValid: function(id) {
return handler.isValid(id);
},
getResumableFilesData: function() {
if (handler.getResumableFilesData) {
return handler.getResumableFilesData();
}
return [];
},
getThirdPartyFileId: function(id) {
if (controller.isValid(id)) {
return handler.getThirdPartyFileId(id);
}
},
pause: function(id) {
if (controller.isResumable(id) && handler.pause && controller.isValid(id) && handler.pause(id)) {
connectionManager.free(id);
handler.moveInProgressToRemaining(id);
return true;
}
return false;
},
isResumable: function(id) {
return !!handler.isResumable && handler.isResumable(id);
}
});
qq.extend(options, o);
log = options.log;
chunkingPossible = options.chunking.enabled && qq.supportedFeatures.chunking;
concurrentChunkingPossible = chunkingPossible && options.chunking.concurrent.enabled;
preventRetryResponse = function() {
var response = {};
response[options.preventRetryParam] = true;
return response;
}();
upload.initHandler();
};
qq.WindowReceiveMessage = function(o) {
"use strict";
var options = {
log: function(message, level) {}
}, callbackWrapperDetachers = {};
qq.extend(options, o);
qq.extend(this, {
receiveMessage: function(id, callback) {
var onMessageCallbackWrapper = function(event) {
callback(event.data);
};
if (window.postMessage) {
callbackWrapperDetachers[id] = qq(window).attach("message", onMessageCallbackWrapper);
} else {
log("iframe message passing not supported in this browser!", "error");
}
},
stopReceivingMessages: function(id) {
if (window.postMessage) {
var detacher = callbackWrapperDetachers[id];
if (detacher) {
detacher();
}
}
}
});
};
qq.FormUploadHandler = function(spec) {
"use strict";
var options = spec.options, handler = this, proxy = spec.proxy, formHandlerInstanceId = qq.getUniqueId(), onloadCallbacks = {}, detachLoadEvents = {}, postMessageCallbackTimers = {}, isCors = options.isCors, inputName = options.inputName, getUuid = proxy.getUuid, log = proxy.log, corsMessageReceiver = new qq.WindowReceiveMessage({
log: log
});
function expungeFile(id) {
delete detachLoadEvents[id];
if (isCors) {
clearTimeout(postMessageCallbackTimers[id]);
delete postMessageCallbackTimers[id];
corsMessageReceiver.stopReceivingMessages(id);
}
var iframe = document.getElementById(handler._getIframeName(id));
if (iframe) {
iframe.setAttribute("src", "javascript:false;");
qq(iframe).remove();
}
}
function getFileIdForIframeName(iframeName) {
return iframeName.split("_")[0];
}
function initIframeForUpload(name) {
var iframe = qq.toElement("<iframe src='javascript:false;' name='" + name + "' />");
iframe.setAttribute("id", name);
iframe.style.display = "none";
document.body.appendChild(iframe);
return iframe;
}
function registerPostMessageCallback(iframe, callback) {
var iframeName = iframe.id, fileId = getFileIdForIframeName(iframeName), uuid = getUuid(fileId);
onloadCallbacks[uuid] = callback;
detachLoadEvents[fileId] = qq(iframe).attach("load", function() {
if (handler.getInput(fileId)) {
log("Received iframe load event for CORS upload request (iframe name " + iframeName + ")");
postMessageCallbackTimers[iframeName] = setTimeout(function() {
var errorMessage = "No valid message received from loaded iframe for iframe name " + iframeName;
log(errorMessage, "error");
callback({
error: errorMessage
});
}, 1e3);
}
});
corsMessageReceiver.receiveMessage(iframeName, function(message) {
log("Received the following window message: '" + message + "'");
var fileId = getFileIdForIframeName(iframeName), response = handler._parseJsonResponse(message), uuid = response.uuid, onloadCallback;
if (uuid && onloadCallbacks[uuid]) {
log("Handling response for iframe name " + iframeName);
clearTimeout(postMessageCallbackTimers[iframeName]);
delete postMessageCallbackTimers[iframeName];
handler._detachLoadEvent(iframeName);
onloadCallback = onloadCallbacks[uuid];
delete onloadCallbacks[uuid];
corsMessageReceiver.stopReceivingMessages(iframeName);
onloadCallback(response);
} else if (!uuid) {
log("'" + message + "' does not contain a UUID - ignoring.");
}
});
}
qq.extend(this, new qq.UploadHandler(spec));
qq.override(this, function(super_) {
return {
add: function(id, fileInput) {
super_.add(id, {
input: fileInput
});
fileInput.setAttribute("name", inputName);
if (fileInput.parentNode) {
qq(fileInput).remove();
}
},
expunge: function(id) {
expungeFile(id);
super_.expunge(id);
},
isValid: function(id) {
return super_.isValid(id) && handler._getFileState(id).input !== undefined;
}
};
});
qq.extend(this, {
getInput: function(id) {
return handler._getFileState(id).input;
},
_attachLoadEvent: function(iframe, callback) {
var responseDescriptor;
if (isCors) {
registerPostMessageCallback(iframe, callback);
} else {
detachLoadEvents[iframe.id] = qq(iframe).attach("load", function() {
log("Received response for " + iframe.id);
if (!iframe.parentNode) {
return;
}
try {
if (iframe.contentDocument && iframe.contentDocument.body && iframe.contentDocument.body.innerHTML == "false") {
return;
}
} catch (error) {
log("Error when attempting to access iframe during handling of upload response (" + error.message + ")", "error");
responseDescriptor = {
success: false
};
}
callback(responseDescriptor);
});
}
},
_createIframe: function(id) {
var iframeName = handler._getIframeName(id);
return initIframeForUpload(iframeName);
},
_detachLoadEvent: function(id) {
if (detachLoadEvents[id] !== undefined) {
detachLoadEvents[id]();
delete detachLoadEvents[id];
}
},
_getIframeName: function(fileId) {
return fileId + "_" + formHandlerInstanceId;
},
_initFormForUpload: function(spec) {
var method = spec.method, endpoint = spec.endpoint, params = spec.params, paramsInBody = spec.paramsInBody, targetName = spec.targetName, form = qq.toElement("<form method='" + method + "' enctype='multipart/form-data'></form>"), url = endpoint;
if (paramsInBody) {
qq.obj2Inputs(params, form);
} else {
url = qq.obj2url(params, endpoint);
}
form.setAttribute("action", url);
form.setAttribute("target", targetName);
form.style.display = "none";
document.body.appendChild(form);
return form;
},
_parseJsonResponse: function(innerHtmlOrMessage) {
var response = {};
try {
response = qq.parseJson(innerHtmlOrMessage);
} catch (error) {
log("Error when attempting to parse iframe upload response (" + error.message + ")", "error");
}
return response;
}
});
};
qq.XhrUploadHandler = function(spec) {
"use strict";
var handler = this, namespace = spec.options.namespace, proxy = spec.proxy, chunking = spec.options.chunking, resume = spec.options.resume, chunkFiles = chunking && spec.options.chunking.enabled && qq.supportedFeatures.chunking, resumeEnabled = resume && spec.options.resume.enabled && chunkFiles && qq.supportedFeatures.resume, getName = proxy.getName, getSize = proxy.getSize, getUuid = proxy.getUuid, getEndpoint = proxy.getEndpoint, getDataByUuid = proxy.getDataByUuid, onUuidChanged = proxy.onUuidChanged, onProgress = proxy.onProgress, log = proxy.log;
function abort(id) {
qq.each(handler._getXhrs(id), function(xhrId, xhr) {
var ajaxRequester = handler._getAjaxRequester(id, xhrId);
xhr.onreadystatechange = null;
xhr.upload.onprogress = null;
xhr.abort();
ajaxRequester && ajaxRequester.canceled && ajaxRequester.canceled(id);
});
}
qq.extend(this, new qq.UploadHandler(spec));
qq.override(this, function(super_) {
return {
add: function(id, blobOrProxy) {
if (qq.isFile(blobOrProxy) || qq.isBlob(blobOrProxy)) {
super_.add(id, {
file: blobOrProxy
});
} else if (blobOrProxy instanceof qq.BlobProxy) {
super_.add(id, {
proxy: blobOrProxy
});
} else {
throw new Error("Passed obj is not a File, Blob, or proxy");
}
handler._initTempState(id);
resumeEnabled && handler._maybePrepareForResume(id);
},
expunge: function(id) {
abort(id);
handler._maybeDeletePersistedChunkData(id);
handler._clearXhrs(id);
super_.expunge(id);
}
};
});
qq.extend(this, {
clearCachedChunk: function(id, chunkIdx) {
delete handler._getFileState(id).temp.cachedChunks[chunkIdx];
},
clearXhr: function(id, chunkIdx) {
var tempState = handler._getFileState(id).temp;
if (tempState.xhrs) {
delete tempState.xhrs[chunkIdx];
}
if (tempState.ajaxRequesters) {
delete tempState.ajaxRequesters[chunkIdx];
}
},
finalizeChunks: function(id, responseParser) {
var lastChunkIdx = handler._getTotalChunks(id) - 1, xhr = handler._getXhr(id, lastChunkIdx);
if (responseParser) {
return new qq.Promise().success(responseParser(xhr), xhr);
}
return new qq.Promise().success({}, xhr);
},
getFile: function(id) {
return handler.isValid(id) && handler._getFileState(id).file;
},
getProxy: function(id) {
return handler.isValid(id) && handler._getFileState(id).proxy;
},
getResumableFilesData: function() {
var resumableFilesData = [];
handler._iterateResumeRecords(function(key, uploadData) {
handler.moveInProgressToRemaining(null, uploadData.chunking.inProgress, uploadData.chunking.remaining);
var data = {
name: uploadData.name,
remaining: uploadData.chunking.remaining,
size: uploadData.size,
uuid: uploadData.uuid
};
if (uploadData.key) {
data.key = uploadData.key;
}
resumableFilesData.push(data);
});
return resumableFilesData;
},
isResumable: function(id) {
return !!chunking && handler.isValid(id) && !handler._getFileState(id).notResumable;
},
moveInProgressToRemaining: function(id, optInProgress, optRemaining) {
var inProgress = optInProgress || handler._getFileState(id).chunking.inProgress, remaining = optRemaining || handler._getFileState(id).chunking.remaining;
if (inProgress) {
log(qq.format("Moving these chunks from in-progress {}, to remaining.", JSON.stringify(inProgress)));
inProgress.reverse();
qq.each(inProgress, function(idx, chunkIdx) {
remaining.unshift(chunkIdx);
});
inProgress.length = 0;
}
},
pause: function(id) {
if (handler.isValid(id)) {
log(qq.format("Aborting XHR upload for {} '{}' due to pause instruction.", id, getName(id)));
handler._getFileState(id).paused = true;
abort(id);
return true;
}
},
reevaluateChunking: function(id) {
if (chunking && handler.isValid(id)) {
var state = handler._getFileState(id), totalChunks, i;
delete state.chunking;
state.chunking = {};
totalChunks = handler._getTotalChunks(id);
if (totalChunks > 1 || chunking.mandatory) {
state.chunking.enabled = true;
state.chunking.parts = totalChunks;
state.chunking.remaining = [];
for (i = 0; i < totalChunks; i++) {
state.chunking.remaining.push(i);
}
handler._initTempState(id);
} else {
state.chunking.enabled = false;
}
}
},
updateBlob: function(id, newBlob) {
if (handler.isValid(id)) {
handler._getFileState(id).file = newBlob;
}
},
_clearXhrs: function(id) {
var tempState = handler._getFileState(id).temp;
qq.each(tempState.ajaxRequesters, function(chunkId) {
delete tempState.ajaxRequesters[chunkId];
});
qq.each(tempState.xhrs, function(chunkId) {
delete tempState.xhrs[chunkId];
});
},
_createXhr: function(id, optChunkIdx) {
return handler._registerXhr(id, optChunkIdx, qq.createXhrInstance());
},
_getAjaxRequester: function(id, optChunkIdx) {
var chunkIdx = optChunkIdx == null ? -1 : optChunkIdx;
return handler._getFileState(id).temp.ajaxRequesters[chunkIdx];
},
_getChunkData: function(id, chunkIndex) {
var chunkSize = chunking.partSize, fileSize = getSize(id), fileOrBlob = handler.getFile(id), startBytes = chunkSize * chunkIndex, endBytes = startBytes + chunkSize >= fileSize ? fileSize : startBytes + chunkSize, totalChunks = handler._getTotalChunks(id), cachedChunks = this._getFileState(id).temp.cachedChunks, blob = cachedChunks[chunkIndex] || qq.sliceBlob(fileOrBlob, startBytes, endBytes);
cachedChunks[chunkIndex] = blob;
return {
part: chunkIndex,
start: startBytes,
end: endBytes,
count: totalChunks,
blob: blob,
size: endBytes - startBytes
};
},
_getChunkDataForCallback: function(chunkData) {
return {
partIndex: chunkData.part,
startByte: chunkData.start + 1,
endByte: chunkData.end,
totalParts: chunkData.count
};
},
_getLocalStorageId: function(id) {
var formatVersion = "5.0", name = getName(id), size = getSize(id), chunkSize = chunking.partSize, endpoint = getEndpoint(id);
return qq.format("qq{}resume{}-{}-{}-{}-{}", namespace, formatVersion, name, size, chunkSize, endpoint);
},
_getMimeType: function(id) {
return handler.getFile(id).type;
},
_getPersistableData: function(id) {
return handler._getFileState(id).chunking;
},
_getTotalChunks: function(id) {
if (chunking) {
var fileSize = getSize(id), chunkSize = chunking.partSize;
return Math.ceil(fileSize / chunkSize);
}
},
_getXhr: function(id, optChunkIdx) {
var chunkIdx = optChunkIdx == null ? -1 : optChunkIdx;
return handler._getFileState(id).temp.xhrs[chunkIdx];
},
_getXhrs: function(id) {
return handler._getFileState(id).temp.xhrs;
},
_iterateResumeRecords: function(callback) {
if (resumeEnabled) {
qq.each(localStorage, function(key, item) {
if (key.indexOf(qq.format("qq{}resume", namespace)) === 0) {
var uploadData = JSON.parse(item);
callback(key, uploadData);
}
});
}
},
_initTempState: function(id) {
handler._getFileState(id).temp = {
ajaxRequesters: {},
chunkProgress: {},
xhrs: {},
cachedChunks: {}
};
},
_markNotResumable: function(id) {
handler._getFileState(id).notResumable = true;
},
_maybeDeletePersistedChunkData: function(id) {
var localStorageId;
if (resumeEnabled && handler.isResumable(id)) {
localStorageId = handler._getLocalStorageId(id);
if (localStorageId && localStorage.getItem(localStorageId)) {
localStorage.removeItem(localStorageId);
return true;
}
}
return false;
},
_maybePrepareForResume: function(id) {
var state = handler._getFileState(id), localStorageId, persistedData;
if (resumeEnabled && state.key === undefined) {
localStorageId = handler._getLocalStorageId(id);
persistedData = localStorage.getItem(localStorageId);
if (persistedData) {
persistedData = JSON.parse(persistedData);
if (getDataByUuid(persistedData.uuid)) {
handler._markNotResumable(id);
} else {
log(qq.format("Identified file with ID {} and name of {} as resumable.", id, getName(id)));
onUuidChanged(id, persistedData.uuid);
state.key = persistedData.key;
state.chunking = persistedData.chunking;
state.loaded = persistedData.loaded;
state.attemptingResume = true;
handler.moveInProgressToRemaining(id);
}
}
}
},
_maybePersistChunkedState: function(id) {
var state = handler._getFileState(id), localStorageId, persistedData;
if (resumeEnabled && handler.isResumable(id)) {
localStorageId = handler._getLocalStorageId(id);
persistedData = {
name: getName(id),
size: getSize(id),
uuid: getUuid(id),
key: state.key,
chunking: state.chunking,
loaded: state.loaded,
lastUpdated: Date.now()
};
try {
localStorage.setItem(localStorageId, JSON.stringify(persistedData));
} catch (error) {
log(qq.format("Unable to save resume data for '{}' due to error: '{}'.", id, error.toString()), "warn");
}
}
},
_registerProgressHandler: function(id, chunkIdx, chunkSize) {
var xhr = handler._getXhr(id, chunkIdx), name = getName(id), progressCalculator = {
simple: function(loaded, total) {
var fileSize = getSize(id);
if (loaded === total) {
onProgress(id, name, fileSize, fileSize);
} else {
onProgress(id, name, loaded >= fileSize ? fileSize - 1 : loaded, fileSize);
}
},
chunked: function(loaded, total) {
var chunkProgress = handler._getFileState(id).temp.chunkProgress, totalSuccessfullyLoadedForFile = handler._getFileState(id).loaded, loadedForRequest = loaded, totalForRequest = total, totalFileSize = getSize(id), estActualChunkLoaded = loadedForRequest - (totalForRequest - chunkSize), totalLoadedForFile = totalSuccessfullyLoadedForFile;
chunkProgress[chunkIdx] = estActualChunkLoaded;
qq.each(chunkProgress, function(chunkIdx, chunkLoaded) {
totalLoadedForFile += chunkLoaded;
});
onProgress(id, name, totalLoadedForFile, totalFileSize);
}
};
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var type = chunkSize == null ? "simple" : "chunked";
progressCalculator[type](e.loaded, e.total);
}
};
},
_registerXhr: function(id, optChunkIdx, xhr, optAjaxRequester) {
var xhrsId = optChunkIdx == null ? -1 : optChunkIdx, tempState = handler._getFileState(id).temp;
tempState.xhrs = tempState.xhrs || {};
tempState.ajaxRequesters = tempState.ajaxRequesters || {};
tempState.xhrs[xhrsId] = xhr;
if (optAjaxRequester) {
tempState.ajaxRequesters[xhrsId] = optAjaxRequester;
}
return xhr;
},
_removeExpiredChunkingRecords: function() {
var expirationDays = resume.recordsExpireIn;
handler._iterateResumeRecords(function(key, uploadData) {
var expirationDate = new Date(uploadData.lastUpdated);
expirationDate.setDate(expirationDate.getDate() + expirationDays);
if (expirationDate.getTime() <= Date.now()) {
log("Removing expired resume record with key " + key);
localStorage.removeItem(key);
}
});
},
_shouldChunkThisFile: function(id) {
var state = handler._getFileState(id);
if (!state.chunking) {
handler.reevaluateChunking(id);
}
return state.chunking.enabled;
}
});
};
qq.DeleteFileAjaxRequester = function(o) {
"use strict";
var requester, options = {
method: "DELETE",
uuidParamName: "qquuid",
endpointStore: {},
maxConnections: 3,
customHeaders: function(id) {
return {};
},
paramsStore: {},
cors: {
expected: false,
sendCredentials: false
},
log: function(str, level) {},
onDelete: function(id) {},
onDeleteComplete: function(id, xhrOrXdr, isError) {}
};
qq.extend(options, o);
function getMandatedParams() {
if (options.method.toUpperCase() === "POST") {
return {
_method: "DELETE"
};
}
return {};
}
requester = qq.extend(this, new qq.AjaxRequester({
acceptHeader: "application/json",
validMethods: [ "POST", "DELETE" ],
method: options.method,
endpointStore: options.endpointStore,
paramsStore: options.paramsStore,
mandatedParams: getMandatedParams(),
maxConnections: options.maxConnections,
customHeaders: function(id) {
return options.customHeaders.get(id);
},
log: options.log,
onSend: options.onDelete,
onComplete: options.onDeleteComplete,
cors: options.cors
}));
qq.extend(this, {
sendDelete: function(id, uuid, additionalMandatedParams) {
var additionalOptions = additionalMandatedParams || {};
options.log("Submitting delete file request for " + id);
if (options.method === "DELETE") {
requester.initTransport(id).withPath(uuid).withParams(additionalOptions).send();
} else {
additionalOptions[options.uuidParamName] = uuid;
requester.initTransport(id).withParams(additionalOptions).send();
}
}
});
};
(function() {
function detectSubsampling(img) {
var iw = img.naturalWidth, ih = img.naturalHeight, canvas = document.createElement("canvas"), ctx;
if (iw * ih > 1024 * 1024) {
canvas.width = canvas.height = 1;
ctx = canvas.getContext("2d");
ctx.drawImage(img, -iw + 1, 0);
return ctx.getImageData(0, 0, 1, 1).data[3] === 0;
} else {
return false;
}
}
function detectVerticalSquash(img, iw, ih) {
var canvas = document.createElement("canvas"), sy = 0, ey = ih, py = ih, ctx, data, alpha, ratio;
canvas.width = 1;
canvas.height = ih;
ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
data = ctx.getImageData(0, 0, 1, ih).data;
while (py > sy) {
alpha = data[(py - 1) * 4 + 3];
if (alpha === 0) {
ey = py;
} else {
sy = py;
}
py = ey + sy >> 1;
}
ratio = py / ih;
return ratio === 0 ? 1 : ratio;
}
function renderImageToDataURL(img, blob, options, doSquash) {
var canvas = document.createElement("canvas"), mime = options.mime || "image/jpeg", promise = new qq.Promise();
renderImageToCanvas(img, blob, canvas, options, doSquash).then(function() {
promise.success(canvas.toDataURL(mime, options.quality || .8));
});
return promise;
}
function maybeCalculateDownsampledDimensions(spec) {
var maxPixels = 5241e3;
if (!qq.ios()) {
throw new qq.Error("Downsampled dimensions can only be reliably calculated for iOS!");
}
if (spec.origHeight * spec.origWidth > maxPixels) {
return {
newHeight: Math.round(Math.sqrt(maxPixels * (spec.origHeight / spec.origWidth))),
newWidth: Math.round(Math.sqrt(maxPixels * (spec.origWidth / spec.origHeight)))
};
}
}
function renderImageToCanvas(img, blob, canvas, options, doSquash) {
var iw = img.naturalWidth, ih = img.naturalHeight, width = options.width, height = options.height, ctx = canvas.getContext("2d"), promise = new qq.Promise(), modifiedDimensions;
ctx.save();
if (options.resize) {
return renderImageToCanvasWithCustomResizer({
blob: blob,
canvas: canvas,
image: img,
imageHeight: ih,
imageWidth: iw,
orientation: options.orientation,
resize: options.resize,
targetHeight: height,
targetWidth: width
});
}
if (!qq.supportedFeatures.unlimitedScaledImageSize) {
modifiedDimensions = maybeCalculateDownsampledDimensions({
origWidth: width,
origHeight: height
});
if (modifiedDimensions) {
qq.log(qq.format("Had to reduce dimensions due to device limitations from {}w / {}h to {}w / {}h", width, height, modifiedDimensions.newWidth, modifiedDimensions.newHeight), "warn");
width = modifiedDimensions.newWidth;
height = modifiedDimensions.newHeight;
}
}
transformCoordinate(canvas, width, height, options.orientation);
if (qq.ios()) {
(function() {
if (detectSubsampling(img)) {
iw /= 2;
ih /= 2;
}
var d = 1024, tmpCanvas = document.createElement("canvas"), vertSquashRatio = doSquash ? detectVerticalSquash(img, iw, ih) : 1, dw = Math.ceil(d * width / iw), dh = Math.ceil(d * height / ih / vertSquashRatio), sy = 0, dy = 0, tmpCtx, sx, dx;
tmpCanvas.width = tmpCanvas.height = d;
tmpCtx = tmpCanvas.getContext("2d");
while (sy < ih) {
sx = 0;
dx = 0;
while (sx < iw) {
tmpCtx.clearRect(0, 0, d, d);
tmpCtx.drawImage(img, -sx, -sy);
ctx.drawImage(tmpCanvas, 0, 0, d, d, dx, dy, dw, dh);
sx += d;
dx += dw;
}
sy += d;
dy += dh;
}
ctx.restore();
tmpCanvas = tmpCtx = null;
})();
} else {
ctx.drawImage(img, 0, 0, width, height);
}
canvas.qqImageRendered && canvas.qqImageRendered();
promise.success();
return promise;
}
function renderImageToCanvasWithCustomResizer(resizeInfo) {
var blob = resizeInfo.blob, image = resizeInfo.image, imageHeight = resizeInfo.imageHeight, imageWidth = resizeInfo.imageWidth, orientation = resizeInfo.orientation, promise = new qq.Promise(), resize = resizeInfo.resize, sourceCanvas = document.createElement("canvas"), sourceCanvasContext = sourceCanvas.getContext("2d"), targetCanvas = resizeInfo.canvas, targetHeight = resizeInfo.targetHeight, targetWidth = resizeInfo.targetWidth;
transformCoordinate(sourceCanvas, imageWidth, imageHeight, orientation);
targetCanvas.height = targetHeight;
targetCanvas.width = targetWidth;
sourceCanvasContext.drawImage(image, 0, 0);
resize({
blob: blob,
height: targetHeight,
image: image,
sourceCanvas: sourceCanvas,
targetCanvas: targetCanvas,
width: targetWidth
}).then(function success() {
targetCanvas.qqImageRendered && targetCanvas.qqImageRendered();
promise.success();
}, promise.failure);
return promise;
}
function transformCoordinate(canvas, width, height, orientation) {
switch (orientation) {
case 5:
case 6:
case 7:
case 8:
canvas.width = height;
canvas.height = width;
break;
default:
canvas.width = width;
canvas.height = height;
}
var ctx = canvas.getContext("2d");
switch (orientation) {
case 2:
ctx.translate(width, 0);
ctx.scale(-1, 1);
break;
case 3:
ctx.translate(width, height);
ctx.rotate(Math.PI);
break;
case 4:
ctx.translate(0, height);
ctx.scale(1, -1);
break;
case 5:
ctx.rotate(.5 * Math.PI);
ctx.scale(1, -1);
break;
case 6:
ctx.rotate(.5 * Math.PI);
ctx.translate(0, -height);
break;
case 7:
ctx.rotate(.5 * Math.PI);
ctx.translate(width, -height);
ctx.scale(-1, 1);
break;
case 8:
ctx.rotate(-.5 * Math.PI);
ctx.translate(-width, 0);
break;
default:
break;
}
}
function MegaPixImage(srcImage, errorCallback) {
var self = this;
if (window.Blob && srcImage instanceof Blob) {
(function() {
var img = new Image(), URL = window.URL && window.URL.createObjectURL ? window.URL : window.webkitURL && window.webkitURL.createObjectURL ? window.webkitURL : null;
if (!URL) {
throw Error("No createObjectURL function found to create blob url");
}
img.src = URL.createObjectURL(srcImage);
self.blob = srcImage;
srcImage = img;
})();
}
if (!srcImage.naturalWidth && !srcImage.naturalHeight) {
srcImage.onload = function() {
var listeners = self.imageLoadListeners;
if (listeners) {
self.imageLoadListeners = null;
setTimeout(function() {
for (var i = 0, len = listeners.length; i < len; i++) {
listeners[i]();
}
}, 0);
}
};
srcImage.onerror = errorCallback;
this.imageLoadListeners = [];
}
this.srcImage = srcImage;
}
MegaPixImage.prototype.render = function(target, options) {
options = options || {};
var self = this, imgWidth = this.srcImage.naturalWidth, imgHeight = this.srcImage.naturalHeight, width = options.width, height = options.height, maxWidth = options.maxWidth, maxHeight = options.maxHeight, doSquash = !this.blob || this.blob.type === "image/jpeg", tagName = target.tagName.toLowerCase(), opt;
if (this.imageLoadListeners) {
this.imageLoadListeners.push(function() {
self.render(target, options);
});
return;
}
if (width && !height) {
height = imgHeight * width / imgWidth << 0;
} else if (height && !width) {
width = imgWidth * height / imgHeight << 0;
} else {
width = imgWidth;
height = imgHeight;
}
if (maxWidth && width > maxWidth) {
width = maxWidth;
height = imgHeight * width / imgWidth << 0;
}
if (maxHeight && height > maxHeight) {
height = maxHeight;
width = imgWidth * height / imgHeight << 0;
}
opt = {
width: width,
height: height
}, qq.each(options, function(optionsKey, optionsValue) {
opt[optionsKey] = optionsValue;
});
if (tagName === "img") {
(function() {
var oldTargetSrc = target.src;
renderImageToDataURL(self.srcImage, self.blob, opt, doSquash).then(function(dataUri) {
target.src = dataUri;
oldTargetSrc === target.src && target.onload();
});
})();
} else if (tagName === "canvas") {
renderImageToCanvas(this.srcImage, this.blob, target, opt, doSquash);
}
if (typeof this.onrender === "function") {
this.onrender(target);
}
};
qq.MegaPixImage = MegaPixImage;
})();
qq.ImageGenerator = function(log) {
"use strict";
function isImg(el) {
return el.tagName.toLowerCase() === "img";
}
function isCanvas(el) {
return el.tagName.toLowerCase() === "canvas";
}
function isImgCorsSupported() {
return new Image().crossOrigin !== undefined;
}
function isCanvasSupported() {
var canvas = document.createElement("canvas");
return canvas.getContext && canvas.getContext("2d");
}
function determineMimeOfFileName(nameWithPath) {
var pathSegments = nameWithPath.split("/"), name = pathSegments[pathSegments.length - 1].split("?")[0], extension = qq.getExtension(name);
extension = extension && extension.toLowerCase();
switch (extension) {
case "jpeg":
case "jpg":
return "image/jpeg";
case "png":
return "image/png";
case "bmp":
return "image/bmp";
case "gif":
return "image/gif";
case "tiff":
case "tif":
return "image/tiff";
}
}
function isCrossOrigin(url) {
var targetAnchor = document.createElement("a"), targetProtocol, targetHostname, targetPort;
targetAnchor.href = url;
targetProtocol = targetAnchor.protocol;
targetPort = targetAnchor.port;
targetHostname = targetAnchor.hostname;
if (targetProtocol.toLowerCase() !== window.location.protocol.toLowerCase()) {
return true;
}
if (targetHostname.toLowerCase() !== window.location.hostname.toLowerCase()) {
return true;
}
if (targetPort !== window.location.port && !qq.ie()) {
return true;
}
return false;
}
function registerImgLoadListeners(img, promise) {
img.onload = function() {
img.onload = null;
img.onerror = null;
promise.success(img);
};
img.onerror = function() {
img.onload = null;
img.onerror = null;
log("Problem drawing thumbnail!", "error");
promise.failure(img, "Problem drawing thumbnail!");
};
}
function registerCanvasDrawImageListener(canvas, promise) {
canvas.qqImageRendered = function() {
promise.success(canvas);
};
}
function registerThumbnailRenderedListener(imgOrCanvas, promise) {
var registered = isImg(imgOrCanvas) || isCanvas(imgOrCanvas);
if (isImg(imgOrCanvas)) {
registerImgLoadListeners(imgOrCanvas, promise);
} else if (isCanvas(imgOrCanvas)) {
registerCanvasDrawImageListener(imgOrCanvas, promise);
} else {
promise.failure(imgOrCanvas);
log(qq.format("Element container of type {} is not supported!", imgOrCanvas.tagName), "error");
}
return registered;
}
function draw(fileOrBlob, container, options) {
var drawPreview = new qq.Promise(), identifier = new qq.Identify(fileOrBlob, log), maxSize = options.maxSize, orient = options.orient == null ? true : options.orient, megapixErrorHandler = function() {
container.onerror = null;
container.onload = null;
log("Could not render preview, file may be too large!", "error");
drawPreview.failure(container, "Browser cannot render image!");
};
identifier.isPreviewable().then(function(mime) {
var dummyExif = {
parse: function() {
return new qq.Promise().success();
}
}, exif = orient ? new qq.Exif(fileOrBlob, log) : dummyExif, mpImg = new qq.MegaPixImage(fileOrBlob, megapixErrorHandler);
if (registerThumbnailRenderedListener(container, drawPreview)) {
exif.parse().then(function(exif) {
var orientation = exif && exif.Orientation;
mpImg.render(container, {
maxWidth: maxSize,
maxHeight: maxSize,
orientation: orientation,
mime: mime,
resize: options.customResizeFunction
});
}, function(failureMsg) {
log(qq.format("EXIF data could not be parsed ({}). Assuming orientation = 1.", failureMsg));
mpImg.render(container, {
maxWidth: maxSize,
maxHeight: maxSize,
mime: mime,
resize: options.customResizeFunction
});
});
}
}, function() {
log("Not previewable");
drawPreview.failure(container, "Not previewable");
});
return drawPreview;
}
function drawOnCanvasOrImgFromUrl(url, canvasOrImg, draw, maxSize, customResizeFunction) {
var tempImg = new Image(), tempImgRender = new qq.Promise();
registerThumbnailRenderedListener(tempImg, tempImgRender);
if (isCrossOrigin(url)) {
tempImg.crossOrigin = "anonymous";
}
tempImg.src = url;
tempImgRender.then(function rendered() {
registerThumbnailRenderedListener(canvasOrImg, draw);
var mpImg = new qq.MegaPixImage(tempImg);
mpImg.render(canvasOrImg, {
maxWidth: maxSize,
maxHeight: maxSize,
mime: determineMimeOfFileName(url),
resize: customResizeFunction
});
}, draw.failure);
}
function drawOnImgFromUrlWithCssScaling(url, img, draw, maxSize) {
registerThumbnailRenderedListener(img, draw);
qq(img).css({
maxWidth: maxSize + "px",
maxHeight: maxSize + "px"
});
img.src = url;
}
function drawFromUrl(url, container, options) {
var draw = new qq.Promise(), scale = options.scale, maxSize = scale ? options.maxSize : null;
if (scale && isImg(container)) {
if (isCanvasSupported()) {
if (isCrossOrigin(url) && !isImgCorsSupported()) {
drawOnImgFromUrlWithCssScaling(url, container, draw, maxSize);
} else {
drawOnCanvasOrImgFromUrl(url, container, draw, maxSize);
}
} else {
drawOnImgFromUrlWithCssScaling(url, container, draw, maxSize);
}
} else if (isCanvas(container)) {
drawOnCanvasOrImgFromUrl(url, container, draw, maxSize);
} else if (registerThumbnailRenderedListener(container, draw)) {
container.src = url;
}
return draw;
}
qq.extend(this, {
generate: function(fileBlobOrUrl, container, options) {
if (qq.isString(fileBlobOrUrl)) {
log("Attempting to update thumbnail based on server response.");
return drawFromUrl(fileBlobOrUrl, container, options || {});
} else {
log("Attempting to draw client-side image preview.");
return draw(fileBlobOrUrl, container, options || {});
}
}
});
this._testing = {};
this._testing.isImg = isImg;
this._testing.isCanvas = isCanvas;
this._testing.isCrossOrigin = isCrossOrigin;
this._testing.determineMimeOfFileName = determineMimeOfFileName;
};
qq.Exif = function(fileOrBlob, log) {
"use strict";
var TAG_IDS = [ 274 ], TAG_INFO = {
274: {
name: "Orientation",
bytes: 2
}
};
function parseLittleEndian(hex) {
var result = 0, pow = 0;
while (hex.length > 0) {
result += parseInt(hex.substring(0, 2), 16) * Math.pow(2, pow);
hex = hex.substring(2, hex.length);
pow += 8;
}
return result;
}
function seekToApp1(offset, promise) {
var theOffset = offset, thePromise = promise;
if (theOffset === undefined) {
theOffset = 2;
thePromise = new qq.Promise();
}
qq.readBlobToHex(fileOrBlob, theOffset, 4).then(function(hex) {
var match = /^ffe([0-9])/.exec(hex), segmentLength;
if (match) {
if (match[1] !== "1") {
segmentLength = parseInt(hex.slice(4, 8), 16);
seekToApp1(theOffset + segmentLength + 2, thePromise);
} else {
thePromise.success(theOffset);
}
} else {
thePromise.failure("No EXIF header to be found!");
}
});
return thePromise;
}
function getApp1Offset() {
var promise = new qq.Promise();
qq.readBlobToHex(fileOrBlob, 0, 6).then(function(hex) {
if (hex.indexOf("ffd8") !== 0) {
promise.failure("Not a valid JPEG!");
} else {
seekToApp1().then(function(offset) {
promise.success(offset);
}, function(error) {
promise.failure(error);
});
}
});
return promise;
}
function isLittleEndian(app1Start) {
var promise = new qq.Promise();
qq.readBlobToHex(fileOrBlob, app1Start + 10, 2).then(function(hex) {
promise.success(hex === "4949");
});
return promise;
}
function getDirEntryCount(app1Start, littleEndian) {
var promise = new qq.Promise();
qq.readBlobToHex(fileOrBlob, app1Start + 18, 2).then(function(hex) {
if (littleEndian) {
return promise.success(parseLittleEndian(hex));
} else {
promise.success(parseInt(hex, 16));
}
});
return promise;
}
function getIfd(app1Start, dirEntries) {
var offset = app1Start + 20, bytes = dirEntries * 12;
return qq.readBlobToHex(fileOrBlob, offset, bytes);
}
function getDirEntries(ifdHex) {
var entries = [], offset = 0;
while (offset + 24 <= ifdHex.length) {
entries.push(ifdHex.slice(offset, offset + 24));
offset += 24;
}
return entries;
}
function getTagValues(littleEndian, dirEntries) {
var TAG_VAL_OFFSET = 16, tagsToFind = qq.extend([], TAG_IDS), vals = {};
qq.each(dirEntries, function(idx, entry) {
var idHex = entry.slice(0, 4), id = littleEndian ? parseLittleEndian(idHex) : parseInt(idHex, 16), tagsToFindIdx = tagsToFind.indexOf(id), tagValHex, tagName, tagValLength;
if (tagsToFindIdx >= 0) {
tagName = TAG_INFO[id].name;
tagValLength = TAG_INFO[id].bytes;
tagValHex = entry.slice(TAG_VAL_OFFSET, TAG_VAL_OFFSET + tagValLength * 2);
vals[tagName] = littleEndian ? parseLittleEndian(tagValHex) : parseInt(tagValHex, 16);
tagsToFind.splice(tagsToFindIdx, 1);
}
if (tagsToFind.length === 0) {
return false;
}
});
return vals;
}
qq.extend(this, {
parse: function() {
var parser = new qq.Promise(), onParseFailure = function(message) {
log(qq.format("EXIF header parse failed: '{}' ", message));
parser.failure(message);
};
getApp1Offset().then(function(app1Offset) {
log(qq.format("Moving forward with EXIF header parsing for '{}'", fileOrBlob.name === undefined ? "blob" : fileOrBlob.name));
isLittleEndian(app1Offset).then(function(littleEndian) {
log(qq.format("EXIF Byte order is {} endian", littleEndian ? "little" : "big"));
getDirEntryCount(app1Offset, littleEndian).then(function(dirEntryCount) {
log(qq.format("Found {} APP1 directory entries", dirEntryCount));
getIfd(app1Offset, dirEntryCount).then(function(ifdHex) {
var dirEntries = getDirEntries(ifdHex), tagValues = getTagValues(littleEndian, dirEntries);
log("Successfully parsed some EXIF tags");
parser.success(tagValues);
}, onParseFailure);
}, onParseFailure);
}, onParseFailure);
}, onParseFailure);
return parser;
}
});
this._testing = {};
this._testing.parseLittleEndian = parseLittleEndian;
};
qq.Identify = function(fileOrBlob, log) {
"use strict";
function isIdentifiable(magicBytes, questionableBytes) {
var identifiable = false, magicBytesEntries = [].concat(magicBytes);
qq.each(magicBytesEntries, function(idx, magicBytesArrayEntry) {
if (questionableBytes.indexOf(magicBytesArrayEntry) === 0) {
identifiable = true;
return false;
}
});
return identifiable;
}
qq.extend(this, {
isPreviewable: function() {
var self = this, identifier = new qq.Promise(), previewable = false, name = fileOrBlob.name === undefined ? "blob" : fileOrBlob.name;
log(qq.format("Attempting to determine if {} can be rendered in this browser", name));
log("First pass: check type attribute of blob object.");
if (this.isPreviewableSync()) {
log("Second pass: check for magic bytes in file header.");
qq.readBlobToHex(fileOrBlob, 0, 4).then(function(hex) {
qq.each(self.PREVIEWABLE_MIME_TYPES, function(mime, bytes) {
if (isIdentifiable(bytes, hex)) {
if (mime !== "image/tiff" || qq.supportedFeatures.tiffPreviews) {
previewable = true;
identifier.success(mime);
}
return false;
}
});
log(qq.format("'{}' is {} able to be rendered in this browser", name, previewable ? "" : "NOT"));
if (!previewable) {
identifier.failure();
}
}, function() {
log("Error reading file w/ name '" + name + "'. Not able to be rendered in this browser.");
identifier.failure();
});
} else {
identifier.failure();
}
return identifier;
},
isPreviewableSync: function() {
var fileMime = fileOrBlob.type, isRecognizedImage = qq.indexOf(Object.keys(this.PREVIEWABLE_MIME_TYPES), fileMime) >= 0, previewable = false, name = fileOrBlob.name === undefined ? "blob" : fileOrBlob.name;
if (isRecognizedImage) {
if (fileMime === "image/tiff") {
previewable = qq.supportedFeatures.tiffPreviews;
} else {
previewable = true;
}
}
!previewable && log(name + " is not previewable in this browser per the blob's type attr");
return previewable;
}
});
};
qq.Identify.prototype.PREVIEWABLE_MIME_TYPES = {
"image/jpeg": "ffd8ff",
"image/gif": "474946",
"image/png": "89504e",
"image/bmp": "424d",
"image/tiff": [ "49492a00", "4d4d002a" ]
};
qq.Identify = function(fileOrBlob, log) {
"use strict";
function isIdentifiable(magicBytes, questionableBytes) {
var identifiable = false, magicBytesEntries = [].concat(magicBytes);
qq.each(magicBytesEntries, function(idx, magicBytesArrayEntry) {
if (questionableBytes.indexOf(magicBytesArrayEntry) === 0) {
identifiable = true;
return false;
}
});
return identifiable;
}
qq.extend(this, {
isPreviewable: function() {
var self = this, identifier = new qq.Promise(), previewable = false, name = fileOrBlob.name === undefined ? "blob" : fileOrBlob.name;
log(qq.format("Attempting to determine if {} can be rendered in this browser", name));
log("First pass: check type attribute of blob object.");
if (this.isPreviewableSync()) {
log("Second pass: check for magic bytes in file header.");
qq.readBlobToHex(fileOrBlob, 0, 4).then(function(hex) {
qq.each(self.PREVIEWABLE_MIME_TYPES, function(mime, bytes) {
if (isIdentifiable(bytes, hex)) {
if (mime !== "image/tiff" || qq.supportedFeatures.tiffPreviews) {
previewable = true;
identifier.success(mime);
}
return false;
}
});
log(qq.format("'{}' is {} able to be rendered in this browser", name, previewable ? "" : "NOT"));
if (!previewable) {
identifier.failure();
}
}, function() {
log("Error reading file w/ name '" + name + "'. Not able to be rendered in this browser.");
identifier.failure();
});
} else {
identifier.failure();
}
return identifier;
},
isPreviewableSync: function() {
var fileMime = fileOrBlob.type, isRecognizedImage = qq.indexOf(Object.keys(this.PREVIEWABLE_MIME_TYPES), fileMime) >= 0, previewable = false, name = fileOrBlob.name === undefined ? "blob" : fileOrBlob.name;
if (isRecognizedImage) {
if (fileMime === "image/tiff") {
previewable = qq.supportedFeatures.tiffPreviews;
} else {
previewable = true;
}
}
!previewable && log(name + " is not previewable in this browser per the blob's type attr");
return previewable;
}
});
};
qq.Identify.prototype.PREVIEWABLE_MIME_TYPES = {
"image/jpeg": "ffd8ff",
"image/gif": "474946",
"image/png": "89504e",
"image/bmp": "424d",
"image/tiff": [ "49492a00", "4d4d002a" ]
};
qq.ImageValidation = function(blob, log) {
"use strict";
function hasNonZeroLimits(limits) {
var atLeastOne = false;
qq.each(limits, function(limit, value) {
if (value > 0) {
atLeastOne = true;
return false;
}
});
return atLeastOne;
}
function getWidthHeight() {
var sizeDetermination = new qq.Promise();
new qq.Identify(blob, log).isPreviewable().then(function() {
var image = new Image(), url = window.URL && window.URL.createObjectURL ? window.URL : window.webkitURL && window.webkitURL.createObjectURL ? window.webkitURL : null;
if (url) {
image.onerror = function() {
log("Cannot determine dimensions for image. May be too large.", "error");
sizeDetermination.failure();
};
image.onload = function() {
sizeDetermination.success({
width: this.width,
height: this.height
});
};
image.src = url.createObjectURL(blob);
} else {
log("No createObjectURL function available to generate image URL!", "error");
sizeDetermination.failure();
}
}, sizeDetermination.failure);
return sizeDetermination;
}
function getFailingLimit(limits, dimensions) {
var failingLimit;
qq.each(limits, function(limitName, limitValue) {
if (limitValue > 0) {
var limitMatcher = /(max|min)(Width|Height)/.exec(limitName), dimensionPropName = limitMatcher[2].charAt(0).toLowerCase() + limitMatcher[2].slice(1), actualValue = dimensions[dimensionPropName];
switch (limitMatcher[1]) {
case "min":
if (actualValue < limitValue) {
failingLimit = limitName;
return false;
}
break;
case "max":
if (actualValue > limitValue) {
failingLimit = limitName;
return false;
}
break;
}
}
});
return failingLimit;
}
this.validate = function(limits) {
var validationEffort = new qq.Promise();
log("Attempting to validate image.");
if (hasNonZeroLimits(limits)) {
getWidthHeight().then(function(dimensions) {
var failingLimit = getFailingLimit(limits, dimensions);
if (failingLimit) {
validationEffort.failure(failingLimit);
} else {
validationEffort.success();
}
}, validationEffort.success);
} else {
validationEffort.success();
}
return validationEffort;
};
};
qq.Session = function(spec) {
"use strict";
var options = {
endpoint: null,
params: {},
customHeaders: {},
cors: {},
addFileRecord: function(sessionData) {},
log: function(message, level) {}
};
qq.extend(options, spec, true);
function isJsonResponseValid(response) {
if (qq.isArray(response)) {
return true;
}
options.log("Session response is not an array.", "error");
}
function handleFileItems(fileItems, success, xhrOrXdr, promise) {
var someItemsIgnored = false;
success = success && isJsonResponseValid(fileItems);
if (success) {
qq.each(fileItems, function(idx, fileItem) {
if (fileItem.uuid == null) {
someItemsIgnored = true;
options.log(qq.format("Session response item {} did not include a valid UUID - ignoring.", idx), "error");
} else if (fileItem.name == null) {
someItemsIgnored = true;
options.log(qq.format("Session response item {} did not include a valid name - ignoring.", idx), "error");
} else {
try {
options.addFileRecord(fileItem);
return true;
} catch (err) {
someItemsIgnored = true;
options.log(err.message, "error");
}
}
return false;
});
}
promise[success && !someItemsIgnored ? "success" : "failure"](fileItems, xhrOrXdr);
}
this.refresh = function() {
var refreshEffort = new qq.Promise(), refreshCompleteCallback = function(response, success, xhrOrXdr) {
handleFileItems(response, success, xhrOrXdr, refreshEffort);
}, requesterOptions = qq.extend({}, options), requester = new qq.SessionAjaxRequester(qq.extend(requesterOptions, {
onComplete: refreshCompleteCallback
}));
requester.queryServer();
return refreshEffort;
};
};
qq.SessionAjaxRequester = function(spec) {
"use strict";
var requester, options = {
endpoint: null,
customHeaders: {},
params: {},
cors: {
expected: false,
sendCredentials: false
},
onComplete: function(response, success, xhrOrXdr) {},
log: function(str, level) {}
};
qq.extend(options, spec);
function onComplete(id, xhrOrXdr, isError) {
var response = null;
if (xhrOrXdr.responseText != null) {
try {
response = qq.parseJson(xhrOrXdr.responseText);
} catch (err) {
options.log("Problem parsing session response: " + err.message, "error");
isError = true;
}
}
options.onComplete(response, !isError, xhrOrXdr);
}
requester = qq.extend(this, new qq.AjaxRequester({
acceptHeader: "application/json",
validMethods: [ "GET" ],
method: "GET",
endpointStore: {
get: function() {
return options.endpoint;
}
},
customHeaders: options.customHeaders,
log: options.log,
onComplete: onComplete,
cors: options.cors
}));
qq.extend(this, {
queryServer: function() {
var params = qq.extend({}, options.params);
options.log("Session query request.");
requester.initTransport("sessionRefresh").withParams(params).withCacheBuster().send();
}
});
};
qq.Scaler = function(spec, log) {
"use strict";
var self = this, customResizeFunction = spec.customResizer, includeOriginal = spec.sendOriginal, orient = spec.orient, defaultType = spec.defaultType, defaultQuality = spec.defaultQuality / 100, failedToScaleText = spec.failureText, includeExif = spec.includeExif, sizes = this._getSortedSizes(spec.sizes);
qq.extend(this, {
enabled: qq.supportedFeatures.scaling && sizes.length > 0,
getFileRecords: function(originalFileUuid, originalFileName, originalBlobOrBlobData) {
var self = this, records = [], originalBlob = originalBlobOrBlobData.blob ? originalBlobOrBlobData.blob : originalBlobOrBlobData, identifier = new qq.Identify(originalBlob, log);
if (identifier.isPreviewableSync()) {
qq.each(sizes, function(idx, sizeRecord) {
var outputType = self._determineOutputType({
defaultType: defaultType,
requestedType: sizeRecord.type,
refType: originalBlob.type
});
records.push({
uuid: qq.getUniqueId(),
name: self._getName(originalFileName, {
name: sizeRecord.name,
type: outputType,
refType: originalBlob.type
}),
blob: new qq.BlobProxy(originalBlob, qq.bind(self._generateScaledImage, self, {
customResizeFunction: customResizeFunction,
maxSize: sizeRecord.maxSize,
orient: orient,
type: outputType,
quality: defaultQuality,
failedText: failedToScaleText,
includeExif: includeExif,
log: log
}))
});
});
records.push({
uuid: originalFileUuid,
name: originalFileName,
size: originalBlob.size,
blob: includeOriginal ? originalBlob : null
});
} else {
records.push({
uuid: originalFileUuid,
name: originalFileName,
size: originalBlob.size,
blob: originalBlob
});
}
return records;
},
handleNewFile: function(file, name, uuid, size, fileList, batchId, uuidParamName, api) {
var self = this, buttonId = file.qqButtonId || file.blob && file.blob.qqButtonId, scaledIds = [], originalId = null, addFileToHandler = api.addFileToHandler, uploadData = api.uploadData, paramsStore = api.paramsStore, proxyGroupId = qq.getUniqueId();
qq.each(self.getFileRecords(uuid, name, file), function(idx, record) {
var blobSize = record.size, id;
if (record.blob instanceof qq.BlobProxy) {
blobSize = -1;
}
id = uploadData.addFile({
uuid: record.uuid,
name: record.name,
size: blobSize,
batchId: batchId,
proxyGroupId: proxyGroupId
});
if (record.blob instanceof qq.BlobProxy) {
scaledIds.push(id);
} else {
originalId = id;
}
if (record.blob) {
addFileToHandler(id, record.blob);
fileList.push({
id: id,
file: record.blob
});
} else {
uploadData.setStatus(id, qq.status.REJECTED);
}
});
if (originalId !== null) {
qq.each(scaledIds, function(idx, scaledId) {
var params = {
qqparentuuid: uploadData.retrieve({
id: originalId
}).uuid,
qqparentsize: uploadData.retrieve({
id: originalId
}).size
};
params[uuidParamName] = uploadData.retrieve({
id: scaledId
}).uuid;
uploadData.setParentId(scaledId, originalId);
paramsStore.addReadOnly(scaledId, params);
});
if (scaledIds.length) {
(function() {
var param = {};
param[uuidParamName] = uploadData.retrieve({
id: originalId
}).uuid;
paramsStore.addReadOnly(originalId, param);
})();
}
}
}
});
};
qq.extend(qq.Scaler.prototype, {
scaleImage: function(id, specs, api) {
"use strict";
if (!qq.supportedFeatures.scaling) {
throw new qq.Error("Scaling is not supported in this browser!");
}
var scalingEffort = new qq.Promise(), log = api.log, file = api.getFile(id), uploadData = api.uploadData.retrieve({
id: id
}), name = uploadData && uploadData.name, uuid = uploadData && uploadData.uuid, scalingOptions = {
customResizer: specs.customResizer,
sendOriginal: false,
orient: specs.orient,
defaultType: specs.type || null,
defaultQuality: specs.quality,
failedToScaleText: "Unable to scale",
sizes: [ {
name: "",
maxSize: specs.maxSize
} ]
}, scaler = new qq.Scaler(scalingOptions, log);
if (!qq.Scaler || !qq.supportedFeatures.imagePreviews || !file) {
scalingEffort.failure();
log("Could not generate requested scaled image for " + id + ". " + "Scaling is either not possible in this browser, or the file could not be located.", "error");
} else {
qq.bind(function() {
var record = scaler.getFileRecords(uuid, name, file)[0];
if (record && record.blob instanceof qq.BlobProxy) {
record.blob.create().then(scalingEffort.success, scalingEffort.failure);
} else {
log(id + " is not a scalable image!", "error");
scalingEffort.failure();
}
}, this)();
}
return scalingEffort;
},
_determineOutputType: function(spec) {
"use strict";
var requestedType = spec.requestedType, defaultType = spec.defaultType, referenceType = spec.refType;
if (!defaultType && !requestedType) {
if (referenceType !== "image/jpeg") {
return "image/png";
}
return referenceType;
}
if (!requestedType) {
return defaultType;
}
if (qq.indexOf(Object.keys(qq.Identify.prototype.PREVIEWABLE_MIME_TYPES), requestedType) >= 0) {
if (requestedType === "image/tiff") {
return qq.supportedFeatures.tiffPreviews ? requestedType : defaultType;
}
return requestedType;
}
return defaultType;
},
_getName: function(originalName, scaledVersionProperties) {
"use strict";
var startOfExt = originalName.lastIndexOf("."), versionType = scaledVersionProperties.type || "image/png", referenceType = scaledVersionProperties.refType, scaledName = "", scaledExt = qq.getExtension(originalName), nameAppendage = "";
if (scaledVersionProperties.name && scaledVersionProperties.name.trim().length) {
nameAppendage = " (" + scaledVersionProperties.name + ")";
}
if (startOfExt >= 0) {
scaledName = originalName.substr(0, startOfExt);
if (referenceType !== versionType) {
scaledExt = versionType.split("/")[1];
}
scaledName += nameAppendage + "." + scaledExt;
} else {
scaledName = originalName + nameAppendage;
}
return scaledName;
},
_getSortedSizes: function(sizes) {
"use strict";
sizes = qq.extend([], sizes);
return sizes.sort(function(a, b) {
if (a.maxSize > b.maxSize) {
return 1;
}
if (a.maxSize < b.maxSize) {
return -1;
}
return 0;
});
},
_generateScaledImage: function(spec, sourceFile) {
"use strict";
var self = this, customResizeFunction = spec.customResizeFunction, log = spec.log, maxSize = spec.maxSize, orient = spec.orient, type = spec.type, quality = spec.quality, failedText = spec.failedText, includeExif = spec.includeExif && sourceFile.type === "image/jpeg" && type === "image/jpeg", scalingEffort = new qq.Promise(), imageGenerator = new qq.ImageGenerator(log), canvas = document.createElement("canvas");
log("Attempting to generate scaled version for " + sourceFile.name);
imageGenerator.generate(sourceFile, canvas, {
maxSize: maxSize,
orient: orient,
customResizeFunction: customResizeFunction
}).then(function() {
var scaledImageDataUri = canvas.toDataURL(type, quality), signalSuccess = function() {
log("Success generating scaled version for " + sourceFile.name);
var blob = qq.dataUriToBlob(scaledImageDataUri);
scalingEffort.success(blob);
};
if (includeExif) {
self._insertExifHeader(sourceFile, scaledImageDataUri, log).then(function(scaledImageDataUriWithExif) {
scaledImageDataUri = scaledImageDataUriWithExif;
signalSuccess();
}, function() {
log("Problem inserting EXIF header into scaled image. Using scaled image w/out EXIF data.", "error");
signalSuccess();
});
} else {
signalSuccess();
}
}, function() {
log("Failed attempt to generate scaled version for " + sourceFile.name, "error");
scalingEffort.failure(failedText);
});
return scalingEffort;
},
_insertExifHeader: function(originalImage, scaledImageDataUri, log) {
"use strict";
var reader = new FileReader(), insertionEffort = new qq.Promise(), originalImageDataUri = "";
reader.onload = function() {
originalImageDataUri = reader.result;
insertionEffort.success(qq.ExifRestorer.restore(originalImageDataUri, scaledImageDataUri));
};
reader.onerror = function() {
log("Problem reading " + originalImage.name + " during attempt to transfer EXIF data to scaled version.", "error");
insertionEffort.failure();
};
reader.readAsDataURL(originalImage);
return insertionEffort;
},
_dataUriToBlob: function(dataUri) {
"use strict";
var byteString, mimeString, arrayBuffer, intArray;
if (dataUri.split(",")[0].indexOf("base64") >= 0) {
byteString = atob(dataUri.split(",")[1]);
} else {
byteString = decodeURI(dataUri.split(",")[1]);
}
mimeString = dataUri.split(",")[0].split(":")[1].split(";")[0];
arrayBuffer = new ArrayBuffer(byteString.length);
intArray = new Uint8Array(arrayBuffer);
qq.each(byteString, function(idx, character) {
intArray[idx] = character.charCodeAt(0);
});
return this._createBlob(arrayBuffer, mimeString);
},
_createBlob: function(data, mime) {
"use strict";
var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder, blobBuilder = BlobBuilder && new BlobBuilder();
if (blobBuilder) {
blobBuilder.append(data);
return blobBuilder.getBlob(mime);
} else {
return new Blob([ data ], {
type: mime
});
}
}
});
qq.ExifRestorer = function() {
var ExifRestorer = {};
ExifRestorer.KEY_STR = "ABCDEFGHIJKLMNOP" + "QRSTUVWXYZabcdef" + "ghijklmnopqrstuv" + "wxyz0123456789+/" + "=";
ExifRestorer.encode64 = function(input) {
var output = "", chr1, chr2, chr3 = "", enc1, enc2, enc3, enc4 = "", i = 0;
do {
chr1 = input[i++];
chr2 = input[i++];
chr3 = input[i++];
enc1 = chr1 >> 2;
enc2 = (chr1 & 3) << 4 | chr2 >> 4;
enc3 = (chr2 & 15) << 2 | chr3 >> 6;
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output + this.KEY_STR.charAt(enc1) + this.KEY_STR.charAt(enc2) + this.KEY_STR.charAt(enc3) + this.KEY_STR.charAt(enc4);
chr1 = chr2 = chr3 = "";
enc1 = enc2 = enc3 = enc4 = "";
} while (i < input.length);
return output;
};
ExifRestorer.restore = function(origFileBase64, resizedFileBase64) {
var expectedBase64Header = "data:image/jpeg;base64,";
if (!origFileBase64.match(expectedBase64Header)) {
return resizedFileBase64;
}
var rawImage = this.decode64(origFileBase64.replace(expectedBase64Header, ""));
var segments = this.slice2Segments(rawImage);
var image = this.exifManipulation(resizedFileBase64, segments);
return expectedBase64Header + this.encode64(image);
};
ExifRestorer.exifManipulation = function(resizedFileBase64, segments) {
var exifArray = this.getExifArray(segments), newImageArray = this.insertExif(resizedFileBase64, exifArray), aBuffer = new Uint8Array(newImageArray);
return aBuffer;
};
ExifRestorer.getExifArray = function(segments) {
var seg;
for (var x = 0; x < segments.length; x++) {
seg = segments[x];
if (seg[0] == 255 & seg[1] == 225) {
return seg;
}
}
return [];
};
ExifRestorer.insertExif = function(resizedFileBase64, exifArray) {
var imageData = resizedFileBase64.replace("data:image/jpeg;base64,", ""), buf = this.decode64(imageData), separatePoint = buf.indexOf(255, 3), mae = buf.slice(0, separatePoint), ato = buf.slice(separatePoint), array = mae;
array = array.concat(exifArray);
array = array.concat(ato);
return array;
};
ExifRestorer.slice2Segments = function(rawImageArray) {
var head = 0, segments = [];
while (1) {
if (rawImageArray[head] == 255 & rawImageArray[head + 1] == 218) {
break;
}
if (rawImageArray[head] == 255 & rawImageArray[head + 1] == 216) {
head += 2;
} else {
var length = rawImageArray[head + 2] * 256 + rawImageArray[head + 3], endPoint = head + length + 2, seg = rawImageArray.slice(head, endPoint);
segments.push(seg);
head = endPoint;
}
if (head > rawImageArray.length) {
break;
}
}
return segments;
};
ExifRestorer.decode64 = function(input) {
var output = "", chr1, chr2, chr3 = "", enc1, enc2, enc3, enc4 = "", i = 0, buf = [];
var base64test = /[^A-Za-z0-9\+\/\=]/g;
if (base64test.exec(input)) {
throw new Error("There were invalid base64 characters in the input text. " + "Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='");
}
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
do {
enc1 = this.KEY_STR.indexOf(input.charAt(i++));
enc2 = this.KEY_STR.indexOf(input.charAt(i++));
enc3 = this.KEY_STR.indexOf(input.charAt(i++));
enc4 = this.KEY_STR.indexOf(input.charAt(i++));
chr1 = enc1 << 2 | enc2 >> 4;
chr2 = (enc2 & 15) << 4 | enc3 >> 2;
chr3 = (enc3 & 3) << 6 | enc4;
buf.push(chr1);
if (enc3 != 64) {
buf.push(chr2);
}
if (enc4 != 64) {
buf.push(chr3);
}
chr1 = chr2 = chr3 = "";
enc1 = enc2 = enc3 = enc4 = "";
} while (i < input.length);
return buf;
};
return ExifRestorer;
}();
qq.TotalProgress = function(callback, getSize) {
"use strict";
var perFileProgress = {}, totalLoaded = 0, totalSize = 0, lastLoadedSent = -1, lastTotalSent = -1, callbackProxy = function(loaded, total) {
if (loaded !== lastLoadedSent || total !== lastTotalSent) {
callback(loaded, total);
}
lastLoadedSent = loaded;
lastTotalSent = total;
}, noRetryableFiles = function(failed, retryable) {
var none = true;
qq.each(failed, function(idx, failedId) {
if (qq.indexOf(retryable, failedId) >= 0) {
none = false;
return false;
}
});
return none;
}, onCancel = function(id) {
updateTotalProgress(id, -1, -1);
delete perFileProgress[id];
}, onAllComplete = function(successful, failed, retryable) {
if (failed.length === 0 || noRetryableFiles(failed, retryable)) {
callbackProxy(totalSize, totalSize);
this.reset();
}
}, onNew = function(id) {
var size = getSize(id);
if (size > 0) {
updateTotalProgress(id, 0, size);
perFileProgress[id] = {
loaded: 0,
total: size
};
}
}, updateTotalProgress = function(id, newLoaded, newTotal) {
var oldLoaded = perFileProgress[id] ? perFileProgress[id].loaded : 0, oldTotal = perFileProgress[id] ? perFileProgress[id].total : 0;
if (newLoaded === -1 && newTotal === -1) {
totalLoaded -= oldLoaded;
totalSize -= oldTotal;
} else {
if (newLoaded) {
totalLoaded += newLoaded - oldLoaded;
}
if (newTotal) {
totalSize += newTotal - oldTotal;
}
}
callbackProxy(totalLoaded, totalSize);
};
qq.extend(this, {
onAllComplete: onAllComplete,
onStatusChange: function(id, oldStatus, newStatus) {
if (newStatus === qq.status.CANCELED || newStatus === qq.status.REJECTED) {
onCancel(id);
} else if (newStatus === qq.status.SUBMITTING) {
onNew(id);
}
},
onIndividualProgress: function(id, loaded, total) {
updateTotalProgress(id, loaded, total);
perFileProgress[id] = {
loaded: loaded,
total: total
};
},
onNewSize: function(id) {
onNew(id);
},
reset: function() {
perFileProgress = {};
totalLoaded = 0;
totalSize = 0;
}
});
};
qq.PasteSupport = function(o) {
"use strict";
var options, detachPasteHandler;
options = {
targetElement: null,
callbacks: {
log: function(message, level) {},
pasteReceived: function(blob) {}
}
};
function isImage(item) {
return item.type && item.type.indexOf("image/") === 0;
}
function registerPasteHandler() {
detachPasteHandler = qq(options.targetElement).attach("paste", function(event) {
var clipboardData = event.clipboardData;
if (clipboardData) {
qq.each(clipboardData.items, function(idx, item) {
if (isImage(item)) {
var blob = item.getAsFile();
options.callbacks.pasteReceived(blob);
}
});
}
});
}
function unregisterPasteHandler() {
if (detachPasteHandler) {
detachPasteHandler();
}
}
qq.extend(options, o);
registerPasteHandler();
qq.extend(this, {
reset: function() {
unregisterPasteHandler();
}
});
};
qq.FormSupport = function(options, startUpload, log) {
"use strict";
var self = this, interceptSubmit = options.interceptSubmit, formEl = options.element, autoUpload = options.autoUpload;
qq.extend(this, {
newEndpoint: null,
newAutoUpload: autoUpload,
attachedToForm: false,
getFormInputsAsObject: function() {
if (formEl == null) {
return null;
}
return self._form2Obj(formEl);
}
});
function determineNewEndpoint(formEl) {
if (formEl.getAttribute("action")) {
self.newEndpoint = formEl.getAttribute("action");
}
}
function validateForm(formEl, nativeSubmit) {
if (formEl.checkValidity && !formEl.checkValidity()) {
log("Form did not pass validation checks - will not upload.", "error");
nativeSubmit();
} else {
return true;
}
}
function maybeUploadOnSubmit(formEl) {
var nativeSubmit = formEl.submit;
qq(formEl).attach("submit", function(event) {
event = event || window.event;
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
validateForm(formEl, nativeSubmit) && startUpload();
});
formEl.submit = function() {
validateForm(formEl, nativeSubmit) && startUpload();
};
}
function determineFormEl(formEl) {
if (formEl) {
if (qq.isString(formEl)) {
formEl = document.getElementById(formEl);
}
if (formEl) {
log("Attaching to form element.");
determineNewEndpoint(formEl);
interceptSubmit && maybeUploadOnSubmit(formEl);
}
}
return formEl;
}
formEl = determineFormEl(formEl);
this.attachedToForm = !!formEl;
};
qq.extend(qq.FormSupport.prototype, {
_form2Obj: function(form) {
"use strict";
var obj = {}, notIrrelevantType = function(type) {
var irrelevantTypes = [ "button", "image", "reset", "submit" ];
return qq.indexOf(irrelevantTypes, type.toLowerCase()) < 0;
}, radioOrCheckbox = function(type) {
return qq.indexOf([ "checkbox", "radio" ], type.toLowerCase()) >= 0;
}, ignoreValue = function(el) {
if (radioOrCheckbox(el.type) && !el.checked) {
return true;
}
return el.disabled && el.type.toLowerCase() !== "hidden";
}, selectValue = function(select) {
var value = null;
qq.each(qq(select).children(), function(idx, child) {
if (child.tagName.toLowerCase() === "option" && child.selected) {
value = child.value;
return false;
}
});
return value;
};
qq.each(form.elements, function(idx, el) {
if ((qq.isInput(el, true) || el.tagName.toLowerCase() === "textarea") && notIrrelevantType(el.type) && !ignoreValue(el)) {
obj[el.name] = el.value;
} else if (el.tagName.toLowerCase() === "select" && !ignoreValue(el)) {
var value = selectValue(el);
if (value !== null) {
obj[el.name] = value;
}
}
});
return obj;
}
});
qq.azure = qq.azure || {};
qq.azure.util = qq.azure.util || function() {
"use strict";
return {
AZURE_PARAM_PREFIX: "x-ms-meta-",
_paramNameMatchesAzureParameter: function(name) {
switch (name) {
case "Cache-Control":
case "Content-Disposition":
case "Content-Encoding":
case "Content-MD5":
case "x-ms-blob-content-encoding":
case "x-ms-blob-content-disposition":
case "x-ms-blob-content-md5":
case "x-ms-blob-cache-control":
return true;
default:
return false;
}
},
_getPrefixedParamName: function(name) {
if (qq.azure.util._paramNameMatchesAzureParameter(name)) {
return name;
} else {
return qq.azure.util.AZURE_PARAM_PREFIX + name;
}
},
getParamsAsHeaders: function(params) {
var headers = {};
qq.each(params, function(name, val) {
var headerName = qq.azure.util._getPrefixedParamName(name), value = null;
if (qq.isFunction(val)) {
value = String(val());
} else if (qq.isObject(val)) {
qq.extend(headers, qq.azure.util.getParamsAsHeaders(val));
} else {
value = String(val);
}
if (value !== null) {
if (qq.azure.util._paramNameMatchesAzureParameter(name)) {
headers[headerName] = value;
} else {
headers[headerName] = encodeURIComponent(value);
}
}
});
return headers;
},
parseAzureError: function(responseText, log) {
var domParser = new DOMParser(), responseDoc = domParser.parseFromString(responseText, "application/xml"), errorTag = responseDoc.getElementsByTagName("Error")[0], errorDetails = {}, codeTag, messageTag;
log("Received error response: " + responseText, "error");
if (errorTag) {
messageTag = errorTag.getElementsByTagName("Message")[0];
if (messageTag) {
errorDetails.message = messageTag.textContent;
}
codeTag = errorTag.getElementsByTagName("Code")[0];
if (codeTag) {
errorDetails.code = codeTag.textContent;
}
log("Parsed Azure error: " + JSON.stringify(errorDetails), "error");
return errorDetails;
}
}
};
}();
(function() {
"use strict";
qq.nonTraditionalBasePublicApi = {
setUploadSuccessParams: function(params, id) {
this._uploadSuccessParamsStore.set(params, id);
},
setUploadSuccessEndpoint: function(endpoint, id) {
this._uploadSuccessEndpointStore.set(endpoint, id);
}
};
qq.nonTraditionalBasePrivateApi = {
_onComplete: function(id, name, result, xhr) {
var success = result.success ? true : false, self = this, onCompleteArgs = arguments, successEndpoint = this._uploadSuccessEndpointStore.get(id), successCustomHeaders = this._options.uploadSuccess.customHeaders, successMethod = this._options.uploadSuccess.method, cors = this._options.cors, promise = new qq.Promise(), uploadSuccessParams = this._uploadSuccessParamsStore.get(id), fileParams = this._paramsStore.get(id), onSuccessFromServer = function(successRequestResult) {
delete self._failedSuccessRequestCallbacks[id];
qq.extend(result, successRequestResult);
qq.FineUploaderBasic.prototype._onComplete.apply(self, onCompleteArgs);
promise.success(successRequestResult);
}, onFailureFromServer = function(successRequestResult) {
var callback = submitSuccessRequest;
qq.extend(result, successRequestResult);
if (result && result.reset) {
callback = null;
}
if (!callback) {
delete self._failedSuccessRequestCallbacks[id];
} else {
self._failedSuccessRequestCallbacks[id] = callback;
}
if (!self._onAutoRetry(id, name, result, xhr, callback)) {
qq.FineUploaderBasic.prototype._onComplete.apply(self, onCompleteArgs);
promise.failure(successRequestResult);
}
}, submitSuccessRequest, successAjaxRequester;
if (success && successEndpoint) {
successAjaxRequester = new qq.UploadSuccessAjaxRequester({
endpoint: successEndpoint,
method: successMethod,
customHeaders: successCustomHeaders,
cors: cors,
log: qq.bind(this.log, this)
});
qq.extend(uploadSuccessParams, self._getEndpointSpecificParams(id, result, xhr), true);
fileParams && qq.extend(uploadSuccessParams, fileParams, true);
submitSuccessRequest = qq.bind(function() {
successAjaxRequester.sendSuccessRequest(id, uploadSuccessParams).then(onSuccessFromServer, onFailureFromServer);
}, self);
submitSuccessRequest();
return promise;
}
return qq.FineUploaderBasic.prototype._onComplete.apply(this, arguments);
},
_manualRetry: function(id) {
var successRequestCallback = this._failedSuccessRequestCallbacks[id];
return qq.FineUploaderBasic.prototype._manualRetry.call(this, id, successRequestCallback);
}
};
})();
(function() {
"use strict";
qq.azure.FineUploaderBasic = function(o) {
if (!qq.supportedFeatures.ajaxUploading) {
throw new qq.Error("Uploading directly to Azure is not possible in this browser.");
}
var options = {
signature: {
endpoint: null,
customHeaders: {}
},
blobProperties: {
name: "uuid"
},
uploadSuccess: {
endpoint: null,
method: "POST",
params: {},
customHeaders: {}
},
chunking: {
partSize: 4e6,
minFileSize: 4000001
}
};
qq.extend(options, o, true);
qq.FineUploaderBasic.call(this, options);
this._uploadSuccessParamsStore = this._createStore(this._options.uploadSuccess.params);
this._uploadSuccessEndpointStore = this._createStore(this._options.uploadSuccess.endpoint);
this._failedSuccessRequestCallbacks = {};
this._cannedBlobNames = {};
};
qq.extend(qq.azure.FineUploaderBasic.prototype, qq.basePublicApi);
qq.extend(qq.azure.FineUploaderBasic.prototype, qq.basePrivateApi);
qq.extend(qq.azure.FineUploaderBasic.prototype, qq.nonTraditionalBasePublicApi);
qq.extend(qq.azure.FineUploaderBasic.prototype, qq.nonTraditionalBasePrivateApi);
qq.extend(qq.azure.FineUploaderBasic.prototype, {
getBlobName: function(id) {
if (this._cannedBlobNames[id] == null) {
return this._handler.getThirdPartyFileId(id);
}
return this._cannedBlobNames[id];
},
_getEndpointSpecificParams: function(id) {
return {
blob: this.getBlobName(id),
uuid: this.getUuid(id),
name: this.getName(id),
container: this._endpointStore.get(id)
};
},
_createUploadHandler: function() {
return qq.FineUploaderBasic.prototype._createUploadHandler.call(this, {
signature: this._options.signature,
onGetBlobName: qq.bind(this._determineBlobName, this),
deleteBlob: qq.bind(this._deleteBlob, this, true)
}, "azure");
},
_determineBlobName: function(id) {
var self = this, blobNameOptionValue = this._options.blobProperties.name, uuid = this.getUuid(id), filename = this.getName(id), fileExtension = qq.getExtension(filename), blobNameToUse = uuid;
if (qq.isString(blobNameOptionValue)) {
switch (blobNameOptionValue) {
case "uuid":
if (fileExtension !== undefined) {
blobNameToUse += "." + fileExtension;
}
return new qq.Promise().success(blobNameToUse);
case "filename":
return new qq.Promise().success(filename);
default:
return new qq.Promise.failure("Invalid blobName option value - " + blobNameOptionValue);
}
} else {
return blobNameOptionValue.call(this, id);
}
},
_addCannedFile: function(sessionData) {
var id;
if (sessionData.blobName == null) {
throw new qq.Error("Did not find blob name property in server session response. This is required!");
} else {
id = qq.FineUploaderBasic.prototype._addCannedFile.apply(this, arguments);
this._cannedBlobNames[id] = sessionData.blobName;
}
return id;
},
_deleteBlob: function(relatedToCancel, id) {
var self = this, deleteBlobSasUri = {}, blobUriStore = {
get: function(id) {
return self._endpointStore.get(id) + "/" + self.getBlobName(id);
}
}, deleteFileEndpointStore = {
get: function(id) {
return deleteBlobSasUri[id];
}
}, getSasSuccess = function(id, sasUri) {
deleteBlobSasUri[id] = sasUri;
deleteBlob.send(id);
}, getSasFailure = function(id, reason, xhr) {
if (relatedToCancel) {
self.log("Will cancel upload, but cannot remove uncommitted parts from Azure due to issue retrieving SAS", "error");
qq.FineUploaderBasic.prototype._onCancel.call(self, id, self.getName(id));
} else {
self._onDeleteComplete(id, xhr, true);
self._options.callbacks.onDeleteComplete(id, xhr, true);
}
}, deleteBlob = new qq.azure.DeleteBlob({
endpointStore: deleteFileEndpointStore,
log: qq.bind(self.log, self),
onDelete: function(id) {
self._onDelete(id);
self._options.callbacks.onDelete(id);
},
onDeleteComplete: function(id, xhrOrXdr, isError) {
delete deleteBlobSasUri[id];
if (isError) {
if (relatedToCancel) {
self.log("Will cancel upload, but failed to remove uncommitted parts from Azure.", "error");
} else {
qq.azure.util.parseAzureError(xhrOrXdr.responseText, qq.bind(self.log, self));
}
}
if (relatedToCancel) {
qq.FineUploaderBasic.prototype._onCancel.call(self, id, self.getName(id));
self.log("Deleted uncommitted blob chunks for " + id);
} else {
self._onDeleteComplete(id, xhrOrXdr, isError);
self._options.callbacks.onDeleteComplete(id, xhrOrXdr, isError);
}
}
}), getSas = new qq.azure.GetSas({
cors: this._options.cors,
endpointStore: {
get: function() {
return self._options.signature.endpoint;
}
},
restRequestVerb: deleteBlob.method,
log: qq.bind(self.log, self)
});
getSas.request(id, blobUriStore.get(id)).then(qq.bind(getSasSuccess, self, id), qq.bind(getSasFailure, self, id));
},
_createDeleteHandler: function() {
var self = this;
return {
sendDelete: function(id, uuid) {
self._deleteBlob(false, id);
}
};
}
});
})();
qq.azure.XhrUploadHandler = function(spec, proxy) {
"use strict";
var handler = this, log = proxy.log, cors = spec.cors, endpointStore = spec.endpointStore, paramsStore = spec.paramsStore, signature = spec.signature, filenameParam = spec.filenameParam, minFileSizeForChunking = spec.chunking.minFileSize, deleteBlob = spec.deleteBlob, onGetBlobName = spec.onGetBlobName, getName = proxy.getName, getSize = proxy.getSize, getBlobMetadata = function(id) {
var params = paramsStore.get(id);
params[filenameParam] = getName(id);
return params;
}, api = {
putBlob: new qq.azure.PutBlob({
getBlobMetadata: getBlobMetadata,
log: log
}),
putBlock: new qq.azure.PutBlock({
log: log
}),
putBlockList: new qq.azure.PutBlockList({
getBlobMetadata: getBlobMetadata,
log: log
}),
getSasForPutBlobOrBlock: new qq.azure.GetSas({
cors: cors,
customHeaders: signature.customHeaders,
endpointStore: {
get: function() {
return signature.endpoint;
}
},
log: log,
restRequestVerb: "PUT"
})
};
function combineChunks(id) {
var promise = new qq.Promise();
getSignedUrl(id).then(function(sasUri) {
var mimeType = handler._getMimeType(id), blockIdEntries = handler._getPersistableData(id).blockIdEntries;
api.putBlockList.send(id, sasUri, blockIdEntries, mimeType, function(xhr) {
handler._registerXhr(id, null, xhr, api.putBlockList);
}).then(function(xhr) {
log("Success combining chunks for id " + id);
promise.success({}, xhr);
}, function(xhr) {
log("Attempt to combine chunks failed for id " + id, "error");
handleFailure(xhr, promise);
});
}, promise.failure);
return promise;
}
function determineBlobUrl(id) {
var containerUrl = endpointStore.get(id), promise = new qq.Promise(), getBlobNameSuccess = function(blobName) {
handler._setThirdPartyFileId(id, blobName);
promise.success(containerUrl + "/" + blobName);
}, getBlobNameFailure = function(reason) {
promise.failure(reason);
};
onGetBlobName(id).then(getBlobNameSuccess, getBlobNameFailure);
return promise;
}
function getSignedUrl(id, optChunkIdx) {
var getSasId = optChunkIdx == null ? id : id + "." + optChunkIdx, promise = new qq.Promise(), getSasSuccess = function(sasUri) {
log("GET SAS request succeeded.");
promise.success(sasUri);
}, getSasFailure = function(reason, getSasXhr) {
log("GET SAS request failed: " + reason, "error");
promise.failure({
error: "Problem communicating with local server"
}, getSasXhr);
}, determineBlobUrlSuccess = function(blobUrl) {
api.getSasForPutBlobOrBlock.request(getSasId, blobUrl).then(getSasSuccess, getSasFailure);
}, determineBlobUrlFailure = function(reason) {
log(qq.format("Failed to determine blob name for ID {} - {}", id, reason), "error");
promise.failure({
error: reason
});
};
determineBlobUrl(id).then(determineBlobUrlSuccess, determineBlobUrlFailure);
return promise;
}
function handleFailure(xhr, promise) {
var azureError = qq.azure.util.parseAzureError(xhr.responseText, log), errorMsg = "Problem sending file to Azure";
promise.failure({
error: errorMsg,
azureError: azureError && azureError.message,
reset: xhr.status === 403
});
}
qq.extend(this, {
uploadChunk: function(id, chunkIdx) {
var promise = new qq.Promise();
getSignedUrl(id, chunkIdx).then(function(sasUri) {
var xhr = handler._createXhr(id, chunkIdx), chunkData = handler._getChunkData(id, chunkIdx);
handler._registerProgressHandler(id, chunkIdx, chunkData.size);
handler._registerXhr(id, chunkIdx, xhr, api.putBlock);
api.putBlock.upload(id + "." + chunkIdx, xhr, sasUri, chunkIdx, chunkData.blob).then(function(blockIdEntry) {
if (!handler._getPersistableData(id).blockIdEntries) {
handler._getPersistableData(id).blockIdEntries = [];
}
handler._getPersistableData(id).blockIdEntries.push(blockIdEntry);
log("Put Block call succeeded for " + id);
promise.success({}, xhr);
}, function() {
log(qq.format("Put Block call failed for ID {} on part {}", id, chunkIdx), "error");
handleFailure(xhr, promise);
});
}, promise.failure);
return promise;
},
uploadFile: function(id) {
var promise = new qq.Promise(), fileOrBlob = handler.getFile(id);
getSignedUrl(id).then(function(sasUri) {
var xhr = handler._createXhr(id);
handler._registerProgressHandler(id);
api.putBlob.upload(id, xhr, sasUri, fileOrBlob).then(function() {
log("Put Blob call succeeded for " + id);
promise.success({}, xhr);
}, function() {
log("Put Blob call failed for " + id, "error");
handleFailure(xhr, promise);
});
}, promise.failure);
return promise;
}
});
qq.extend(this, new qq.XhrUploadHandler({
options: qq.extend({
namespace: "azure"
}, spec),
proxy: qq.extend({
getEndpoint: spec.endpointStore.get
}, proxy)
}));
qq.override(this, function(super_) {
return {
expunge: function(id) {
var relatedToCancel = handler._wasCanceled(id), chunkingData = handler._getPersistableData(id), blockIdEntries = chunkingData && chunkingData.blockIdEntries || [];
if (relatedToCancel && blockIdEntries.length > 0) {
deleteBlob(id);
}
super_.expunge(id);
},
finalizeChunks: function(id) {
return combineChunks(id);
},
_shouldChunkThisFile: function(id) {
var maybePossible = super_._shouldChunkThisFile(id);
return maybePossible && getSize(id) >= minFileSizeForChunking;
}
};
});
};
qq.azure.GetSas = function(o) {
"use strict";
var requester, options = {
cors: {
expected: false,
sendCredentials: false
},
customHeaders: {},
restRequestVerb: "PUT",
endpointStore: null,
log: function(str, level) {}
}, requestPromises = {};
qq.extend(options, o);
function sasResponseReceived(id, xhr, isError) {
var promise = requestPromises[id];
if (isError) {
promise.failure("Received response code " + xhr.status, xhr);
} else {
if (xhr.responseText.length) {
promise.success(xhr.responseText);
} else {
promise.failure("Empty response.", xhr);
}
}
delete requestPromises[id];
}
requester = qq.extend(this, new qq.AjaxRequester({
acceptHeader: "application/json",
validMethods: [ "GET" ],
method: "GET",
successfulResponseCodes: {
GET: [ 200 ]
},
contentType: null,
customHeaders: options.customHeaders,
endpointStore: options.endpointStore,
cors: options.cors,
log: options.log,
onComplete: sasResponseReceived
}));
qq.extend(this, {
request: function(id, blobUri) {
var requestPromise = new qq.Promise(), restVerb = options.restRequestVerb;
options.log(qq.format("Submitting GET SAS request for a {} REST request related to file ID {}.", restVerb, id));
requestPromises[id] = requestPromise;
requester.initTransport(id).withParams({
bloburi: blobUri,
_method: restVerb
}).withCacheBuster().send();
return requestPromise;
}
});
};
qq.UploadSuccessAjaxRequester = function(o) {
"use strict";
var requester, pendingRequests = [], options = {
method: "POST",
endpoint: null,
maxConnections: 3,
customHeaders: {},
paramsStore: {},
cors: {
expected: false,
sendCredentials: false
},
log: function(str, level) {}
};
qq.extend(options, o);
function handleSuccessResponse(id, xhrOrXdr, isError) {
var promise = pendingRequests[id], responseJson = xhrOrXdr.responseText, successIndicator = {
success: true
}, failureIndicator = {
success: false
}, parsedResponse;
delete pendingRequests[id];
options.log(qq.format("Received the following response body to an upload success request for id {}: {}", id, responseJson));
try {
parsedResponse = qq.parseJson(responseJson);
if (isError || parsedResponse && (parsedResponse.error || parsedResponse.success === false)) {
options.log("Upload success request was rejected by the server.", "error");
promise.failure(qq.extend(parsedResponse, failureIndicator));
} else {
options.log("Upload success was acknowledged by the server.");
promise.success(qq.extend(parsedResponse, successIndicator));
}
} catch (error) {
if (isError) {
options.log(qq.format("Your server indicated failure in its upload success request response for id {}!", id), "error");
promise.failure(failureIndicator);
} else {
options.log("Upload success was acknowledged by the server.");
promise.success(successIndicator);
}
}
}
requester = qq.extend(this, new qq.AjaxRequester({
acceptHeader: "application/json",
method: options.method,
endpointStore: {
get: function() {
return options.endpoint;
}
},
paramsStore: options.paramsStore,
maxConnections: options.maxConnections,
customHeaders: options.customHeaders,
log: options.log,
onComplete: handleSuccessResponse,
cors: options.cors
}));
qq.extend(this, {
sendSuccessRequest: function(id, spec) {
var promise = new qq.Promise();
options.log("Submitting upload success request/notification for " + id);
requester.initTransport(id).withParams(spec).send();
pendingRequests[id] = promise;
return promise;
}
});
};
qq.azure.DeleteBlob = function(o) {
"use strict";
var requester, method = "DELETE", options = {
endpointStore: {},
onDelete: function(id) {},
onDeleteComplete: function(id, xhr, isError) {},
log: function(str, level) {}
};
qq.extend(options, o);
requester = qq.extend(this, new qq.AjaxRequester({
validMethods: [ method ],
method: method,
successfulResponseCodes: function() {
var codes = {};
codes[method] = [ 202 ];
return codes;
}(),
contentType: null,
endpointStore: options.endpointStore,
allowXRequestedWithAndCacheControl: false,
cors: {
expected: true
},
log: options.log,
onSend: options.onDelete,
onComplete: options.onDeleteComplete
}));
qq.extend(this, {
method: method,
send: function(id) {
options.log("Submitting Delete Blob request for " + id);
return requester.initTransport(id).send();
}
});
};
qq.azure.PutBlob = function(o) {
"use strict";
var requester, method = "PUT", options = {
getBlobMetadata: function(id) {},
log: function(str, level) {}
}, endpoints = {}, promises = {}, endpointHandler = {
get: function(id) {
return endpoints[id];
}
};
qq.extend(options, o);
requester = qq.extend(this, new qq.AjaxRequester({
validMethods: [ method ],
method: method,
successfulResponseCodes: function() {
var codes = {};
codes[method] = [ 201 ];
return codes;
}(),
contentType: null,
customHeaders: function(id) {
var params = options.getBlobMetadata(id), headers = qq.azure.util.getParamsAsHeaders(params);
headers["x-ms-blob-type"] = "BlockBlob";
return headers;
},
endpointStore: endpointHandler,
allowXRequestedWithAndCacheControl: false,
cors: {
expected: true
},
log: options.log,
onComplete: function(id, xhr, isError) {
var promise = promises[id];
delete endpoints[id];
delete promises[id];
if (isError) {
promise.failure();
} else {
promise.success();
}
}
}));
qq.extend(this, {
method: method,
upload: function(id, xhr, url, file) {
var promise = new qq.Promise();
options.log("Submitting Put Blob request for " + id);
promises[id] = promise;
endpoints[id] = url;
requester.initTransport(id).withPayload(file).withHeaders({
"Content-Type": file.type
}).send(xhr);
return promise;
}
});
};
qq.azure.PutBlock = function(o) {
"use strict";
var requester, method = "PUT", blockIdEntries = {}, promises = {}, options = {
log: function(str, level) {}
}, endpoints = {}, endpointHandler = {
get: function(id) {
return endpoints[id];
}
};
qq.extend(options, o);
requester = qq.extend(this, new qq.AjaxRequester({
validMethods: [ method ],
method: method,
successfulResponseCodes: function() {
var codes = {};
codes[method] = [ 201 ];
return codes;
}(),
contentType: null,
endpointStore: endpointHandler,
allowXRequestedWithAndCacheControl: false,
cors: {
expected: true
},
log: options.log,
onComplete: function(id, xhr, isError) {
var promise = promises[id], blockIdEntry = blockIdEntries[id];
delete endpoints[id];
delete promises[id];
delete blockIdEntries[id];
if (isError) {
promise.failure();
} else {
promise.success(blockIdEntry);
}
}
}));
function createBlockId(partNum) {
var digits = 5, zeros = new Array(digits + 1).join("0"), paddedPartNum = (zeros + partNum).slice(-digits);
return btoa(paddedPartNum);
}
qq.extend(this, {
method: method,
upload: function(id, xhr, sasUri, partNum, blob) {
var promise = new qq.Promise(), blockId = createBlockId(partNum);
promises[id] = promise;
options.log(qq.format("Submitting Put Block request for {} = part {}", id, partNum));
endpoints[id] = qq.format("{}&comp=block&blockid={}", sasUri, encodeURIComponent(blockId));
blockIdEntries[id] = {
part: partNum,
id: blockId
};
requester.initTransport(id).withPayload(blob).send(xhr);
return promise;
}
});
};
qq.azure.PutBlockList = function(o) {
"use strict";
var requester, method = "PUT", promises = {}, options = {
getBlobMetadata: function(id) {},
log: function(str, level) {}
}, endpoints = {}, endpointHandler = {
get: function(id) {
return endpoints[id];
}
};
qq.extend(options, o);
requester = qq.extend(this, new qq.AjaxRequester({
validMethods: [ method ],
method: method,
successfulResponseCodes: function() {
var codes = {};
codes[method] = [ 201 ];
return codes;
}(),
customHeaders: function(id) {
var params = options.getBlobMetadata(id);
return qq.azure.util.getParamsAsHeaders(params);
},
contentType: "text/plain",
endpointStore: endpointHandler,
allowXRequestedWithAndCacheControl: false,
cors: {
expected: true
},
log: options.log,
onSend: function() {},
onComplete: function(id, xhr, isError) {
var promise = promises[id];
delete endpoints[id];
delete promises[id];
if (isError) {
promise.failure(xhr);
} else {
promise.success(xhr);
}
}
}));
function createRequestBody(blockIdEntries) {
var doc = document.implementation.createDocument(null, "BlockList", null);
blockIdEntries.sort(function(a, b) {
return a.part - b.part;
});
qq.each(blockIdEntries, function(idx, blockIdEntry) {
var latestEl = doc.createElement("Latest"), latestTextEl = doc.createTextNode(blockIdEntry.id);
latestEl.appendChild(latestTextEl);
qq(doc).children()[0].appendChild(latestEl);
});
return new XMLSerializer().serializeToString(doc);
}
qq.extend(this, {
method: method,
send: function(id, sasUri, blockIdEntries, fileMimeType, registerXhrCallback) {
var promise = new qq.Promise(), blockIdsXml = createRequestBody(blockIdEntries), xhr;
promises[id] = promise;
options.log(qq.format("Submitting Put Block List request for {}", id));
endpoints[id] = qq.format("{}&comp=blocklist", sasUri);
xhr = requester.initTransport(id).withPayload(blockIdsXml).withHeaders({
"x-ms-blob-content-type": fileMimeType
}).send();
registerXhrCallback(xhr);
return promise;
}
});
};
})(window);
//# sourceMappingURL=azure.fine-uploader.core.js.map |
/*! JointJS v0.9.10 (2016-06-13) - JavaScript diagramming library
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
// JointJS library.
// (c) 2011-2013 client IO
joint.shapes.pn = {};
joint.shapes.pn.Place = joint.shapes.basic.Generic.extend({
markup: '<g class="rotatable"><g class="scalable"><circle class="root"/><g class="tokens" /></g><text class="label"/></g>',
defaults: joint.util.deepSupplement({
type: 'pn.Place',
size: { width: 50, height: 50 },
attrs: {
'.root': {
r: 25,
fill: '#ffffff',
stroke: '#000000',
transform: 'translate(25, 25)'
},
'.label': {
'text-anchor': 'middle',
'ref-x': .5,
'ref-y': -20,
ref: '.root',
fill: '#000000',
'font-size': 12
},
'.tokens > circle': {
fill: '#000000',
r: 5
},
'.tokens.one > circle': { transform: 'translate(25, 25)' },
'.tokens.two > circle:nth-child(1)': { transform: 'translate(19, 25)' },
'.tokens.two > circle:nth-child(2)': { transform: 'translate(31, 25)' },
'.tokens.three > circle:nth-child(1)': { transform: 'translate(18, 29)' },
'.tokens.three > circle:nth-child(2)': { transform: 'translate(25, 19)' },
'.tokens.three > circle:nth-child(3)': { transform: 'translate(32, 29)' },
'.tokens.alot > text': {
transform: 'translate(25, 18)',
'text-anchor': 'middle',
fill: '#000000'
}
}
}, joint.shapes.basic.Generic.prototype.defaults)
});
joint.shapes.pn.PlaceView = joint.dia.ElementView.extend({
initialize: function() {
joint.dia.ElementView.prototype.initialize.apply(this, arguments);
this.model.on('change:tokens', function() {
this.renderTokens();
this.update();
}, this);
},
render: function() {
joint.dia.ElementView.prototype.render.apply(this, arguments);
this.renderTokens();
this.update();
},
renderTokens: function() {
var $tokens = this.$('.tokens').empty();
$tokens[0].className.baseVal = 'tokens';
var tokens = this.model.get('tokens');
if (!tokens) return;
switch (tokens) {
case 1:
$tokens[0].className.baseVal += ' one';
$tokens.append(V('<circle/>').node);
break;
case 2:
$tokens[0].className.baseVal += ' two';
$tokens.append(V('<circle/>').node, V('<circle/>').node);
break;
case 3:
$tokens[0].className.baseVal += ' three';
$tokens.append(V('<circle/>').node, V('<circle/>').node, V('<circle/>').node);
break;
default:
$tokens[0].className.baseVal += ' alot';
$tokens.append(V('<text/>').text(tokens + '' ).node);
break;
}
}
});
joint.shapes.pn.Transition = joint.shapes.basic.Generic.extend({
markup: '<g class="rotatable"><g class="scalable"><rect class="root"/></g></g><text class="label"/>',
defaults: joint.util.deepSupplement({
type: 'pn.Transition',
size: { width: 12, height: 50 },
attrs: {
'rect': {
width: 12,
height: 50,
fill: '#000000',
stroke: '#000000'
},
'.label': {
'text-anchor': 'middle',
'ref-x': .5,
'ref-y': -20,
ref: 'rect',
fill: '#000000',
'font-size': 12
}
}
}, joint.shapes.basic.Generic.prototype.defaults)
});
joint.shapes.pn.Link = joint.dia.Link.extend({
defaults: joint.util.deepSupplement({
type: 'pn.Link',
attrs: { '.marker-target': { d: 'M 10 0 L 0 5 L 10 10 z' }}
}, joint.dia.Link.prototype.defaults)
});
|
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.frzr = global.frzr || {})));
}(this, (function (exports) { 'use strict';
function text (str) {
return document.createTextNode(str || '');
}
var customElements;
var customAttributes;
function el (tagName) {
if (customElements) {
var customElement = customElements[tagName];
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
if (customElement) {
return customElement.apply(this, args);
}
}
if (typeof tagName === 'function') {
var args = new Array(arguments.length);
args[0] = this;
for (var i = 1; i < arguments.length; i++) {
args[i] = arguments[i];
}
return new (Function.prototype.bind.apply(tagName, args));
} else {
var element = document.createElement(tagName);
}
for (var i = 1; i < arguments.length; i++) {
var arg = arguments[i];
if (arg == null) {
continue;
} else if (mount(element, arg)) {
continue;
} else if (typeof arg === 'object') {
for (var attr in arg) {
if (customAttributes) {
var customAttribute = customAttributes[attr];
if (customAttribute) {
customAttribute(element, arg[attr]);
continue;
}
}
var value = arg[attr];
if (attr === 'style' || (element[attr] == null && typeof value != 'function')) {
element.setAttribute(attr, value);
} else {
element[attr] = value;
}
}
}
}
return element;
}
el.extend = function (tagName) {
return function (a, b, c, d, e, f) {
var len = arguments.length;
switch (len) {
case 0: return el(tagName);
case 1: return el(tagName, a);
case 2: return el(tagName, a, b);
case 3: return el(tagName, a, b, c);
case 4: return el(tagName, a, b, c, d);
case 5: return el(tagName, a, b, c, d, e);
case 6: return el(tagName, a, b, c, d, e, f);
}
var args = new Array(len + 1);
var arg, i = 0;
args[0] = tagName;
while (i < len) {
// args[1] = arguments[0] and so on
arg = arguments[i++];
args[i] = arg;
}
return el.apply(this, args);
}
}
function registerElement (tagName, handler) {
customElements || (customElements = {});
customElements[tagName] = handler;
}
function registerAttribute (attr, handler) {
customAttributes || (customAttributes = {});
customAttributes[attr] = handler;
}
function unregisterElement (tagName) {
if (customElements && customElements[tagName]) {
delete customElements[tagName];
}
}
function unregisterAttribute (attr) {
if (customAttributes && customAttributes[attr]) {
delete customAttributes[attr];
}
}
function svg (tagName) {
var element = document.createElementNS('http://www.w3.org/2000/svg', tagName);
for (var i = 1; i < arguments.length; i++) {
var arg = arguments[i];
if (arg == null) {
continue;
} else if (mount(element, arg)) {
continue;
} else if (typeof arg === 'object') {
for (var attr in arg) {
var value = arg[attr];
if (typeof value === 'function') {
element[attr] = value;
} else {
element.setAttribute(attr, value);
}
}
}
}
return element;
}
svg.extend = function (tagName) {
return function () {
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
return svg.apply(this, [tagName].concat(args));
}
}
function list (View, key, initData, skipRender) {
return new List(View, key, initData, skipRender);
}
function List (View, key, initData, skipRender) {
this.View = View;
this.views = [];
this.initData = initData;
this.skipRender = skipRender;
if (key) {
this.key = key;
this.lookup = {};
}
}
List.prototype.update = function (data, cb) {
var View = this.View;
var views = this.views;
var parent = this.parent;
var key = this.key;
var initData = this.initData;
var skipRender = this.skipRender;
if (cb) {
var added = [];
var updated = [];
var removed = [];
}
if (key) {
var lookup = this.lookup;
var newLookup = {};
views.length = data.length;
for (var i = 0; i < data.length; i++) {
var item = data[i];
var id = item[key];
var view = lookup[id];
if (!view) {
view = new View(initData, item, i);
cb && added.push(view);
} else {
cb && updated.push(view);
}
views[i] = newLookup[id] = view;
view.update && view.update(item, i);
}
if (cb) {
for (var id in lookup) {
if (!newLookup[id]) {
removed.push(lookup[id]);
!skipRender && parent && destroy(lookup[id]);
}
}
}
this.lookup = newLookup;
} else {
if (cb) {
for (var i = data.length; i < views.length; i++) {
var view = views[i];
!skipRender && parent && destroy(view);
removed.push(view);
}
}
views.length = data.length;
for (var i = 0; i < data.length; i++) {
var item = data[i];
var view = views[i];
if (!view) {
view = new View(initData, item, i);
cb && added.push(view);
} else {
cb && updated.push(view);
}
view.update && view.update(item, i);
views[i] = view;
}
}
!skipRender && parent && setChildren(parent, views);
cb && cb(added, updated, removed);
}
function append (parent, child, before) {
if (before) {
parent.insertBefore(child, before.el || before);
} else {
parent.appendChild(child);
}
}
function mount (parent, child, before) {
var parentEl = parent.el || parent;
var type = child && child.constructor;
if (type === String || type === Number) {
append(parentEl, text(child), before);
return true;
} else if (type === Array) {
for (var i = 0; i < child.length; i++) {
mount(parent, child[i], before);
}
return true;
}
var childEl = child.el || child;
var childWasMounted = childEl.parentNode != null;
if (childWasMounted) {
child.remounting && child.remounting();
} else {
child.mounting && child.mounting();
}
if (childEl.nodeType) {
append(parentEl, childEl, before);
if (childEl !== child) {
if (childWasMounted) {
child.remounted && child.remounted();
} else {
child.mounted && child.mounted();
}
childEl.view = child;
child.parent = parent;
}
} else if (child.views) {
child.parent = parent;
setChildren(parentEl, child.views);
} else {
return false;
}
return true;
}
var mountBefore = mount;
function replace (parent, child, replace) {
var parentEl = parent.el || parent;
var childEl = child.el || child;
var replaceEl = replace.el || replace;
var childWasMounted = childEl.parentNode != null;
replace.unmounting && replace.unmounting();
if (childWasMounted) {
child.remounting && child.remounting();
} else {
child.mounting && child.mounting();
}
parentEl.replaceChild(childEl, replaceEl);
replace.unmounted && replace.unmounted();
if (replaceEl !== replace) {
replace.parent = null;
}
if (childWasMounted) {
child.remounted && child.remounted();
} else {
child.mounted && child.mounted();
}
if (childEl !== child) {
childEl.view = child;
child.parent = parent;
}
}
function unmount (parent, child) {
var parentEl = parent.el || parent;
var childEl = child.el || child;
child.unmounting && child.unmounting();
parentEl.removeChild(childEl);
child.unmounted && child.unmounted();
if (childEl !== child) {
child.parent = null;
}
}
function destroy (child) {
var childEl = child.el || child;
var parent = childEl.parentNode;
var parentView = parent.view || parent;
child.destroying && child.destroying(child);
notifyDown(child, 'destroying');
parent && unmount(parentView, child);
child.destroyed && child.destroyed(child);
notifyDown(child, 'destroyed');
}
function notifyDown (child, eventName, originalChild) {
var childEl = child.el || child;
var traverse = childEl.firstChild;
while (traverse) {
var next = traverse.nextSibling;
var view = traverse.view || traverse;
var event = view[eventName];
event && event.call(view, originalChild || child);
notifyDown(traverse, eventName, originalChild || child);
traverse = next;
}
}
function setChildren (parent, children) {
var parentEl = parent.el || parent;
var traverse = parentEl.firstChild;
for (var i = 0; i < children.length; i++) {
var child = children[i];
if (!child) {
continue;
}
var childEl = child.el || child;
if (traverse === childEl) {
traverse = traverse.nextSibling;
continue;
}
mount(parent, child, traverse);
}
while (traverse) {
var next = traverse.nextSibling;
unmount(parent, traverse.view || traverse);
traverse = next;
}
}
exports.text = text;
exports.el = el;
exports.registerElement = registerElement;
exports.registerAttribute = registerAttribute;
exports.unregisterElement = unregisterElement;
exports.unregisterAttribute = unregisterAttribute;
exports.svg = svg;
exports.list = list;
exports.List = List;
exports.mount = mount;
exports.mountBefore = mountBefore;
exports.replace = replace;
exports.unmount = unmount;
exports.destroy = destroy;
exports.notifyDown = notifyDown;
exports.setChildren = setChildren;
Object.defineProperty(exports, '__esModule', { value: true });
}))); |
document.addEventListener("DOMContentLoaded", function () {
window.addEventListener("click", function (ev) {
var micronTrigger = ev.target;
var micronPrefix = "mjs-";
var micronData = micronTrigger.dataset.micron;
var micronDataDuration = micronTrigger.dataset.micronDuration;
var micronDataTiming = micronTrigger.dataset.micronTiming;
var micronBind = micronTrigger.dataset.micronBind;
var micronPuppet = micronTrigger.dataset.micronId;
//Global Trigger
if (micronData !== undefined) {
if (micronBind === "true") {
if (micronPuppet !== undefined) {
var node = document.getElementById(micronPuppet);
if (node !== undefined && node !== null) {
var twinNode = node.cloneNode(true);
node.parentNode.replaceChild(twinNode, node);
twinNode.classList.add(micronPrefix + micronData);
} else {
console.log("%c Micron Error : None of the DOM element reference to the declared ID", "color:red");
return false;
}
} else {
console.log("%c Micron Error : add data-micron-id to bind an interaction", "color:red");
return false;
}
} else {
var node = micronTrigger;
var twinNode = node.cloneNode(true);
node.parentNode.replaceChild(twinNode, node);
twinNode.classList.add(micronPrefix + micronData);
}
} else {
return false;
}
//Duration
if (micronDataDuration !== undefined) {
if (isNaN(micronDataDuration)) {
console.log("%c Micron Error : data-micron-duration can only be number or decimal", "color:red");
console.log("%c Micron Fallback : data-micron-duration set to default", "color:orange");
twinNode.style.animationDuration = ".30s";
} else {
twinNode.style.animationDuration = micronDataDuration + "s";
}
} else {
twinNode.style.animationDuration = ".45s";
}
//Easing Timing Function
if (micronDataTiming !== undefined) {
if (micronDataTiming === "linear" || micronDataTiming === "ease-in" || micronDataTiming === "ease-out" || micronDataTiming === "ease-in-out") {
twinNode.classList.add(micronPrefix + micronDataTiming);
} else {
console.log("%c Micron Error : data-micron-timing currently supports linear, ease-in, ease-out and ease-in-out only", "color:red");
console.log("%c Micron Fallback : data-micron-timing set to default", "color:orange");
twinNode.classList.add(micronPrefix + "ease-in-out");
}
} else {
twinNode.classList.add(micronPrefix + "ease-in-out");
}
});
});
//Micron Prototype
var Micron = function () {
var ele;
var node;
//Get Element from DOM
var getEle = function (paramEle) {
ele = document.querySelector(paramEle);
if (ele != undefined && ele != null) {
node = ele.cloneNode("true");
ele.parentNode.replaceChild(node, ele);
return this;
} else {
console.log(
"%c Micron Error : None of the DOM element reference to the argument which is passed to getEle() method",
"color:red");
return this;
}
}
//Animation
var interaction = function (paramAnimation) {
if (node !== undefined && node !== null) {
if (paramAnimation != undefined && paramAnimation != null && paramAnimation.indexOf(" ") ==
-1) {
var prefixAnimation = "mjs-" + paramAnimation;
node.classList.add(prefixAnimation);
return this;
} else {
console.log(
"%c Micron Error : either you are missing an argument or trying to pass an argument with spaces to animation() method",
"color:red");
return this;
}
} else {
return this;
}
}
//Duration
var duration = function (paramDuration) {
if (node != undefined && node != null) {
if (isNaN(paramDuration) == false) {
node.style.animationDuration = paramDuration + "s";
return this;
} else {
console.log("%c Micron Error : you can only pass number or decimal as arguments to duration() method", "color:red");
return this;
}
} else {
return this;
}
}
var timing = function (paramTiming) {
if (node != undefined && node != null) {
if (paramTiming == "linear" || paramTiming == "ease-in" || paramTiming == "ease-out" ||
paramTiming == "ease-in-out") {
var prefixTiming = "mjs-" + paramTiming;
node.classList.add(prefixTiming);
return this;
} else {
console.log("%c Micron Error : you can only pass linear, ease-in, ease-out and ease-in-out as arguments to timing() method", "color:red");
return this;
}
} else {
return this;
}
}
return {
getEle: getEle,
interaction: interaction,
duration: duration,
timing: timing
}
}
var micron = Micron();
//Usage Sample
//micron.getEle().interaction().duration().timing(); |
(function(){ return })
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var PolygonMaskType_1 = require("../../../Enums/PolygonMaskType");
var Draw_1 = require("./Draw");
var Move_1 = require("./Move");
var PolygonInline_1 = require("./PolygonInline");
var PolygonMask = (function () {
function PolygonMask() {
this.draw = new Draw_1.Draw();
this.enable = false;
this.inline = new PolygonInline_1.PolygonInline();
this.move = new Move_1.Move();
this.scale = 1;
this.type = PolygonMaskType_1.PolygonMaskType.none;
this.url = "";
}
Object.defineProperty(PolygonMask.prototype, "inlineArrangement", {
get: function () {
return this.inline.arrangement;
},
set: function (value) {
this.inline.arrangement = value;
},
enumerable: true,
configurable: true
});
PolygonMask.prototype.load = function (data) {
var _a;
if (data !== undefined) {
this.draw.load(data.draw);
var inline = (_a = data.inline) !== null && _a !== void 0 ? _a : {
arrangement: data.inlineArrangement,
};
if (inline !== undefined) {
this.inline.load(inline);
}
this.move.load(data.move);
if (data.scale !== undefined) {
this.scale = data.scale;
}
if (data.type !== undefined) {
this.type = data.type;
}
if (data.enable !== undefined) {
this.enable = data.enable;
}
else {
this.enable = this.type !== PolygonMaskType_1.PolygonMaskType.none;
}
if (data.url !== undefined) {
this.url = data.url;
}
if (data.position !== undefined) {
this.position = {
x: data.position.x,
y: data.position.y,
};
}
}
};
return PolygonMask;
}());
exports.PolygonMask = PolygonMask;
|
/*!
* Bonzo: DOM Utility (c) Dustin Diaz 2012
* https://github.com/ded/bonzo
* License MIT
*/
(function (name, definition, context) {
if (typeof module != 'undefined' && module.exports) module.exports = definition()
else if (typeof context['define'] == 'function' && context['define']['amd']) define(name, definition)
else context[name] = definition()
})('bonzo', function() {
var context = this
, win = window
, doc = win.document
, html = doc.documentElement
, parentNode = 'parentNode'
, query = null
, specialAttributes = /^(checked|value|selected)$/i
, specialTags = /^(select|fieldset|table|tbody|tfoot|td|tr|colgroup)$/i // tags that we have trouble inserting *into*
, table = ['<table>', '</table>', 1]
, td = ['<table><tbody><tr>', '</tr></tbody></table>', 3]
, option = ['<select>', '</select>', 1]
, noscope = ['_', '', 0, 1]
, tagMap = { // tags that we have trouble *inserting*
thead: table, tbody: table, tfoot: table, colgroup: table, caption: table
, tr: ['<table><tbody>', '</tbody></table>', 2]
, th: td , td: td
, col: ['<table><colgroup>', '</colgroup></table>', 2]
, fieldset: ['<form>', '</form>', 1]
, legend: ['<form><fieldset>', '</fieldset></form>', 2]
, option: option, optgroup: option
, script: noscope, style: noscope, link: noscope, param: noscope, base: noscope
}
, stateAttributes = /^(checked|selected)$/
, ie = /msie/i.test(navigator.userAgent)
, hasClass, addClass, removeClass
, uidMap = {}
, uuids = 0
, digit = /^-?[\d\.]+$/
, dattr = /^data-(.+)$/
, px = 'px'
, setAttribute = 'setAttribute'
, getAttribute = 'getAttribute'
, byTag = 'getElementsByTagName'
, features = function() {
var e = doc.createElement('p')
e.innerHTML = '<a href="#x">x</a><table style="float:left;"></table>'
return {
hrefExtended: e[byTag]('a')[0][getAttribute]('href') != '#x' // IE < 8
, autoTbody: e[byTag]('tbody').length !== 0 // IE < 8
, computedStyle: doc.defaultView && doc.defaultView.getComputedStyle
, cssFloat: e[byTag]('table')[0].style.styleFloat ? 'styleFloat' : 'cssFloat'
, transform: function () {
var props = ['webkitTransform', 'MozTransform', 'OTransform', 'msTransform', 'Transform'], i
for (i = 0; i < props.length; i++) {
if (props[i] in e.style) return props[i]
}
}()
, classList: 'classList' in e
}
}()
, trimReplace = /(^\s*|\s*$)/g
, whitespaceRegex = /\s+/
, toString = String.prototype.toString
, unitless = { lineHeight: 1, zoom: 1, zIndex: 1, opacity: 1, boxFlex: 1, WebkitBoxFlex: 1, MozBoxFlex: 1 }
, trim = String.prototype.trim ?
function (s) {
return s.trim()
} :
function (s) {
return s.replace(trimReplace, '')
}
function classReg(c) {
return new RegExp("(^|\\s+)" + c + "(\\s+|$)")
}
/**
* @param {Array|Bonzo} ar
* @param {function(Object, number, Array)} fn
* @param {Object=} opt_scope
* @return {Array}
*/
function each(ar, fn, opt_scope) {
for (var i = 0, l = ar.length; i < l; i++) fn.call(opt_scope || ar[i], ar[i], i, ar)
return ar
}
/**
* @param {Array} ar
* @param {function(Object, number, Array)} fn
* @param {Object=} opt_scope
* @return {Array}
*/
function deepEach(ar, fn, opt_scope) {
for (var i = 0, l = ar.length; i < l; i++) {
if (isNode(ar[i])) {
deepEach(ar[i].childNodes, fn, opt_scope)
fn.call(opt_scope || ar[i], ar[i], i, ar)
}
}
return ar
}
function camelize(s) {
return s.replace(/-(.)/g, function (m, m1) {
return m1.toUpperCase()
})
}
function decamelize(s) {
return s ? s.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase() : s
}
function data(el) {
el[getAttribute]('data-node-uid') || el[setAttribute]('data-node-uid', ++uuids)
var uid = el[getAttribute]('data-node-uid')
return uidMap[uid] || (uidMap[uid] = {})
}
function clearData(el) {
var uid = el[getAttribute]('data-node-uid')
if (uid) delete uidMap[uid]
}
function dataValue(d) {
var f
try {
return (d === null || d === undefined) ? undefined :
d === 'true' ? true :
d === 'false' ? false :
d === 'null' ? null :
(f = parseFloat(d)) == d ? f : d;
} catch(e) {}
return undefined
}
function isNode(node) {
return node && node.nodeName && (node.nodeType == 1 || node.nodeType == 11)
}
/**
* @param {Array} ar
* @param {function(Object, number, Array)} fn
* @param {Object=} opt_scope
* @return {boolean} whether `some`thing was found
*/
function some(ar, fn, opt_scope) {
for (var i = 0, j = ar.length; i < j; ++i) if (fn.call(opt_scope || null, ar[i], i, ar)) return true
return false
}
function styleProperty(p) {
(p == 'transform' && (p = features.transform)) ||
(/^transform-?[Oo]rigin$/.test(p) && (p = features.transform + "Origin")) ||
(p == 'float' && (p = features.cssFloat))
return p ? camelize(p) : null
}
var getStyle = features.computedStyle ?
function (el, property) {
var value = null
, computed = doc.defaultView.getComputedStyle(el, '')
computed && (value = computed[property])
return el.style[property] || value
} :
(ie && html.currentStyle) ?
function (el, property) {
if (property == 'opacity') {
var val = 100
try {
val = el.filters['DXImageTransform.Microsoft.Alpha'].opacity
} catch (e1) {
try {
val = el.filters('alpha').opacity
} catch (e2) {}
}
return val / 100
}
var value = el.currentStyle ? el.currentStyle[property] : null
return el.style[property] || value
} :
function (el, property) {
return el.style[property]
}
// this insert method is intense
function insert(target, host, fn) {
var i = 0, self = host || this, r = []
// target nodes could be a css selector if it's a string and a selector engine is present
// otherwise, just use target
, nodes = query && typeof target == 'string' && target.charAt(0) != '<' ? query(target) : target
// normalize each node in case it's still a string and we need to create nodes on the fly
each(normalize(nodes), function (t) {
each(self, function (el) {
var n = !el[parentNode] || (el[parentNode] && !el[parentNode][parentNode]) ?
function () {
var c = el.cloneNode(true)
, cloneElems
, elElems
// check for existence of an event cloner
// preferably https://github.com/fat/bean
// otherwise Bonzo won't do this for you
if (self.$ && self.cloneEvents) {
self.$(c).cloneEvents(el)
// clone events from every child node
cloneElems = self.$(c).find('*')
elElems = self.$(el).find('*')
for (var i = 0; i < elElems.length; i++)
self.$(cloneElems[i]).cloneEvents(elElems[i])
}
return c
}() : el
fn(t, n)
r[i] = n
i++
})
}, this)
each(r, function (e, i) {
self[i] = e
})
self.length = i
return self
}
function xy(el, x, y) {
var $el = bonzo(el)
, style = $el.css('position')
, offset = $el.offset()
, rel = 'relative'
, isRel = style == rel
, delta = [parseInt($el.css('left'), 10), parseInt($el.css('top'), 10)]
if (style == 'static') {
$el.css('position', rel)
style = rel
}
isNaN(delta[0]) && (delta[0] = isRel ? 0 : el.offsetLeft)
isNaN(delta[1]) && (delta[1] = isRel ? 0 : el.offsetTop)
x != null && (el.style.left = x - offset.left + delta[0] + px)
y != null && (el.style.top = y - offset.top + delta[1] + px)
}
// classList support for class management
// altho to be fair, the api sucks because it won't accept multiple classes at once
// so we iterate down below
if (features.classList) {
hasClass = function (el, c) {
return el.classList.contains(c)
}
addClass = function (el, c) {
el.classList.add(c)
}
removeClass = function (el, c) {
el.classList.remove(c)
}
}
else {
hasClass = function (el, c) {
return classReg(c).test(el.className)
}
addClass = function (el, c) {
el.className = trim(el.className + ' ' + c)
}
removeClass = function (el, c) {
el.className = trim(el.className.replace(classReg(c), ' '))
}
}
// this allows method calling for setting values
// example:
// bonzo(elements).css('color', function (el) {
// return el.getAttribute('data-original-color')
// })
function setter(el, v) {
return typeof v == 'function' ? v(el) : v
}
function Bonzo(elements) {
this.length = 0
if (elements) {
elements = typeof elements !== 'string' &&
!elements.nodeType &&
typeof elements.length !== 'undefined' ?
elements :
[elements]
this.length = elements.length
for (var i = 0; i < elements.length; i++) this[i] = elements[i]
}
}
Bonzo.prototype = {
// indexr method, because jQueriers want this method. Jerks
get: function (index) {
return this[index] || null
}
// itetators
/**
* @param {Function} fn
* @param {Object=} opt_scope
* @return {Bonzo}
*/
, each: function (fn, opt_scope) {
return each(this, fn, opt_scope)
}
/**
* @param {Function} fn
* @param {Object=} opt_scope
* @return {Bonzo}
*/
, deepEach: function (fn, opt_scope) {
return deepEach(this, fn, opt_scope)
}
/**
* @param {Function} fn
* @param {Function=} opt_reject
* @return {Array}
*/
, map: function (fn, opt_reject) {
var m = [], n, i
for (i = 0; i < this.length; i++) {
n = fn.call(this, this[i], i)
opt_reject ? (opt_reject(n) && m.push(n)) : m.push(n)
}
return m
}
// text and html inserters!
/**
* @param {string} h the HTML to insert
* @param {boolean=} opt_text whether to set or get text content
* @return {Bonzo|string}
*/
, html: function (h, opt_text) {
var method = opt_text ?
html.textContent === undefined ?
'innerText' :
'textContent' :
'innerHTML';
function append(el) {
each(normalize(h), function (node) {
el.appendChild(node)
})
}
return typeof h !== 'undefined' ?
this.empty().each(function (el) {
!opt_text && specialTags.test(el.tagName) ?
append(el) :
(function () {
try { (el[method] = h) }
catch(e) { append(el) }
}())
}) :
this[0] ? this[0][method] : ''
}
/**
* @param {string=} opt_text the text to set, otherwise this is a getter
* @return {string|Bonzo}
*/
, text: function (opt_text) {
return this.html(opt_text, true)
}
// more related insertion methods
, append: function (node) {
return this.each(function (el) {
each(normalize(node), function (i) {
el.appendChild(i)
})
})
}
, prepend: function (node) {
return this.each(function (el) {
var first = el.firstChild
each(normalize(node), function (i) {
el.insertBefore(i, first)
})
})
}
/**
* @param {string|Element|Array} target the location for which you'll insert your new content
* @param {Object=} opt_host an optional host scope (primarily used when integrated with Ender)
* @return {Bonzo}
*/
, appendTo: function (target, opt_host) {
return insert.call(this, target, opt_host, function (t, el) {
t.appendChild(el)
})
}
/**
* @param {string|Element|Array} target the location for which you'll insert your new content
* @param {Object=} opt_host an optional host scope (primarily used when integrated with Ender)
* @return {Bonzo}
*/
, prependTo: function (target, host) {
return insert.call(this, target, host, function (t, el) {
t.insertBefore(el, t.firstChild)
})
}
, before: function (node) {
return this.each(function (el) {
each(bonzo.create(node), function (i) {
el[parentNode].insertBefore(i, el)
})
})
}
, after: function (node) {
return this.each(function (el) {
each(bonzo.create(node), function (i) {
el[parentNode].insertBefore(i, el.nextSibling)
})
})
}
/**
* @param {string|Element|Array} target the location for which you'll insert your new content
* @param {Object=} opt_host an optional host scope (primarily used when integrated with Ender)
* @return {Bonzo}
*/
, insertBefore: function (target, host) {
return insert.call(this, target, host, function (t, el) {
t[parentNode].insertBefore(el, t)
})
}
/**
* @param {string|Element|Array} target the location for which you'll insert your new content
* @param {Object=} opt_host an optional host scope (primarily used when integrated with Ender)
* @return {Bonzo}
*/
, insertAfter: function (target, host) {
return insert.call(this, target, host, function (t, el) {
var sibling = t.nextSibling
sibling ?
t[parentNode].insertBefore(el, sibling) :
t[parentNode].appendChild(el)
})
}
, replaceWith: function (html) {
this.deepEach(clearData)
return this.each(function (el) {
el.parentNode.replaceChild(bonzo.create(html)[0], el)
})
}
// class management
, addClass: function (c) {
c = toString.call(c).split(whitespaceRegex)
return this.each(function (el) {
// we `each` here so you can do $el.addClass('foo bar')
each(c, function (c) {
if (c && !hasClass(el, setter(el, c)))
addClass(el, setter(el, c))
})
})
}
, removeClass: function (c) {
c = toString.call(c).split(whitespaceRegex)
return this.each(function (el) {
each(c, function (c) {
if (c && hasClass(el, setter(el, c)))
removeClass(el, setter(el, c))
})
})
}
, hasClass: function (c) {
c = toString.call(c).split(whitespaceRegex)
return some(this, function (el) {
return some(c, function (c) {
return c && hasClass(el, c)
})
})
}
/**
* @param {string} c classname to toggle
* @param {boolean=} opt_condition whether to add or remove the class straight away
* @return {Bonzo}
*/
, toggleClass: function (c, opt_condition) {
c = toString.call(c).split(whitespaceRegex)
return this.each(function (el) {
each(c, function (c) {
if (c) {
typeof opt_condition !== 'undefined' ?
opt_condition ? addClass(el, c) : removeClass(el, c) :
hasClass(el, c) ? removeClass(el, c) : addClass(el, c)
}
})
})
}
// display togglers
/**
* @param {string=} opt_type useful to set back to anything other than an empty string
* @return {Bonzo}
*/
, show: function (opt_type) {
return this.each(function (el) {
el.style.display = opt_type || ''
})
}
, hide: function () {
return this.each(function (el) {
el.style.display = 'none'
})
}
/**
* @param {Function=} opt_callback
* @param {string=} opt_type
* @return {Bonzo}
*/
, toggle: function (opt_callback, opt_type) {
this.each(function (el) {
el.style.display = (el.offsetWidth || el.offsetHeight) ? 'none' : opt_type || ''
})
if (opt_callback) opt_callback()
return this
}
// DOM Walkers & getters
, first: function () {
return bonzo(this.length ? this[0] : [])
}
, last: function () {
return bonzo(this.length ? this[this.length - 1] : [])
}
, next: function () {
return this.related('nextSibling')
}
, previous: function () {
return this.related('previousSibling')
}
, parent: function() {
return this.related(parentNode)
}
, related: function (method) {
return this.map(
function (el) {
el = el[method]
while (el && el.nodeType !== 1) {
el = el[method]
}
return el || 0
},
function (el) {
return el
}
)
}
// meh. use with care. the ones in Bean are better
, focus: function () {
this.length && this[0].focus()
return this
}
, blur: function () {
this.length && this[0].blur()
return this
}
// style getter setter & related methods
/**
* @param {Object|string} o
* @param {string=} opt_v
* @return {string|Bonzo}
*/
, css: function (o, opt_v) {
var p
// is this a request for just getting a style?
if (opt_v === undefined && typeof o == 'string') {
// repurpose 'v'
opt_v = this[0]
if (!opt_v) return null
if (opt_v === doc || opt_v === win) {
p = (opt_v === doc) ? bonzo.doc() : bonzo.viewport()
return o == 'width' ? p.width : o == 'height' ? p.height : ''
}
return (o = styleProperty(o)) ? getStyle(opt_v, o) : null
}
var iter = o
if (typeof o == 'string') {
iter = {}
iter[o] = opt_v
}
if (ie && iter.opacity) {
// oh this 'ol gamut
iter.filter = 'alpha(opacity=' + (iter.opacity * 100) + ')'
// give it layout
iter.zoom = o.zoom || 1;
delete iter.opacity;
}
function fn(el, p, v) {
for (var k in iter) {
if (iter.hasOwnProperty(k)) {
v = iter[k];
// change "5" to "5px" - unless you're line-height, which is allowed
(p = styleProperty(k)) && digit.test(v) && !(p in unitless) && (v += px)
el.style[p] = setter(el, v)
}
}
}
return this.each(fn)
}
/**
* @param {number=} opt_x
* @param {number=} opt_y
* @return {number|Bonzo}
*/
, offset: function (opt_x, opt_y) {
if (typeof opt_x == 'number' || typeof opt_y == 'number') {
return this.each(function (el) {
xy(el, opt_x, opt_y)
})
}
if (!this[0]) return {
top: 0
, left: 0
, height: 0
, width: 0
}
var el = this[0]
, width = el.offsetWidth
, height = el.offsetHeight
, top = el.offsetTop
, left = el.offsetLeft
while (el = el.offsetParent) {
top = top + el.offsetTop
left = left + el.offsetLeft
if (el != doc.body) {
top -= el.scrollTop
left -= el.scrollLeft
}
}
return {
top: top
, left: left
, height: height
, width: width
}
}
, dim: function () {
if (!this.length) return { height: 0, width: 0 }
var el = this[0]
, orig = !el.offsetWidth && !el.offsetHeight ?
// el isn't visible, can't be measured properly, so fix that
function (t) {
var s = {
position: el.style.position || ''
, visibility: el.style.visibility || ''
, display: el.style.display || ''
}
t.first().css({
position: 'absolute'
, visibility: 'hidden'
, display: 'block'
})
return s
}(this) : null
, width = el.offsetWidth
, height = el.offsetHeight
orig && this.first().css(orig)
return {
height: height
, width: width
}
}
// attributes are hard. go shopping
/**
* @param {string} k an attribute to get or set
* @param {string=} opt_v the value to set
* @return {string|Bonzo}
*/
, attr: function (k, opt_v) {
var el = this[0]
if (typeof k != 'string' && !(k instanceof String)) {
for (var n in k) {
k.hasOwnProperty(n) && this.attr(n, k[n])
}
return this
}
return typeof opt_v == 'undefined' ?
!el ? null : specialAttributes.test(k) ?
stateAttributes.test(k) && typeof el[k] == 'string' ?
true : el[k] : (k == 'href' || k =='src') && features.hrefExtended ?
el[getAttribute](k, 2) : el[getAttribute](k) :
this.each(function (el) {
specialAttributes.test(k) ? (el[k] = setter(el, opt_v)) : el[setAttribute](k, setter(el, opt_v))
})
}
, removeAttr: function (k) {
return this.each(function (el) {
stateAttributes.test(k) ? (el[k] = false) : el.removeAttribute(k)
})
}
/**
* @param {string=} opt_s
* @return {string|Bonzo}
*/
, val: function (s) {
return (typeof s == 'string') ?
this.attr('value', s) :
this.length ? this[0].value : null
}
// use with care and knowledge. this data() method uses data attributes on the DOM nodes
// to do this differently costs a lot more code. c'est la vie
/**
* @param {string|Object=} opt_k the key for which to get or set data
* @param {Object=} opt_v
* @return {Object|Bonzo}
*/
, data: function (opt_k, opt_v) {
var el = this[0], uid, o, m
if (typeof opt_v === 'undefined') {
if (!el) return null
o = data(el)
if (typeof opt_k === 'undefined') {
each(el.attributes, function (a) {
(m = ('' + a.name).match(dattr)) && (o[camelize(m[1])] = dataValue(a.value))
})
return o
} else {
if (typeof o[opt_k] === 'undefined')
o[opt_k] = dataValue(this.attr('data-' + decamelize(opt_k)))
return o[opt_k]
}
} else {
return this.each(function (el) { data(el)[opt_k] = opt_v })
}
}
// DOM detachment & related
, remove: function () {
this.deepEach(clearData)
return this.each(function (el) {
el[parentNode] && el[parentNode].removeChild(el)
})
}
, empty: function () {
return this.each(function (el) {
deepEach(el.childNodes, clearData)
while (el.firstChild) {
el.removeChild(el.firstChild)
}
})
}
, detach: function () {
return this.each(function (el) {
el[parentNode].removeChild(el)
})
}
// who uses a mouse anyway? oh right.
, scrollTop: function (y) {
return scroll.call(this, null, y, 'y')
}
, scrollLeft: function (x) {
return scroll.call(this, x, null, 'x')
}
}
function normalize(node) {
return typeof node == 'string' ? bonzo.create(node) : isNode(node) ? [node] : node // assume [nodes]
}
function scroll(x, y, type) {
var el = this[0]
if (!el) return this
if (x == null && y == null) {
return (isBody(el) ? getWindowScroll() : { x: el.scrollLeft, y: el.scrollTop })[type]
}
if (isBody(el)) {
win.scrollTo(x, y)
} else {
x != null && (el.scrollLeft = x)
y != null && (el.scrollTop = y)
}
return this
}
function isBody(element) {
return element === win || (/^(?:body|html)$/i).test(element.tagName)
}
function getWindowScroll() {
return { x: win.pageXOffset || html.scrollLeft, y: win.pageYOffset || html.scrollTop }
}
/**
* @param {Array.<Element>|Element|Node|string} els
* @param {Object=} opt_scopeHost
* @return {Bonzo}
*/
function bonzo(els, opt_scopeHost) {
return new Bonzo(els, opt_scopeHost)
}
bonzo.setQueryEngine = function (q) {
query = q;
delete bonzo.setQueryEngine
}
bonzo.aug = function (o, target) {
// for those standalone bonzo users. this love is for you.
for (var k in o) {
o.hasOwnProperty(k) && ((target || Bonzo.prototype)[k] = o[k])
}
}
bonzo.create = function (node) {
// hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
return typeof node == 'string' && node !== '' ?
function () {
var tag = /^\s*<([^\s>]+)/.exec(node)
, el = doc.createElement('div')
, els = []
, p = tag ? tagMap[tag[1].toLowerCase()] : null
, dep = p ? p[2] + 1 : 1
, ns = p && p[3]
, pn = parentNode
, tb = features.autoTbody && p && p[0] == '<table>' && !(/<tbody/i).test(node)
el.innerHTML = p ? (p[0] + node + p[1]) : node
while (dep--) el = el.firstChild
// for IE NoScope, we may insert cruft at the begining just to get it to work
if (ns && el && el.nodeType !== 1) el = el.nextSibling
do {
// tbody special case for IE<8, creates tbody on any empty table
// we don't want it if we're just after a <thead>, <caption>, etc.
if ((!tag || el.nodeType == 1) && (!tb || el.tagName.toLowerCase() != 'tbody')) {
els.push(el)
}
} while (el = el.nextSibling)
// IE < 9 gives us a parentNode which messes up insert() check for cloning
// `dep` > 1 can also cause problems with the insert() check (must do this last)
each(els, function(el) { el[pn] && el[pn].removeChild(el) })
return els
}() : isNode(node) ? [node.cloneNode(true)] : []
}
bonzo.doc = function () {
var vp = bonzo.viewport()
return {
width: Math.max(doc.body.scrollWidth, html.scrollWidth, vp.width)
, height: Math.max(doc.body.scrollHeight, html.scrollHeight, vp.height)
}
}
bonzo.firstChild = function (el) {
for (var c = el.childNodes, i = 0, j = (c && c.length) || 0, e; i < j; i++) {
if (c[i].nodeType === 1) e = c[j = i]
}
return e
}
bonzo.viewport = function () {
return {
width: ie ? html.clientWidth : self.innerWidth
, height: ie ? html.clientHeight : self.innerHeight
}
}
bonzo.isAncestor = 'compareDocumentPosition' in html ?
function (container, element) {
return (container.compareDocumentPosition(element) & 16) == 16
} : 'contains' in html ?
function (container, element) {
return container !== element && container.contains(element);
} :
function (container, element) {
while (element = element[parentNode]) {
if (element === container) {
return true
}
}
return false
}
return bonzo
}, this); // the only line we care about using a semi-colon. placed here for concatenation tools
|
/**
* The Studio: Artist of the Day plugin
* This is a daily activity where users nominate the featured artist for the day, which is selected randomly once voting has ended.
* Only works in a room with the id 'thestudio'
*/
function toArrayOfArrays(map) {
var ret = [];
map.forEach(function (value, key) {
ret.push([value, key]);
});
return ret;
}
function toArtistId(artist) { // toId would return '' for foreign/sadistic artists
return artist.toLowerCase().replace(/\s/g, '').replace(/\b&\b/g, '');
}
var artistOfTheDay = {
pendingNominations: false,
nominations: new Map(),
removedNominators: []
};
var theStudio = Rooms.get('thestudio');
if (theStudio && !theStudio.plugin) {
theStudio.plugin = artistOfTheDay;
}
var commands = {
start: function (target, room, user) {
if (room.id !== 'thestudio') return this.sendReply('This command can only be used in The Studio.');
if (!room.chatRoomData || !this.can('mute', null, room)) return false;
if ((user.locked || room.isMuted(user)) && !user.can('bypassall')) return this.sendReply("You cannot do this while unable to talk.");
if (artistOfTheDay.pendingNominations) return this.sendReply("Nominations for the Artist of the Day are already in progress.");
var nominations = artistOfTheDay.nominations;
var prenominations = room.chatRoomData.prenominations;
if (prenominations && prenominations.length) {
for (var i = 0; i < prenominations.length; i++) {
var prenomination = prenominations[i];
nominations.set(Users.get(prenomination[0].userid) || prenomination[0], prenomination[1]);
}
}
artistOfTheDay.pendingNominations = true;
room.chatRoomData.prenominations = [];
Rooms.global.writeChatRoomData();
room.addRaw(
"<div class=\"broadcast-blue\"><strong>Nominations for the Artist of the Day have begun!</strong><br />" +
"Use /aotd nom to nominate an artist.</div>"
);
this.privateModCommand("(" + user.name + " began nominations for the Artist of the Day.)");
},
starthelp: ["/aotd start - Start nominations for the Artist of the Day. Requires: % @ # & ~"],
end: function (target, room, user) {
if (room.id !== 'thestudio') return this.sendReply('This command can only be used in The Studio.');
if (!room.chatRoomData || !this.can('mute', null, room)) return false;
if ((user.locked || room.isMuted(user)) && !user.can('bypassall')) return this.sendReply("You cannot do this while unable to talk.");
if (!artistOfTheDay.pendingNominations) return this.sendReply("Nominations for the Artist of the Day are not in progress.");
if (!artistOfTheDay.nominations.size) return this.sendReply("No nominations have been submitted yet.");
var nominations = toArrayOfArrays(artistOfTheDay.nominations);
var artist = nominations[~~(Math.random() * nominations.length)][0];
artistOfTheDay.pendingNominations = false;
artistOfTheDay.nominations.clear();
artistOfTheDay.removedNominators = [];
room.chatRoomData.artistOfTheDay = artist;
Rooms.global.writeChatRoomData();
room.addRaw(
"<div class=\"broadcast-blue\"><strong>Nominations for the Artist of the Day have ended!</strong><br />" +
"Randomly selected artist: " + Tools.escapeHTML(artist) + "</div>"
);
this.privateModCommand("(" + user.name + " ended nominations for the Artist of the Day.)");
},
endhelp: ["/aotd end - End nominations for the Artist of the Day and set it to a randomly selected artist. Requires: % @ # & ~"],
prenom: function (target, room, user) {
if (room.id !== 'thestudio') return this.sendReply('This command can only be used in The Studio.');
if (!target) this.parse('/help aotd prenom');
if (!room.chatRoomData || !target) return false;
if ((user.locked || room.isMuted(user)) && !user.can('bypassall')) return this.sendReply("You cannot do this while unable to talk.");
if (artistOfTheDay.pendingNominations) return this.sendReply("Nominations for the Artist of the Day are in progress.");
if (!room.chatRoomData.prenominations) room.chatRoomData.prenominations = [];
var userid = user.userid;
var ips = user.ips;
var prenominationId = toArtistId(target);
if (!prenominationId) return this.sendReply("" + target + " is not a valid artist name.");
if (room.chatRoomData.artistOfTheDay && toArtistId(room.chatRoomData.artistOfTheDay) === prenominationId) return this.sendReply("" + target + " is already the current Artist of the Day.");
var prenominations = room.chatRoomData.prenominations;
var prenominationIndex = -1;
var latestIp = user.latestIp;
for (var i = 0; i < prenominations.length; i++) {
if (toArtistId(prenominations[i][1]) === prenominationId) return this.sendReply("" + target + " has already been prenominated.");
if (prenominationIndex < 0) {
var prenominator = prenominations[i][0];
if (prenominator.userid === userid || prenominator.ips[latestIp]) {
prenominationIndex = i;
break;
}
}
}
if (prenominationIndex >= 0) {
prenominations[prenominationIndex][1] = target;
Rooms.global.writeChatRoomData();
return this.sendReply("Your prenomination was changed to " + target + ".");
}
prenominations.push([{name: user.name, userid: userid, ips: user.ips}, target]);
Rooms.global.writeChatRoomData();
this.sendReply("" + target + " was submitted for the next nomination period for the Artist of the Day.");
},
prenomhelp: ["/aotd prenom [artist] - Nominate an artist for the Artist of the Day between nomination periods."],
nom: function (target, room, user) {
if (room.id !== 'thestudio') return this.sendReply('This command can only be used in The Studio.');
if (!target) this.parse('/help aotd nom');
if (!room.chatRoomData || !target) return false;
if ((user.locked || room.isMuted(user)) && !user.can('bypassall')) return this.sendReply("You cannot do this while unable to talk.");
if (!artistOfTheDay.pendingNominations) return this.sendReply("Nominations for the Artist of the Day are not in progress.");
var removedNominators = artistOfTheDay.removedNominators;
if (removedNominators.indexOf(user) >= 0) return this.sendReply("Since your nomination has been removed, you cannot submit another artist until the next round.");
var alts = user.getAlts();
for (var i = 0; i < removedNominators.length; i++) {
if (alts.indexOf(removedNominators[i].name) >= 0) return this.sendReply("Since your nomination has been removed, you cannot submit another artist until the next round.");
}
var nominationId = toArtistId(target);
if (room.chatRoomData.artistOfTheDay && toArtistId(room.chatRoomData.artistOfTheDay) === nominationId) return this.sendReply("" + target + " was the last Artist of the Day.");
var userid = user.userid;
var latestIp = user.latestIp;
for (var data, nominationsIterator = artistOfTheDay.nominations.entries(); !!(data = nominationsIterator.next().value);) { // replace with for-of loop once available
var nominator = data[0];
if (nominator.ips[latestIp] && nominator.userid !== userid || alts.indexOf(nominator.name) >= 0) return this.sendReply("You have already submitted a nomination for the Artist of the Day under the name " + nominator.name + ".");
if (toArtistId(data[1]) === nominationId) return this.sendReply("" + target + " has already been nominated.");
}
var response = "" + user.name + (artistOfTheDay.nominations.has(user) ? " changed their nomination from " + artistOfTheDay.nominations.get(user) + " to " + target + "." : " nominated " + target + " for the Artist of the Day.");
artistOfTheDay.nominations.set(user, target);
room.add(response);
},
nomhelp: ["/aotd nom [artist] - Nominate an artist for the Artist of the Day."],
viewnoms: function (target, room, user) {
if (room.id !== 'thestudio') return this.sendReply('This command can only be used in The Studio.');
if (!room.chatRoomData) return false;
var buffer = "";
if (!artistOfTheDay.pendingNominations) {
if (!user.can('mute', null, room)) return false;
var prenominations = room.chatRoomData.prenominations;
if (!prenominations || !prenominations.length) return this.sendReplyBox("No prenominations have been submitted yet.");
prenominations = prenominations.sort(function (a, b) {
if (a[1] > b[1]) return 1;
if (a[1] < b[1]) return -1;
return 0;
});
buffer += "Current prenominations:";
for (var i = 0; i < prenominations.length; i++) {
buffer += "<br />" +
"- " + Tools.escapeHTML(prenominations[i][1]) + " (submitted by " + Tools.escapeHTML(prenominations[i][0].name) + ")";
}
return this.sendReplyBox(buffer);
}
if (!this.canBroadcast()) return false;
if (!artistOfTheDay.nominations.size) return this.sendReplyBox("No nominations have been submitted yet.");
var nominations = toArrayOfArrays(artistOfTheDay.nominations).sort(function (a, b) {
if (a[1] > b[1]) return 1;
if (a[1] < b[1]) return -1;
return 0;
});
buffer += "Current nominations:";
for (var i = 0; i < nominations.length; i++) {
buffer += "<br />" +
"- " + Tools.escapeHTML(nominations[i][0]) + " (submitted by " + Tools.escapeHTML(nominations[i][1].name) + ")";
}
this.sendReplyBox(buffer);
},
viewnomshelp: ["/aotd viewnoms - View the current nominations for the Artist of the Day. Requires: % @ # & ~"],
removenom: function (target, room, user) {
if (room.id !== 'thestudio') return this.sendReply('This command can only be used in The Studio.');
if (!target) this.parse('/help aotd removenom');
if (!room.chatRoomData || !target || !this.can('mute', null, room)) return false;
if ((user.locked || room.isMuted(user)) && !user.can('bypassall')) return this.sendReply("You cannot do this while unable to talk.");
if (!artistOfTheDay.pendingNominations) return this.sendReply("Nominations for the Artist of the Day are not in progress.");
if (!artistOfTheDay.nominations.size) return this.sendReply("No nominations have been submitted yet.");
target = this.splitTarget(target);
var name = this.targetUsername;
var userid = toId(name);
if (!userid) return this.sendReply("'" + name + "' is not a valid username.");
for (var nominator, nominatorsIterator = artistOfTheDay.nominations.keys(); !!(nominator = nominatorsIterator.next().value);) { // replace with for-of loop once available
if (nominator.userid === userid) {
artistOfTheDay.nominations.delete(nominator);
artistOfTheDay.removedNominators.push(nominator);
return this.privateModCommand("(" + user.name + " removed " + nominator.name + "'s nomination for the Artist of the Day.)");
}
}
this.sendReply("User '" + name + "' has no nomination for the Artist of the Day.");
},
removenomhelp: ["/aotd removenom [username] - Remove a user\'s nomination for the Artist of the Day and prevent them from voting again until the next round. Requires: % @ # & ~"],
set: function (target, room, user) {
if (room.id !== 'thestudio') return this.sendReply('This command can only be used in The Studio.');
if (!target) this.parse('/help aotd set');
if (!room.chatRoomData || !this.can('mute', null, room)) return false;
if ((user.locked || room.isMuted(user)) && !user.can('bypassall')) return this.sendReply("You cannot do this while unable to talk.");
if (!toId(target)) return this.sendReply("No valid artist was specified.");
if (artistOfTheDay.pendingNominations) return this.sendReply("The Artist of the Day cannot be set while nominations are in progress.");
room.chatRoomData.artistOfTheDay = target;
Rooms.global.writeChatRoomData();
this.privateModCommand("(" + user.name + " set the Artist of the Day to " + target + ".)");
},
sethelp: ["/aotd set [artist] - Set the Artist of the Day. Requires: % @ # & ~"],
'': function (target, room) {
if (room.id !== 'thestudio') return this.sendReply('This command can only be used in The Studio.');
if (!room.chatRoomData || !this.canBroadcast()) return false;
this.sendReplyBox("The Artist of the Day " + (room.chatRoomData.artistOfTheDay ? "is " + room.chatRoomData.artistOfTheDay + "." : "has not been set yet."));
},
help: function (target, room) {
if (room.id !== 'thestudio') return this.sendReply('This command can only be used in The Studio.');
if (!room.chatRoomData || !this.canBroadcast()) return false;
this.sendReply("Use /help aotd to view help for all commands, or /help aotd [command] for help on a specific command.");
}
};
exports.commands = {
aotd: commands,
aotdhelp: [
"The Studio: Artist of the Day plugin commands:",
"- /aotd - View the Artist of the Day.",
"- /aotd start - Start nominations for the Artist of the Day. Requires: % @ # & ~",
"- /aotd nom [artist] - Nominate an artist for the Artist of the Day.",
"- /aotd viewnoms - View the current nominations for the Artist of the Day. Requires: % @ # & ~",
"- /aotd removenom [username] - Remove a user's nomination for the Artist of the Day and prevent them from voting again until the next round. Requires: % @ # & ~",
"- /aotd end - End nominations for the Artist of the Day and set it to a randomly selected artist. Requires: % @ # & ~",
"- /aotd prenom [artist] - Nominate an artist for the Artist of the Day between nomination periods.",
"- /aotd set [artist] - Set the Artist of the Day. Requires: % @ # & ~"
]
};
|
/*! angular-multi-select 6.0.7 */
var angular_multi_select=angular.module("angular-multi-select");angular_multi_select.config(function(a){a.createTranslation("es",{CHECK_ALL:"Marcar todo",CHECK_NONE:"Desmarcar todo",RESET:"Resetear",SEARCH:"Buscar...",CLEAR:"Limpiar"}),a.setLang("es")}); |
/**
* @fileoverview Rule to check for tabs inside a file
* @author Gyandeep Singh
*/
"use strict";
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
const regex = /\t/;
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
module.exports = {
meta: {
docs: {
description: "disallow tabs in file",
category: "Stylistic Issues",
recommended: false
},
schema: []
},
create(context) {
return {
Program(node) {
context.getSourceLines().forEach((line, index) => {
const match = regex.exec(line);
if (match) {
context.report(
node,
{
line: index + 1,
column: match.index + 1
},
"Unexpected tab character."
);
}
});
}
};
}
};
|
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v4.1.2
* @link http://www.ag-grid.com/
* @license MIT
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var utils_1 = require("../utils");
var column_1 = require("../entities/column");
var filterManager_1 = require("../filter/filterManager");
var columnController_1 = require("../columnController/columnController");
var headerTemplateLoader_1 = require("./headerTemplateLoader");
var gridOptionsWrapper_1 = require("../gridOptionsWrapper");
var horizontalDragService_1 = require("./horizontalDragService");
var gridCore_1 = require("../gridCore");
var context_1 = require("../context/context");
var cssClassApplier_1 = require("./cssClassApplier");
var dragAndDropService_1 = require("../dragAndDrop/dragAndDropService");
var sortController_1 = require("../sortController");
var RenderedHeaderCell = (function () {
function RenderedHeaderCell(column, parentScope, eRoot, dragSourceDropTarget) {
// for better structured code, anything we need to do when this column gets destroyed,
// we put a function in here. otherwise we would have a big destroy function with lots
// of 'if / else' mapping to things that got created.
this.destroyFunctions = [];
this.column = column;
this.parentScope = parentScope;
this.eRoot = eRoot;
this.dragSourceDropTarget = dragSourceDropTarget;
}
RenderedHeaderCell.prototype.init = function () {
this.eHeaderCell = this.headerTemplateLoader.createHeaderElement(this.column);
utils_1.Utils.addCssClass(this.eHeaderCell, 'ag-header-cell');
this.createScope(this.parentScope);
this.addAttributes();
cssClassApplier_1.CssClassApplier.addHeaderClassesFromCollDef(this.column.getColDef(), this.eHeaderCell, this.gridOptionsWrapper);
// label div
var eHeaderCellLabel = this.eHeaderCell.querySelector('#agHeaderCellLabel');
this.setupMovingCss();
this.setupTooltip();
this.setupResize();
this.setupMove(eHeaderCellLabel);
this.setupMenu();
this.setupSort(eHeaderCellLabel);
this.setupFilterIcon();
this.setupText();
this.setupWidth();
};
RenderedHeaderCell.prototype.setupTooltip = function () {
var colDef = this.column.getColDef();
// add tooltip if exists
if (colDef.headerTooltip) {
this.eHeaderCell.title = colDef.headerTooltip;
}
};
RenderedHeaderCell.prototype.setupText = function () {
var colDef = this.column.getColDef();
// render the cell, use a renderer if one is provided
var headerCellRenderer;
if (colDef.headerCellRenderer) {
headerCellRenderer = colDef.headerCellRenderer;
}
else if (this.gridOptionsWrapper.getHeaderCellRenderer()) {
headerCellRenderer = this.gridOptionsWrapper.getHeaderCellRenderer();
}
var headerNameValue = this.columnController.getDisplayNameForCol(this.column);
var eText = this.eHeaderCell.querySelector('#agText');
if (eText) {
if (headerCellRenderer) {
this.useRenderer(headerNameValue, headerCellRenderer, eText);
}
else {
// no renderer, default text render
eText.className = 'ag-header-cell-text';
eText.innerHTML = headerNameValue;
}
}
};
RenderedHeaderCell.prototype.setupFilterIcon = function () {
var _this = this;
var eFilterIcon = this.eHeaderCell.querySelector('#agFilter');
if (!eFilterIcon) {
return;
}
var filterChangedListener = function () {
var filterPresent = _this.column.isFilterActive();
utils_1.Utils.addOrRemoveCssClass(_this.eHeaderCell, 'ag-header-cell-filtered', filterPresent);
utils_1.Utils.addOrRemoveCssClass(eFilterIcon, 'ag-hidden', !filterPresent);
};
this.column.addEventListener(column_1.Column.EVENT_FILTER_ACTIVE_CHANGED, filterChangedListener);
this.destroyFunctions.push(function () {
_this.column.removeEventListener(column_1.Column.EVENT_FILTER_ACTIVE_CHANGED, filterChangedListener);
});
filterChangedListener();
};
RenderedHeaderCell.prototype.setupWidth = function () {
var _this = this;
var widthChangedListener = function () {
_this.eHeaderCell.style.width = _this.column.getActualWidth() + 'px';
};
this.column.addEventListener(column_1.Column.EVENT_WIDTH_CHANGED, widthChangedListener);
this.destroyFunctions.push(function () {
_this.column.removeEventListener(column_1.Column.EVENT_WIDTH_CHANGED, widthChangedListener);
});
widthChangedListener();
};
RenderedHeaderCell.prototype.getGui = function () {
return this.eHeaderCell;
};
RenderedHeaderCell.prototype.destroy = function () {
this.destroyFunctions.forEach(function (func) {
func();
});
};
RenderedHeaderCell.prototype.createScope = function (parentScope) {
var _this = this;
if (this.gridOptionsWrapper.isAngularCompileHeaders()) {
this.childScope = parentScope.$new();
this.childScope.colDef = this.column.getColDef();
this.childScope.colDefWrapper = this.column;
this.destroyFunctions.push(function () {
_this.childScope.$destroy();
});
}
};
RenderedHeaderCell.prototype.addAttributes = function () {
this.eHeaderCell.setAttribute("colId", this.column.getColId());
};
RenderedHeaderCell.prototype.setupMenu = function () {
var _this = this;
var eMenu = this.eHeaderCell.querySelector('#agMenu');
// if no menu provided in template, do nothing
if (!eMenu) {
return;
}
var weWantMenu = this.menuFactory.isMenuEnabled(this.column) && !this.column.getColDef().suppressMenu;
if (!weWantMenu) {
utils_1.Utils.removeFromParent(eMenu);
return;
}
eMenu.addEventListener('click', function () { return _this.showMenu(eMenu); });
if (!this.gridOptionsWrapper.isSuppressMenuHide()) {
eMenu.style.opacity = '0';
this.eHeaderCell.addEventListener('mouseover', function () {
eMenu.style.opacity = '1';
});
this.eHeaderCell.addEventListener('mouseout', function () {
eMenu.style.opacity = '0';
});
}
var style = eMenu.style;
style['transition'] = 'opacity 0.2s, border 0.2s';
style['-webkit-transition'] = 'opacity 0.2s, border 0.2s';
};
RenderedHeaderCell.prototype.showMenu = function (eventSource) {
this.menuFactory.showMenuAfterButtonClick(this.column, eventSource);
};
RenderedHeaderCell.prototype.setupMovingCss = function () {
var _this = this;
// this function adds or removes the moving css, based on if the col is moving
var addMovingCssFunc = function () {
if (_this.column.isMoving()) {
utils_1.Utils.addCssClass(_this.eHeaderCell, 'ag-header-cell-moving');
}
else {
utils_1.Utils.removeCssClass(_this.eHeaderCell, 'ag-header-cell-moving');
}
};
// call it now once, so the col is set up correctly
addMovingCssFunc();
// then call it every time we are informed of a moving state change in the col
this.column.addEventListener(column_1.Column.EVENT_MOVING_CHANGED, addMovingCssFunc);
// finally we remove the listener when this cell is no longer rendered
this.destroyFunctions.push(function () {
_this.column.removeEventListener(column_1.Column.EVENT_MOVING_CHANGED, addMovingCssFunc);
});
};
RenderedHeaderCell.prototype.setupMove = function (eHeaderCellLabel) {
if (this.gridOptionsWrapper.isSuppressMovableColumns() || this.column.getColDef().suppressMovable) {
return;
}
if (this.gridOptionsWrapper.isForPrint()) {
// don't allow moving of headers when forPrint, as the header overlay doesn't exist
return;
}
if (eHeaderCellLabel) {
var dragSource = {
eElement: eHeaderCellLabel,
dragItem: this.column,
dragSourceDropTarget: this.dragSourceDropTarget
};
this.dragAndDropService.addDragSource(dragSource);
}
};
RenderedHeaderCell.prototype.setupResize = function () {
var _this = this;
var colDef = this.column.getColDef();
var eResize = this.eHeaderCell.querySelector('#agResizeBar');
// if no eResize in template, do nothing
if (!eResize) {
return;
}
var weWantResize = this.gridOptionsWrapper.isEnableColResize() && !colDef.suppressResize;
if (!weWantResize) {
utils_1.Utils.removeFromParent(eResize);
return;
}
this.dragService.addDragHandling({
eDraggableElement: eResize,
eBody: this.eRoot,
cursor: 'col-resize',
startAfterPixels: 0,
onDragStart: this.onDragStart.bind(this),
onDragging: this.onDragging.bind(this)
});
var weWantAutoSize = !this.gridOptionsWrapper.isSuppressAutoSize() && !colDef.suppressAutoSize;
if (weWantAutoSize) {
eResize.addEventListener('dblclick', function () {
_this.columnController.autoSizeColumn(_this.column);
});
}
};
RenderedHeaderCell.prototype.useRenderer = function (headerNameValue, headerCellRenderer, eText) {
// renderer provided, use it
var cellRendererParams = {
colDef: this.column.getColDef(),
$scope: this.childScope,
context: this.gridOptionsWrapper.getContext(),
value: headerNameValue,
api: this.gridOptionsWrapper.getApi(),
eHeaderCell: this.eHeaderCell
};
var cellRendererResult = headerCellRenderer(cellRendererParams);
var childToAppend;
if (utils_1.Utils.isNodeOrElement(cellRendererResult)) {
// a dom node or element was returned, so add child
childToAppend = cellRendererResult;
}
else {
// otherwise assume it was html, so just insert
var eTextSpan = document.createElement("span");
eTextSpan.innerHTML = cellRendererResult;
childToAppend = eTextSpan;
}
// angular compile header if option is turned on
if (this.gridOptionsWrapper.isAngularCompileHeaders()) {
var childToAppendCompiled = this.$compile(childToAppend)(this.childScope)[0];
eText.appendChild(childToAppendCompiled);
}
else {
eText.appendChild(childToAppend);
}
};
RenderedHeaderCell.prototype.setupSort = function (eHeaderCellLabel) {
var _this = this;
var enableSorting = this.gridOptionsWrapper.isEnableSorting() && !this.column.getColDef().suppressSorting;
if (!enableSorting) {
utils_1.Utils.removeFromParent(this.eHeaderCell.querySelector('#agSortAsc'));
utils_1.Utils.removeFromParent(this.eHeaderCell.querySelector('#agSortDesc'));
utils_1.Utils.removeFromParent(this.eHeaderCell.querySelector('#agNoSort'));
return;
}
// add the event on the header, so when clicked, we do sorting
if (eHeaderCellLabel) {
eHeaderCellLabel.addEventListener("click", function (event) {
_this.sortController.progressSort(_this.column, event.shiftKey);
});
}
// add listener for sort changing, and update the icons accordingly
var eSortAsc = this.eHeaderCell.querySelector('#agSortAsc');
var eSortDesc = this.eHeaderCell.querySelector('#agSortDesc');
var eSortNone = this.eHeaderCell.querySelector('#agNoSort');
var sortChangedListener = function () {
utils_1.Utils.addOrRemoveCssClass(_this.eHeaderCell, 'ag-header-cell-sorted-asc', _this.column.isSortAscending());
utils_1.Utils.addOrRemoveCssClass(_this.eHeaderCell, 'ag-header-cell-sorted-desc', _this.column.isSortDescending());
utils_1.Utils.addOrRemoveCssClass(_this.eHeaderCell, 'ag-header-cell-sorted-none', _this.column.isSortNone());
if (eSortAsc) {
utils_1.Utils.addOrRemoveCssClass(eSortAsc, 'ag-hidden', !_this.column.isSortAscending());
}
if (eSortDesc) {
utils_1.Utils.addOrRemoveCssClass(eSortDesc, 'ag-hidden', !_this.column.isSortDescending());
}
if (eSortNone) {
var alwaysHideNoSort = !_this.column.getColDef().unSortIcon && !_this.gridOptionsWrapper.isUnSortIcon();
utils_1.Utils.addOrRemoveCssClass(eSortNone, 'ag-hidden', alwaysHideNoSort || !_this.column.isSortNone());
}
};
this.column.addEventListener(column_1.Column.EVENT_SORT_CHANGED, sortChangedListener);
this.destroyFunctions.push(function () {
_this.column.removeEventListener(column_1.Column.EVENT_SORT_CHANGED, sortChangedListener);
});
sortChangedListener();
};
RenderedHeaderCell.prototype.onDragStart = function () {
this.startWidth = this.column.getActualWidth();
};
RenderedHeaderCell.prototype.onDragging = function (dragChange, finished) {
var newWidth = this.startWidth + dragChange;
this.columnController.setColumnWidth(this.column, newWidth, finished);
};
RenderedHeaderCell.prototype.onIndividualColumnResized = function (column) {
if (this.column !== column) {
return;
}
var newWidthPx = column.getActualWidth() + "px";
this.eHeaderCell.style.width = newWidthPx;
};
__decorate([
context_1.Autowired('context'),
__metadata('design:type', context_1.Context)
], RenderedHeaderCell.prototype, "context", void 0);
__decorate([
context_1.Autowired('filterManager'),
__metadata('design:type', filterManager_1.FilterManager)
], RenderedHeaderCell.prototype, "filterManager", void 0);
__decorate([
context_1.Autowired('columnController'),
__metadata('design:type', columnController_1.ColumnController)
], RenderedHeaderCell.prototype, "columnController", void 0);
__decorate([
context_1.Autowired('$compile'),
__metadata('design:type', Object)
], RenderedHeaderCell.prototype, "$compile", void 0);
__decorate([
context_1.Autowired('gridCore'),
__metadata('design:type', gridCore_1.GridCore)
], RenderedHeaderCell.prototype, "gridCore", void 0);
__decorate([
context_1.Autowired('headerTemplateLoader'),
__metadata('design:type', headerTemplateLoader_1.HeaderTemplateLoader)
], RenderedHeaderCell.prototype, "headerTemplateLoader", void 0);
__decorate([
context_1.Autowired('horizontalDragService'),
__metadata('design:type', horizontalDragService_1.HorizontalDragService)
], RenderedHeaderCell.prototype, "dragService", void 0);
__decorate([
context_1.Autowired('menuFactory'),
__metadata('design:type', Object)
], RenderedHeaderCell.prototype, "menuFactory", void 0);
__decorate([
context_1.Autowired('gridOptionsWrapper'),
__metadata('design:type', gridOptionsWrapper_1.GridOptionsWrapper)
], RenderedHeaderCell.prototype, "gridOptionsWrapper", void 0);
__decorate([
context_1.Autowired('dragAndDropService'),
__metadata('design:type', dragAndDropService_1.DragAndDropService)
], RenderedHeaderCell.prototype, "dragAndDropService", void 0);
__decorate([
context_1.Autowired('sortController'),
__metadata('design:type', sortController_1.SortController)
], RenderedHeaderCell.prototype, "sortController", void 0);
__decorate([
context_1.PostConstruct,
__metadata('design:type', Function),
__metadata('design:paramtypes', []),
__metadata('design:returntype', void 0)
], RenderedHeaderCell.prototype, "init", null);
return RenderedHeaderCell;
})();
exports.RenderedHeaderCell = RenderedHeaderCell;
|
'use strict'; /**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/var _require =
require('jest-util');const clearLine = _require.clearLine;
const chalk = require('chalk');
const isCI = require('is-ci');
const print = stream => {
if (process.stdout.isTTY && !isCI) {
stream.write(chalk.bold.dim('Determining test suites to run...'));
}
};
const remove = stream => {
if (stream.isTTY && !isCI) {
clearLine(stream);
}
};
module.exports = {
print,
remove }; |
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v4.0.4
* @link http://www.ag-grid.com/
* @license MIT
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var context_1 = require("../context/context");
var HorizontalDragService = (function () {
function HorizontalDragService() {
}
HorizontalDragService.prototype.addDragHandling = function (params) {
params.eDraggableElement.addEventListener('mousedown', function (startEvent) {
new DragInstance(params, startEvent);
});
};
HorizontalDragService = __decorate([
context_1.Bean('horizontalDragService'),
__metadata('design:paramtypes', [])
], HorizontalDragService);
return HorizontalDragService;
})();
exports.HorizontalDragService = HorizontalDragService;
var DragInstance = (function () {
function DragInstance(params, startEvent) {
this.mouseMove = this.onMouseMove.bind(this);
this.mouseUp = this.onMouseUp.bind(this);
this.mouseLeave = this.onMouseLeave.bind(this);
this.lastDelta = 0;
this.params = params;
this.eDragParent = document.querySelector('body');
this.dragStartX = startEvent.clientX;
this.startEvent = startEvent;
this.eDragParent.addEventListener('mousemove', this.mouseMove);
this.eDragParent.addEventListener('mouseup', this.mouseUp);
this.eDragParent.addEventListener('mouseleave', this.mouseLeave);
this.draggingStarted = false;
var startAfterPixelsExist = typeof params.startAfterPixels === 'number' && params.startAfterPixels > 0;
if (!startAfterPixelsExist) {
this.startDragging();
}
}
DragInstance.prototype.startDragging = function () {
this.draggingStarted = true;
this.oldBodyCursor = this.params.eBody.style.cursor;
this.oldParentCursor = this.eDragParent.style.cursor;
this.oldMsUserSelect = this.eDragParent.style.msUserSelect;
this.oldWebkitUserSelect = this.eDragParent.style.webkitUserSelect;
// change the body cursor, so when drag moves out of the drag bar, the cursor is still 'resize' (or 'move'
this.params.eBody.style.cursor = this.params.cursor;
// same for outside the grid, we want to keep the resize (or move) cursor
this.eDragParent.style.cursor = this.params.cursor;
// we don't want text selection outside the grid (otherwise it looks weird as text highlights when we move)
this.eDragParent.style.msUserSelect = 'none';
this.eDragParent.style.webkitUserSelect = 'none';
this.params.onDragStart(this.startEvent);
};
DragInstance.prototype.onMouseMove = function (moveEvent) {
var newX = moveEvent.clientX;
this.lastDelta = newX - this.dragStartX;
if (!this.draggingStarted) {
var dragExceededStartAfterPixels = Math.abs(this.lastDelta) >= this.params.startAfterPixels;
if (dragExceededStartAfterPixels) {
this.startDragging();
}
}
if (this.draggingStarted) {
this.params.onDragging(this.lastDelta, false);
}
};
DragInstance.prototype.onMouseUp = function () {
this.stopDragging();
};
DragInstance.prototype.onMouseLeave = function () {
this.stopDragging();
};
DragInstance.prototype.stopDragging = function () {
// reset cursor back to original cursor, if they were changed in the first place
if (this.draggingStarted) {
this.params.eBody.style.cursor = this.oldBodyCursor;
this.eDragParent.style.cursor = this.oldParentCursor;
this.eDragParent.style.msUserSelect = this.oldMsUserSelect;
this.eDragParent.style.webkitUserSelect = this.oldWebkitUserSelect;
this.params.onDragging(this.lastDelta, true);
}
// always remove the listeners, as these are always added
this.eDragParent.removeEventListener('mousemove', this.mouseMove);
this.eDragParent.removeEventListener('mouseup', this.mouseUp);
this.eDragParent.removeEventListener('mouseleave', this.mouseLeave);
};
return DragInstance;
})();
|
/*!
* jQuery UI Effects Clip 1.11.1
* http://jqueryui.com
*
* Copyright 2014 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/clip-effect/
*/
(function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define([
"jquery",
"./effect"
], factory );
} else {
// Browser globals
factory( jQuery );
}
}(function( $ ) {
return $.effects.effect.clip = function( o, done ) {
// Create element
var el = $( this ),
props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
mode = $.effects.setMode( el, o.mode || "hide" ),
show = mode === "show",
direction = o.direction || "vertical",
vert = direction === "vertical",
size = vert ? "height" : "width",
position = vert ? "top" : "left",
animation = {},
wrapper, animate, distance;
// Save & Show
$.effects.save( el, props );
el.show();
// Create Wrapper
wrapper = $.effects.createWrapper( el ).css({
overflow: "hidden"
});
animate = ( el[0].tagName === "IMG" ) ? wrapper : el;
distance = animate[ size ]();
// Shift
if ( show ) {
animate.css( size, 0 );
animate.css( position, distance / 2 );
}
// Create Animation Object:
animation[ size ] = show ? distance : 0;
animation[ position ] = show ? 0 : distance / 2;
// Animate
animate.animate( animation, {
queue: false,
duration: o.duration,
easing: o.easing,
complete: function() {
if ( !show ) {
el.hide();
}
$.effects.restore( el, props );
$.effects.removeWrapper( el );
done();
}
});
};
}));
|
/*
* PrimeUI 4.1.1
*
* Copyright 2009-2015 PrimeTek.
*
* 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.
*/
/**
* PUI Object
*/
var PUI = {
zindex : 1000,
gridColumns: {
'1': 'ui-grid-col-12',
'2': 'ui-grid-col-6',
'3': 'ui-grid-col-4',
'4': 'ui-grid-col-3',
'6': 'ui-grid-col-2',
'12': 'ui-grid-col-11'
},
charSet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
/**
* Aligns container scrollbar to keep item in container viewport, algorithm copied from jquery-ui menu widget
*/
scrollInView: function(container, item) {
var borderTop = parseFloat(container.css('borderTopWidth')) || 0,
paddingTop = parseFloat(container.css('paddingTop')) || 0,
offset = item.offset().top - container.offset().top - borderTop - paddingTop,
scroll = container.scrollTop(),
elementHeight = container.height(),
itemHeight = item.outerHeight(true);
if(offset < 0) {
container.scrollTop(scroll + offset);
}
else if((offset + itemHeight) > elementHeight) {
container.scrollTop(scroll + offset - elementHeight + itemHeight);
}
},
generateRandomId: function() {
var id = '';
for (var i = 1; i <= 10; i++) {
var randPos = Math.floor(Math.random() * this.charSet.length);
id += this.charSet[randPos];
}
return id;
},
isIE: function(version) {
return (this.browser.msie && parseInt(this.browser.version, 10) === version);
},
escapeRegExp: function(text) {
return text.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
},
escapeHTML: function(value) {
return value.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
},
escapeClientId: function(id) {
return "#" + id.replace(/:/g,"\\:");
},
clearSelection: function() {
if(window.getSelection) {
if(window.getSelection().empty) {
window.getSelection().empty();
} else if(window.getSelection().removeAllRanges) {
window.getSelection().removeAllRanges();
}
} else if(document.selection && document.selection.empty) {
document.selection.empty();
}
},
inArray: function(arr, item) {
for(var i = 0; i < arr.length; i++) {
if(arr[i] === item) {
return true;
}
}
return false;
},
calculateScrollbarWidth: function() {
if(!this.scrollbarWidth) {
if(this.browser.msie) {
var $textarea1 = $('<textarea cols="10" rows="2"></textarea>')
.css({ position: 'absolute', top: -1000, left: -1000 }).appendTo('body'),
$textarea2 = $('<textarea cols="10" rows="2" style="overflow: hidden;"></textarea>')
.css({ position: 'absolute', top: -1000, left: -1000 }).appendTo('body');
this.scrollbarWidth = $textarea1.width() - $textarea2.width();
$textarea1.add($textarea2).remove();
}
else {
var $div = $('<div />')
.css({ width: 100, height: 100, overflow: 'auto', position: 'absolute', top: -1000, left: -1000 })
.prependTo('body').append('<div />').find('div')
.css({ width: '100%', height: 200 });
this.scrollbarWidth = 100 - $div.width();
$div.parent().remove();
}
}
return this.scrollbarWidth;
},
//adapted from jquery browser plugin
resolveUserAgent: function() {
var matched, browser;
jQuery.uaMatch = function( ua ) {
ua = ua.toLowerCase();
var match = /(opr)[\/]([\w.]+)/.exec( ua ) ||
/(chrome)[ \/]([\w.]+)/.exec( ua ) ||
/(version)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
/(msie) ([\w.]+)/.exec( ua ) ||
ua.indexOf("trident") >= 0 && /(rv)(?::| )([\w.]+)/.exec( ua ) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
[];
var platform_match = /(ipad)/.exec( ua ) ||
/(iphone)/.exec( ua ) ||
/(android)/.exec( ua ) ||
/(windows phone)/.exec( ua ) ||
/(win)/.exec( ua ) ||
/(mac)/.exec( ua ) ||
/(linux)/.exec( ua ) ||
/(cros)/i.exec( ua ) ||
[];
return {
browser: match[ 3 ] || match[ 1 ] || "",
version: match[ 2 ] || "0",
platform: platform_match[ 0 ] || ""
};
};
matched = jQuery.uaMatch( window.navigator.userAgent );
browser = {};
if ( matched.browser ) {
browser[ matched.browser ] = true;
browser.version = matched.version;
browser.versionNumber = parseInt(matched.version);
}
if ( matched.platform ) {
browser[ matched.platform ] = true;
}
// These are all considered mobile platforms, meaning they run a mobile browser
if ( browser.android || browser.ipad || browser.iphone || browser[ "windows phone" ] ) {
browser.mobile = true;
}
// These are all considered desktop platforms, meaning they run a desktop browser
if ( browser.cros || browser.mac || browser.linux || browser.win ) {
browser.desktop = true;
}
// Chrome, Opera 15+ and Safari are webkit based browsers
if ( browser.chrome || browser.opr || browser.safari ) {
browser.webkit = true;
}
// IE11 has a new token so we will assign it msie to avoid breaking changes
if ( browser.rv )
{
var ie = "msie";
matched.browser = ie;
browser[ie] = true;
}
// Opera 15+ are identified as opr
if ( browser.opr )
{
var opera = "opera";
matched.browser = opera;
browser[opera] = true;
}
// Stock Android browsers are marked as Safari on Android.
if ( browser.safari && browser.android )
{
var android = "android";
matched.browser = android;
browser[android] = true;
}
// Assign the name and platform variable
browser.name = matched.browser;
browser.platform = matched.platform;
this.browser = browser;
$.browser = browser;
},
getGridColumn: function(number) {
return this.gridColumns[number + ''];
},
executeFunctionByName: function(functionName /*, args */) {
var args = [].slice.call(arguments).splice(1),
context = window,
namespaces = functionName.split("."),
func = namespaces.pop();
for(var i = 0; i < namespaces.length; i++) {
context = context[namespaces[i]];
}
return context[func].apply(this, args);
},
resolveObjectByName: function(name) {
if(name) {
var parts = name.split(".");
for(var i = 0, len = parts.length, obj = window; i < len; ++i) {
obj = obj[parts[i]];
}
return obj;
}
else {
return null;
}
},
getCookie : function(name) {
return $.cookie(name);
},
setCookie : function(name, value, cfg) {
$.cookie(name, value, cfg);
},
deleteCookie: function(name, cfg) {
$.removeCookie(name, cfg);
}
};
PUI.resolveUserAgent();/**
* PrimeUI Accordion widget
*/
(function() {
$.widget("primeui.puiaccordion", {
options: {
activeIndex: 0,
multiple: false
},
_create: function() {
if(this.options.multiple) {
this.options.activeIndex = this.options.activeIndex||[0];
}
var $this = this;
this.element.addClass('ui-accordion ui-widget ui-helper-reset');
var tabContainers = this.element.children();
//primeui
if(tabContainers.is('div')) {
this.panelMode = 'native';
this.headers = this.element.children('h3');
this.panels = this.element.children('div');
}
//primeng
else {
this.panelMode = 'wrapped';
this.headers = tabContainers.children('h3');
this.panels = tabContainers.children('div');
}
this.headers.addClass('ui-accordion-header ui-helper-reset ui-state-default').each(function(i) {
var header = $(this),
title = header.html(),
active = $this.options.multiple ? ($.inArray(i, $this.options.activeIndex) !== -1) : (i == $this.options.activeIndex),
headerClass = (active) ? 'ui-state-active ui-corner-top' : 'ui-corner-all',
iconClass = (active) ? 'fa fa-fw fa-caret-down' : 'fa fa-fw fa-caret-right';
header.addClass(headerClass).html('<span class="' + iconClass + '"></span><a href="#">' + title + '</a>');
});
this.panels.each(function(i) {
var content = $(this);
content.addClass('ui-accordion-content ui-helper-reset ui-widget-content'),
active = $this.options.multiple ? ($.inArray(i, $this.options.activeIndex) !== -1) : (i == $this.options.activeIndex);
if(!active) {
content.addClass('ui-helper-hidden');
}
});
this.headers.children('a').disableSelection();
this._bindEvents();
},
_destroy: function() {
this._unbindEvents();
this.element.removeClass('ui-accordion ui-widget ui-helper-reset');
this.headers.removeClass('ui-accordion-header ui-helper-reset ui-state-default ui-state-hover ui-state-active ui-state-disabled ui-corner-all ui-corner-top');
this.panels.removeClass('ui-accordion-content ui-helper-reset ui-widget-content ui-helper-hidden');
this.headers.children('.fa').remove();
this.headers.children('a').contents().unwrap();
},
_bindEvents: function() {
var $this = this;
this.headers.on('mouseover.puiaccordion', function() {
var element = $(this);
if(!element.hasClass('ui-state-active')&&!element.hasClass('ui-state-disabled')) {
element.addClass('ui-state-hover');
}
}).on('mouseout.puiaccordion', function() {
var element = $(this);
if(!element.hasClass('ui-state-active')&&!element.hasClass('ui-state-disabled')) {
element.removeClass('ui-state-hover');
}
}).on('click.puiaccordion', function(e) {
var element = $(this);
if(!element.hasClass('ui-state-disabled')) {
var tabIndex = ($this.panelMode === 'native') ? element.index() / 2 : element.parent().index();
if(element.hasClass('ui-state-active')) {
$this.unselect(tabIndex);
}
else {
$this.select(tabIndex, false);
}
}
e.preventDefault();
});
},
_unbindEvents: function() {
this.headers.off('mouseover.puiaccordion mouseout.puiaccordion click.puiaccordion');
},
/**
* Activates a tab with given index
*/
select: function(index, silent) {
var panel = this.panels.eq(index);
if(!silent) {
this._trigger('change', null, {'index': index});
}
//update state
if(this.options.multiple) {
this._addToSelection(index);
}
else {
this.options.activeIndex = index;
}
this._show(panel);
},
/**
* Deactivates a tab with given index
*/
unselect: function(index) {
var panel = this.panels.eq(index),
header = panel.prev();
header.attr('aria-expanded', false).children('.fa').removeClass('fa-caret-down').addClass('fa-caret-right');
header.removeClass('ui-state-active ui-corner-top').addClass('ui-corner-all');
panel.attr('aria-hidden', true).slideUp();
this._removeFromSelection(index);
},
_show: function(panel) {
//deactivate current
if(!this.options.multiple) {
var oldHeader = this.headers.filter('.ui-state-active');
oldHeader.children('.fa').removeClass('fa-caret-down').addClass('fa-caret-right');
oldHeader.attr('aria-expanded', false).removeClass('ui-state-active ui-corner-top').addClass('ui-corner-all').next().attr('aria-hidden', true).slideUp();
}
//activate selected
var newHeader = panel.prev();
newHeader.attr('aria-expanded', true).addClass('ui-state-active ui-corner-top').removeClass('ui-state-hover ui-corner-all')
.children('.fa').removeClass('fa-caret-right').addClass('fa-caret-down');
panel.attr('aria-hidden', false).slideDown('normal');
},
_addToSelection: function(nodeId) {
this.options.activeIndex.push(nodeId);
},
_removeFromSelection: function(index) {
this.options.activeIndex = $.grep(this.options.activeIndex, function(r) {
return r != index;
});
},
_setOption: function(key, value) {
if(key === 'activeIndex') {
this.select(value, true);
}
else {
$.Widget.prototype._setOption.apply(this, arguments);
}
}
});
})();/**
* PrimeUI autocomplete widget
*/
(function() {
$.widget("primeui.puiautocomplete", {
options: {
delay: 300,
minQueryLength: 1,
multiple: false,
dropdown: false,
scrollHeight: 200,
forceSelection: false,
effect:null,
effectOptions: {},
effectSpeed: 'normal',
content: null,
caseSensitive: false
},
_create: function() {
this.element.wrap('<span class="ui-autocomplete ui-widget" />');
this.element.puiinputtext();
this.panel = $('<div class="ui-autocomplete-panel ui-widget-content ui-corner-all ui-helper-hidden ui-shadow"></div>').appendTo('body');
if(this.options.multiple) {
this.element.wrap('<ul class="ui-autocomplete-multiple ui-widget ui-inputtext ui-state-default ui-corner-all">' +
'<li class="ui-autocomplete-input-token"></li></ul>');
this.inputContainer = this.element.parent();
this.multiContainer = this.inputContainer.parent();
}
else {
if(this.options.dropdown) {
this.dropdown = $('<button type="button" class="ui-autocomplete-dropdown ui-button ui-widget ui-state-default ui-corner-right ui-button-icon-only">' +
'<span class="fa fa-fw fa-caret-down"></span><span class="ui-button-text"> </span></button>')
.insertAfter(this.element);
this.element.removeClass('ui-corner-all').addClass('ui-corner-left');
}
}
this._bindEvents();
},
_bindEvents: function() {
var $this = this;
this._bindKeyEvents();
if(this.options.dropdown) {
this.dropdown.on('mouseenter.puiautocomplete', function() {
if(!$this.element.prop('disabled')) {
$this.dropdown.addClass('ui-state-hover');
}
})
.on('mouseleave.puiautocomplete', function() {
$this.dropdown.removeClass('ui-state-hover');
})
.on('mousedown.puiautocomplete', function() {
if(!$this.element.prop('disabled')) {
$this.dropdown.addClass('ui-state-active');
}
})
.on('mouseup.puiautocomplete', function() {
if(!$this.element.prop('disabled')) {
$this.dropdown.removeClass('ui-state-active');
$this.search('');
$this.element.focus();
}
})
.on('focus.puiautocomplete', function() {
$this.dropdown.addClass('ui-state-focus');
})
.on('blur.puiautocomplete', function() {
$this.dropdown.removeClass('ui-state-focus');
})
.on('keydown.puiautocomplete', function(e) {
var keyCode = $.ui.keyCode;
if(e.which == keyCode.ENTER || e.which == keyCode.NUMPAD_ENTER) {
$this.search('');
$this.input.focus();
e.preventDefault();
}
});
}
if(this.options.multiple) {
this.multiContainer.on('hover.puiautocomplete', function() {
$(this).toggleClass('ui-state-hover');
})
.on('click.puiautocomplete', function() {
$this.element.trigger('focus');
});
this.element.on('focus.ui-autocomplete', function() {
$this.multiContainer.addClass('ui-state-focus');
})
.on('blur.ui-autocomplete', function(e) {
$this.multiContainer.removeClass('ui-state-focus');
});
}
if(this.options.forceSelection) {
this.currentItems = [this.element.val()];
this.element.on('blur.puiautocomplete', function() {
var value = $(this).val(),
valid = false;
for(var i = 0; i < $this.currentItems.length; i++) {
if($this.currentItems[i] === value) {
valid = true;
break;
}
}
if(!valid) {
$this.element.val('');
}
});
}
$(document.body).bind('mousedown.puiautocomplete', function (e) {
if($this.panel.is(":hidden")) {
return;
}
if(e.target === $this.element.get(0)) {
return;
}
var offset = $this.panel.offset();
if (e.pageX < offset.left ||
e.pageX > offset.left + $this.panel.width() ||
e.pageY < offset.top ||
e.pageY > offset.top + $this.panel.height()) {
$this.hide();
}
});
$(window).bind('resize.' + this.element.id, function() {
if($this.panel.is(':visible')) {
$this._alignPanel();
}
});
},
_bindKeyEvents: function() {
var $this = this;
this.element.on('keyup.puiautocomplete', function(e) {
var keyCode = $.ui.keyCode,
key = e.which,
shouldSearch = true;
if(key == keyCode.UP ||
key == keyCode.LEFT ||
key == keyCode.DOWN ||
key == keyCode.RIGHT ||
key == keyCode.TAB ||
key == keyCode.SHIFT ||
key == keyCode.ENTER ||
key == keyCode.NUMPAD_ENTER) {
shouldSearch = false;
}
if(shouldSearch) {
var value = $this.element.val();
if(!value.length) {
$this.hide();
}
if(value.length >= $this.options.minQueryLength) {
if($this.timeout) {
window.clearTimeout($this.timeout);
}
$this.timeout = window.setTimeout(function() {
$this.search(value);
},
$this.options.delay);
}
}
}).on('keydown.puiautocomplete', function(e) {
if($this.panel.is(':visible')) {
var keyCode = $.ui.keyCode,
highlightedItem = $this.items.filter('.ui-state-highlight');
switch(e.which) {
case keyCode.UP:
case keyCode.LEFT:
var prev = highlightedItem.prev();
if(prev.length == 1) {
highlightedItem.removeClass('ui-state-highlight');
prev.addClass('ui-state-highlight');
if($this.options.scrollHeight) {
PUI.scrollInView($this.panel, prev);
}
}
e.preventDefault();
break;
case keyCode.DOWN:
case keyCode.RIGHT:
var next = highlightedItem.next();
if(next.length == 1) {
highlightedItem.removeClass('ui-state-highlight');
next.addClass('ui-state-highlight');
if($this.options.scrollHeight) {
PUI.scrollInView($this.panel, next);
}
}
e.preventDefault();
break;
case keyCode.ENTER:
case keyCode.NUMPAD_ENTER:
highlightedItem.trigger('click');
e.preventDefault();
break;
case keyCode.ALT:
case 224:
break;
case keyCode.TAB:
highlightedItem.trigger('click');
$this.hide();
break;
}
}
});
},
_bindDynamicEvents: function() {
var $this = this;
this.items.on('mouseover.puiautocomplete', function() {
var item = $(this);
if(!item.hasClass('ui-state-highlight')) {
$this.items.filter('.ui-state-highlight').removeClass('ui-state-highlight');
item.addClass('ui-state-highlight');
}
})
.on('click.puiautocomplete', function(event) {
var item = $(this);
if($this.options.multiple) {
var tokenMarkup = '<li class="ui-autocomplete-token ui-state-active ui-corner-all ui-helper-hidden">';
tokenMarkup += '<span class="ui-autocomplete-token-icon fa fa-fw fa-close" />';
tokenMarkup += '<span class="ui-autocomplete-token-label">' + item.data('label') + '</span></li>';
$(tokenMarkup).data(item.data())
.insertBefore($this.inputContainer).fadeIn()
.children('.ui-autocomplete-token-icon').on('click.ui-autocomplete', function(e) {
var token = $(this).parent();
$this._removeItem(token);
$this._trigger('unselect', e, token);
});
$this.element.val('').trigger('focus');
}
else {
$this.element.val(item.data('label')).focus();
}
$this._trigger('select', event, item);
$this.hide();
});
},
search: function(q) {
this.query = this.options.caseSensitive ? q : q.toLowerCase();
var request = {
query: this.query
};
if(this.options.completeSource) {
if($.isArray(this.options.completeSource)) {
var sourceArr = this.options.completeSource,
data = [],
emptyQuery = ($.trim(q) === '');
for(var i = 0 ; i < sourceArr.length; i++) {
var item = sourceArr[i],
itemLabel = item.label||item;
if(!this.options.caseSensitive) {
itemLabel = itemLabel.toLowerCase();
}
if(emptyQuery||itemLabel.indexOf(this.query) === 0) {
data.push({label:sourceArr[i], value: item});
}
}
this._handleData(data);
}
else {
this.options.completeSource.call(this, request, this._handleData);
}
}
},
_handleData: function(data) {
var $this = this;
this.panel.html('');
this.listContainer = $('<ul class="ui-autocomplete-items ui-autocomplete-list ui-widget-content ui-widget ui-corner-all ui-helper-reset"></ul>').appendTo(this.panel);
for(var i = 0; i < data.length; i++) {
var item = $('<li class="ui-autocomplete-item ui-autocomplete-list-item ui-corner-all"></li>');
item.data(data[i]);
if(this.options.content)
item.html(this.options.content.call(this, data[i]));
else
item.text(data[i].label);
this.listContainer.append(item);
}
this.items = this.listContainer.children('.ui-autocomplete-item');
this._bindDynamicEvents();
if(this.items.length > 0) {
var firstItem = $this.items.eq(0),
hidden = this.panel.is(':hidden');
firstItem.addClass('ui-state-highlight');
if($this.query.length > 0 && !$this.options.content) {
$this.items.each(function() {
var item = $(this),
text = item.html(),
re = new RegExp(PUI.escapeRegExp($this.query), 'gi'),
highlighedText = text.replace(re, '<span class="ui-autocomplete-query">$&</span>');
item.html(highlighedText);
});
}
if(this.options.forceSelection) {
this.currentItems = [];
$.each(data, function(i, item) {
$this.currentItems.push(item.label);
});
}
//adjust height
if($this.options.scrollHeight) {
var heightConstraint = hidden ? $this.panel.height() : $this.panel.children().height();
if(heightConstraint > $this.options.scrollHeight)
$this.panel.height($this.options.scrollHeight);
else
$this.panel.css('height', 'auto');
}
if(hidden) {
$this.show();
}
else {
$this._alignPanel();
}
}
else {
this.panel.hide();
}
},
show: function() {
this._alignPanel();
if(this.options.effect)
this.panel.show(this.options.effect, {}, this.options.effectSpeed);
else
this.panel.show();
},
hide: function() {
this.panel.hide();
this.panel.css('height', 'auto');
},
_removeItem: function(item) {
item.fadeOut('fast', function() {
var token = $(this);
token.remove();
});
},
_alignPanel: function() {
var panelWidth = null;
if(this.options.multiple) {
panelWidth = this.multiContainer.innerWidth() - (this.element.position().left - this.multiContainer.position().left);
}
else {
if(this.panel.is(':visible')) {
panelWidth = this.panel.children('.ui-autocomplete-items').outerWidth();
}
else {
this.panel.css({'visibility':'hidden','display':'block'});
panelWidth = this.panel.children('.ui-autocomplete-items').outerWidth();
this.panel.css({'visibility':'visible','display':'none'});
}
var inputWidth = this.element.outerWidth();
if(panelWidth < inputWidth) {
panelWidth = inputWidth;
}
}
this.panel.css({
'left':'',
'top':'',
'width': panelWidth,
'z-index': ++PUI.zindex
})
.position({
my: 'left top',
at: 'left bottom',
of: this.element
});
}
});
})();/**
* PrimeFaces Button Widget
*/
(function() {
$.widget("primeui.puibutton", {
options: {
value: null,
icon: null,
iconPos: 'left',
click: null
},
_create: function() {
var element = this.element;
this.elementText = this.element.text();
var value = this.options.value||(this.elementText === '' ? 'ui-button' : this.elementText),
disabled = element.prop('disabled'),
styleClass = null;
if(this.options.icon) {
styleClass = (value === 'ui-button') ? 'ui-button-icon-only' : 'ui-button-text-icon-' + this.options.iconPos;
}
else {
styleClass = 'ui-button-text-only';
}
if(disabled) {
styleClass += ' ui-state-disabled';
}
this.element.addClass('ui-button ui-widget ui-state-default ui-corner-all ' + styleClass).text('');
if(this.options.icon) {
this.element.append('<span class="ui-button-icon-' + this.options.iconPos + ' ui-c fa fa-fw ' + this.options.icon + '" />');
}
this.element.append('<span class="ui-button-text ui-c">' + value + '</span>');
if(!disabled) {
this._bindEvents();
}
},
_destroy: function() {
this.element.removeClass('ui-button ui-widget ui-state-default ui-state-hover ui-state-active ui-state-disabled ui-state-focus ui-corner-all ' +
'ui-button-text-only ui-button-icon-only ui-button-text-icon-right ui-button-text-icon-left');
this._unbindEvents();
this.element.children('.fa').remove();
this.element.children('.ui-button-text').remove();
this.element.text(this.elementText);
},
_bindEvents: function() {
var element = this.element,
$this = this;
element.on('mouseover.puibutton', function(){
if(!element.prop('disabled')) {
element.addClass('ui-state-hover');
}
}).on('mouseout.puibutton', function() {
$(this).removeClass('ui-state-active ui-state-hover');
}).on('mousedown.puibutton', function() {
if(!element.hasClass('ui-state-disabled')) {
element.addClass('ui-state-active').removeClass('ui-state-hover');
}
}).on('mouseup.puibutton', function(e) {
element.removeClass('ui-state-active').addClass('ui-state-hover');
$this._trigger('click', e);
}).on('focus.puibutton', function() {
element.addClass('ui-state-focus');
}).on('blur.puibutton', function() {
element.removeClass('ui-state-focus');
}).on('keydown.puibutton',function(e) {
if(e.keyCode == $.ui.keyCode.SPACE || e.keyCode == $.ui.keyCode.ENTER || e.keyCode == $.ui.keyCode.NUMPAD_ENTER) {
element.addClass('ui-state-active');
}
}).on('keyup.puibutton', function() {
element.removeClass('ui-state-active');
});
return this;
},
_unbindEvents: function() {
this.element.off('mouseover.puibutton mouseout.puibutton mousedown.puibutton mouseup.puibutton focus.puibutton blur.puibutton keydown.puibutton keyup.puibutton');
},
disable: function() {
this._unbindEvents();
this.element.addClass('ui-state-disabled').prop('disabled',true);
},
enable: function() {
if(this.element.prop('disabled')) {
this._bindEvents();
this.element.prop('disabled', false).removeClass('ui-state-disabled');
}
},
_setOption: function(key, value) {
if(key === 'disabled') {
if(value)
this.disable();
else
this.enable();
}
else {
$.Widget.prototype._setOption.apply(this, arguments);
}
}
});
})();/**
* PrimeUI Carousel widget
*/
(function() {
$.widget("primeui.puicarousel", {
options: {
datasource: null,
numVisible: 3,
firstVisible: 0,
headerText: null,
effectDuration: 500,
circular :false,
breakpoint: 560,
itemContent: null,
responsive: true,
autoplayInterval: 0,
easing: 'easeInOutCirc',
pageLinks: 3,
style: null,
styleClass: null,
template: null,
enhanced: false
},
_create: function() {
this.id = this.element.attr('id');
if(!this.id) {
this.id = this.element.uniqueId().attr('id');
}
if(!this.options.enhanced) {
this.element.wrap('<div class="ui-carousel ui-widget ui-widget-content ui-corner-all"><div class="ui-carousel-viewport"></div></div>');
}
this.container = this.element.parent().parent();
this.element.addClass('ui-carousel-items');
this.viewport = this.element.parent();
this.container.prepend('<div class="ui-carousel-header ui-widget-header"><div class="ui-carousel-header-title"></div></div>');
this.header = this.container.children('.ui-carousel-header');
this.header.append('<span class="ui-carousel-button ui-carousel-next-button fa fa-arrow-circle-right"></span>' +
'<span class="ui-carousel-button ui-carousel-prev-button fa fa-arrow-circle-left"></span>');
if(this.options.headerText) {
this.header.children('.ui-carousel-header-title').html(this.options.headerText);
}
if(this.options.styleClass) {
this.container.addClass(this.options.styleClass);
}
if(this.options.style) {
this.container.attr('style', this.options.style);
}
if(this.options.datasource)
this._loadData();
else
this._render();
},
_destroy: function() {
this._unbindEvents();
this.header.remove();
this.items.removeClass('ui-carousel-item ui-widget-content ui-corner-all').css('width','auto');
this.element.removeClass('ui-carousel-items').css('left','auto');
if(!this.options.enhanced) {
this.element.unwrap().unwrap();
}
if(this.options.datasource) {
this.items.remove();
}
},
_loadData: function() {
if($.isArray(this.options.datasource))
this._render(this.options.datasource);
else if($.type(this.options.datasource) === 'function')
this.options.datasource.call(this, this._render);
},
_updateDatasource: function(value) {
this.options.datasource = value;
this.element.children().remove();
this.header.children('.ui-carousel-page-links').remove();
this.header.children('select').remove();
this._loadData();
},
_render: function(data) {
this.data = data;
if(this.data) {
for(var i = 0; i < data.length; i++) {
var itemContent = this._createItemContent(data[i]);
if($.type(itemContent) === 'string')
this.element.append('<li>' + itemContent + '</li>');
else
this.element.append($('<li></li>').wrapInner(itemContent));
}
}
this.items = this.element.children('li');
this.items.addClass('ui-carousel-item ui-widget-content ui-corner-all');
this.itemsCount = this.items.length;
this.columns = this.options.numVisible;
this.first = this.options.firstVisible;
this.page = parseInt(this.first/this.columns);
this.totalPages = Math.ceil(this.itemsCount/this.options.numVisible);
this._renderPageLinks();
this.prevNav = this.header.children('.ui-carousel-prev-button');
this.nextNav = this.header.children('.ui-carousel-next-button');
this.pageLinks = this.header.find('> .ui-carousel-page-links > .ui-carousel-page-link');
this.dropdown = this.header.children('.ui-carousel-dropdown');
this.mobileDropdown = this.header.children('.ui-carousel-mobiledropdown');
this._bindEvents();
if(this.options.responsive) {
this.refreshDimensions();
}
else {
this.calculateItemWidths();
this.container.width(this.container.width());
this.updateNavigators();
}
},
_renderPageLinks: function() {
if(this.totalPages <= this.options.pageLinks) {
this.pageLinksContainer = $('<div class="ui-carousel-page-links"></div>');
for(var i = 0; i < this.totalPages; i++) {
this.pageLinksContainer.append('<a href="#" class="ui-carousel-page-link fa fa-circle-o"></a>');
}
this.header.append(this.pageLinksContainer);
}
else {
this.dropdown = $('<select class="ui-carousel-dropdown ui-widget ui-state-default ui-corner-left"></select>');
for(var i = 0; i < this.totalPages; i++) {
var pageNumber = (i+1);
this.dropdown.append('<option value="' + pageNumber + '">' + pageNumber + '</option>');
}
this.header.append(this.dropdown);
}
if(this.options.responsive) {
this.mobileDropdown = $('<select class="ui-carousel-mobiledropdown ui-widget ui-state-default ui-corner-left"></select>');
for(var i = 0; i < this.itemsCount; i++) {
var pageNumber = (i+1);
this.mobileDropdown.append('<option value="' + pageNumber + '">' + pageNumber + '</option>');
}
this.header.append(this.mobileDropdown);
}
},
calculateItemWidths: function() {
var firstItem = this.items.eq(0);
if(firstItem.length) {
var itemFrameWidth = firstItem.outerWidth(true) - firstItem.width(); //sum of margin, border and padding
this.items.width((this.viewport.innerWidth() - itemFrameWidth * this.columns) / this.columns);
}
},
refreshDimensions: function() {
var win = $(window);
if(win.width() <= this.options.breakpoint) {
this.columns = 1;
this.calculateItemWidths(this.columns);
this.totalPages = this.itemsCount;
this.mobileDropdown.show();
this.pageLinks.hide();
}
else {
this.columns = this.options.numVisible;
this.calculateItemWidths();
this.totalPages = Math.ceil(this.itemsCount / this.options.numVisible);
this.mobileDropdown.hide();
this.pageLinks.show();
}
this.page = parseInt(this.first / this.columns);
this.updateNavigators();
this.element.css('left', (-1 * (this.viewport.innerWidth() * this.page)));
},
_bindEvents: function() {
var $this = this;
if(this.eventsBound) {
return;
}
this.prevNav.on('click.puicarousel', function() {
if($this.page !== 0) {
$this.setPage($this.page - 1);
}
else if($this.options.circular) {
$this.setPage($this.totalPages - 1);
}
});
this.nextNav.on('click.puicarousel', function() {
var lastPage = ($this.page === ($this.totalPages - 1));
if(!lastPage) {
$this.setPage($this.page + 1);
}
else if($this.options.circular) {
$this.setPage(0);
}
});
if($.swipe) {
this.element.swipe({
swipe:function(event, direction) {
if(direction === 'left') {
if($this.page === ($this.totalPages - 1)) {
if($this.options.circular)
$this.setPage(0);
}
else {
$this.setPage($this.page + 1);
}
}
else if(direction === 'right') {
if($this.page === 0) {
if($this.options.circular)
$this.setPage($this.totalPages - 1);
}
else {
$this.setPage($this.page - 1);
}
}
}
});
}
if(this.pageLinks.length) {
this.pageLinks.on('click.puicarousel', function(e) {
$this.setPage($(this).index());
e.preventDefault();
});
}
this.header.children('select').on('change.puicarousel', function() {
$this.setPage(parseInt($(this).val()) - 1);
});
if(this.options.autoplayInterval) {
this.options.circular = true;
this.startAutoplay();
}
if(this.options.responsive) {
var resizeNS = 'resize.' + this.id;
$(window).off(resizeNS).on(resizeNS, function() {
$this.refreshDimensions();
});
}
this.eventsBound = true;
},
_unbindEvents: function() {
this.prevNav.off('click.puicarousel');
this.nextNav.off('click.puicarousel');
if(this.pageLinks.length) {
this.pageLinks.off('click.puicarousel');
}
this.header.children('select').off('change.puicarousel');
if(this.options.autoplayInterval) {
this.stopAutoplay();
}
if(this.options.responsive) {
$(window).off('resize.' + this.id)
}
},
updateNavigators: function() {
if(!this.options.circular) {
if(this.page === 0) {
this.prevNav.addClass('ui-state-disabled');
this.nextNav.removeClass('ui-state-disabled');
}
else if(this.page === (this.totalPages - 1)) {
this.prevNav.removeClass('ui-state-disabled');
this.nextNav.addClass('ui-state-disabled');
}
else {
this.prevNav.removeClass('ui-state-disabled');
this.nextNav.removeClass('ui-state-disabled');
}
}
if(this.pageLinks.length) {
this.pageLinks.filter('.fa-dot-circle-o').removeClass('fa-dot-circle-o');
this.pageLinks.eq(this.page).addClass('fa-dot-circle-o');
}
if(this.dropdown.length) {
this.dropdown.val(this.page + 1);
}
if(this.mobileDropdown.length) {
this.mobileDropdown.val(this.page + 1);
}
},
setPage: function(p) {
if(p !== this.page && !this.element.is(':animated')) {
var $this = this;
this.element.animate({
left: -1 * (this.viewport.innerWidth() * p)
,easing: this.options.easing
},
{
duration: this.options.effectDuration,
easing: this.options.easing,
complete: function() {
$this.page = p;
$this.first = $this.page * $this.columns;
$this.updateNavigators();
$this._trigger('pageChange', null, {'page':p});
}
});
}
},
startAutoplay: function() {
var $this = this;
this.interval = setInterval(function() {
if($this.page === ($this.totalPages - 1))
$this.setPage(0);
else
$this.setPage($this.page + 1);
}, this.options.autoplayInterval);
},
stopAutoplay: function() {
clearInterval(this.interval);
},
_setOption: function(key, value) {
if(key === 'datasource')
this._updateDatasource(value);
else
$.Widget.prototype._setOption.apply(this, arguments);
},
_createItemContent: function(obj) {
if(this.options.template) {
var template = this.options.template.html();
Mustache.parse(template);
return Mustache.render(template, obj);
}
else {
return this.options.itemContent.call(this, obj);
}
}
});
})();/**
* PrimeUI checkbox widget
*/
(function() {
$.widget("primeui.puicheckbox", {
_create: function() {
this.element.wrap('<div class="ui-chkbox ui-widget"><div class="ui-helper-hidden-accessible"></div></div>');
this.container = this.element.parent().parent();
this.box = $('<div class="ui-chkbox-box ui-widget ui-corner-all ui-state-default">').appendTo(this.container);
this.icon = $('<span class="ui-chkbox-icon ui-c"></span>').appendTo(this.box);
this.disabled = this.element.prop('disabled');
this.label = $('label[for="' + this.element.attr('id') + '"]');
if(this.isChecked()) {
this.box.addClass('ui-state-active');
this.icon.addClass('fa fa-fw fa-check');
}
if(this.disabled) {
this.box.addClass('ui-state-disabled');
} else {
this._bindEvents();
}
},
_bindEvents: function() {
var $this = this;
this.box.on('mouseover.puicheckbox', function() {
if(!$this.isChecked())
$this.box.addClass('ui-state-hover');
})
.on('mouseout.puicheckbox', function() {
$this.box.removeClass('ui-state-hover');
})
.on('click.puicheckbox', function() {
$this.toggle();
});
this.element.on('focus.puicheckbox', function() {
if($this.isChecked()) {
$this.box.removeClass('ui-state-active');
}
$this.box.addClass('ui-state-focus');
})
.on('blur.puicheckbox', function() {
if($this.isChecked()) {
$this.box.addClass('ui-state-active');
}
$this.box.removeClass('ui-state-focus');
})
.on('keydown.puicheckbox', function(e) {
var keyCode = $.ui.keyCode;
if(e.which == keyCode.SPACE) {
e.preventDefault();
}
})
.on('keyup.puicheckbox', function(e) {
var keyCode = $.ui.keyCode;
if(e.which == keyCode.SPACE) {
$this.toggle(true);
e.preventDefault();
}
});
this.label.on('click.puicheckbox', function(e) {
$this.toggle();
e.preventDefault();
});
},
toggle: function(keypress) {
if(this.isChecked()) {
this.uncheck(keypress);
} else {
this.check(keypress);
}
this._trigger('change', null, this.isChecked());
},
isChecked: function() {
return this.element.prop('checked');
},
check: function(activate, silent) {
if(!this.isChecked()) {
this.element.prop('checked', true);
this.icon.addClass('fa fa-fw fa-check');
if(!activate) {
this.box.addClass('ui-state-active');
}
if(!silent) {
this.element.trigger('change');
}
}
},
uncheck: function() {
if(this.isChecked()) {
this.element.prop('checked', false);
this.box.removeClass('ui-state-active');
this.icon.removeClass('fa fa-fw fa-check');
this.element.trigger('change');
}
},
_unbindEvents: function() {
this.box.off('mouseover.puicheckbox mouseout.puicheckbox click.puicheckbox');
this.element.off('focus.puicheckbox blur.puicheckbox keydown.puicheckbox keyup.puicheckbox');
if (this.label.length) {
this.label.off('click.puicheckbox');
}
},
disable: function() {
this.box.prop('disabled', true);
this.box.attr('aria-disabled', true);
this.box.addClass('ui-state-disabled').removeClass('ui-state-hover');
this._unbindEvents();
},
enable: function() {
this.box.prop('disabled', false);
this.box.attr('aria-disabled', false);
this.box.removeClass('ui-state-disabled');
this._bindEvents();
},
_destroy: function() {
this._unbindEvents();
this.container.removeClass('ui-chkbox ui-widget');
this.box.remove();
this.element.unwrap().unwrap();
}
});
})();/**
* PrimeUI Datatable Widget
*/
(function() {
$.widget("primeui.puidatatable", {
options: {
columns: null,
datasource: null,
paginator: null,
selectionMode: null,
caption: null,
footer: null,
sortField: null,
sortOrder: null,
scrollable: false,
scrollHeight: null,
scrollWidth: null,
responsive: false,
expandableRows: false,
expandedRowContent: null,
rowExpandMode: 'multiple',
draggableColumns: false,
resizableColumns: false,
columnResizeMode: 'fit',
draggableRows: false,
filterDelay: 300,
stickyHeader: false,
editMode: null,
tabindex: 0,
emptyMessage: 'No records found',
sort: null,
rowSelect: null,
rowUnselect: null,
rowSelectContextMenu: null,
rowCollapse: null,
rowExpand: null,
colReorder: null,
colResize: null,
rowReorder: null,
cellEdit: null
},
_create: function() {
this.id = this.element.attr('id');
if(!this.id) {
this.id = this.element.uniqueId().attr('id');
}
this.element.addClass('ui-datatable ui-widget');
if(this.options.responsive) {
this.element.addClass('ui-datatable-reflow');
}
if(this.options.scrollable) {
this._createScrollableDatatable();
}
else {
this._createRegularDatatable();
}
if(this.options.datasource) {
if($.isArray(this.options.datasource)) {
this._onDataInit(this.options.datasource);
}
else {
if($.type(this.options.datasource) === 'string') {
var $this = this,
dataURL = this.options.datasource;
this.options.datasource = function() {
$.ajax({
type: 'GET',
url: dataURL,
dataType: "json",
context: $this,
success: function (response) {
this._onDataInit(response);
}
});
};
}
if($.type(this.options.datasource) === 'function') {
if(this.options.lazy)
this.options.datasource.call(this, this._onDataInit, {first:0, rows:this._getRows(), sortField:this.options.sortField, sortOrder:this.options.sortOrder, filters: this._createFilterMap()});
else
this.options.datasource.call(this, this._onDataInit);
}
}
}
},
_createRegularDatatable: function() {
this.tableWrapper = $('<div class="ui-datatable-tablewrapper" />').appendTo(this.element);
this.table = $('<table><thead></thead><tbody></tbody></table>').appendTo(this.tableWrapper);
this.thead = this.table.children('thead');
this.tbody = this.table.children('tbody').addClass('ui-datatable-data ui-widget-content');
if(this.containsFooter()) {
this.tfoot = this.thead.after('<tfoot></tfoot>').next();
}
},
_createScrollableDatatable: function() {
this.element.append('<div class="ui-widget-header ui-datatable-scrollable-header"><div class="ui-datatable-scrollable-header-box"><table><thead></thead></table></div></div>')
.append('<div class="ui-datatable-scrollable-body"><table><tbody></tbody></table></div>');
this.thead = this.element.find('> .ui-datatable-scrollable-header > .ui-datatable-scrollable-header-box > table > thead');
this.tbody = this.element.find('> .ui-datatable-scrollable-body > table > tbody');
if(this.containsFooter()) {
this.element.append('<div class="ui-widget-header ui-datatable-scrollable-footer"><div class="ui-datatable-scrollable-footer-box"><table><tfoot></tfoot></table></div></div>');
this.tfoot = this.element.find('> .ui-datatable-scrollable-footer > .ui-datatable-scrollable-footer-box > table > tfoot');
}
},
_initialize: function() {
var $this = this;
this._initHeader();
this._initFooter();
if(this.options.caption) {
this.element.prepend('<div class="ui-datatable-header ui-widget-header">' + this.options.caption + '</div>');
}
if(this.options.paginator) {
this.options.paginator.paginate = function(event, state) {
$this.paginate();
};
this.options.paginator.totalRecords = this.options.lazy ? this.options.paginator.totalRecords : this.data.length;
this.paginator = $('<div></div>').insertAfter(this.tableWrapper).puipaginator(this.options.paginator);
if(this.options.paginator.contentLeft) {
this.paginator.prepend(this.options.paginator.contentLeft.call());
}
if(this.options.paginator.contentRight) {
this.paginator.append(this.options.paginator.contentRight.call());
}
}
if(this.options.footer) {
this.element.append('<div class="ui-datatable-footer ui-widget-header">' + this.options.footer + '</div>');
}
if(this._isSortingEnabled()) {
this._initSorting();
}
if(this.hasFiltering) {
this._initFiltering();
}
if(this.options.selectionMode) {
this._initSelection();
}
if(this.options.expandableRows) {
this._initExpandableRows();
}
if(this.options.draggableColumns) {
this._initDraggableColumns();
}
if(this.options.stickyHeader) {
this._initStickyHeader();
}
if (this.options.sortField && this.options.sortOrder) {
this._indicateInitialSortColumn();
this.sort(this.options.sortField, this.options.sortOrder);
}
else {
this._renderData();
}
if(this.options.scrollable) {
this._initScrolling();
}
if(this.options.resizableColumns) {
this._initResizableColumns();
}
if(this.options.draggableRows) {
this._initDraggableRows();
}
if(this.options.editMode) {
this._initEditing();
}
},
_initHeader: function() {
if(this.options.headerRows) {
for(var i = 0; i < this.options.headerRows.length; i++) {
this._initHeaderColumns(this.options.headerRows[i].columns);
}
}
else if(this.options.columns) {
this._initHeaderColumns(this.options.columns);
}
},
_initFooter: function() {
if(this.containsFooter()) {
if(this.options.footerRows) {
for(var i = 0; i < this.options.footerRows.length; i++) {
this._initFooterColumns(this.options.footerRows[i].columns);
}
}
else if(this.options.columns) {
this._initFooterColumns(this.options.columns);
}
}
},
_initHeaderColumns: function(columns) {
var headerRow = $('<tr class="ui-state-default"></tr>').appendTo(this.thead),
$this = this;
$.each(columns, function(i, col) {
var cell = $('<th class="ui-state-default"><span class="ui-column-title"></span></th>').data('field', col.field).uniqueId().appendTo(headerRow);
if(col.headerClass) {
cell.addClass(col.headerClass);
}
if(col.headerStyle) {
cell.attr('style', col.headerStyle);
}
if(col.headerText)
cell.children('.ui-column-title').text(col.headerText);
else if(col.headerContent)
cell.children('.ui-column-title').append(col.headerContent.call(this, col));
if(col.rowspan) {
cell.attr('rowspan', col.rowspan);
}
if(col.colspan) {
cell.attr('colspan', col.colspan);
}
if(col.sortable) {
cell.addClass('ui-sortable-column')
.data('order', 0)
.append('<span class="ui-sortable-column-icon fa fa-fw fa-sort"></span>');
}
if(col.filter) {
$this.hasFiltering = true;
var filterElement = $('<input type="text" class="ui-column-filter" />').puiinputtext().data({
'field': col.field,
'filtermatchmode': col.filterMatchMode||'startsWith'
}).appendTo(cell);
if(col.filterFunction) {
filterElement.on('filter', function(event, dataValue, filterValue) {
return col.filterFunction.call($this, dataValue, filterValue);
});
}
}
});
},
_initFooterColumns: function(columns) {
var footerRow = $('<tr></tr>').appendTo(this.tfoot);
$.each(columns, function(i, col) {
var cell = $('<td class="ui-state-default"></td>');
if(col.footerText) {
cell.text(col.footerText);
}
if(col.rowspan) {
cell.attr('rowspan', col.rowspan);
}
if(col.colspan) {
cell.attr('colspan', col.colspan);
}
cell.appendTo(footerRow);
});
},
_indicateInitialSortColumn: function() {
this.sortableColumns = this.thead.find('> tr > th.ui-sortable-column');
var $this = this;
$.each(this.sortableColumns, function(i, column) {
var $column = $(column),
data = $column.data();
if ($this.options.sortField === data.field) {
var sortIcon = $column.children('.ui-sortable-column-icon');
$column.data('order', $this.options.sortOrder).removeClass('ui-state-hover').addClass('ui-state-active');
if($this.options.sortOrder === -1)
sortIcon.removeClass('fa-sort fa-sort-asc').addClass('fa-sort-desc');
else if($this.options.sortOrder === 1)
sortIcon.removeClass('fa-sort fa-sort-desc').addClass('fa-sort-asc');
}
});
},
_onDataInit: function(data) {
this.data = data;
if(!this.data) {
this.data = [];
}
this._initialize();
},
_onDataUpdate: function(data) {
this.data = data;
if(!this.data) {
this.data = [];
}
this.reset();
this._renderData();
},
_onLazyLoad: function(data) {
this.data = data;
if(!this.data) {
this.data = [];
}
this._renderData();
},
reset: function() {
if(this.options.selectionMode) {
this.selection = [];
}
if(this.paginator) {
this.paginator.puipaginator('setState', {
page: 0,
totalRecords: this.options.lazy ? this.options.paginator.totalRecords : this.data.length
});
}
this.thead.find('> tr > th.ui-sortable-column').data('order', 0).filter('.ui-state-active').removeClass('ui-state-active')
.children('span.ui-sortable-column-icon').removeClass('fa-sort-asc fa-sort-desc').addClass('fa-sort');
},
_initSorting: function() {
var $this = this,
sortableColumns = this.thead.find('> tr > th.ui-sortable-column');
sortableColumns.on('mouseover.puidatatable', function() {
var column = $(this);
if(!column.hasClass('ui-state-active'))
column.addClass('ui-state-hover');
})
.on('mouseout.puidatatable', function() {
var column = $(this);
if(!column.hasClass('ui-state-active'))
column.removeClass('ui-state-hover');
})
.on('click.puidatatable', function(event) {
if(!$(event.target).is('th,span')) {
return;
}
var column = $(this),
sortField = column.data('field'),
order = column.data('order'),
sortOrder = (order === 0) ? 1 : (order * -1),
sortIcon = column.children('.ui-sortable-column-icon');
//clean previous sort state
column.siblings().filter('.ui-state-active').data('order', 0).removeClass('ui-state-active').children('span.ui-sortable-column-icon')
.removeClass('fa-sort-asc fa-sort-desc').addClass('fa-sort');
//update state
$this.options.sortField = sortField;
$this.options.sortOrder = sortOrder;
$this.sort(sortField, sortOrder);
column.data('order', sortOrder).removeClass('ui-state-hover').addClass('ui-state-active');
if(sortOrder === -1)
sortIcon.removeClass('fa-sort fa-sort-asc').addClass('fa-sort-desc');
else if(sortOrder === 1)
sortIcon.removeClass('fa-sort fa-sort-desc').addClass('fa-sort-asc');
$this._trigger('sort', event, {'sortOrder' : sortOrder, 'sortField' : sortField});
});
},
paginate: function() {
if(this.options.lazy) {
this.options.datasource.call(this, this._onLazyLoad, this._createStateMeta());
}
else {
this._renderData();
}
},
sort: function(field, order) {
if(this.options.selectionMode) {
this.selection = [];
}
if(this.options.lazy) {
this.options.datasource.call(this, this._onLazyLoad, this._createStateMeta());
}
else {
this.data.sort(function(data1, data2) {
var value1 = data1[field], value2 = data2[field],
result = null;
if (typeof value1 == 'string' || value1 instanceof String) {
if ( value1.localeCompare ) {
return (order * value1.localeCompare(value2));
}
else {
if (value1.toLowerCase) {
value1 = value1.toLowerCase();
}
if (value2.toLowerCase) {
value2 = value2.toLowerCase();
}
result = (value1 < value2) ? -1 : (value1 > value2) ? 1 : 0;
}
}
else {
result = (value1 < value2) ? -1 : (value1 > value2) ? 1 : 0;
}
return (order * result);
});
if(this.options.selectionMode) {
this.selection = [];
}
if(this.paginator) {
this.paginator.puipaginator('option', 'page', 0);
}
this._renderData();
}
},
sortByField: function(a, b) {
var aName = a.name.toLowerCase();
var bName = b.name.toLowerCase();
return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
},
_renderData: function() {
this.tbody.html('');
var dataToRender = this.filteredData||this.data;
if(dataToRender && dataToRender.length) {
var firstNonLazy = this._getFirst(),
first = this.options.lazy ? 0 : firstNonLazy,
rows = this._getRows();
for(var i = first; i < (first + rows); i++) {
var rowData = dataToRender[i];
if(rowData) {
var row = $('<tr class="ui-widget-content" />').appendTo(this.tbody),
zebraStyle = (i%2 === 0) ? 'ui-datatable-even' : 'ui-datatable-odd',
rowIndex = i;
row.addClass(zebraStyle);
row.data('rowdata', rowData);
if(this.options.selectionMode && this._isSelected(rowData)) {
row.addClass("ui-state-highlight");
}
for(var j = 0; j < this.options.columns.length; j++) {
var column = $('<td />').appendTo(row),
columnOptions = this.options.columns[j];
if(columnOptions.bodyClass) {
column.addClass(columnOptions.bodyClass);
}
if(columnOptions.bodyStyle) {
column.attr('style', columnOptions.bodyStyle);
}
if(columnOptions.editor) {
column.addClass('ui-editable-column').data({
'editor': columnOptions.editor,
'rowdata': rowData,
'field': columnOptions.field
});
}
if(columnOptions.content) {
var content = columnOptions.content.call(this, rowData, columnOptions);
if($.type(content) === 'string')
column.html(content);
else
column.append(content);
}
else if(columnOptions.rowToggler) {
column.append('<div class="ui-row-toggler fa fa-fw fa-chevron-circle-right ui-c"></div>');
}
else if(columnOptions.field) {
column.text(rowData[columnOptions.field]);
}
if(this.options.responsive && columnOptions.headerText) {
column.prepend('<span class="ui-column-title">' + columnOptions.headerText + '</span>');
}
}
}
}
}
else {
var emptyRow = $('<tr class="ui-widget-content"></tr>').appendTo(this.tbody);
var emptyColumn = $('<td></td>').attr('colspan',this.options.columns.length).appendTo(emptyRow);
emptyColumn.html(this.options.emptyMessage);
}
},
_getFirst: function() {
if(this.paginator) {
var page = this.paginator.puipaginator('option', 'page'),
rows = this.paginator.puipaginator('option', 'rows');
return (page * rows);
}
else {
return 0;
}
},
_getRows: function() {
return this.paginator ? this.paginator.puipaginator('option', 'rows') : (this.data ? this.data.length : 0);
},
_isSortingEnabled: function() {
var cols = this.options.columns;
if(cols) {
for(var i = 0; i < cols.length; i++) {
if(cols[i].sortable) {
return true;
}
}
}
return false;
},
_initSelection: function() {
var $this = this;
this.selection = [];
this.rowSelector = '> tr.ui-widget-content:not(.ui-datatable-empty-message,.ui-datatable-unselectable)';
//shift key based range selection
if(this._isMultipleSelection()) {
this.originRowIndex = 0;
this.cursorIndex = null;
}
this.tbody.off('mouseover.puidatatable mouseout.puidatatable mousedown.puidatatable click.puidatatable', this.rowSelector)
.on('mouseover.datatable', this.rowSelector, null, function() {
var element = $(this);
if(!element.hasClass('ui-state-highlight')) {
element.addClass('ui-state-hover');
}
})
.on('mouseout.datatable', this.rowSelector, null, function() {
var element = $(this);
if(!element.hasClass('ui-state-highlight')) {
element.removeClass('ui-state-hover');
}
})
.on('mousedown.datatable', this.rowSelector, null, function() {
$this.mousedownOnRow = true;
})
.on('click.datatable', this.rowSelector, null, function(e) {
$this._onRowClick(e, this);
$this.mousedownOnRow = false;
});
this._bindSelectionKeyEvents();
},
_onRowClick: function(event, rowElement) {
if(!$(event.target).is(':input,:button,a,.ui-c')) {
var row = $(rowElement),
selected = row.hasClass('ui-state-highlight'),
metaKey = event.metaKey||event.ctrlKey,
shiftKey = event.shiftKey;
this.focusedRow = row;
//unselect a selected row if metakey is on
if(selected && metaKey) {
this.unselectRow(row);
}
else {
//unselect previous selection if this is single selection or multiple one with no keys
if(this._isSingleSelection() || (this._isMultipleSelection() && !metaKey && !shiftKey)) {
if (this._isMultipleSelection()) {
var selections = this.getSelection();
for (var i = 0; i < selections.length; i++) {
this._trigger('rowUnselect', null, selections[i]);
}
}
this.unselectAllRows();
}
this.selectRow(row, false, event);
}
PUI.clearSelection();
}
},
onRowRightClick: function(event, rowElement) {
var row = $(rowElement),
selectedData = row.data('rowdata'),
selected = row.hasClass('ui-state-highlight');
if(this._isSingleSelection() || !selected) {
this.unselectAllRows();
}
this.selectRow(row, true);
this.dataSelectedByContextMenu = selectedData;
this._trigger('rowSelectContextMenu', event, selectedData);
PUI.clearSelection();
},
_bindSelectionKeyEvents: function() {
var $this = this;
this.tbody.attr('tabindex', this.options.tabindex).on('focus', function(e) {
//ignore mouse click on row
if(!$this.mousedownOnRow) {
$this.focusedRow = $this.tbody.children('tr.ui-widget-content').eq(0);
$this.focusedRow.addClass('ui-state-hover');
}
})
.on('blur', function() {
if($this.focusedRow) {
$this.focusedRow.removeClass('ui-state-hover');
$this.focusedRow = null;
}
})
.on('keydown', function(e) {
var keyCode = $.ui.keyCode,
key = e.which;
if($this.focusedRow) {
switch(key) {
case keyCode.UP:
var prevRow = $this.focusedRow.prev('tr.ui-widget-content');
if(prevRow.length) {
$this.focusedRow.removeClass('ui-state-hover');
$this.focusedRow = prevRow;
$this.focusedRow.addClass('ui-state-hover');
}
e.preventDefault();
break;
case keyCode.DOWN:
var nextRow = $this.focusedRow.next('tr.ui-widget-content');
if(nextRow.length) {
$this.focusedRow.removeClass('ui-state-hover');
$this.focusedRow = nextRow;
$this.focusedRow.addClass('ui-state-hover');
}
e.preventDefault();
break;
case keyCode.ENTER:
case keyCode.NUMPAD_ENTER:
case keyCode.SPACE:
e.target = $this.focusedRow.children().eq(0).get(0);
$this._onRowClick(e, $this.focusedRow.get(0));
e.preventDefault();
break;
default:
break;
};
}
});
},
_isSingleSelection: function() {
return this.options.selectionMode === 'single';
},
_isMultipleSelection: function() {
return this.options.selectionMode === 'multiple';
},
unselectAllRows: function() {
this.tbody.children('tr.ui-state-highlight').removeClass('ui-state-highlight').attr('aria-selected', false);
this.selection = [];
},
unselectRow: function(row, silent) {
var unselectedData = row.data('rowdata');
row.removeClass('ui-state-highlight').attr('aria-selected', false);
this._removeSelection(unselectedData);
if(!silent) {
this._trigger('rowUnselect', null, unselectedData);
}
},
selectRow: function(row, silent, event) {
var selectedData = row.data('rowdata');
row.removeClass('ui-state-hover').addClass('ui-state-highlight').attr('aria-selected', true);
this._addSelection(selectedData);
if(!silent) {
this._trigger('rowSelect', event, selectedData);
}
},
getSelection: function() {
return this.selection;
},
_removeSelection: function(rowData) {
this.selection = $.grep(this.selection, function(value) {
return value !== rowData;
});
},
_addSelection: function(rowData) {
if(!this._isSelected(rowData)) {
this.selection.push(rowData);
}
},
_isSelected: function(rowData) {
return PUI.inArray(this.selection, rowData);
},
_initExpandableRows: function() {
var $this = this,
togglerSelector = '> tr > td > div.ui-row-toggler';
this.tbody.off('click', togglerSelector)
.on('click', togglerSelector, null, function() {
$this.toggleExpansion($(this));
})
.on('keydown', togglerSelector, null, function(e) {
var key = e.which,
keyCode = $.ui.keyCode;
if((key === keyCode.ENTER||key === keyCode.NUMPAD_ENTER)) {
$this.toggleExpansion($(this));
e.preventDefault();
}
});
},
toggleExpansion: function(toggler) {
var row = toggler.closest('tr'),
expanded = toggler.hasClass('fa-chevron-circle-down');
if(expanded) {
toggler.addClass('fa-chevron-circle-right').removeClass('fa-chevron-circle-down').attr('aria-expanded', false);
this.collapseRow(row);
this._trigger('rowCollapse', null, row.data('rowdata'));
}
else {
if(this.options.rowExpandMode === 'single') {
this.collapseAllRows();
}
toggler.addClass('fa-chevron-circle-down').removeClass('fa-chevron-circle-right').attr('aria-expanded', true);
this.loadExpandedRowContent(row);
}
},
loadExpandedRowContent: function(row) {
var expandedRow = $('<tr class="ui-expanded-row-content ui-datatable-unselectable ui-widget-content"><td colspan="' + this.options.columns.length + '"></td></tr>');
expandedRow.children('td').append(this.options.expandedRowContent.call(this, row.data('rowdata')));
row.addClass('ui-expanded-row').after(expandedRow);
this._trigger('rowExpand', null, row.data('rowdata'));
},
collapseRow: function(row) {
row.removeClass('ui-expanded-row').next('.ui-expanded-row-content').remove();
},
collapseAllRows: function() {
var $this = this;
this.getExpandedRows().each(function () {
var expandedRow = $(this);
$this.collapseRow(expandedRow);
var columns = expandedRow.children('td');
for (var i = 0; i < columns.length; i++) {
var column = columns.eq(i),
toggler = column.children('.ui-row-toggler');
if (toggler.length) {
toggler.addClass('fa-chevron-circle-right').removeClass('fa-chevron-circle-down');
}
}
});
},
getExpandedRows: function () {
return this.tbody.children('.ui-expanded-row');
},
_createStateMeta: function() {
var state = {
first: this._getFirst(),
rows: this._getRows(),
sortField: this.options.sortField,
sortOrder: this.options.sortOrder,
filters: this.filterMetaMap
};
return state;
},
_updateDatasource: function(datasource) {
this.options.datasource = datasource;
if($.isArray(this.options.datasource)) {
this._onDataUpdate(this.options.datasource);
}
else if($.type(this.options.datasource) === 'function') {
if(this.options.lazy)
this.options.datasource.call(this, this._onDataUpdate, {first:0, rows: this._getRows(), sortField:this.options.sortField, sortorder:this.options.sortOrder, filters: this._createFilterMap()});
else
this.options.datasource.call(this, this._onDataUpdate);
}
},
_setOption: function(key, value) {
if(key === 'datasource') {
this._updateDatasource(value);
}
else {
$.Widget.prototype._setOption.apply(this, arguments);
}
},
_initScrolling: function() {
this.scrollHeader = this.element.children('.ui-datatable-scrollable-header');
this.scrollBody = this.element.children('.ui-datatable-scrollable-body');
this.scrollHeaderBox = this.scrollHeader.children('.ui-datatable-scrollable-header-box');
this.headerTable = this.scrollHeaderBox.children('table');
this.bodyTable = this.scrollBody.children('table');
this.percentageScrollHeight = this.options.scrollHeight && (this.options.scrollHeight.indexOf('%') !== -1);
this.percentageScrollWidth = this.options.scrollWidth && (this.options.scrollWidth.indexOf('%') !== -1);
var $this = this,
scrollBarWidth = this.getScrollbarWidth() + 'px';
if(this.options.scrollHeight) {
if(this.percentageScrollHeight)
this.adjustScrollHeight();
else
this.scrollBody.css('max-height', this.options.scrollHeight + 'px');
if(this.hasVerticalOverflow()) {
this.scrollHeaderBox.css('margin-right', scrollBarWidth);
}
}
this.fixColumnWidths();
if(this.options.scrollWidth) {
if(this.percentageScrollWidth)
this.adjustScrollWidth();
else
this.setScrollWidth(parseInt(this.options.scrollWidth));
}
this.cloneHead();
this.scrollBody.on('scroll.dataTable', function() {
var scrollLeft = $this.scrollBody.scrollLeft();
$this.scrollHeaderBox.css('margin-left', -scrollLeft);
});
this.scrollHeader.on('scroll.dataTable', function() {
$this.scrollHeader.scrollLeft(0);
});
var resizeNS = 'resize.' + this.id;
$(window).off(resizeNS).on(resizeNS, function() {
if($this.element.is(':visible')) {
if($this.percentageScrollHeight)
$this.adjustScrollHeight();
if($this.percentageScrollWidth)
$this.adjustScrollWidth();
}
});
},
cloneHead: function() {
this.theadClone = this.thead.clone();
this.theadClone.find('th').each(function() {
var header = $(this);
header.attr('id', header.attr('id') + '_clone');
$(this).children().not('.ui-column-title').remove();
});
this.theadClone.removeAttr('id').addClass('ui-datatable-scrollable-theadclone').height(0).prependTo(this.bodyTable);
//align horizontal scroller on keyboard tab
if(this.options.scrollWidth) {
var clonedSortableColumns = this.theadClone.find('> tr > th.ui-sortable-column');
clonedSortableColumns.each(function() {
$(this).data('original', $(this).attr('id').split('_clone')[0]);
});
clonedSortableColumns.on('blur.dataTable', function() {
$(PUI.escapeClientId($(this).data('original'))).removeClass('ui-state-focus');
})
.on('focus.dataTable', function() {
$(PUI.escapeClientId($(this).data('original'))).addClass('ui-state-focus');
})
.on('keydown.dataTable', function(e) {
var key = e.which,
keyCode = $.ui.keyCode;
if((key === keyCode.ENTER||key === keyCode.NUMPAD_ENTER) && $(e.target).is(':not(:input)')) {
$(PUI.escapeClientId($(this).data('original'))).trigger('click.dataTable', (e.metaKey||e.ctrlKey));
e.preventDefault();
}
});
}
},
adjustScrollHeight: function() {
var relativeHeight = this.element.parent().innerHeight() * (parseInt(this.options.scrollHeight) / 100),
tableHeaderHeight = this.element.children('.ui-datatable-header').outerHeight(true),
tableFooterHeight = this.element.children('.ui-datatable-footer').outerHeight(true),
scrollersHeight = (this.scrollHeader.outerHeight(true) + this.scrollFooter.outerHeight(true)),
paginatorsHeight = this.paginator ? this.paginator.getContainerHeight(true) : 0,
height = (relativeHeight - (scrollersHeight + paginatorsHeight + tableHeaderHeight + tableFooterHeight));
this.scrollBody.css('max-height', height + 'px');
},
adjustScrollWidth: function() {
var width = parseInt((this.element.parent().innerWidth() * (parseInt(this.options.scrollWidth) / 100)));
this.setScrollWidth(width);
},
setOuterWidth: function(element, width) {
var diff = element.outerWidth() - element.width();
element.width(width - diff);
},
setScrollWidth: function(width) {
var $this = this;
this.element.children('.ui-widget-header').each(function() {
$this.setOuterWidth($(this), width);
});
this.scrollHeader.width(width);
this.scrollBody.css('margin-right', 0).width(width);
},
alignScrollBody: function() {
var marginRight = this.hasVerticalOverflow() ? this.getScrollbarWidth() + 'px' : '0px';
this.scrollHeaderBox.css('margin-right', marginRight);
},
getScrollbarWidth: function() {
if(!this.scrollbarWidth) {
this.scrollbarWidth = PUI.browser.webkit ? '15' : PUI.calculateScrollbarWidth();
}
return this.scrollbarWidth;
},
hasVerticalOverflow: function() {
return (this.options.scrollHeight && this.bodyTable.outerHeight() > this.scrollBody.outerHeight())
},
restoreScrollState: function() {
var scrollState = this.scrollStateHolder.val(),
scrollValues = scrollState.split(',');
this.scrollBody.scrollLeft(scrollValues[0]);
this.scrollBody.scrollTop(scrollValues[1]);
},
saveScrollState: function() {
var scrollState = this.scrollBody.scrollLeft() + ',' + this.scrollBody.scrollTop();
this.scrollStateHolder.val(scrollState);
},
clearScrollState: function() {
this.scrollStateHolder.val('0,0');
},
fixColumnWidths: function() {
if(!this.columnWidthsFixed) {
if(this.options.scrollable) {
this.scrollHeaderBox.find('> table > thead > tr > th').each(function() {
var headerCol = $(this),
width = headerCol.width();
headerCol.width(width);
});
}
else {
this.element.find('> .ui-datatable-tablewrapper > table > thead > tr > th').each(function() {
var col = $(this);
col.width(col.width());
});
}
this.columnWidthsFixed = true;
}
},
_initDraggableColumns: function() {
var $this = this;
this.dragIndicatorTop = $('<span class="fa fa-arrow-down" style="position:absolute"/></span>').hide().appendTo(this.element);
this.dragIndicatorBottom = $('<span class="fa fa-arrow-up" style="position:absolute"/></span>').hide().appendTo(this.element);
this.thead.find('> tr > th').draggable({
appendTo: 'body',
opacity: 0.75,
cursor: 'move',
scope: this.id,
cancel: ':input,.ui-column-resizer',
drag: function(event, ui) {
var droppable = ui.helper.data('droppable-column');
if(droppable) {
var droppableOffset = droppable.offset(),
topArrowY = droppableOffset.top - 10,
bottomArrowY = droppableOffset.top + droppable.height() + 8,
arrowX = null;
//calculate coordinates of arrow depending on mouse location
if(event.originalEvent.pageX >= droppableOffset.left + (droppable.width() / 2)) {
var nextDroppable = droppable.next();
if(nextDroppable.length == 1)
arrowX = nextDroppable.offset().left - 9;
else
arrowX = droppable.offset().left + droppable.innerWidth() - 9;
ui.helper.data('drop-location', 1); //right
}
else {
arrowX = droppableOffset.left - 9;
ui.helper.data('drop-location', -1); //left
}
$this.dragIndicatorTop.offset({
'left': arrowX,
'top': topArrowY - 3
}).show();
$this.dragIndicatorBottom.offset({
'left': arrowX,
'top': bottomArrowY - 3
}).show();
}
},
stop: function(event, ui) {
//hide dnd arrows
$this.dragIndicatorTop.css({
'left':0,
'top':0
}).hide();
$this.dragIndicatorBottom.css({
'left':0,
'top':0
}).hide();
},
helper: function() {
var header = $(this),
helper = $('<div class="ui-widget ui-state-default" style="padding:4px 10px;text-align:center;"></div>');
helper.width(header.width());
helper.height(header.height());
helper.html(header.html());
return helper.get(0);
}
}).droppable({
hoverClass:'ui-state-highlight',
tolerance:'pointer',
scope: this.id,
over: function(event, ui) {
ui.helper.data('droppable-column', $(this));
},
drop: function(event, ui) {
var draggedColumnHeader = ui.draggable,
dropLocation = ui.helper.data('drop-location'),
droppedColumnHeader = $(this),
draggedColumnFooter = null,
droppedColumnFooter = null;
var draggedCells = $this.tbody.find('> tr:not(.ui-expanded-row-content) > td:nth-child(' + (draggedColumnHeader.index() + 1) + ')'),
droppedCells = $this.tbody.find('> tr:not(.ui-expanded-row-content) > td:nth-child(' + (droppedColumnHeader.index() + 1) + ')');
if($this.containsFooter()) {
var footerColumns = $this.tfoot.find('> tr > td'),
draggedColumnFooter = footerColumns.eq(draggedColumnHeader.index()),
droppedColumnFooter = footerColumns.eq(droppedColumnHeader.index());
}
//drop right
if(dropLocation > 0) {
/* TODO :Resizable columns
* if($this.options.resizableColumns) {
if(droppedColumnHeader.next().length) {
droppedColumnHeader.children('span.ui-column-resizer').show();
draggedColumnHeader.children('span.ui-column-resizer').hide();
}
}*/
draggedColumnHeader.insertAfter(droppedColumnHeader);
draggedCells.each(function(i, item) {
$(this).insertAfter(droppedCells.eq(i));
});
if(draggedColumnFooter && droppedColumnFooter) {
draggedColumnFooter.insertAfter(droppedColumnFooter);
}
//sync clone
if($this.options.scrollable) {
var draggedColumnClone = $(document.getElementById(draggedColumnHeader.attr('id') + '_clone')),
droppedColumnClone = $(document.getElementById(droppedColumnHeader.attr('id') + '_clone'));
draggedColumnClone.insertAfter(droppedColumnClone);
}
}
//drop left
else {
draggedColumnHeader.insertBefore(droppedColumnHeader);
draggedCells.each(function(i, item) {
$(this).insertBefore(droppedCells.eq(i));
});
if(draggedColumnFooter && droppedColumnFooter) {
draggedColumnFooter.insertBefore(droppedColumnFooter);
}
//sync clone
if($this.options.scrollable) {
var draggedColumnClone = $(document.getElementById(draggedColumnHeader.attr('id') + '_clone')),
droppedColumnClone = $(document.getElementById(droppedColumnHeader.attr('id') + '_clone'));
draggedColumnClone.insertBefore(droppedColumnClone);
}
}
//fire colReorder event
$this._trigger('colReorder', null, {
dragIndex: draggedColumnHeader.index(),
dropIndex: droppedColumnHeader.index()
});
}
});
},
containsFooter: function() {
if(this.hasFooter === undefined) {
this.hasFooter = this.options.footerRows !== undefined;
if(!this.hasFooter) {
if(this.options.columns) {
for(var i = 0; i < this.options.columns.length; i++) {
if(this.options.columns[i].footerText !== undefined) {
this.hasFooter = true;
break;
}
}
}
}
}
return this.hasFooter;
},
_initResizableColumns: function() {
this.element.addClass('ui-datatable-resizable');
this.thead.find('> tr > th').addClass('ui-resizable-column');
this.resizerHelper = $('<div class="ui-column-resizer-helper ui-state-highlight"></div>').appendTo(this.element);
this.addResizers();
var resizers = this.thead.find('> tr > th > span.ui-column-resizer'),
$this = this;
setTimeout(function() {
$this.fixColumnWidths();
}, 5);
resizers.draggable({
axis: 'x',
start: function(event, ui) {
ui.helper.data('originalposition', ui.helper.offset());
var height = $this.options.scrollable ? $this.scrollBody.height() : $this.thead.parent().height() - $this.thead.height() - 1;
$this.resizerHelper.height(height);
$this.resizerHelper.show();
},
drag: function(event, ui) {
$this.resizerHelper.offset({
left: ui.helper.offset().left + ui.helper.width() / 2,
top: $this.thead.offset().top + $this.thead.height()
});
},
stop: function(event, ui) {
ui.helper.css({
'left': '',
'top': '0px',
'right': '0px'
});
$this.resize(event, ui);
$this.resizerHelper.hide();
if($this.options.columnResizeMode === 'expand') {
setTimeout(function() {
$this._trigger('colResize', null, {element: ui.helper.parent()});
}, 5);
}
else {
$this._trigger('colResize', null, {element: ui.helper.parent()});
}
if($this.options.stickyHeader) {
$this.thead.find('.ui-column-filter').prop('disabled', false);
$this.clone = $this.thead.clone(true);
$this.cloneContainer.find('thead').remove();
$this.cloneContainer.children('table').append($this.clone);
$this.thead.find('.ui-column-filter').prop('disabled', true);
}
},
containment: this.element
});
},
resize: function(event, ui) {
var columnHeader, nextColumnHeader, change = null, newWidth = null, nextColumnWidth = null,
expandMode = (this.options.columnResizeMode === 'expand'),
table = this.thead.parent(),
columnHeader = ui.helper.parent(),
nextColumnHeader = columnHeader.next();
change = (ui.position.left - ui.originalPosition.left),
newWidth = (columnHeader.width() + change),
nextColumnWidth = (nextColumnHeader.width() - change);
if((newWidth > 15 && nextColumnWidth > 15) || (expandMode && newWidth > 15)) {
if(expandMode) {
table.width(table.width() + change);
setTimeout(function() {
columnHeader.width(newWidth);
}, 1);
}
else {
columnHeader.width(newWidth);
nextColumnHeader.width(nextColumnWidth);
}
if(this.options.scrollable) {
var cloneTable = this.theadClone.parent(),
colIndex = columnHeader.index();
if(expandMode) {
var $this = this;
//body
cloneTable.width(cloneTable.width() + change);
//footer
this.footerTable.width(this.footerTable.width() + change);
setTimeout(function() {
if($this.hasColumnGroup) {
$this.theadClone.find('> tr:first').children('th').eq(colIndex).width(newWidth); //body
$this.footerTable.find('> tfoot > tr:first').children('th').eq(colIndex).width(newWidth); //footer
}
else {
$this.theadClone.find(PUI.escapeClientId(columnHeader.attr('id') + '_clone')).width(newWidth); //body
$this.footerCols.eq(colIndex).width(newWidth); //footer
}
}, 1);
}
else {
//body
this.theadClone.find(PUI.escapeClientId(columnHeader.attr('id') + '_clone')).width(newWidth);
this.theadClone.find(PUI.escapeClientId(nextColumnHeader.attr('id') + '_clone')).width(nextColumnWidth);
//footer
/*if(this.footerCols.length > 0) {
var footerCol = this.footerCols.eq(colIndex),
nextFooterCol = footerCol.next();
footerCol.width(newWidth);
nextFooterCol.width(nextColumnWidth);
}*/
}
}
}
},
addResizers: function() {
var resizableColumns = this.thead.find('> tr > th.ui-resizable-column');
resizableColumns.prepend('<span class="ui-column-resizer"> </span>');
if(this.options.columnResizeMode === 'fit') {
resizableColumns.filter(':last-child').children('span.ui-column-resizer').hide();
}
},
_initDraggableRows: function() {
var $this = this;
this.tbody.sortable({
placeholder: 'ui-datatable-rowordering ui-state-active',
cursor: 'move',
handle: 'td,span:not(.ui-c)',
appendTo: document.body,
helper: function(event, ui) {
var cells = ui.children(),
helper = $('<div class="ui-datatable ui-widget"><table><tbody></tbody></table></div>'),
helperRow = ui.clone(),
helperCells = helperRow.children();
for(var i = 0; i < helperCells.length; i++) {
helperCells.eq(i).width(cells.eq(i).width());
}
helperRow.appendTo(helper.find('tbody'));
return helper;
},
update: function(event, ui) {
$this.syncRowParity();
$this._trigger('rowReorder', null, {
fromIndex: ui.item.data('ri'),
toIndex: $this._getFirst() + ui.item.index()
});
},
change: function(event, ui) {
if($this.options.scrollable) {
PUI.scrollInView($this.scrollBody, ui.placeholder);
}
}
});
},
syncRowParity: function() {
var rows = this.tbody.children('tr.ui-widget-content');
for(var i = this._getFirst(); i < rows.length; i++) {
var row = rows.eq(i);
row.data('ri', i).removeClass('ui-datatable-even ui-datatable-odd');
if(i % 2 === 0)
row.addClass('ui-datatable-even');
else
row.addClass('ui-datatable-odd');
}
},
getContextMenuSelection: function(data) {
return this.dataSelectedByContextMenu;
},
_initFiltering: function() {
var $this = this;
this.filterElements = this.thead.find('.ui-column-filter');
this.filterElements.on('keyup', function() {
if($this.filterTimeout) {
clearTimeout($this.filterTimeout);
}
$this.filterTimeout = setTimeout(function() {
$this.filter();
$this.filterTimeout = null;
},
$this.options.filterDelay);
});
},
filter: function() {
this.filterMetaMap = [];
for(var i = 0; i < this.filterElements.length; i++) {
var filterElement = this.filterElements.eq(i),
filterElementValue = filterElement.val();
if(filterElementValue && $.trim(filterElementValue) !== '') {
this.filterMetaMap.push({
field: filterElement.data('field'),
filterMatchMode: filterElement.data('filtermatchmode'),
value: filterElementValue.toLowerCase(),
element: filterElement
});
}
}
if(this.options.lazy) {
this.options.datasource.call(this, this._onLazyLoad, this._createStateMeta());
}
else {
if(this.filterMetaMap.length) {
this.filteredData = [];
for(var i = 0; i < this.data.length; i++) {
var localMatch = true;
for(var j = 0; j < this.filterMetaMap.length; j++) {
var filterMeta = this.filterMetaMap[j],
filterValue = filterMeta.value,
filterField = filterMeta.field,
dataFieldValue = this.data[i][filterField];
if(filterMeta.filterMatchMode === 'custom') {
localMatch = filterMeta.element.triggerHandler('filter', [dataFieldValue, filterValue]);
}
else {
var filterConstraint = this.filterConstraints[filterMeta.filterMatchMode];
if(!filterConstraint(dataFieldValue, filterValue)) {
localMatch = false;
}
}
if(!localMatch) {
break;
}
}
if(localMatch) {
this.filteredData.push(this.data[i]);
}
}
}
else {
this.filteredData = null;
}
if(this.paginator) {
this.paginator.puipaginator('option', 'totalRecords', this.filteredData ? this.filteredData.length : this.data ? this.data.length : 0);
}
this._renderData();
}
},
filterConstraints: {
startsWith: function(value, filter) {
if(filter === undefined || filter === null || $.trim(filter) === '') {
return true;
}
if(value === undefined || value === null) {
return false;
}
return value.toString().toLowerCase().slice(0, filter.length) === filter;
},
contains: function(value, filter) {
if(filter === undefined || filter === null || $.trim(filter) === '') {
return true;
}
if(value === undefined || value === null) {
return false;
}
return value.toString().toLowerCase().indexOf(filter) !== -1;
}
},
_initStickyHeader: function() {
var table = this.thead.parent(),
offset = table.offset(),
win = $(window),
$this = this,
stickyNS = 'scroll.' + this.id,
resizeNS = 'resize.sticky-' + this.id;
this.cloneContainer = $('<div class="ui-datatable ui-datatable-sticky ui-widget"><table></table></div>');
this.clone = this.thead.clone(true);
this.cloneContainer.children('table').append(this.clone);
this.cloneContainer.css({
position: 'absolute',
width: table.outerWidth(),
top: offset.top,
left: offset.left,
'z-index': ++PUI.zindex
})
.appendTo(this.element);
win.off(stickyNS).on(stickyNS, function() {
var scrollTop = win.scrollTop(),
tableOffset = table.offset();
if(scrollTop > tableOffset.top) {
$this.cloneContainer.css({
'position': 'fixed',
'top': '0px'
})
.addClass('ui-shadow ui-sticky');
if(scrollTop >= (tableOffset.top + $this.tbody.height()))
$this.cloneContainer.hide();
else
$this.cloneContainer.show();
}
else {
$this.cloneContainer.css({
'position': 'absolute',
'top': tableOffset.top
})
.removeClass('ui-shadow ui-sticky');
}
})
.off(resizeNS).on(resizeNS, function() {
$this.cloneContainer.width(table.outerWidth());
});
//filter support
this.thead.find('.ui-column-filter').prop('disabled', true);
},
_initEditing: function() {
var cellSelector = '> tr > td.ui-editable-column',
$this = this;
this.tbody.off('click', cellSelector)
.on('click', cellSelector, null, function(e) {
var cell = $(this);
if(!cell.hasClass('ui-cell-editing')) {
$this._showCellEditor(cell);
e.stopPropagation();
}
});
},
_showCellEditor: function(cell) {
var editor = this.editors[cell.data('editor')].call(),
$this = this;
editor.val(cell.data('rowdata')[cell.data('field')]);
cell.addClass('ui-cell-editing').html('').append(editor);
editor.focus().on('change', function() {
$this._onCellEditorChange(cell);
})
.on('blur', function() {
$this._onCellEditorBlur(cell);
})
.on('keydown', function(e) {
var key = e.which,
keyCode = $.ui.keyCode;
if((key === keyCode.ENTER||key === keyCode.NUMPAD_ENTER)) {
$(this).trigger('change').trigger('blur');
e.preventDefault();
}
else if(key === keyCode.TAB) {
if(e.shiftKey) {
var prevCell = cell.prevAll('td.ui-editable-column').eq(0);
if(!prevCell.length) {
prevCell = cell.parent().prev('tr').children('td.ui-editable-column:last');
}
if(prevCell.length) {
$this._showCellEditor(prevCell);
}
}
else {
var nextCell = cell.nextAll('td.ui-editable-column').eq(0);
if(!nextCell.length) {
nextCell = cell.parent().next('tr').children('td.ui-editable-column').eq(0);
}
if(nextCell.length) {
$this._showCellEditor(nextCell);
}
}
e.preventDefault();
} else if(key === keyCode.ESCAPE) {
$this._onCellEditorBlur(cell);
}
});
},
_onCellEditorChange: function(cell) {
var newCellValue = cell.children('.ui-cell-editor').val();
var retVal = this._trigger('cellEdit', null, {
oldValue: cell.data('rowdata')[cell.data('field')],
newValue: newCellValue,
data: cell.data('rowdata'),
field: cell.data('field')
});
if(retVal !== false) {
cell.data('rowdata')[cell.data('field')] = newCellValue;
}
},
_onCellEditorBlur: function(cell) {
cell.removeClass('ui-cell-editing').text(cell.data('rowdata')[cell.data('field')])
.children('.ui-cell-editor').remove();
},
reload: function() {
this._updateDatasource(this.options.datasource);
},
getPaginator: function() {
return this.paginator;
},
setTotalRecords: function(val) {
this.paginator.puipaginator('option','totalRecords', val);
},
_createFilterMap: function() {
var filters = null;
if(this.filterElements) {
filters = {};
for(var i = 0; i < this.filterElements.length; i++) {
var filterElement = this.filterElements.eq(i),
value = filterElement.val();
if($.trim(value).length) {
filters[filterElement.data('field')] = value;
}
}
}
return filters;
},
editors: {
'input': function() {
return $('<input type="text" class="ui-cell-editor"/>');
}
}
});
})();
/**
* PrimeUI Datagrid Widget
*/
(function() {
$.widget("primeui.puidatagrid", {
options: {
columns: 3,
datasource: null,
paginator: null,
header: null,
footer: null,
content: null,
lazy: false,
template: null
},
_create: function() {
this.id = this.element.attr('id');
if(!this.id) {
this.id = this.element.uniqueId().attr('id');
}
this.element.addClass('ui-datagrid ui-widget');
//header
if(this.options.header) {
this.element.append('<div class="ui-datagrid-header ui-widget-header ui-corner-top">' + this.options.header + '</div>');
}
//content
this.content = $('<div class="ui-datagrid-content ui-widget-content ui-grid ui-grid-responsive"></div>').appendTo(this.element);
//footer
if(this.options.footer) {
this.element.append('<div class="ui-datagrid-footer ui-widget-header ui-corner-top">' + this.options.footer + '</div>');
}
//data
if(this.options.datasource) {
this._initDatasource();
}
},
_onDataInit: function(data) {
this._onDataUpdate(data);
this._initPaginator();
},
_onDataUpdate: function(data) {
this.data = data;
if(!this.data) {
this.data = [];
}
this.reset();
this._renderData();
},
_onLazyLoad: function(data) {
this.data = data;
if(!this.data) {
this.data = [];
}
this._renderData();
},
reset: function() {
if(this.paginator) {
this.paginator.puipaginator('setState', {
page: 0,
totalRecords: this.options.lazy ? this.options.paginator.totalRecords : this.data.length
});
}
},
paginate: function() {
if(this.options.lazy) {
this.options.datasource.call(this, this._onLazyLoad, this._createStateMeta());
}
else {
this._renderData();
}
},
_renderData: function() {
if(this.data) {
this.content.html('');
var firstNonLazy = this._getFirst(),
first = this.options.lazy ? 0 : firstNonLazy,
rows = this._getRows(),
gridRow = null;
for(var i = first; i < (first + rows); i++) {
var dataValue = this.data[i];
if(dataValue) {
if(i % this.options.columns === 0) {
gridRow = $('<div class="ui-grid-row"></div>').appendTo(this.content);
}
var gridColumn = $('<div class="ui-datagrid-column ' + PUI.getGridColumn(this.options.columns) + '"></div>').appendTo(gridRow),
markup = this._createItemContent(dataValue);
gridColumn.append(markup);
}
}
}
},
_getFirst: function() {
if(this.paginator) {
var page = this.paginator.puipaginator('option', 'page'),
rows = this.paginator.puipaginator('option', 'rows');
return (page * rows);
}
else {
return 0;
}
},
_getRows: function() {
if(this.options.paginator)
return this.paginator ? this.paginator.puipaginator('option', 'rows') : this.options.paginator.rows;
else
return this.data ? this.data.length : 0;
},
_createStateMeta: function() {
var state = {
first: this._getFirst(),
rows: this._getRows()
};
return state;
},
_initPaginator: function() {
var $this = this;
if(this.options.paginator) {
this.options.paginator.paginate = function(event, state) {
$this.paginate();
};
this.options.paginator.totalRecords = this.options.lazy ? this.options.paginator.totalRecords : this.data.length;
this.paginator = $('<div></div>').insertAfter(this.content).puipaginator(this.options.paginator);
}
},
_initDatasource: function() {
if($.isArray(this.options.datasource)) {
this._onDataInit(this.options.datasource);
}
else {
if($.type(this.options.datasource) === 'string') {
var $this = this,
dataURL = this.options.datasource;
this.options.datasource = function() {
$.ajax({
type: 'GET',
url: dataURL,
dataType: "json",
context: $this,
success: function (response) {
this._onDataInit(response);
}
});
};
}
if($.type(this.options.datasource) === 'function') {
if(this.options.lazy)
this.options.datasource.call(this, this._onDataInit, {first:0, rows: this._getRows()});
else
this.options.datasource.call(this, this._onDataInit);
}
}
},
_updateDatasource: function(datasource) {
this.options.datasource = datasource;
if($.isArray(this.options.datasource)) {
this._onDataUpdate(this.options.datasource);
}
else if($.type(this.options.datasource) === 'function') {
if(this.options.lazy)
this.options.datasource.call(this, this._onDataUpdate, {first:0, rows: this._getRows()});
else
this.options.datasource.call(this, this._onDataUpdate);
}
},
_setOption: function(key, value) {
if(key === 'datasource') {
this._updateDatasource(value);
}
else {
$.Widget.prototype._setOption.apply(this, arguments);
}
},
_createItemContent: function(obj) {
if(this.options.template) {
var templateContent = this.options.template.html();
Mustache.parse(templateContent);
return Mustache.render(templateContent, obj);
}
else {
return this.options.content.call(this, obj);
}
}
});
})();/**
* PrimeUI Datascroller Widget
*/
(function() {
$.widget("primeui.puidatascroller", {
options: {
header: null,
buffer: 0.9,
chunkSize: 10,
datasource: null,
lazy: false,
content: null,
template: null,
mode: 'document',
loader: null,
scrollHeight: null,
totalSize: null
},
_create: function() {
this.id = this.element.attr('id');
if(!this.id) {
this.id = this.element.uniqueId().attr('id');
}
this.element.addClass('ui-datascroller ui-widget');
if(this.options.header) {
this.header = this.element.append('<div class="ui-datascroller-header ui-widget-header ui-corner-top">' + this.options.header + '</div>').children('.ui-datascroller-header');
}
this.content = this.element.append('<div class="ui-datascroller-content ui-widget-content ui-corner-bottom"></div>').children('.ui-datascroller-content');
this.list = this.content.append('<ul class="ui-datascroller-list"></ul>').children('.ui-datascroller-list');
this.loaderContainer = this.content.append('<div class="ui-datascroller-loader"></div>').children('.ui-datascroller-loader');
this.loadStatus = $('<div class="ui-datascroller-loading"></div>');
this.loading = false;
this.allLoaded = false;
this.offset = 0;
if(this.options.mode === 'self') {
this.element.addClass('ui-datascroller-inline');
if(this.options.scrollHeight) {
this.content.css('height', this.options.scrollHeight);
}
}
if(this.options.loader) {
this.bindManualLoader();
}
else {
this.bindScrollListener();
}
if(this.options.datasource) {
if($.isArray(this.options.datasource)) {
this._onDataInit(this.options.datasource);
}
else {
if($.type(this.options.datasource) === 'string') {
var $this = this,
dataURL = this.options.datasource;
this.options.datasource = function() {
$.ajax({
type: 'GET',
url: dataURL,
dataType: "json",
context: $this,
success: function (response) {
this._onDataInit(response);
}
});
};
}
if($.type(this.options.datasource) === 'function') {
if(this.options.lazy)
this.options.datasource.call(this, this._onLazyLoad, {first:this.offset});
else
this.options.datasource.call(this, this._onDataInit);
}
}
}
},
_onDataInit: function(data) {
this.data = data||[];
this.options.totalSize = this.data.length;
this._load();
},
_onLazyLoad: function(data) {
this._renderData(data, 0, this.options.chunkSize);
this._onloadComplete();
},
bindScrollListener: function() {
var $this = this;
if(this.options.mode === 'document') {
var win = $(window),
doc = $(document),
$this = this,
NS = 'scroll.' + this.id;
win.off(NS).on(NS, function () {
if(win.scrollTop() >= ((doc.height() * $this.options.buffer) - win.height()) && $this.shouldLoad()) {
$this._load();
}
});
}
else {
this.content.on('scroll', function () {
var scrollTop = this.scrollTop,
scrollHeight = this.scrollHeight,
viewportHeight = this.clientHeight;
if((scrollTop >= ((scrollHeight * $this.options.buffer) - (viewportHeight))) && $this.shouldLoad()) {
$this._load();
}
});
}
},
bindManualLoader: function() {
var $this = this;
this.options.loader.on('click.dataScroller', function(e) {
$this._load();
e.preventDefault();
});
},
_load: function() {
this.loading = true;
this.loadStatus.appendTo(this.loaderContainer);
if(this.options.loader) {
this.options.loader.hide();
}
if(this.options.lazy) {
this.options.datasource.call(this, this._onLazyLoad, {first: this.offset});
}
else {
this._renderData(this.data, this.offset, (this.offset + this.options.chunkSize));
this._onloadComplete();
}
},
_renderData: function(data, start, end) {
if(data && data.length) {
for(var i = start; i < end; i++) {
var listItem = $('<li class="ui-datascroller-item"></li>'),
content = this._createItemContent(data[i]);
listItem.append(content);
this.list.append(listItem);
}
}
},
shouldLoad: function() {
return (!this.loading && !this.allLoaded);
},
_createItemContent: function(obj) {
if(this.options.template) {
var template = this.options.template.html();
Mustache.parse(template);
return Mustache.render(template, obj);
}
else {
return this.options.content.call(this, obj);
}
},
_onloadComplete: function() {
this.offset += this.options.chunkSize;
this.loading = false;
this.allLoaded = this.offset >= this.options.totalSize;
this.loadStatus.remove();
if(this.options.loader && !this.allLoaded) {
this.options.loader.show();
}
}
});
})();/**
* PrimeUI Dialog Widget
*/
(function() {
$.widget("primeui.puidialog", {
options: {
draggable: true,
resizable: true,
location: 'center',
minWidth: 150,
minHeight: 25,
height: 'auto',
width: '300px',
visible: false,
modal: false,
showEffect: null,
hideEffect: null,
effectOptions: {},
effectSpeed: 'normal',
closeOnEscape: true,
rtl: false,
closable: true,
minimizable: false,
maximizable: false,
appendTo: null,
buttons: null,
responsive: false,
title: null,
enhanced: false
},
_create: function() {
this.id = this.element.attr('id');
if(!this.id) {
this.id = this.element.uniqueId().attr('id');
}
//container
if(!this.options.enhanced) {
this.element.addClass('ui-dialog ui-widget ui-widget-content ui-helper-hidden ui-corner-all ui-shadow')
.contents().wrapAll('<div class="ui-dialog-content ui-widget-content" />');
//header
var title = this.options.title||this.element.attr('title');
this.element.prepend('<div class="ui-dialog-titlebar ui-widget-header ui-helper-clearfix ui-corner-top">' +
'<span id="' + this.element.attr('id') + '_label" class="ui-dialog-title">' + title + '</span>')
.removeAttr('title');
//footer
if(this.options.buttons) {
this.footer = $('<div class="ui-dialog-buttonpane ui-widget-content ui-helper-clearfix"></div>').appendTo(this.element);
for(var i = 0; i < this.options.buttons.length; i++) {
var buttonMeta = this.options.buttons[i],
button = $('<button type="button"></button>').appendTo(this.footer);
if(buttonMeta.text) {
button.text(buttonMeta.text);
}
button.puibutton(buttonMeta);
}
}
if(this.options.rtl) {
this.element.addClass('ui-dialog-rtl');
}
}
//elements
this.content = this.element.children('.ui-dialog-content');
this.titlebar = this.element.children('.ui-dialog-titlebar');
if(!this.options.enhanced) {
if(this.options.closable) {
this._renderHeaderIcon('ui-dialog-titlebar-close', 'fa-close');
}
if(this.options.maximizable) {
this._renderHeaderIcon('ui-dialog-titlebar-maximize', 'fa-sort');
}
if(this.options.minimizable) {
this._renderHeaderIcon('ui-dialog-titlebar-minimize', 'fa-minus');
}
}
//icons
this.icons = this.titlebar.children('.ui-dialog-titlebar-icon');
this.closeIcon = this.titlebar.children('.ui-dialog-titlebar-close');
this.minimizeIcon = this.titlebar.children('.ui-dialog-titlebar-minimize');
this.maximizeIcon = this.titlebar.children('.ui-dialog-titlebar-maximize');
this.blockEvents = 'focus.puidialog mousedown.puidialog mouseup.puidialog keydown.puidialog keyup.puidialog';
this.parent = this.element.parent();
//size
this.element.css({'width': this.options.width, 'height': 'auto'});
this.content.height(this.options.height);
//events
this._bindEvents();
if(this.options.draggable) {
this._setupDraggable();
}
if(this.options.resizable) {
this._setupResizable();
}
if(this.options.appendTo) {
this.element.appendTo(this.options.appendTo);
}
if(this.options.responsive) {
this.resizeNS = 'resize.' + this.id;
}
//docking zone
if($(document.body).children('.ui-dialog-docking-zone').length === 0) {
$(document.body).append('<div class="ui-dialog-docking-zone"></div>');
}
//aria
this._applyARIA();
if(this.options.visible) {
this.show();
}
},
_destroy: function() {
//restore dom
if(!this.options.enhanced) {
this.element.removeClass('ui-dialog ui-widget ui-widget-content ui-helper-hidden ui-corner-all ui-shadow');
if(this.options.buttons) {
this.footer.children('button').puibutton('destroy');
this.footer.remove();
}
if(this.options.rtl) {
this.element.removeClass('ui-dialog-rtl');
}
var title = this.titlebar.children('.ui-dialog-title').text()||this.options.title;
if(title) {
this.element.attr('title', title);
}
this.titlebar.remove();
this.content.contents().unwrap();
}
//remove events
this._unbindEvents();
if(this.options.draggable) {
this.element.draggable('destroy');
}
if(this.options.resizable) {
this.element.resizable('destroy');
}
if(this.options.appendTo) {
this.element.appendTo(this.parent);
}
this._unbindResizeListener();
if(this.options.modal) {
this._disableModality();
}
this._removeARIA();
this.element.css({
'width': 'auto',
'height': 'auto'
});
},
_renderHeaderIcon: function(styleClass, icon) {
this.titlebar.append('<a class="ui-dialog-titlebar-icon ' + styleClass + ' ui-corner-all" href="#" role="button">' +
'<span class="fa fa-fw ' + icon + '"></span></a>');
},
_enableModality: function() {
var $this = this,
doc = $(document);
this.modality = $('<div id="' + this.element.attr('id') + '_modal" class="ui-widget-overlay ui-dialog-mask"></div>').appendTo(document.body)
.css('z-index', this.element.css('z-index') - 1);
//Disable tabbing out of modal dialog and stop events from targets outside of dialog
doc.on('keydown.puidialog',
function(event) {
if(event.keyCode == $.ui.keyCode.TAB) {
var tabbables = $this.content.find(':tabbable'),
first = tabbables.filter(':first'),
last = tabbables.filter(':last');
if(event.target === last[0] && !event.shiftKey) {
first.focus(1);
return false;
}
else if (event.target === first[0] && event.shiftKey) {
last.focus(1);
return false;
}
}
})
.bind(this.blockEvents, function(event) {
if ($(event.target).zIndex() < $this.element.zIndex()) {
return false;
}
});
},
_disableModality: function() {
if(this.modality) {
this.modality.remove();
this.modality = null;
}
$(document).off(this.blockEvents).off('keydown.dialog');
},
show: function() {
if(this.element.is(':visible')) {
return;
}
if(!this.positionInitialized) {
this._initPosition();
}
this._trigger('beforeShow', null);
if(this.options.showEffect) {
var $this = this;
this.element.show(this.options.showEffect, this.options.effectOptions, this.options.effectSpeed, function() {
$this._postShow();
});
}
else {
this.element.show();
this._postShow();
}
this._moveToTop();
if(this.options.modal) {
this._enableModality();
}
},
_postShow: function() {
//execute user defined callback
this._trigger('afterShow', null);
this.element.attr({
'aria-hidden': false,
'aria-live': 'polite'
});
this._applyFocus();
if(this.options.responsive) {
this._bindResizeListener();
}
},
hide: function() {
if(this.element.is(':hidden')) {
return;
}
this._trigger('beforeHide', null);
if(this.options.hideEffect) {
var _self = this;
this.element.hide(this.options.hideEffect, this.options.effectOptions, this.options.effectSpeed, function() {
_self._postHide();
});
}
else {
this.element.hide();
this._postHide();
}
if(this.options.modal) {
this._disableModality();
}
},
_postHide: function() {
//execute user defined callback
this._trigger('afterHide', null);
this.element.attr({
'aria-hidden': true,
'aria-live': 'off'
});
if(this.options.responsive) {
this._unbindResizeListener();
}
},
_applyFocus: function() {
this.element.find(':not(:submit):not(:button):input:visible:enabled:first').focus();
},
_bindEvents: function() {
var $this = this;
this.element.on('mousedown.puidialog', function(e) {
if(!$(e.target).data('ui-widget-overlay')) {
$this._moveToTop();
}
});
this.icons.mouseover(function() {
$(this).addClass('ui-state-hover');
}).mouseout(function() {
$(this).removeClass('ui-state-hover');
});
this.closeIcon.on('click.puidialog', function(e) {
$this.hide();
$this._trigger('clickClose');
e.preventDefault();
});
this.maximizeIcon.click(function(e) {
$this.toggleMaximize();
e.preventDefault();
});
this.minimizeIcon.click(function(e) {
$this.toggleMinimize();
e.preventDefault();
});
if(this.options.closeOnEscape) {
$(document).on('keydown.dialog_' + this.id, function(e) {
var keyCode = $.ui.keyCode,
active = parseInt($this.element.css('z-index'), 10) === PUI.zindex;
if(e.which === keyCode.ESCAPE && $this.element.is(':visible') && active) {
$this.hide();
}
});
}
},
_unbindEvents: function() {
this.element.off('mousedown.puidialog');
this.icons.off();
$(document).off('keydown.dialog_' + this.id);
},
_setupDraggable: function() {
this.element.draggable({
cancel: '.ui-dialog-content, .ui-dialog-titlebar-close',
handle: '.ui-dialog-titlebar',
containment : 'document'
});
},
_setupResizable: function() {
var $this = this;
this.element.resizable({
minWidth : this.options.minWidth,
minHeight : this.options.minHeight,
alsoResize : this.content,
containment: 'document',
start: function(event, ui) {
$this.element.data('offset', $this.element.offset());
},
stop: function(event, ui) {
var offset = $this.element.data('offset');
$this.element.css('position', 'fixed');
$this.element.offset(offset);
}
});
this.resizers = this.element.children('.ui-resizable-handle');
},
_initPosition: function() {
//reset
this.element.css({left:0,top:0});
if(/(center|left|top|right|bottom)/.test(this.options.location)) {
this.options.location = this.options.location.replace(',', ' ');
this.element.position({
my: 'center',
at: this.options.location,
collision: 'fit',
of: window,
//make sure dialog stays in viewport
using: function(pos) {
var l = pos.left < 0 ? 0 : pos.left,
t = pos.top < 0 ? 0 : pos.top;
$(this).css({
left: l,
top: t
});
}
});
}
else {
var coords = this.options.position.split(','),
x = $.trim(coords[0]),
y = $.trim(coords[1]);
this.element.offset({
left: x,
top: y
});
}
this.positionInitialized = true;
},
_moveToTop: function() {
this.element.css('z-index',++PUI.zindex);
},
toggleMaximize: function() {
if(this.minimized) {
this.toggleMinimize();
}
if(this.maximized) {
this.element.removeClass('ui-dialog-maximized');
this._restoreState();
this.maximizeIcon.removeClass('ui-state-hover');
this.maximized = false;
}
else {
this._saveState();
var win = $(window);
this.element.addClass('ui-dialog-maximized').css({
'width': win.width() - 6,
'height': win.height()
}).offset({
top: win.scrollTop(),
left: win.scrollLeft()
});
//maximize content
this.content.css({
width: 'auto',
height: 'auto'
});
this.maximizeIcon.removeClass('ui-state-hover');
this.maximized = true;
this._trigger('maximize');
}
},
toggleMinimize: function() {
var animate = true,
dockingZone = $(document.body).children('.ui-dialog-docking-zone');
if(this.maximized) {
this.toggleMaximize();
animate = false;
}
var $this = this;
if(this.minimized) {
this.element.appendTo(this.parent).removeClass('ui-dialog-minimized').css({'position':'fixed', 'float':'none'});
this._restoreState();
this.content.show();
this.minimizeIcon.removeClass('ui-state-hover').children('.fa').removeClass('fa-plus').addClass('fa-minus');
this.minimized = false;
if(this.options.resizable) {
this.resizers.show();
}
if(this.footer) {
this.footer.show();
}
}
else {
this._saveState();
if(animate) {
this.element.effect('transfer', {
to: dockingZone,
className: 'ui-dialog-minimizing'
}, 500,
function() {
$this._dock(dockingZone);
$this.element.addClass('ui-dialog-minimized');
});
}
else {
this._dock(dockingZone);
}
}
},
_dock: function(zone) {
this.element.appendTo(zone).css('position', 'static');
this.element.css({'height':'auto', 'width':'auto', 'float': 'left'});
this.content.hide();
this.minimizeIcon.removeClass('ui-state-hover').children('.fa').removeClass('fa-minus').addClass('fa-plus');
this.minimized = true;
if(this.options.resizable) {
this.resizers.hide();
}
if(this.footer) {
this.footer.hide();
}
zone.css('z-index',++PUI.zindex);
this._trigger('minimize');
},
_saveState: function() {
this.state = {
width: this.element.width(),
height: this.element.height()
};
var win = $(window);
this.state.offset = this.element.offset();
this.state.windowScrollLeft = win.scrollLeft();
this.state.windowScrollTop = win.scrollTop();
},
_restoreState: function() {
this.element.width(this.state.width).height(this.state.height);
var win = $(window);
this.element.offset({
top: this.state.offset.top + (win.scrollTop() - this.state.windowScrollTop),
left: this.state.offset.left + (win.scrollLeft() - this.state.windowScrollLeft)
});
},
_applyARIA: function() {
this.element.attr({
'role': 'dialog',
'aria-labelledby': this.element.attr('id') + '_title',
'aria-hidden': !this.options.visible
});
this.titlebar.children('a.ui-dialog-titlebar-icon').attr('role', 'button');
},
_removeARIA: function() {
this.element.removeAttr('role').removeAttr('aria-labelledby').removeAttr('aria-hidden')
.removeAttr('aria-live').removeAttr('aria-hidden');
},
_bindResizeListener: function() {
var $this = this;
$(window).on(this.resizeNS, function(e) {
if(e.target === window) {
$this._initPosition();
}
});
},
_unbindResizeListener: function() {
$(window).off(this.resizeNS);
},
_setOption: function(key, value) {
if(key === 'visible') {
if(value)
this.show();
else
this.hide();
}
else {
$.Widget.prototype._setOption.apply(this, arguments);
}
}
});
})();/**
* PrimeUI dropdown widget
*/
(function() {
$.widget("primeui.puidropdown", {
options: {
effect: 'fade',
effectSpeed: 'normal',
filter: false,
filterMatchMode: 'startsWith',
caseSensitiveFilter: false,
filterFunction: null,
data: null,
content: null,
scrollHeight: 200,
appendTo: 'body',
editable: false,
value: null,
style: null,
styleClass: null
},
_create: function() {
this.id = this.element.attr('id');
if(!this.id) {
this.id = this.element.uniqueId().attr('id');
}
if(!this.options.enhanced) {
if(this.options.data) {
if($.isArray(this.options.data)) {
this._generateOptionElements(this.options.data);
}
else {
if($.type(this.options.data) === 'function') {
this.options.data.call(this, this._onRemoteOptionsLoad);
return;
}
else {
if($.type(this.options.data) === 'string') {
var $this = this,
dataURL = this.options.data;
var loader = function() {
$.ajax({
type: 'GET',
url: dataURL,
dataType: "json",
context: $this,
success: function (response) {
this._onRemoteOptionsLoad(response);
}
});
};
loader.call(this);
}
}
return;
}
}
this._render();
}
else {
this.choices = this.element.children('option');
this.container = this.element.closest('.ui-dropdown');
this.focusElementContainer = this.container.children('.ui-helper-hidden-accessible:last');
this.focusElement = this.focusElementContainer.children('input');
this.label = this.container.children('.ui-dropdown-label');
this.menuIcon = this.container.children('.ui-dropdown-trigger');
this.panel = this.container.children('.ui-dropdown-panel');
this.itemsWrapper = this.panel.children('.ui-dropdown-items-wrapper');
this.itemsContainer = this.itemsWrapper.children('ul');
this.itemsContainer.addClass('ui-dropdown-items ui-dropdown-list ui-widget-content ui-widget ui-corner-all ui-helper-reset');
this.items = this.itemsContainer.children('li').addClass('ui-dropdown-item ui-dropdown-list-item ui-corner-all');
var $this = this;
this.items.each(function(i) {
$(this).data('label', $this.choices.eq(i).text());
});
if(this.options.filter) {
this.filterContainer = this.panel.children('.ui-dropdown-filter-container');
this.filterInput = this.filterContainer.children('input');
}
}
this._postRender();
},
_render: function() {
this.choices = this.element.children('option');
this.element.attr('tabindex', '-1').wrap('<div class="ui-dropdown ui-widget ui-state-default ui-corner-all ui-helper-clearfix" />')
.wrap('<div class="ui-helper-hidden-accessible" />');
this.container = this.element.closest('.ui-dropdown');
this.focusElementContainer = $('<div class="ui-helper-hidden-accessible"><input type="text" /></div>').appendTo(this.container);
this.focusElement = this.focusElementContainer.children('input');
this.label = this.options.editable ? $('<input type="text" class="ui-dropdown-label ui-inputtext ui-corner-all"">')
: $('<label class="ui-dropdown-label ui-inputtext ui-corner-all"/>');
this.label.appendTo(this.container);
this.menuIcon = $('<div class="ui-dropdown-trigger ui-state-default ui-corner-right"><span class="fa fa-fw fa-caret-down"></span></div>')
.appendTo(this.container);
//panel
this.panel = $('<div class="ui-dropdown-panel ui-widget-content ui-corner-all ui-helper-hidden ui-shadow" />');
this.itemsWrapper = $('<div class="ui-dropdown-items-wrapper" />').appendTo(this.panel);
this.itemsContainer = $('<ul class="ui-dropdown-items ui-dropdown-list ui-widget-content ui-widget ui-corner-all ui-helper-reset"></ul>')
.appendTo(this.itemsWrapper);
this.optGroupsSize = this.itemsContainer.children('li.puiselectonemenu-item-group').length;
if(this.options.filter) {
this.filterContainer = $('<div class="ui-dropdown-filter-container" />').prependTo(this.panel);
this.filterInput = $('<input type="text" autocomplete="off" class="ui-dropdown-filter ui-inputtext ui-widget ui-state-default ui-corner-all" />')
.appendTo(this.filterContainer);
this.filterContainer.append('<span class="fa fa-search"></span>');
}
this._generateItems();
},
_postRender: function() {
if(this.options.style) {
this.container.attr('style', this.options.style);
}
if(this.options.styleClass) {
this.container.addClass(this.options.styleClass);
}
this.disabled = this.element.prop('disabled')||this.options.disabled;
if(this.options.appendTo === 'self')
this.panel.appendTo(this.container);
else
this.panel.appendTo(this.options.appendTo);
if(this.options.scrollHeight && this.panel.outerHeight() > this.options.scrollHeight) {
this.itemsWrapper.height(this.options.scrollHeight);
}
var $this = this;
//preselection via value option
if(this.options.value) {
this.choices.filter('[value="'+this.options.value+'"]').prop('selected', true);
}
var selectedOption = this.choices.filter(':selected');
//disable options
this.choices.filter(':disabled').each(function() {
$this.items.eq($(this).index()).addClass('ui-state-disabled');
});
//triggers
this.triggers = this.options.editable ? this.menuIcon : this.container.children('.ui-dropdown-trigger, .ui-dropdown-label');
//activate selected
if(this.options.editable) {
var customInputVal = this.label.val();
//predefined input
if(customInputVal === selectedOption.text()) {
this._highlightItem(this.items.eq(selectedOption.index()));
}
//custom input
else {
this.items.eq(0).addClass('ui-state-highlight');
this.customInput = true;
this.customInputVal = customInputVal;
}
}
else {
this._highlightItem(this.items.eq(selectedOption.index()));
}
if(!this.disabled) {
this._bindEvents();
this._bindConstantEvents();
}
},
_onRemoteOptionsLoad: function(data) {
this._generateOptionElements(data);
this._render();
this._postRender();
},
_generateOptionElements: function(data) {
for(var i = 0; i < data.length; i++) {
var choice = data[i];
if(choice.label)
this.element.append('<option value="' + choice.value + '">' + choice.label + '</option>');
else
this.element.append('<option value="' + choice + '">' + choice + '</option>');
}
},
_generateItems: function() {
for(var i = 0; i < this.choices.length; i++) {
var option = this.choices.eq(i),
optionLabel = option.text(),
content = this.options.content ? this.options.content.call(this, this.options.data[i]) : optionLabel;
this.itemsContainer.append('<li data-label="' + optionLabel + '" class="ui-dropdown-item ui-dropdown-list-item ui-corner-all">' + content + '</li>');
}
this.items = this.itemsContainer.children('.ui-dropdown-item');
},
_bindEvents: function() {
var $this = this;
this.items.filter(':not(.ui-state-disabled)').each(function(i, item) {
$this._bindItemEvents($(item));
});
this.triggers.on('mouseenter.puidropdown', function() {
if(!$this.container.hasClass('ui-state-focus')) {
$this.container.addClass('ui-state-hover');
$this.menuIcon.addClass('ui-state-hover');
}
})
.on('mouseleave.puidropdown', function() {
$this.container.removeClass('ui-state-hover');
$this.menuIcon.removeClass('ui-state-hover');
})
.on('click.puidropdown', function(e) {
if($this.panel.is(":hidden")) {
$this._show();
}
else {
$this._hide();
$this._revert();
}
$this.container.removeClass('ui-state-hover');
$this.menuIcon.removeClass('ui-state-hover');
$this.focusElement.trigger('focus.puidropdown');
e.preventDefault();
});
this.focusElement.on('focus.puidropdown', function() {
$this.container.addClass('ui-state-focus');
$this.menuIcon.addClass('ui-state-focus');
})
.on('blur.puidropdown', function() {
$this.container.removeClass('ui-state-focus');
$this.menuIcon.removeClass('ui-state-focus');
});
if(this.options.editable) {
this.label.on('change.ui-dropdown', function() {
$this._triggerChange(true);
$this.customInput = true;
$this.customInputVal = $(this).val();
$this.items.filter('.ui-state-highlight').removeClass('ui-state-highlight');
$this.items.eq(0).addClass('ui-state-highlight');
});
}
this._bindKeyEvents();
if(this.options.filter) {
this._setupFilterMatcher();
this.filterInput.puiinputtext();
this.filterInput.on('keyup.ui-dropdown', function() {
$this._filter($(this).val());
});
}
},
_bindItemEvents: function(item) {
var $this = this;
item.on('mouseover.puidropdown', function() {
var el = $(this);
if(!el.hasClass('ui-state-highlight'))
$(this).addClass('ui-state-hover');
})
.on('mouseout.puidropdown', function() {
$(this).removeClass('ui-state-hover');
})
.on('click.puidropdown', function() {
$this._selectItem($(this));
});
},
_bindConstantEvents: function() {
var $this = this;
$(document.body).on('mousedown.ui-dropdown-' + this.id, function (e) {
if($this.panel.is(":hidden")) {
return;
}
var offset = $this.panel.offset();
if (e.target === $this.label.get(0) ||
e.target === $this.menuIcon.get(0) ||
e.target === $this.menuIcon.children().get(0)) {
return;
}
if (e.pageX < offset.left ||
e.pageX > offset.left + $this.panel.width() ||
e.pageY < offset.top ||
e.pageY > offset.top + $this.panel.height()) {
$this._hide();
$this._revert();
}
});
this.resizeNS = 'resize.' + this.id;
this._unbindResize();
this._bindResize();
},
_bindKeyEvents: function() {
var $this = this;
this.focusElement.on('keydown.puidropdown', function(e) {
var keyCode = $.ui.keyCode,
key = e.which,
activeItem;
switch(key) {
case keyCode.UP:
case keyCode.LEFT:
activeItem = $this._getActiveItem();
var prev = activeItem.prevAll(':not(.ui-state-disabled,.ui-selectonemenu-item-group):first');
if(prev.length == 1) {
if($this.panel.is(':hidden')) {
$this._selectItem(prev);
}
else {
$this._highlightItem(prev);
PUI.scrollInView($this.itemsWrapper, prev);
}
}
e.preventDefault();
break;
case keyCode.DOWN:
case keyCode.RIGHT:
activeItem = $this._getActiveItem();
var next = activeItem.nextAll(':not(.ui-state-disabled,.ui-selectonemenu-item-group):first');
if(next.length == 1) {
if($this.panel.is(':hidden')) {
if(e.altKey) {
$this._show();
} else {
$this._selectItem(next);
}
}
else {
$this._highlightItem(next);
PUI.scrollInView($this.itemsWrapper, next);
}
}
e.preventDefault();
break;
case keyCode.ENTER:
case keyCode.NUMPAD_ENTER:
if($this.panel.is(':hidden')) {
$this._show();
}
else {
$this._selectItem($this._getActiveItem());
}
e.preventDefault();
break;
case keyCode.TAB:
if($this.panel.is(':visible')) {
$this._revert();
$this._hide();
}
break;
case keyCode.ESCAPE:
if($this.panel.is(':visible')) {
$this._revert();
$this._hide();
}
break;
default:
var k = String.fromCharCode((96 <= key && key <= 105)? key-48 : key),
currentItem = $this.items.filter('.ui-state-highlight');
//Search items forward from current to end and on no result, search from start until current
var highlightItem = $this._search(k, currentItem.index() + 1, $this.options.length);
if(!highlightItem) {
highlightItem = $this._search(k, 0, currentItem.index());
}
if(highlightItem) {
if($this.panel.is(':hidden')) {
$this._selectItem(highlightItem);
}
else {
$this._highlightItem(highlightItem);
PUI.scrollInView($this.itemsWrapper, highlightItem);
}
}
break;
}
});
},
_unbindEvents: function() {
this.items.off('mouseover.puidropdown mouseout.puidropdown click.puidropdown');
this.triggers.off('mouseenter.puidropdown mouseleave.puidropdown click.puidropdown');
this.focusElement.off('keydown.puidropdown focus.puidropdown blur.puidropdown');
if(this.options.editable) {
this.label.off('change.puidropdown');
}
if(this.options.filter) {
this.filterInput.off('keyup.ui-dropdown');
}
$(document.body).off('mousedown.ui-dropdown-' + this.id);
this._unbindResize();
},
_selectItem: function(item, silent) {
var selectedOption = this.choices.eq(this._resolveItemIndex(item)),
currentOption = this.choices.filter(':selected'),
sameOption = selectedOption.val() == currentOption.val(),
shouldChange = null;
if(this.options.editable) {
shouldChange = (!sameOption)||(selectedOption.text() != this.label.val());
}
else {
shouldChange = !sameOption;
}
if(shouldChange) {
this._highlightItem(item);
this.element.val(selectedOption.val());
this._triggerChange();
if(this.options.editable) {
this.customInput = false;
}
}
if(!silent) {
this.focusElement.trigger('focus.puidropdown');
}
if(this.panel.is(':visible')) {
this._hide();
}
},
_highlightItem: function(item) {
this.items.filter('.ui-state-highlight').removeClass('ui-state-highlight');
if(item.length) {
item.addClass('ui-state-highlight');
this._setLabel(item.data('label'));
}
else {
this._setLabel(' ');
}
},
_triggerChange: function(edited) {
this.changed = false;
var selectedOption = this.choices.filter(':selected');
if(this.options.change) {
this._trigger('change', null, {
value: selectedOption.val(),
index: selectedOption.index()
});
}
if(!edited) {
this.value = this.choices.filter(':selected').val();
}
},
_resolveItemIndex: function(item) {
if(this.optGroupsSize === 0) {
return item.index();
}
else {
return item.index() - item.prevAll('li.ui-dropdown-item-group').length;
}
},
_setLabel: function(value) {
if(this.options.editable) {
this.label.val(value);
}
else {
if(value === ' ') {
this.label.html(' ');
}
else {
this.label.text(value);
}
}
},
_bindResize: function() {
var $this = this;
$(window).bind(this.resizeNS, function(e) {
if($this.panel.is(':visible')) {
$this._alignPanel();
}
});
},
_unbindResize: function() {
$(window).unbind(this.resizeNS);
},
_alignPanelWidth: function() {
if(!this.panelWidthAdjusted) {
var jqWidth = this.container.outerWidth();
if(this.panel.outerWidth() < jqWidth) {
this.panel.width(jqWidth);
}
this.panelWidthAdjusted = true;
}
},
_alignPanel: function() {
if(this.panel.parent().is(this.container)) {
this.panel.css({
left: '0px',
top: this.container.outerHeight() + 'px'
})
.width(this.container.outerWidth());
}
else {
this._alignPanelWidth();
this.panel.css({left:'', top:''}).position({
my: 'left top',
at: 'left bottom',
of: this.container,
collision: 'flipfit'
});
}
},
_show: function() {
this._alignPanel();
this.panel.css('z-index', ++PUI.zindex);
if(this.options.effect !== 'none') {
this.panel.show(this.options.effect, {}, this.options.effectSpeed);
}
else {
this.panel.show();
}
this.preShowValue = this.choices.filter(':selected');
},
_hide: function() {
this.panel.hide();
},
_revert: function() {
if(this.options.editable && this.customInput) {
this._setLabel(this.customInputVal);
this.items.filter('.ui-state-active').removeClass('ui-state-active');
this.items.eq(0).addClass('ui-state-active');
}
else {
this._highlightItem(this.items.eq(this.preShowValue.index()));
}
},
_getActiveItem: function() {
return this.items.filter('.ui-state-highlight');
},
_setupFilterMatcher: function() {
this.filterMatchers = {
'startsWith': this._startsWithFilter,
'contains': this._containsFilter,
'endsWith': this._endsWithFilter,
'custom': this.options.filterFunction
};
this.filterMatcher = this.filterMatchers[this.options.filterMatchMode];
},
_startsWithFilter: function(value, filter) {
return value.indexOf(filter) === 0;
},
_containsFilter: function(value, filter) {
return value.indexOf(filter) !== -1;
},
_endsWithFilter: function(value, filter) {
return value.indexOf(filter, value.length - filter.length) !== -1;
},
_filter: function(value) {
this.initialHeight = this.initialHeight||this.itemsWrapper.height();
var filterValue = this.options.caseSensitiveFilter ? $.trim(value) : $.trim(value).toLowerCase();
if(filterValue === '') {
this.items.filter(':hidden').show();
}
else {
for(var i = 0; i < this.choices.length; i++) {
var option = this.choices.eq(i),
itemLabel = this.options.caseSensitiveFilter ? option.text() : option.text().toLowerCase(),
item = this.items.eq(i);
if(this.filterMatcher(itemLabel, filterValue))
item.show();
else
item.hide();
}
}
if(this.itemsContainer.height() < this.initialHeight) {
this.itemsWrapper.css('height', 'auto');
}
else {
this.itemsWrapper.height(this.initialHeight);
}
this._alignPanel();
},
_search: function(text, start, end) {
for(var i = start; i < end; i++) {
var option = this.choices.eq(i);
if(option.text().indexOf(text) === 0) {
return this.items.eq(i);
}
}
return null;
},
getSelectedValue: function() {
return this.element.val();
},
getSelectedLabel: function() {
return this.choices.filter(':selected').text();
},
selectValue : function(value) {
var option = this.choices.filter('[value="' + value + '"]');
this._selectItem(this.items.eq(option.index()), true);
},
addOption: function(option, val) {
var value, label;
//backward compatibility for key-value parameters
if(val !== undefined && val !== null) {
value = val;
label = option;
}
//key-value as properties of option object
else {
value = (option.value !== undefined && option.value !== null) ? option.value : option;
label = (option.label !== undefined && option.label !== null) ? option.label : option;
}
var content = this.options.content ? this.options.content.call(this, option) : label,
item = $('<li data-label="' + label + '" class="ui-dropdown-item ui-dropdown-list-item ui-corner-all">' + content + '</li>'),
optionElement = $('<option value="' + value + '">' + label + '</option>');
optionElement.appendTo(this.element);
this._bindItemEvents(item);
item.appendTo(this.itemsContainer);
this.items.push(item[0]);
this.choices = this.element.children('option');
// If this is the first option, it is the default selected one
if (this.items.length === 1) {
this.selectValue(value);
this._highlightItem(item);
}
},
removeAllOptions: function() {
this.element.empty();
this.itemsContainer.empty();
this.items.length = 0;
this.choices.length = 0;
this.element.val('');
this.label.text('');
},
_setOption: function (key, value) {
if (key === 'data' || key === 'options') {
this.options.data = value;
this.removeAllOptions();
for(var i = 0; i < this.options.data.length; i++) {
this.addOption(this.options.data[i]);
}
if(this.options.scrollHeight && this.panel.outerHeight() > this.options.scrollHeight) {
this.itemsWrapper.height(this.options.scrollHeight);
}
}
else if(key === 'value') {
this.options.value = value;
this.choices.prop('selected', false);
var selectedOption = this.choices.filter('[value="'+this.options.value+'"]');
if(selectedOption.length) {
selectedOption.prop('selected', true);
this._highlightItem(this.items.eq(selectedOption.index()));
}
}
else {
$.Widget.prototype._setOption.apply(this, arguments);
}
},
disable: function() {
this._unbindEvents();
this.label.addClass('ui-state-disabled');
this.menuIcon.addClass('ui-state-disabled');
},
enable: function() {
this._bindEvents();
this.label.removeClass('ui-state-disabled');
this.menuIcon.removeClass('ui-state-disabled');
},
getEditableText: function() {
return this.label.val();
},
_destroy: function() {
this._unbindEvents();
if(!this.options.enhanced) {
this.panel.remove();
this.label.remove();
this.menuIcon.remove();
this.focusElementContainer.remove();
this.element.unwrap().unwrap();
}
else {
if(this.options.appendTo == 'body') {
this.panel.appendTo(this.container);
}
if(this.options.style) {
this.container.removeAttr('style');
}
if(this.options.styleClass) {
this.container.removeClass(this.options.styleClass);
}
}
}
});
})();/**
* PrimeFaces Fieldset Widget
*/
(function() {
$.widget("primeui.puifieldset", {
options: {
toggleable: false,
toggleDuration: 'normal',
collapsed: false,
enhanced: false
},
_create: function() {
if(!this.options.enhanced) {
this.element.addClass('ui-fieldset ui-widget ui-widget-content ui-corner-all').
children('legend').addClass('ui-fieldset-legend ui-corner-all ui-state-default');
this.element.contents().wrapAll('<div class="ui-fieldset-content" />');
this.content = this.element.children('div.ui-fieldset-content');
this.legend = this.content.children('legend.ui-fieldset-legend').prependTo(this.element);
}
else {
this.legend = this.element.children('legend');
this.content = this.element.children('div.ui-fieldset-content');
}
if(this.options.toggleable) {
if(this.options.enhanced) {
this.toggler = this.legend.children('.ui-fieldset-toggler');
}
else {
this.element.addClass('ui-fieldset-toggleable');
this.toggler = $('<span class="ui-fieldset-toggler fa fa-fw" />').prependTo(this.legend);
}
this._bindEvents();
if(this.options.collapsed) {
this.content.hide();
this.toggler.addClass('fa-plus');
}
else {
this.toggler.addClass('fa-minus');
}
}
},
_bindEvents: function() {
var $this = this;
this.legend.on('click.puifieldset', function(e) {$this.toggle(e);})
.on('mouseover.puifieldset', function() {$this.legend.addClass('ui-state-hover');})
.on('mouseout.puifieldset', function() {$this.legend.removeClass('ui-state-hover ui-state-active');})
.on('mousedown.puifieldset', function() {$this.legend.removeClass('ui-state-hover').addClass('ui-state-active');})
.on('mouseup.puifieldset', function() {$this.legend.removeClass('ui-state-active').addClass('ui-state-hover');});
},
_unbindEvents: function() {
this.legend.off('click.puifieldset mouseover.puifieldset mouseout.puifieldset mousedown.puifieldset mouseup.puifieldset');
},
toggle: function(e) {
var $this = this;
this._trigger('beforeToggle', e, this.options.collapsed);
if(this.options.collapsed) {
this.toggler.removeClass('fa-plus').addClass('fa-minus');
}
else {
this.toggler.removeClass('fa-minus').addClass('fa-plus');
}
this.content.slideToggle(this.options.toggleSpeed, 'easeInOutCirc', function() {
$this.options.collapsed = !$this.options.collapsed;
$this._trigger('afterToggle', e, $this.options.collapsed);
});
},
_destroy: function() {
if(!this.options.enhanced) {
this.element.removeClass('ui-fieldset ui-widget ui-widget-content ui-corner-all')
.children('legend').removeClass('ui-fieldset-legend ui-corner-all ui-state-default ui-state-hover ui-state-active');
this.content.contents().unwrap();
if(this.options.toggleable) {
this.element.removeClass('ui-fieldset-toggleable');
this.toggler.remove();
}
}
this._unbindEvents();
}
});
})();/**
* PrimeUI Lightbox Widget
*/
(function() {
$.widget("primeui.puigalleria", {
options: {
panelWidth: 600,
panelHeight: 400,
frameWidth: 60,
frameHeight: 40,
activeIndex: 0,
showFilmstrip: true,
autoPlay: true,
transitionInterval: 4000,
effect: 'fade',
effectSpeed: 250,
effectOptions: {},
showCaption: true,
customContent: false
},
_create: function() {
this.element.addClass('ui-galleria ui-widget ui-widget-content ui-corner-all');
this.panelWrapper = this.element.children('ul');
this.panelWrapper.addClass('ui-galleria-panel-wrapper');
this.panels = this.panelWrapper.children('li');
this.panels.addClass('ui-galleria-panel ui-helper-hidden');
this.element.width(this.options.panelWidth);
this.panelWrapper.width(this.options.panelWidth).height(this.options.panelHeight);
this.panels.width(this.options.panelWidth).height(this.options.panelHeight);
if(this.options.showFilmstrip) {
this._renderStrip();
this._bindEvents();
}
if(this.options.customContent) {
this.panels.children('img').hide();
this.panels.children('div').addClass('ui-galleria-panel-content');
}
//show first
var activePanel = this.panels.eq(this.options.activeIndex);
activePanel.removeClass('ui-helper-hidden');
if(this.options.showCaption) {
this._showCaption(activePanel);
}
this.element.css('visibility', 'visible');
if(this.options.autoPlay) {
this.startSlideshow();
}
},
_destroy: function() {
this.stopSlideshow();
this._unbindEvents();
this.element.removeClass('ui-galleria ui-widget ui-widget-content ui-corner-all').removeAttr('style');
this.panelWrapper.removeClass('ui-galleria-panel-wrapper').removeAttr('style');
this.panels.removeClass('ui-galleria-panel ui-helper-hidden').removeAttr('style');
this.strip.remove();
this.stripWrapper.remove();
this.element.children('.fa').remove();
if(this.options.showCaption) {
this.caption.remove();
}
this.panels.children('img').show();
},
_renderStrip: function() {
var frameStyle = 'style="width:' + this.options.frameWidth + "px;height:" + this.options.frameHeight + 'px;"';
this.stripWrapper = $('<div class="ui-galleria-filmstrip-wrapper"></div>')
.width(this.element.width() - 50)
.height(this.options.frameHeight)
.appendTo(this.element);
this.strip = $('<ul class="ui-galleria-filmstrip"></div>').appendTo(this.stripWrapper);
for(var i = 0; i < this.panels.length; i++) {
var image = this.panels.eq(i).children('img'),
frameClass = (i == this.options.activeIndex) ? 'ui-galleria-frame ui-galleria-frame-active' : 'ui-galleria-frame',
frameMarkup = '<li class="'+ frameClass + '" ' + frameStyle + '>' +
'<div class="ui-galleria-frame-content" ' + frameStyle + '>' +
'<img src="' + image.attr('src') + '" class="ui-galleria-frame-image" ' + frameStyle + '/>' +
'</div></li>';
this.strip.append(frameMarkup);
}
this.frames = this.strip.children('li.ui-galleria-frame');
//navigators
this.element.append('<div class="ui-galleria-nav-prev fa fa-fw fa-chevron-circle-left" style="bottom:' + (this.options.frameHeight / 2) + 'px"></div>' +
'<div class="ui-galleria-nav-next fa fa-fw fa-chevron-circle-right" style="bottom:' + (this.options.frameHeight / 2) + 'px"></div>');
//caption
if(this.options.showCaption) {
this.caption = $('<div class="ui-galleria-caption"></div>').css({
'bottom': this.stripWrapper.outerHeight() + 10,
'width': this.panelWrapper.width()
}).appendTo(this.element);
}
},
_bindEvents: function() {
var $this = this;
this.element.children('div.ui-galleria-nav-prev').on('click.puigalleria', function() {
if($this.slideshowActive) {
$this.stopSlideshow();
}
if(!$this.isAnimating()) {
$this.prev();
}
});
this.element.children('div.ui-galleria-nav-next').on('click.puigalleria', function() {
if($this.slideshowActive) {
$this.stopSlideshow();
}
if(!$this.isAnimating()) {
$this.next();
}
});
this.strip.children('li.ui-galleria-frame').on('click.puigalleria', function() {
if($this.slideshowActive) {
$this.stopSlideshow();
}
$this.select($(this).index(), false);
});
},
_unbindEvents: function() {
this.element.children('div.ui-galleria-nav-prev').off('click.puigalleria');
this.element.children('div.ui-galleria-nav-next').off('click.puigalleria');
this.strip.children('li.ui-galleria-frame').off('click.puigalleria');
},
startSlideshow: function() {
var $this = this;
this.interval = window.setInterval(function() {
$this.next();
}, this.options.transitionInterval);
this.slideshowActive = true;
},
stopSlideshow: function() {
if(this.interval) {
window.clearInterval(this.interval);
}
this.slideshowActive = false;
},
isSlideshowActive: function() {
return this.slideshowActive;
},
select: function(index, reposition) {
if(index !== this.options.activeIndex) {
if(this.options.showCaption) {
this._hideCaption();
}
var oldPanel = this.panels.eq(this.options.activeIndex),
newPanel = this.panels.eq(index);
//content
oldPanel.hide(this.options.effect, this.options.effectOptions, this.options.effectSpeed);
newPanel.show(this.options.effect, this.options.effectOptions, this.options.effectSpeed);
if (this.options.showFilmstrip) {
var oldFrame = this.frames.eq(this.options.activeIndex),
newFrame = this.frames.eq(index);
//frame
oldFrame.removeClass('ui-galleria-frame-active').css('opacity', '');
newFrame.animate({opacity:1.0}, this.options.effectSpeed, null, function() {
$(this).addClass('ui-galleria-frame-active');
});
//viewport
if( (reposition === undefined || reposition === true) ) {
var frameLeft = newFrame.position().left,
stepFactor = this.options.frameWidth + parseInt(newFrame.css('margin-right'), 10),
stripLeft = this.strip.position().left,
frameViewportLeft = frameLeft + stripLeft,
frameViewportRight = frameViewportLeft + this.options.frameWidth;
if(frameViewportRight > this.stripWrapper.width()) {
this.strip.animate({left: '-=' + stepFactor}, this.options.effectSpeed, 'easeInOutCirc');
} else if(frameViewportLeft < 0) {
this.strip.animate({left: '+=' + stepFactor}, this.options.effectSpeed, 'easeInOutCirc');
}
}
}
//caption
if(this.options.showCaption) {
this._showCaption(newPanel);
}
this.options.activeIndex = index;
}
},
_hideCaption: function() {
this.caption.slideUp(this.options.effectSpeed);
},
_showCaption: function(panel) {
var image = panel.children('img');
this.caption.html('<h4>' + image.attr('title') + '</h4><p>' + image.attr('alt') + '</p>').slideDown(this.options.effectSpeed);
},
prev: function() {
if(this.options.activeIndex !== 0) {
this.select(this.options.activeIndex - 1);
}
},
next: function() {
if(this.options.activeIndex !== (this.panels.length - 1)) {
this.select(this.options.activeIndex + 1);
}
else {
this.select(0, false);
this.strip.animate({left: 0}, this.options.effectSpeed, 'easeInOutCirc');
}
},
isAnimating: function() {
return this.strip.is(':animated');
}
});
})();/**
* PrimeFaces Growl Widget
*/
(function() {
$.widget("primeui.puigrowl", {
options: {
sticky: false,
life: 3000,
messages: null,
appendTo: document.body
},
_create: function() {
var container = this.element;
this.originalParent = this.element.parent();
container.addClass("ui-growl ui-widget");
if(this.options.appendTo) {
container.appendTo(this.options.appendTo);
}
if(this.options.messages) {
this.show(this.options.messages);
}
},
show: function(msgs) {
var $this = this;
this.element.css('z-index', ++PUI.zindex);
this.clear();
if(msgs && msgs.length) {
$.each(msgs, function(i, msg) {
$this._renderMessage(msg);
});
}
},
clear: function() {
var messageElements = this.element.children('div.ui-growl-item-container');
for(var i = 0; i < messageElements.length; i++) {
this._unbindMessageEvents(messageElements.eq(i));
}
messageElements.remove();
},
_renderMessage: function(msg) {
var markup = '<div class="ui-growl-item-container ui-state-highlight ui-corner-all ui-helper-hidden" aria-live="polite">';
markup += '<div class="ui-growl-item ui-shadow">';
markup += '<div class="ui-growl-icon-close fa fa-close" style="display:none"></div>';
markup += '<span class="ui-growl-image fa fa-2x ' + this._getIcon(msg.severity) + ' ui-growl-image-' + msg.severity + '"/>';
markup += '<div class="ui-growl-message">';
markup += '<span class="ui-growl-title">' + msg.summary + '</span>';
markup += '<p>' + (msg.detail||'') + '</p>';
markup += '</div><div style="clear: both;"></div></div></div>';
var message = $(markup);
this._bindMessageEvents(message);
message.appendTo(this.element).fadeIn();
},
_removeMessage: function(message) {
message.fadeTo('normal', 0, function() {
message.slideUp('normal', 'easeInOutCirc', function() {
message.remove();
});
});
},
_bindMessageEvents: function(message) {
var $this = this,
sticky = this.options.sticky;
message.on('mouseover.puigrowl', function() {
var msg = $(this);
if(!msg.is(':animated')) {
msg.find('div.ui-growl-icon-close:first').show();
}
})
.on('mouseout.puigrowl', function() {
$(this).find('div.ui-growl-icon-close:first').hide();
});
//remove message on click of close icon
message.find('div.ui-growl-icon-close').on('click.puigrowl',function() {
$this._removeMessage(message);
if(!sticky) {
window.clearTimeout(message.data('timeout'));
}
});
if(!sticky) {
this._setRemovalTimeout(message);
}
},
_unbindMessageEvents: function(message) {
var $this = this,
sticky = this.options.sticky;
message.off('mouseover.puigrowl mouseout.puigrowl');
message.find('div.ui-growl-icon-close').off('click.puigrowl');
if(!sticky) {
var timeout = message.data('timeout');
if(timeout) {
window.clearTimeout(timeout);
}
}
},
_setRemovalTimeout: function(message) {
var $this = this;
var timeout = window.setTimeout(function() {
$this._removeMessage(message);
}, this.options.life);
message.data('timeout', timeout);
},
_getIcon: function(severity) {
switch(severity) {
case 'info':
return 'fa-info-circle';
break;
case 'warn':
return 'fa-warning';
break;
case 'error':
return 'fa-close';
break;
default:
return 'fa-info-circle';
break;
}
},
_setOption: function(key, value) {
if(key === 'value' || key === 'messages') {
this.show(value);
}
else {
$.Widget.prototype._setOption.apply(this, arguments);
}
},
_destroy: function() {
this.clear();
this.element.removeClass("ui-growl ui-widget");
if(this.options.appendTo) {
this.element.appendTo(this.originalParent);
}
}
});
})();/**
* PrimeUI inputtext widget
*/
(function() {
$.widget("primeui.puiinputtext", {
options: {
disabled: false
},
_create: function() {
var input = this.element,
disabled = input.prop('disabled');
//visuals
input.addClass('ui-inputtext ui-widget ui-state-default ui-corner-all');
if(input.prop('disabled'))
input.addClass('ui-state-disabled');
else if(this.options.disabled)
this.disable();
else
this._enableMouseEffects();
},
_destroy: function() {
this.element.removeClass('ui-inputtext ui-widget ui-state-default ui-state-disabled ui-state-hover ui-state-focus ui-corner-all');
this._disableMouseEffects();
},
_enableMouseEffects: function () {
var input = this.element;
input.on('mouseover.puiinputtext', function() {
input.addClass('ui-state-hover');
})
.on('mouseout.puiinputtext', function() {
input.removeClass('ui-state-hover');
})
.on('focus.puiinputtext', function() {
input.addClass('ui-state-focus');
})
.on('blur.puiinputtext', function() {
input.removeClass('ui-state-focus');
});
},
_disableMouseEffects: function () {
this.element.off('mouseover.puiinputtext mouseout.puiinputtext focus.puiinputtext blur.puiinputtext');
},
disable: function () {
this.element.prop('disabled', true);
this.element.addClass('ui-state-disabled');
this.element.removeClass('ui-state-focus ui-state-hover');
this._disableMouseEffects();
},
enable: function () {
this.element.prop('disabled', false);
this.element.removeClass('ui-state-disabled');
this._enableMouseEffects();
},
_setOption: function(key, value) {
if(key === 'disabled') {
if(value)
this.disable();
else
this.enable();
}
else {
$.Widget.prototype._setOption.apply(this, arguments);
}
}
});
})();/**
* PrimeUI inputtextarea widget
*/
(function() {
$.widget("primeui.puiinputtextarea", {
options: {
autoResize: false,
autoComplete: false,
maxlength: null,
counter: null,
counterTemplate: '{0}',
minQueryLength: 3,
queryDelay: 700,
completeSource: null
},
_create: function() {
var $this = this;
this.id = this.element.attr('id');
if(!this.id) {
this.id = this.element.uniqueId().attr('id');
}
this.element.puiinputtext();
if(this.options.autoResize) {
this.options.rowsDefault = this.element.attr('rows');
this.options.colsDefault = this.element.attr('cols');
this.element.addClass('ui-inputtextarea-resizable');
this.element.on('keyup.puiinputtextarea-resize', function() {
$this._resize();
}).on('focus.puiinputtextarea-resize', function() {
$this._resize();
}).on('blur.puiinputtextarea-resize', function() {
$this._resize();
});
}
if(this.options.maxlength) {
this.element.on('keyup.puiinputtextarea-maxlength', function(e) {
var value = $this.element.val(),
length = value.length;
if(length > $this.options.maxlength) {
$this.element.val(value.substr(0, $this.options.maxlength));
}
if($this.options.counter) {
$this._updateCounter();
}
});
}
if(this.options.counter) {
this._updateCounter();
}
if(this.options.autoComplete) {
this._initAutoComplete();
}
},
_destroy: function() {
this.element.puiinputtext('destroy');
if(this.options.autoResize) {
this.element.removeClass('ui-inputtextarea-resizable').off('keyup.puiinputtextarea-resize focus.puiinputtextarea-resize blur.puiinputtextarea-resize');
}
if(this.options.maxlength) {
this.element.off('keyup.puiinputtextarea-maxlength');
}
if(this.options.autoComplete) {
this.element.off('keyup.puiinputtextarea-autocomplete keydown.puiinputtextarea-autocomplete');
$(document.body).off('mousedown.puiinputtextarea-' + this.id);
$(window).off('resize.puiinputtextarea-' + this.id);
if(this.items) {
this.items.off();
}
this.panel.remove();
}
},
_updateCounter: function() {
var value = this.element.val(),
length = value.length;
if(this.options.counter) {
var remaining = this.options.maxlength - length,
remainingText = this.options.counterTemplate.replace('{0}', remaining);
this.options.counter.text(remainingText);
}
},
_resize: function() {
var linesCount = 0,
lines = this.element.val().split('\n');
for(var i = lines.length-1; i >= 0 ; --i) {
linesCount += Math.floor((lines[i].length / this.options.colsDefault) + 1);
}
var newRows = (linesCount >= this.options.rowsDefault) ? (linesCount + 1) : this.options.rowsDefault;
this.element.attr('rows', newRows);
},
_initAutoComplete: function() {
var panelMarkup = '<div id="' + this.id + '_panel" class="ui-autocomplete-panel ui-widget-content ui-corner-all ui-helper-hidden ui-shadow"></div>',
$this = this;
this.panel = $(panelMarkup).appendTo(document.body);
this.element.on('keyup.puiinputtextarea-autocomplete', function(e) {
var keyCode = $.ui.keyCode;
switch(e.which) {
case keyCode.UP:
case keyCode.LEFT:
case keyCode.DOWN:
case keyCode.RIGHT:
case keyCode.ENTER:
case keyCode.NUMPAD_ENTER:
case keyCode.TAB:
case keyCode.SPACE:
case keyCode.CONTROL:
case keyCode.ALT:
case keyCode.ESCAPE:
case 224: //mac command
//do not search
break;
default:
var query = $this._extractQuery();
if(query && query.length >= $this.options.minQueryLength) {
//Cancel the search request if user types within the timeout
if($this.timeout) {
$this._clearTimeout($this.timeout);
}
$this.timeout = window.setTimeout(function() {
$this.search(query);
}, $this.options.queryDelay);
}
break;
}
}).on('keydown.puiinputtextarea-autocomplete', function(e) {
var overlayVisible = $this.panel.is(':visible'),
keyCode = $.ui.keyCode,
highlightedItem;
switch(e.which) {
case keyCode.UP:
case keyCode.LEFT:
if(overlayVisible) {
highlightedItem = $this.items.filter('.ui-state-highlight');
var prev = highlightedItem.length === 0 ? $this.items.eq(0) : highlightedItem.prev();
if(prev.length == 1) {
highlightedItem.removeClass('ui-state-highlight');
prev.addClass('ui-state-highlight');
if($this.options.scrollHeight) {
PUI.scrollInView($this.panel, prev);
}
}
e.preventDefault();
}
else {
$this._clearTimeout();
}
break;
case keyCode.DOWN:
case keyCode.RIGHT:
if(overlayVisible) {
highlightedItem = $this.items.filter('.ui-state-highlight');
var next = highlightedItem.length === 0 ? _self.items.eq(0) : highlightedItem.next();
if(next.length == 1) {
highlightedItem.removeClass('ui-state-highlight');
next.addClass('ui-state-highlight');
if($this.options.scrollHeight) {
PUI.scrollInView($this.panel, next);
}
}
e.preventDefault();
}
else {
$this._clearTimeout();
}
break;
case keyCode.ENTER:
case keyCode.NUMPAD_ENTER:
if(overlayVisible) {
$this.items.filter('.ui-state-highlight').trigger('click');
e.preventDefault();
}
else {
$this._clearTimeout();
}
break;
case keyCode.SPACE:
case keyCode.CONTROL:
case keyCode.ALT:
case keyCode.BACKSPACE:
case keyCode.ESCAPE:
case 224: //mac command
$this._clearTimeout();
if(overlayVisible) {
$this._hide();
}
break;
case keyCode.TAB:
$this._clearTimeout();
if(overlayVisible) {
$this.items.filter('.ui-state-highlight').trigger('click');
$this._hide();
}
break;
}
});
//hide panel when outside is clicked
$(document.body).on('mousedown.puiinputtextarea-' + this.id, function (e) {
if($this.panel.is(":hidden")) {
return;
}
var offset = $this.panel.offset();
if(e.target === $this.element.get(0)) {
return;
}
if (e.pageX < offset.left ||
e.pageX > offset.left + $this.panel.width() ||
e.pageY < offset.top ||
e.pageY > offset.top + $this.panel.height()) {
$this._hide();
}
});
//Hide overlay on resize
var resizeNS = 'resize.puiinputtextarea-' + this.id;
$(window).off(resizeNS).on(resizeNS, function() {
if($this.panel.is(':visible')) {
$this._hide();
}
});
},
_bindDynamicEvents: function() {
var $this = this;
//visuals and click handler for items
this.items.on('mouseover', function() {
var item = $(this);
if(!item.hasClass('ui-state-highlight')) {
$this.items.filter('.ui-state-highlight').removeClass('ui-state-highlight');
item.addClass('ui-state-highlight');
}
})
.on('click', function(event) {
var item = $(this),
itemValue = item.attr('data-item-value'),
insertValue = itemValue.substring($this.query.length);
$this.element.focus();
$this.element.insertText(insertValue, $this.element.getSelection().start, true);
$this._hide();
$this._trigger("itemselect", event, item);
});
},
_clearTimeout: function() {
if(this.timeout) {
window.clearTimeout(this.timeout);
}
this.timeout = null;
},
_extractQuery: function() {
var end = this.element.getSelection().end,
result = /\S+$/.exec(this.element.get(0).value.slice(0, end)),
lastWord = result ? result[0] : null;
return lastWord;
},
search: function(q) {
this.query = q;
var request = {
query: q
};
if(this.options.completeSource) {
this.options.completeSource.call(this, request, this._handleResponse);
}
},
_handleResponse: function(data) {
this.panel.html('');
var listContainer = $('<ul class="ui-autocomplete-items ui-autocomplete-list ui-widget-content ui-widget ui-corner-all ui-helper-reset"></ul>');
for(var i = 0; i < data.length; i++) {
var item = $('<li class="ui-autocomplete-item ui-autocomplete-list-item ui-corner-all"></li>');
item.attr('data-item-value', data[i].value);
item.text(data[i].label);
listContainer.append(item);
}
this.panel.append(listContainer);
this.items = this.panel.find('.ui-autocomplete-item');
this._bindDynamicEvents();
if(this.items.length > 0) {
//highlight first item
this.items.eq(0).addClass('ui-state-highlight');
//adjust height
if(this.options.scrollHeight && this.panel.height() > this.options.scrollHeight) {
this.panel.height(this.options.scrollHeight);
}
if(this.panel.is(':hidden')) {
this._show();
}
else {
this._alignPanel(); //with new items
}
}
else {
this.panel.hide();
}
},
_alignPanel: function() {
var pos = this.element.getCaretPosition(),
offset = this.element.offset();
this.panel.css({
'left': offset.left + pos.left,
'top': offset.top + pos.top,
'width': this.element.innerWidth()
});
},
_show: function() {
this._alignPanel();
this.panel.show();
},
_hide: function() {
this.panel.hide();
},
disable: function () {
this.element.puiinputtext('disable');
},
enable: function () {
this.element.puiinputtext('enable');
}
});
})();/**
* PrimeUI Lightbox Widget
*/
(function() {
$.widget("primeui.puilightbox", {
options: {
iframeWidth: 640,
iframeHeight: 480,
iframe: false
},
_create: function() {
this.id = this.element.attr('id');
if(!this.id) {
this.id = this.element.uniqueId().attr('id');
}
this.options.mode = this.options.iframe ? 'iframe' : (this.element.children('div').length == 1) ? 'inline' : 'image';
var dom = '<div class="ui-lightbox ui-widget ui-helper-hidden ui-corner-all ui-shadow">';
dom += '<div class="ui-lightbox-content-wrapper">';
dom += '<a class="ui-state-default ui-lightbox-nav-left ui-corner-right ui-helper-hidden"><span class="fa fa-fw fa-caret-left"></span></a>';
dom += '<div class="ui-lightbox-content ui-corner-all"></div>';
dom += '<a class="ui-state-default ui-lightbox-nav-right ui-corner-left ui-helper-hidden"><span class="fa fa-fw fa-caret-right"></span></a>';
dom += '</div>';
dom += '<div class="ui-lightbox-caption ui-widget-header"><span class="ui-lightbox-caption-text"></span>';
dom += '<a class="ui-lightbox-close ui-corner-all" href="#"><span class="fa fa-fw fa-close"></span></a><div style="clear:both" /></div>';
dom += '</div>';
this.panel = $(dom).appendTo(document.body);
this.contentWrapper = this.panel.children('.ui-lightbox-content-wrapper');
this.content = this.contentWrapper.children('.ui-lightbox-content');
this.caption = this.panel.children('.ui-lightbox-caption');
this.captionText = this.caption.children('.ui-lightbox-caption-text');
this.closeIcon = this.caption.children('.ui-lightbox-close');
if(this.options.mode === 'image') {
this._setupImaging();
}
else if(this.options.mode === 'inline') {
this._setupInline();
}
else if(this.options.mode === 'iframe') {
this._setupIframe();
}
this._bindCommonEvents();
this.links.data('puilightbox-trigger', true).find('*').data('puilightbox-trigger', true);
this.closeIcon.data('puilightbox-trigger', true).find('*').data('puilightbox-trigger', true);
},
_bindCommonEvents: function() {
var $this = this;
this.closeIcon.on('hover.ui-lightbox', function() {
$(this).toggleClass('ui-state-hover');
})
.on('click.ui-lightbox', function(e) {
$this.hide();
e.preventDefault();
});
//hide when outside is clicked
$(document.body).on('click.ui-lightbox-' + this.id, function (e) {
if($this.isHidden()) {
return;
}
//do nothing if target is the link
var target = $(e.target);
if(target.data('puilightbox-trigger')) {
return;
}
//hide if mouse is outside of lightbox
var offset = $this.panel.offset();
if(e.pageX < offset.left ||
e.pageX > offset.left + $this.panel.width() ||
e.pageY < offset.top ||
e.pageY > offset.top + $this.panel.height()) {
$this.hide();
}
});
//sync window resize
$(window).on('resize.ui-lightbox-' + this.id, function() {
if(!$this.isHidden()) {
$(document.body).children('.ui-widget-overlay').css({
'width': $(document).width(),
'height': $(document).height()
});
}
});
},
_destroy: function() {
this.links.removeData('puilightbox-trigger').find('*').removeData('puilightbox-trigger');
this._unbindEvents();
this.panel.remove();
if(this.modality) {
this._disableModality();
}
},
_unbindEvents: function() {
this.closeIcon.off('hover.ui-lightbox click.ui-lightbox');
$(document.body).off('click.ui-lightbox-' + this.id);
$(window).off('resize.ui-lightbox-' + this.id)
this.links.off('click.ui-lightbox');
if(this.options.mode === 'image') {
this.imageDisplay.off('load.ui-lightbox');
this.navigators.off('hover.ui-lightbox click.ui-lightbox');
}
},
_setupImaging: function() {
var $this = this;
this.links = this.element.children('a');
this.content.append('<img class="ui-helper-hidden"></img>');
this.imageDisplay = this.content.children('img');
this.navigators = this.contentWrapper.children('a');
this.imageDisplay.on('load.ui-lightbox', function() {
var image = $(this);
$this._scaleImage(image);
//coordinates to center overlay
var leftOffset = ($this.panel.width() - image.width()) / 2,
topOffset = ($this.panel.height() - image.height()) / 2;
//resize content for new image
$this.content.removeClass('ui-lightbox-loading').animate({
width: image.width(),
height: image.height()
},
500,
function() {
//show image
image.fadeIn();
$this._showNavigators();
$this.caption.slideDown();
});
$this.panel.animate({
left: '+=' + leftOffset,
top: '+=' + topOffset
}, 500);
});
this.navigators.on('hover.ui-lightbox', function() {
$(this).toggleClass('ui-state-hover');
})
.on('click.ui-lightbox', function(e) {
var nav = $(this),
index;
$this._hideNavigators();
if(nav.hasClass('ui-lightbox-nav-left')) {
index = $this.current === 0 ? $this.links.length - 1 : $this.current - 1;
$this.links.eq(index).trigger('click');
}
else {
index = $this.current == $this.links.length - 1 ? 0 : $this.current + 1;
$this.links.eq(index).trigger('click');
}
e.preventDefault();
});
this.links.on('click.ui-lightbox', function(e) {
var link = $(this);
if($this.isHidden()) {
$this.content.addClass('ui-lightbox-loading').width(32).height(32);
$this.show();
}
else {
$this.imageDisplay.fadeOut(function() {
//clear for onload scaling
$(this).css({
'width': 'auto',
'height': 'auto'
});
$this.content.addClass('ui-lightbox-loading');
});
$this.caption.slideUp();
}
window.setTimeout(function() {
$this.imageDisplay.attr('src', link.attr('href'));
$this.current = link.index();
var title = link.attr('title');
if(title) {
$this.captionText.html(title);
}
}, 1000);
e.preventDefault();
});
},
_scaleImage: function(image) {
var win = $(window),
winWidth = win.width(),
winHeight = win.height(),
imageWidth = image.width(),
imageHeight = image.height(),
ratio = imageHeight / imageWidth;
if(imageWidth >= winWidth && ratio <= 1){
imageWidth = winWidth * 0.75;
imageHeight = imageWidth * ratio;
}
else if(imageHeight >= winHeight){
imageHeight = winHeight * 0.75;
imageWidth = imageHeight / ratio;
}
image.css({
'width':imageWidth + 'px',
'height':imageHeight + 'px'
});
},
_setupInline: function() {
this.links = this.element.children('a');
this.inline = this.element.children('div').addClass('ui-lightbox-inline');
this.inline.appendTo(this.content).show();
var $this = this;
this.links.on('click.ui-lightbox', function(e) {
$this.show();
var title = $(this).attr('title');
if(title) {
$this.captionText.html(title);
$this.caption.slideDown();
}
e.preventDefault();
});
},
_setupIframe: function() {
var $this = this;
this.links = this.element;
this.iframe = $('<iframe frameborder="0" style="width:' + this.options.iframeWidth + 'px;height:' +
this.options.iframeHeight + 'px;border:0 none; display: block;"></iframe>').appendTo(this.content);
if(this.options.iframeTitle) {
this.iframe.attr('title', this.options.iframeTitle);
}
this.element.click(function(e) {
if(!$this.iframeLoaded) {
$this.content.addClass('ui-lightbox-loading').css({
width: $this.options.iframeWidth,
height: $this.options.iframeHeight
});
$this.show();
$this.iframe.on('load', function() {
$this.iframeLoaded = true;
$this.content.removeClass('ui-lightbox-loading');
})
.attr('src', $this.element.attr('href'));
}
else {
$this.show();
}
var title = $this.element.attr('title');
if(title) {
$this.caption.html(title);
$this.caption.slideDown();
}
e.preventDefault();
});
},
show: function() {
this.center();
this.panel.css('z-index', ++PUI.zindex).show();
if(!this.modality) {
this._enableModality();
}
this._trigger('show');
},
hide: function() {
this.panel.fadeOut();
this._disableModality();
this.caption.hide();
if(this.options.mode === 'image') {
this.imageDisplay.hide().attr('src', '').removeAttr('style');
this._hideNavigators();
}
this._trigger('hide');
},
center: function() {
var win = $(window),
left = (win.width() / 2 ) - (this.panel.width() / 2),
top = (win.height() / 2 ) - (this.panel.height() / 2);
this.panel.css({
'left': left,
'top': top
});
},
_enableModality: function() {
this.modality = $('<div class="ui-widget-overlay"></div>')
.css({
'width': $(document).width(),
'height': $(document).height(),
'z-index': this.panel.css('z-index') - 1
})
.appendTo(document.body);
},
_disableModality: function() {
this.modality.remove();
this.modality = null;
},
_showNavigators: function() {
this.navigators.zIndex(this.imageDisplay.zIndex() + 1).show();
},
_hideNavigators: function() {
this.navigators.hide();
},
isHidden: function() {
return this.panel.is(':hidden');
},
showURL: function(opt) {
if(opt.width) {
this.iframe.attr('width', opt.width);
}
if(opt.height) {
this.iframe.attr('height', opt.height);
}
this.iframe.attr('src', opt.src);
this.show();
}
});
})();/**
* PrimeUI listvox widget
*/
(function() {
$.widget("primeui.puilistbox", {
options: {
value: null,
scrollHeight: 200,
content: null,
data: null,
template: null,
style: null,
styleClass: null,
multiple: false,
enhanced: false,
change: null
},
_create: function() {
if(!this.options.enhanced) {
this.element.wrap('<div class="ui-listbox ui-inputtext ui-widget ui-widget-content ui-corner-all"><div class="ui-helper-hidden-accessible"></div></div>');
this.container = this.element.parent().parent();
this.listContainer = $('<ul class="ui-listbox-list"></ul>').appendTo(this.container);
if(this.options.data) {
this._populateInputFromData();
}
this._populateContainerFromOptions();
}
else {
this.container = this.element.parent().parent();
this.listContainer = this.container.children('ul').addClass('ui-listbox-list');
this.items = this.listContainer.children('li').addClass('ui-listbox-item ui-corner-all');
this.choices = this.element.children('option');
}
if(this.options.style) {
this.container.attr('style', this.options.style);
}
if(this.options.styleClass) {
this.container.addClass(this.options.styleClass);
}
if(this.options.multiple)
this.element.prop('multiple', true);
else
this.options.multiple = this.element.prop('multiple');
//preselection
if(this.options.value !== null && this.options.value !== undefined) {
this._updateSelection(this.options.value);
}
this._restrictHeight();
this._bindEvents();
},
_populateInputFromData: function() {
for(var i = 0; i < this.options.data.length; i++) {
var choice = this.options.data[i];
if(choice.label) {
this.element.append('<option value="' + choice.value + '">' + choice.label + '</option>');
} else {
this.element.append('<option value="' + choice + '">' + choice + '</option>');
}
}
},
_populateContainerFromOptions: function() {
this.choices = this.element.children('option');
for(var i = 0; i < this.choices.length; i++) {
var choice = this.choices.eq(i);
this.listContainer.append('<li class="ui-listbox-item ui-corner-all">' + this._createItemContent(choice.get(0)) + '</li>');
}
this.items = this.listContainer.find('.ui-listbox-item:not(.ui-state-disabled)');
},
_restrictHeight: function() {
if(this.container.height() > this.options.scrollHeight) {
this.container.height(this.options.scrollHeight);
}
},
_bindEvents: function() {
var $this = this;
//items
this._bindItemEvents(this.items);
//input
this.element.on('focus.puilistbox', function() {
$this.container.addClass('ui-state-focus');
}).on('blur.puilistbox', function() {
$this.container.removeClass('ui-state-focus');
});
},
_bindItemEvents: function(item) {
var $this = this;
item.on('mouseover.puilistbox', function() {
var item = $(this);
if(!item.hasClass('ui-state-highlight')) {
item.addClass('ui-state-hover');
}
})
.on('mouseout.puilistbox', function() {
$(this).removeClass('ui-state-hover');
})
.on('dblclick.puilistbox', function(e) {
$this.element.trigger('dblclick');
PUI.clearSelection();
e.preventDefault();
})
.on('click.puilistbox', function(e) {
if($this.options.multiple)
$this._clickMultiple(e, $(this));
else
$this._clickSingle(e, $(this));
});
},
_unbindEvents: function() {
this._unbindItemEvents();
this.element.off('focus.puilistbox blur.puilistbox');
},
_unbindItemEvents: function() {
this.items.off('mouseover.puilistbox mouseout.puilistbox dblclick.puilistbox click.puilistbox');
},
_clickSingle: function(event, item) {
var selectedItem = this.items.filter('.ui-state-highlight');
if(item.index() !== selectedItem.index()) {
if(selectedItem.length) {
this.unselectItem(selectedItem);
}
this.selectItem(item);
this._trigger('change', event, {
value: this.choices.eq(item.index()).attr('value'),
index: item.index()
});
}
this.element.trigger('click');
PUI.clearSelection();
event.preventDefault();
},
_clickMultiple: function(event, item) {
var selectedItems = this.items.filter('.ui-state-highlight'),
metaKey = (event.metaKey||event.ctrlKey),
unchanged = (!metaKey && selectedItems.length === 1 && selectedItems.index() === item.index());
if(!event.shiftKey) {
if(!metaKey) {
this.unselectAll();
}
if(metaKey && item.hasClass('ui-state-highlight')) {
this.unselectItem(item);
}
else {
this.selectItem(item);
this.cursorItem = item;
}
}
else {
//range selection
if(this.cursorItem) {
this.unselectAll();
var currentItemIndex = item.index(),
cursorItemIndex = this.cursorItem.index(),
startIndex = (currentItemIndex > cursorItemIndex) ? cursorItemIndex : currentItemIndex,
endIndex = (currentItemIndex > cursorItemIndex) ? (currentItemIndex + 1) : (cursorItemIndex + 1);
for(var i = startIndex ; i < endIndex; i++) {
this.selectItem(this.items.eq(i));
}
}
else {
this.selectItem(item);
this.cursorItem = item;
}
}
if(!unchanged) {
var values = [],
indexes = [];
for(var i = 0; i < this.choices.length; i++) {
if(this.choices.eq(i).prop('selected')) {
values.push(this.choices.eq(i).attr('value'));
indexes.push(i);
}
}
this._trigger('change', event, {
value: values,
index: indexes
})
}
this.element.trigger('click');
PUI.clearSelection();
event.preventDefault();
},
unselectAll: function() {
this.items.removeClass('ui-state-highlight ui-state-hover');
this.choices.filter(':selected').prop('selected', false);
},
selectItem: function(value) {
var item = null;
if($.type(value) === 'number') {
item = this.items.eq(value);
}
else {
item = value;
}
item.addClass('ui-state-highlight').removeClass('ui-state-hover');
this.choices.eq(item.index()).prop('selected', true);
this._trigger('itemSelect', null, this.choices.eq(item.index()));
},
unselectItem: function(value) {
var item = null;
if($.type(value) === 'number') {
item = this.items.eq(value);
}
else {
item = value;
}
item.removeClass('ui-state-highlight');
this.choices.eq(item.index()).prop('selected', false);
this._trigger('itemUnselect', null, this.choices.eq(item.index()));
},
_setOption: function (key, value) {
if (key === 'data') {
this.element.empty();
this.listContainer.empty();
this._populateInputFromData();
this._populateContainerFromOptions();
this._restrictHeight();
this._bindEvents();
}
else if (key === 'value') {
this._updateSelection(value);
}
else if (key === 'options') {
this._updateOptions(value);
}
else {
$.Widget.prototype._setOption.apply(this, arguments);
}
},
disable: function () {
this._unbindEvents();
this.items.addClass('ui-state-disabled');
},
enable: function () {
this._bindEvents();
this.items.removeClass('ui-state-disabled');
},
_createItemContent: function(choice) {
if(this.options.template) {
var template = this.options.template.html();
Mustache.parse(template);
return Mustache.render(template, choice);
}
else if(this.options.content) {
return this.options.content.call(this, choice);
}
else {
return choice.label;
}
},
_updateSelection: function(value) {
this.choices.prop('selected', false);
this.items.removeClass('ui-state-highlight');
for(var i = 0; i < this.choices.length; i++) {
var choice = this.choices.eq(i);
if(this.options.multiple) {
if($.inArray(choice.attr('value'), value) >= 0) {
choice.prop('selected', true);
this.items.eq(i).addClass('ui-state-highlight');
}
}
else {
if(choice.attr('value') == value) {
choice.prop('selected', true);
this.items.eq(i).addClass('ui-state-highlight');
break;
}
}
}
},
//primeng
_updateOptions: function(options) {
var $this = this;
setTimeout(function() {
$this.items = $this.listContainer.children('li').addClass('ui-listbox-item ui-corner-all');
$this.choices = $this.element.children('option');
$this._unbindItemEvents();
$this._bindItemEvents(this.items);
}, 50);
},
_destroy: function() {
this._unbindEvents();
if(!this.options.enhanced) {
this.listContainer.remove();
this.element.unwrap().unwrap();
}
if(this.options.style) {
this.container.removeAttr('style');
}
if(this.options.styleClass) {
this.container.removeClass(this.options.styleClass);
}
if(this.options.multiple) {
this.element.prop('multiple', false);
}
if(this.choices) {
this.choices.prop('selected', false);
}
},
removeAllOptions: function() {
this.element.empty();
this.listContainer.empty();
this.container.empty();
this.element.val('');
},
addOption: function(value,label) {
var newListItem;
if(this.options.content) {
var option = (label) ? {'label':label,'value':value}: {'label':value,'value':value};
newListItem = $('<li class="ui-listbox-item ui-corner-all"></li>').append(this.options.content(option)).appendTo(this.listContainer);
}
else {
var listLabel = (label) ? label: value;
newListItem = $('<li class="ui-listbox-item ui-corner-all">' + listLabel + '</li>').appendTo(this.listContainer);
}
if(label)
this.element.append('<option value="' + value + '">' + label + '</option>');
else
this.element.append('<option value="' + value + '">' + value + '</option>');
this._bindItemEvents(newListItem);
this.choices = this.element.children('option');
this.items = this.items.add(newListItem);
}
});
})();
/**
* PrimeUI BaseMenu widget
*/
(function() {
$.widget("primeui.puibasemenu", {
options: {
popup: false,
trigger: null,
my: 'left top',
at: 'left bottom',
triggerEvent: 'click'
},
_create: function() {
if(this.options.popup) {
this._initPopup();
}
},
_initPopup: function() {
var $this = this;
this.element.closest('.ui-menu').addClass('ui-menu-dynamic ui-shadow').appendTo(document.body);
if($.type(this.options.trigger) === 'string') {
this.options.trigger = $(this.options.trigger);
}
this.positionConfig = {
my: this.options.my,
at: this.options.at,
of: this.options.trigger
};
this.options.trigger.on(this.options.triggerEvent + '.ui-menu', function(e) {
if($this.element.is(':visible')) {
$this.hide();
}
else {
$this.show();
}
e.preventDefault();
});
//hide overlay on document click
$(document.body).on('click.ui-menu-' + this.id, function (e) {
var popup = $this.element.closest('.ui-menu');
if(popup.is(":hidden")) {
return;
}
//do nothing if mousedown is on trigger
var target = $(e.target);
if(target.is($this.options.trigger.get(0))||$this.options.trigger.has(target).length > 0) {
return;
}
//hide if mouse is outside of overlay except trigger
var offset = popup.offset();
if(e.pageX < offset.left ||
e.pageX > offset.left + popup.width() ||
e.pageY < offset.top ||
e.pageY > offset.top + popup.height()) {
$this.hide(e);
}
});
//Hide overlay on resize
$(window).on('resize.ui-menu-' + this.id, function() {
if($this.element.closest('.ui-menu').is(':visible')) {
$this.align();
}
});
},
show: function() {
this.align();
this.element.closest('.ui-menu').css('z-index', ++PUI.zindex).show();
},
hide: function() {
this.element.closest('.ui-menu').fadeOut('fast');
},
align: function() {
this.element.closest('.ui-menu').css({left:'', top:''}).position(this.positionConfig);
},
_destroy: function() {
if(this.options.popup) {
$(document.body).off('click.ui-menu-' + this.id);
$(window).off('resize.ui-menu-' + this.id);
this.options.trigger.off(this.options.triggerEvent + '.ui-menu');
}
}
});
})();
/**
* PrimeUI Menu widget
*/
(function() {
$.widget("primeui.puimenu", $.primeui.puibasemenu, {
options: {
enhanced: false
},
_create: function() {
var $this = this;
this.id = this.element.attr('id');
if(!this.id) {
this.id = this.element.uniqueId().attr('id');
}
if(!this.options.enhanced) {
this.element.wrap('<div class="ui-menu ui-widget ui-widget-content ui-corner-all ui-helper-clearfix"></div>');
}
this.container = this.element.parent();
this.originalParent = this.container.parent();
this.element.addClass('ui-menu-list ui-helper-reset');
this.element.children('li').each(function() {
var listItem = $(this);
if(listItem.children('h3').length > 0) {
listItem.addClass('ui-widget-header ui-corner-all');
}
else {
listItem.addClass('ui-menuitem ui-widget ui-corner-all');
var menuitemLink = listItem.children('a'),
icon = menuitemLink.data('icon');
menuitemLink.addClass('ui-menuitem-link ui-corner-all');
if($this.options.enhanced)
menuitemLink.children('span').addClass('ui-menuitem-text');
else
menuitemLink.contents().wrap('<span class="ui-menuitem-text" />');
if(icon) {
menuitemLink.prepend('<span class="ui-menuitem-icon fa fa-fw ' + icon + '"></span>');
}
}
});
this.menuitemLinks = this.element.find('.ui-menuitem-link:not(.ui-state-disabled)');
this._bindEvents();
this._super();
},
_bindEvents: function() {
var $this = this;
this.menuitemLinks.on('mouseenter.ui-menu', function(e) {
$(this).addClass('ui-state-hover');
})
.on('mouseleave.ui-menu', function(e) {
$(this).removeClass('ui-state-hover');
});
if(this.options.popup) {
this.menuitemLinks.on('click.ui-menu', function() {
$this.hide();
});
}
},
_unbindEvents: function() {
this.menuitemLinks.off('mouseenter.ui-menu mouseleave.ui-menu');
if(this.options.popup) {
this.menuitemLinks.off('click.ui-menu');
}
},
_destroy: function() {
this._super();
var $this = this;
this._unbindEvents();
this.element.removeClass('ui-menu-list ui-helper-reset');
this.element.children('li.ui-widget-header').removeClass('ui-widget-header ui-corner-all');
this.element.children('li:not(.ui-widget-header)').removeClass('ui-menuitem ui-widget ui-corner-all')
.children('a').removeClass('ui-menuitem-link ui-corner-all').each(function() {
var link = $(this);
link.children('.ui-menuitem-icon').remove();
if($this.options.enhanced)
link.children('.ui-menuitem-text').removeClass('ui-menuitem-text');
else
link.children('.ui-menuitem-text').contents().unwrap();
});
if(this.options.popup) {
this.container.appendTo(this.originalParent);
}
if(!this.options.enhanced) {
this.element.unwrap();
}
}
});
})();
/**
* PrimeUI BreadCrumb Widget
*/
(function() {
$.widget("primeui.puibreadcrumb", {
_create: function() {
var $this = this;
if(!this.options.enhanced) {
this.element.wrap('<div class="ui-breadcrumb ui-module ui-widget ui-widget-header ui-helper-clearfix ui-corner-all" role="menu">');
}
this.element.children('li').each(function(index) {
var listItem = $(this);
listItem.attr('role', 'menuitem');
var menuitemLink = listItem.children('a');
menuitemLink.addClass('ui-menuitem-link');
if($this.options.enhanced)
menuitemLink.children('span').addClass('ui-menuitem-text');
else
menuitemLink.contents().wrap('<span class="ui-menuitem-text" />');
if(index > 0) {
listItem.before('<li class="ui-breadcrumb-chevron fa fa-chevron-right"></li>');
}
else {
listItem.before('<li class="fa fa-home"></li>');
}
});
},
_destroy: function() {
var $this = this;
if(!this.options.enhanced) {
this.unwrap();
}
this.element.children('li.ui-breadcrumb-chevron,.fa-home').remove();
this.element.children('li').each(function() {
var listItem = $(this),
link = listItem.children('a');
link.removeClass('ui-menuitem-link');
if($this.options.enhanced)
link.children('.ui-menuitem-text').removeClass('ui-menuitem-text');
else
link.children('.ui-menuitem-text').contents().unwrap();
});
}
});
})();
/*
* PrimeUI TieredMenu Widget
*/
(function() {
$.widget("primeui.puitieredmenu", $.primeui.puibasemenu, {
options: {
autoDisplay: true
},
_create: function() {
var $this = this;
this.id = this.element.attr('id');
if(!this.id) {
this.id = this.element.uniqueId().attr('id');
}
if(!this.options.enhanced) {
this.element.wrap('<div class="ui-tieredmenu ui-menu ui-widget ui-widget-content ui-corner-all ui-helper-clearfix"></div>');
}
this.container = this.element.parent();
this.originalParent = this.container.parent();
this.element.addClass('ui-menu-list ui-helper-reset');
this.element.find('li').each(function() {
var listItem = $(this),
menuitemLink = listItem.children('a'),
icon = menuitemLink.data('icon');
menuitemLink.addClass('ui-menuitem-link ui-corner-all');
if($this.options.enhanced)
menuitemLink.children('span').addClass('ui-menuitem-text');
else
menuitemLink.contents().wrap('<span class="ui-menuitem-text" />');
if(icon) {
menuitemLink.prepend('<span class="ui-menuitem-icon fa fa-fw ' + icon + '"></span>');
}
listItem.addClass('ui-menuitem ui-widget ui-corner-all');
if(listItem.children('ul').length > 0) {
var submenuIcon = listItem.parent().hasClass('ui-menu-child') ? 'fa-caret-right' : $this._getRootSubmenuIcon();
listItem.addClass('ui-menu-parent');
listItem.children('ul').addClass('ui-widget-content ui-menu-list ui-corner-all ui-helper-clearfix ui-menu-child ui-shadow');
menuitemLink.prepend('<span class="ui-submenu-icon fa fa-fw ' + submenuIcon + '"></span>');
}
});
this.links = this.element.find('.ui-menuitem-link:not(.ui-state-disabled)');
this._bindEvents();
this._super();
},
_bindEvents: function() {
this._bindItemEvents();
this._bindDocumentHandler();
},
_bindItemEvents: function() {
var $this = this;
this.links.on('mouseenter.ui-menu', function() {
var link = $(this),
menuitem = link.parent(),
autoDisplay = $this.options.autoDisplay;
var activeSibling = menuitem.siblings('.ui-menuitem-active');
if(activeSibling.length === 1) {
$this._deactivate(activeSibling);
}
if(autoDisplay||$this.active) {
if(menuitem.hasClass('ui-menuitem-active')) {
$this._reactivate(menuitem);
}
else {
$this._activate(menuitem);
}
}
else {
$this._highlight(menuitem);
}
});
if(this.options.autoDisplay === false) {
this.rootLinks = this.element.find('> .ui-menuitem > .ui-menuitem-link');
this.rootLinks.data('primeui-tieredmenu-rootlink', this.id).find('*').data('primeui-tieredmenu-rootlink', this.id);
this.rootLinks.on('click.ui-menu', function(e) {
var link = $(this),
menuitem = link.parent(),
submenu = menuitem.children('ul.ui-menu-child');
if(submenu.length === 1) {
if(submenu.is(':visible')) {
$this.active = false;
$this._deactivate(menuitem);
}
else {
$this.active = true;
$this._highlight(menuitem);
$this._showSubmenu(menuitem, submenu);
}
}
});
}
this.element.parent().find('ul.ui-menu-list').on('mouseleave.ui-menu', function(e) {
if($this.activeitem) {
$this._deactivate($this.activeitem);
}
e.stopPropagation();
});
},
_bindDocumentHandler: function() {
var $this = this;
$(document.body).on('click.ui-menu-' + this.id, function(e) {
var target = $(e.target);
if(target.data('primeui-tieredmenu-rootlink') === $this.id) {
return;
}
$this.active = false;
$this.element.find('li.ui-menuitem-active').each(function() {
$this._deactivate($(this), true);
});
});
},
_unbindEvents: function() {
this.links.off('mouseenter.ui-menu');
if(this.options.autoDisplay === false) {
this.rootLinks.off('click.ui-menu');
}
this.element.parent().find('ul.ui-menu-list').off('mouseleave.ui-menu');
$(document.body).off('click.ui-menu-' + this.id);
},
_deactivate: function(menuitem, animate) {
this.activeitem = null;
menuitem.children('a.ui-menuitem-link').removeClass('ui-state-hover');
menuitem.removeClass('ui-menuitem-active');
if(animate) {
menuitem.children('ul.ui-menu-child:visible').fadeOut('fast');
}
else {
menuitem.children('ul.ui-menu-child:visible').hide();
}
},
_activate: function(menuitem) {
this._highlight(menuitem);
var submenu = menuitem.children('ul.ui-menu-child');
if(submenu.length === 1) {
this._showSubmenu(menuitem, submenu);
}
},
_reactivate: function(menuitem) {
this.activeitem = menuitem;
var submenu = menuitem.children('ul.ui-menu-child'),
activeChilditem = submenu.children('li.ui-menuitem-active:first'),
_self = this;
if(activeChilditem.length === 1) {
_self._deactivate(activeChilditem);
}
},
_highlight: function(menuitem) {
this.activeitem = menuitem;
menuitem.children('a.ui-menuitem-link').addClass('ui-state-hover');
menuitem.addClass('ui-menuitem-active');
},
_showSubmenu: function(menuitem, submenu) {
submenu.css({
'left': menuitem.outerWidth(),
'top': 0,
'z-index': ++PUI.zindex
});
submenu.show();
},
_getRootSubmenuIcon: function() {
return 'fa-caret-right';
},
_destroy: function() {
this._super();
var $this = this;
this._unbindEvents();
this.element.removeClass('ui-menu-list ui-helper-reset');
this.element.find('li').removeClass('ui-menuitem ui-widget ui-corner-all ui-menu-parent').each(function() {
var listItem = $(this),
link = listItem.children('a');
link.removeClass('ui-menuitem-link ui-corner-all').children('.fa').remove();
if($this.options.enhanced)
link.children('.ui-menuitem-text').removeClass('ui-menuitem-text');
else
link.children('.ui-menuitem-text').contents().unwrap();
listItem.children('ul').removeClass('ui-widget-content ui-menu-list ui-corner-all ui-helper-clearfix ui-menu-child ui-shadow');
});
if(this.options.popup) {
this.container.appendTo(this.originalParent);
}
if(!this.options.enhanced) {
this.element.unwrap();
}
}
});
})();
/**
* PrimeUI Menubar Widget
*/
(function() {
$.widget("primeui.puimenubar", $.primeui.puitieredmenu, {
options: {
autoDisplay: true,
enhanced: false
},
_create: function() {
this._super();
if(!this.options.enhanced) {
this.element.parent().removeClass('ui-tieredmenu').addClass('ui-menubar');
}
},
_showSubmenu: function(menuitem, submenu) {
var win = $(window),
submenuOffsetTop = null,
submenuCSS = {
'z-index': ++PUI.zindex
};
if(menuitem.parent().hasClass('ui-menu-child')) {
submenuCSS.left = menuitem.outerWidth();
submenuCSS.top = 0;
submenuOffsetTop = menuitem.offset().top - win.scrollTop();
}
else {
submenuCSS.left = 0;
submenuCSS.top = menuitem.outerHeight();
submenuOffsetTop = menuitem.offset().top + submenuCSS.top - win.scrollTop();
}
//adjust height within viewport
submenu.css('height', 'auto');
if((submenuOffsetTop + submenu.outerHeight()) > win.height()) {
submenuCSS.overflow = 'auto';
submenuCSS.height = win.height() - (submenuOffsetTop + 20);
}
submenu.css(submenuCSS).show();
},
_getRootSubmenuIcon: function() {
return 'fa-caret-down';
}
});
})();
/*
* PrimeUI SlideMenu Widget
*/
(function() {
$.widget("primeui.puislidemenu", $.primeui.puibasemenu, {
_create: function() {
this.id = this.element.attr('id');
if(!this.id) {
this.id = this.element.uniqueId().attr('id');
}
this._render();
//elements
this.rootList = this.element;
this.content = this.element.parent();
this.wrapper = this.content.parent();
this.container = this.wrapper.parent();
this.originalParent = this.container.parent();
this.submenus = this.container.find('ul.ui-menu-list');
this.links = this.element.find('a.ui-menuitem-link:not(.ui-state-disabled)');
this.backward = this.wrapper.children('div.ui-slidemenu-backward');
//config
this.stack = [];
this.jqWidth = this.container.width();
if(!this.options.popup) {
var $this = this;
setTimeout(function() {
$this._applyDimensions();
}, 100);
}
this._bindEvents();
this._super();
},
_render: function() {
var $this = this;
if(!this.options.enhanced) {
this.element.wrap('<div class="ui-menu ui-slidemenu ui-widget ui-widget-content ui-corner-all"></div>')
.wrap('<div class="ui-slidemenu-wrapper"></div>')
.wrap('<div class="ui-slidemenu-content"></div>');
this.element.parent().after('<div class="ui-slidemenu-backward ui-widget-header ui-corner-all"><span class="fa fa-fw fa-caret-left"></span>Back</div>');
}
this.element.addClass('ui-menu-list ui-helper-reset');
this.element.find('li').each(function() {
var listItem = $(this),
menuitemLink = listItem.children('a'),
icon = menuitemLink.data('icon');
menuitemLink.addClass('ui-menuitem-link ui-corner-all');
if($this.options.enhanced)
menuitemLink.children('span').addClass('ui-menuitem-text');
else
menuitemLink.contents().wrap('<span class="ui-menuitem-text" />');
if(icon) {
menuitemLink.prepend('<span class="ui-menuitem-icon fa fa-fw ' + icon + '"></span>');
}
listItem.addClass('ui-menuitem ui-widget ui-corner-all');
if(listItem.children('ul').length) {
listItem.addClass('ui-menu-parent');
listItem.children('ul').addClass('ui-widget-content ui-menu-list ui-corner-all ui-helper-clearfix ui-menu-child ui-shadow');
menuitemLink.prepend('<span class="ui-submenu-icon fa fa-fw fa-caret-right"></span>');
}
});
},
_destroy: function() {
this._super();
this._unbindEvents();
var $this = this;
this.element.removeClass('ui-menu-list ui-helper-reset');
this.element.find('li').removeClass('ui-menuitem ui-widget ui-corner-all ui-menu-parent').each(function() {
var listItem = $(this),
link = listItem.children('a');
link.removeClass('ui-menuitem-link ui-corner-all').children('.fa').remove();
if($this.options.enhanced)
link.children('.ui-menuitem-text').removeClass('ui-menuitem-text');
else
link.children('.ui-menuitem-text').contents().unwrap();
listItem.children('ul').removeClass('ui-widget-content ui-menu-list ui-corner-all ui-helper-clearfix ui-menu-child ui-shadow');
});
if(this.options.popup) {
this.container.appendTo(this.originalParent);
}
if(!this.options.enhanced) {
this.content.next('.ui-slidemenu-backward').remove();
this.element.unwrap().unwrap().unwrap();
}
},
_bindEvents: function() {
var $this = this;
this.links.on('mouseenter.ui-menu',function() {
$(this).addClass('ui-state-hover');
})
.on('mouseleave.ui-menu',function() {
$(this).removeClass('ui-state-hover');
})
.on('click.ui-menu',function() {
var link = $(this),
submenu = link.next();
if(submenu.length == 1) {
$this._forward(submenu);
}
});
this.backward.on('click.ui-menu',function() {
$this._back();
});
},
_unbindEvents: function() {
this.links.off('mouseenter.ui-menu mouseleave.ui-menu click.ui-menu');
this.backward.off('click.ui-menu');
},
_forward: function(submenu) {
var $this = this;
this._push(submenu);
var rootLeft = -1 * (this._depth() * this.jqWidth);
submenu.show().css({
left: this.jqWidth
});
this.rootList.animate({
left: rootLeft
}, 500, 'easeInOutCirc', function() {
if($this.backward.is(':hidden')) {
$this.backward.fadeIn('fast');
}
});
},
_back: function() {
if(!this.rootList.is(':animated')) {
var $this = this,
last = this._pop(),
depth = this._depth();
var rootLeft = -1 * (depth * this.jqWidth);
this.rootList.animate({
left: rootLeft
}, 500, 'easeInOutCirc', function() {
if(last) {
last.hide();
}
if(depth === 0) {
$this.backward.fadeOut('fast');
}
});
}
},
_push: function(submenu) {
this.stack.push(submenu);
},
_pop: function() {
return this.stack.pop();
},
_last: function() {
return this.stack[this.stack.length - 1];
},
_depth: function() {
return this.stack.length;
},
_applyDimensions: function() {
this.submenus.width(this.container.width());
this.wrapper.height(this.rootList.outerHeight(true) + this.backward.outerHeight(true));
this.content.height(this.rootList.outerHeight(true));
this.rendered = true;
},
show: function() {
this.align();
this.container.css('z-index', ++PUI.zindex).show();
if(!this.rendered) {
this._applyDimensions();
}
}
});
})();
/**
* PrimeUI Context Menu Widget
*/
(function() {
$.widget("primeui.puicontextmenu", $.primeui.puitieredmenu, {
options: {
autoDisplay: true,
target: null,
event: 'contextmenu'
},
_create: function() {
this._super();
this.element.parent().removeClass('ui-tieredmenu').
addClass('ui-contextmenu ui-menu-dynamic ui-shadow');
var $this = this;
if(this.options.target) {
if($.type(this.options.target) === 'string') {
this.options.target = $(this.options.target);
}
}
else {
this.options.target = $(document);
}
if(!this.element.parent().parent().is(document.body)) {
this.element.parent().appendTo('body');
}
if(this.options.target.hasClass('ui-datatable')) {
$this._bindDataTable();
}
else {
this.options.target.on(this.options.event + '.ui-contextmenu', function(e){
$this.show(e);
});
}
},
_bindItemEvents: function() {
this._super();
var $this = this;
//hide menu on item click
this.links.on('click.ui-contextmenu', function() {
$this._hide();
});
},
_bindDocumentHandler: function() {
var $this = this;
//hide overlay when document is clicked
$(document.body).on('click.ui-contextmenu.' + this.id, function (e) {
if($this.element.parent().is(":hidden")) {
return;
}
$this._hide();
});
},
_bindDataTable: function() {
var rowSelector = '#' + this.options.target.attr('id') + ' tbody.ui-datatable-data > tr.ui-widget-content:not(.ui-datatable-empty-message)',
event = this.options.event + '.ui-datatable',
$this = this;
$(document).off(event, rowSelector)
.on(event, rowSelector, null, function(e) {
$this.options.target.puidatatable('onRowRightClick', event, $(this));
$this.show(e);
});
},
_unbindDataTable: function() {
$(document).off(this.options.event + '.ui-datatable',
'#' + this.options.target.attr('id') + ' tbody.ui-datatable-data > tr.ui-widget-content:not(.ui-datatable-empty-message)');
},
_unbindEvents: function() {
this._super();
this.options.target.off(this.options.event + '.ui-contextmenu');
this.links.off('click.ui-contextmenu');
$(document.body).off('click.ui-contextmenu.' + this.id);
if(this.options.target.hasClass('ui-datatable')) {
this._unbindDataTable();
}
},
show: function(e) {
//hide other contextmenus if any
$(document.body).children('.ui-contextmenu:visible').hide();
var win = $(window),
left = e.pageX,
top = e.pageY,
width = this.element.parent().outerWidth(),
height = this.element.parent().outerHeight();
//collision detection for window boundaries
if((left + width) > (win.width())+ win.scrollLeft()) {
left = left - width;
}
if((top + height ) > (win.height() + win.scrollTop())) {
top = top - height;
}
if(this.options.beforeShow) {
this.options.beforeShow.call(this);
}
this.element.parent().css({
'left': left,
'top': top,
'z-index': ++PUI.zindex
}).show();
e.preventDefault();
e.stopPropagation();
},
_hide: function() {
var $this = this;
//hide submenus
this.element.parent().find('li.ui-menuitem-active').each(function() {
$this._deactivate($(this), true);
});
this.element.parent().fadeOut('fast');
},
isVisible: function() {
return this.element.parent().is(':visible');
},
getTarget: function() {
return this.jqTarget;
},
_destroy: function() {
var $this = this;
this._unbindEvents();
this.element.removeClass('ui-menu-list ui-helper-reset');
this.element.find('li').removeClass('ui-menuitem ui-widget ui-corner-all ui-menu-parent').each(function() {
var listItem = $(this),
link = listItem.children('a');
link.removeClass('ui-menuitem-link ui-corner-all').children('.fa').remove();
if($this.options.enhanced)
link.children('.ui-menuitem-text').removeClass('ui-menuitem-text');
else
link.children('.ui-menuitem-text').contents().unwrap();
listItem.children('ul').removeClass('ui-widget-content ui-menu-list ui-corner-all ui-helper-clearfix ui-menu-child ui-shadow');
});
this.container.appendTo(this.originalParent);
if(!this.options.enhanced) {
this.element.unwrap();
}
}
});
})();
/*
* PrimeUI MegaMenu Widget
*/
(function() {
$.widget("primeui.puimegamenu", $.primeui.puibasemenu, {
options: {
autoDisplay: true,
orientation:'horizontal',
enhanced: false
},
_create: function() {
this.id = this.element.attr('id');
if(!this.id) {
this.id = this.element.uniqueId().attr('id');
}
this._render();
this.rootList = this.element.children('ul');
this.rootLinks = this.rootList.children('li').children('a');
this.subLinks = this.element.find('.ui-megamenu-panel a.ui-menuitem-link');
this.keyboardTarget = this.element.children('.ui-helper-hidden-accessible');
this._bindEvents();
this._bindKeyEvents();
},
_render: function() {
var $this = this;
if(!this.options.enhanced) {
this.element.prepend('<div tabindex="0" class="ui-helper-hidden-accessible"></div>');
this.element.addClass('ui-menu ui-menubar ui-megamenu ui-widget ui-widget-content ui-corner-all ui-helper-clearfix');
if(this._isVertical()) {
this.element.addClass('ui-megamenu-vertical');
}
}
this.element.children('ul').addClass('ui-menu-list ui-helper-reset');
this.element.find('li').each(function(){
var listItem = $(this),
menuitemLink = listItem.children('a'),
icon = menuitemLink.data('icon');
menuitemLink.addClass('ui-menuitem-link ui-corner-all');
if($this.options.enhanced)
menuitemLink.children('span').addClass('ui-menuitem-text');
else
menuitemLink.contents().wrap('<span class="ui-menuitem-text" />');
if(icon) {
menuitemLink.prepend('<span class="ui-menuitem-icon fa fa-fw ' + icon + '"></span>');
}
listItem.addClass('ui-menuitem ui-widget ui-corner-all');
listItem.parent().addClass('ui-menu-list ui-helper-reset');
if(listItem.children('h3').length) {
listItem.addClass('ui-widget-header ui-corner-all');
listItem.removeClass('ui-widget ui-menuitem');
}
else if(listItem.children('div').length) {
var submenuIcon = $this._isVertical() ? 'fa-caret-right' : 'fa-caret-down';
listItem.addClass('ui-menu-parent');
listItem.children('div').addClass('ui-megamenu-panel ui-widget-content ui-menu-list ui-corner-all ui-helper-clearfix ui-menu-child ui-shadow');
menuitemLink.addClass('ui-submenu-link').prepend('<span class="ui-submenu-icon fa fa-fw ' + submenuIcon + '"></span>');
}
});
},
_destroy: function() {
var $this = this;
this._unbindEvents();
if(!this.options.enhanced) {
this.element.children('.ui-helper-hidden-accessible').remove();
this.element.removeClass('ui-menu ui-menubar ui-megamenu ui-widget ui-widget-content ui-corner-all ui-helper-clearfix ui-megamenu-vertical');
}
this.element.find('li').each(function(){
var listItem = $(this),
menuitemLink = listItem.children('a');
menuitemLink.removeClass('ui-menuitem-link ui-corner-all');
if($this.options.enhanced)
menuitemLink.children('span').removeClass('ui-menuitem-text');
else
menuitemLink.contents().unwrap();
menuitemLink.children('.ui-menuitem-icon').remove();
listItem.removeClass('ui-menuitem ui-widget ui-corner-all')
.parent().removeClass('ui-menu-list ui-helper-reset');
if(listItem.children('h3').length) {
listItem.removeClass('ui-widget-header ui-corner-all');
}
else if(listItem.children('div').length) {
var submenuIcon = $this._isVertical() ? 'fa-caret-right' : 'fa-caret-down';
listItem.removeClass('ui-menu-parent');
listItem.children('div').removeClass('ui-megamenu-panel ui-widget-content ui-menu-list ui-corner-all ui-helper-clearfix ui-menu-child ui-shadow');
menuitemLink.removeClass('ui-submenu-link').children('.ui-submenu-icon').remove();
}
});
},
_bindEvents: function() {
var $this = this;
this.rootLinks.on('mouseenter.ui-megamenu', function(e) {
var link = $(this),
menuitem = link.parent();
var current = menuitem.siblings('.ui-menuitem-active');
if(current.length > 0) {
current.find('li.ui-menuitem-active').each(function() {
$this._deactivate($(this));
});
$this._deactivate(current, false);
}
if($this.options.autoDisplay||$this.active) {
$this._activate(menuitem);
}
else {
$this._highlight(menuitem);
}
});
if(this.options.autoDisplay === false) {
this.rootLinks.data('primefaces-megamenu', this.id).find('*').data('primefaces-megamenu', this.id)
this.rootLinks.on('click.ui-megamenu', function(e) {
var link = $(this),
menuitem = link.parent(),
submenu = link.next();
if(submenu.length === 1) {
if(submenu.is(':visible')) {
$this.active = false;
$this._deactivate(menuitem, true);
}
else {
$this.active = true;
$this._activate(menuitem);
}
}
e.preventDefault();
});
}
else {
this.rootLinks.filter('.ui-submenu-link').on('click.ui-megamenu', function(e) {
e.preventDefault();
});
}
this.subLinks.on('mouseenter.ui-megamenu', function() {
if($this.activeitem && !$this.isRootLink($this.activeitem)) {
$this._deactivate($this.activeitem);
}
$this._highlight($(this).parent());
})
.on('mouseleave.ui-megamenu', function() {
if($this.activeitem && !$this.isRootLink($this.activeitem)) {
$this._deactivate($this.activeitem);
}
$(this).removeClass('ui-state-hover');
});
this.rootList.on('mouseleave.ui-megamenu', function(e) {
var activeitem = $this.rootList.children('.ui-menuitem-active');
if(activeitem.length === 1) {
$this._deactivate(activeitem, false);
}
});
this.rootList.find('> li.ui-menuitem > ul.ui-menu-child').on('mouseleave.ui-megamenu', function(e) {
e.stopPropagation();
});
$(document.body).on('click.' + this.id, function(e) {
var target = $(e.target);
if(target.data('primefaces-megamenu') === $this.id) {
return;
}
$this.active = false;
$this._deactivate($this.rootList.children('li.ui-menuitem-active'), true);
});
},
_unbindEvents: function() {
this.rootLinks.off('mouseenter.ui-megamenu mouselave.ui-megamenu click.ui-megamenu');
this.subLinks.off('mouseenter.ui-megamenu mouselave.ui-megamenu');
this.rootList.off('mouseleave.ui-megamenu');
this.rootList.find('> li.ui-menuitem > ul.ui-menu-child').off('mouseleave.ui-megamenu');
$(document.body).off('click.' + this.id);
},
_isVertical: function () {
if(this.options.orientation === 'vertical')
return true;
else
return false;
},
_deactivate: function(menuitem, animate) {
var link = menuitem.children('a.ui-menuitem-link'),
submenu = link.next();
menuitem.removeClass('ui-menuitem-active');
link.removeClass('ui-state-hover');
this.activeitem = null;
if(submenu.length > 0) {
if(animate)
submenu.fadeOut('fast');
else
submenu.hide();
}
},
_activate: function(menuitem) {
var submenu = menuitem.children('.ui-megamenu-panel'),
$this = this;
$this._highlight(menuitem);
if(submenu.length > 0) {
$this._showSubmenu(menuitem, submenu);
}
},
_highlight: function(menuitem) {
var link = menuitem.children('a.ui-menuitem-link');
menuitem.addClass('ui-menuitem-active');
link.addClass('ui-state-hover');
this.activeitem = menuitem;
},
_showSubmenu: function(menuitem, submenu) {
var pos = null;
if(this._isVertical()) {
pos = {
my: 'left top',
at: 'right top',
of: menuitem,
collision: 'flipfit'
};
}
else {
pos = {
my: 'left top',
at: 'left bottom',
of: menuitem,
collision: 'flipfit'
};
}
submenu.css({
'z-index': ++PUI.zindex
});
submenu.show().position(pos);
},
_bindKeyEvents: function() {
var $this = this;
this.keyboardTarget.on('focus.ui-megamenu', function(e) {
$this._highlight($this.rootLinks.eq(0).parent());
})
.on('blur.ui-megamenu', function() {
$this._reset();
})
.on('keydown.ui-megamenu', function(e) {
var currentitem = $this.activeitem;
if(!currentitem) {
return;
}
var isRootLink = $this._isRootLink(currentitem),
keyCode = $.ui.keyCode;
switch(e.which) {
case keyCode.LEFT:
if(isRootLink && !$this._isVertical()) {
var prevItem = currentitem.prevAll('.ui-menuitem:first');
if(prevItem.length) {
$this._deactivate(currentitem);
$this._highlight(prevItem);
}
e.preventDefault();
}
else {
if(currentitem.hasClass('ui-menu-parent') && currentitem.children('.ui-menu-child').is(':visible')) {
$this._deactivate(currentitem);
$this._highlight(currentitem);
}
else {
var parentItem = currentitem.closest('.ui-menu-child').parent();
if(parentItem.length) {
$this._deactivate(currentitem);
$this._deactivate(parentItem);
$this._highlight(parentItem);
}
}
}
break;
case keyCode.RIGHT:
if(isRootLink && !$this._isVertical()) {
var nextItem = currentitem.nextAll('.ui-menuitem:visible:first');
if(nextItem.length) {
$this._deactivate(currentitem);
$this._highlight(nextItem);
}
e.preventDefault();
}
else {
if(currentitem.hasClass('ui-menu-parent')) {
var submenu = currentitem.children('.ui-menu-child');
if(submenu.is(':visible')) {
$this._highlight(submenu.find('.ui-menu-list:visible > .ui-menuitem:visible:first'));
}
else {
$this._activate(currentitem);
}
}
}
break;
case keyCode.UP:
if(!isRootLink || $this._isVertical()) {
var prevItem = $this._findPrevItem(currentitem);
if(prevItem.length) {
$this._deactivate(currentitem);
$this._highlight(prevItem);
}
}
e.preventDefault();
break;
case keyCode.DOWN:
if(isRootLink && !$this._isVertical()) {
var submenu = currentitem.children('.ui-menu-child');
if(submenu.is(':visible')) {
var firstMenulist = $this._getFirstMenuList(submenu);
$this._highlight(firstMenulist.children('.ui-menuitem:visible:first'));
}
else {
$this._activate(currentitem);
}
}
else {
var nextItem = $this._findNextItem(currentitem);
if(nextItem.length) {
$this._deactivate(currentitem);
$this._highlight(nextItem);
}
}
e.preventDefault();
break;
case keyCode.ENTER:
case keyCode.NUMPAD_ENTER:
var currentLink = currentitem.children('.ui-menuitem-link');
currentLink.trigger('click');
$this.element.blur();
var href = currentLink.attr('href');
if(href && href !== '#') {
window.location.href = href;
}
$this._deactivate(currentitem);
e.preventDefault();
break;
case keyCode.ESCAPE:
if(currentitem.hasClass('ui-menu-parent')) {
var submenu = currentitem.children('.ui-menu-list:visible');
if(submenu.length > 0) {
submenu.hide();
}
}
else {
var parentItem = currentitem.closest('.ui-menu-child').parent();
if(parentItem.length) {
$this._deactivate(currentitem);
$this._deactivate(parentItem);
$this._highlight(parentItem);
}
}
e.preventDefault();
break;
}
});
},
_findPrevItem: function(menuitem) {
var previtem = menuitem.prev('.ui-menuitem');
if(!previtem.length) {
var prevSubmenu = menuitem.closest('ul.ui-menu-list').prev('.ui-menu-list');
if(!prevSubmenu.length) {
prevSubmenu = menuitem.closest('div').prev('div').children('.ui-menu-list:visible:last');
}
if(prevSubmenu.length) {
previtem = prevSubmenu.find('li.ui-menuitem:visible:last');
}
}
return previtem;
},
_findNextItem: function(menuitem) {
var nextitem = menuitem.next('.ui-menuitem');
if(!nextitem.length) {
var nextSubmenu = menuitem.closest('ul.ui-menu-list').next('.ui-menu-list');
if(!nextSubmenu.length) {
nextSubmenu = menuitem.closest('div').next('div').children('.ui-menu-list:visible:first');
}
if(nextSubmenu.length) {
nextitem = nextSubmenu.find('li.ui-menuitem:visible:first');
}
}
return nextitem;
},
_getFirstMenuList: function(submenu) {
return submenu.find('.ui-menu-list:not(.ui-state-disabled):first');
},
_isRootLink: function(menuitem) {
var submenu = menuitem.closest('ul');
return submenu.parent().hasClass('ui-menu');
},
_reset: function() {
var $this = this;
this.active = false;
this.element.find('li.ui-menuitem-active').each(function() {
$this._deactivate($(this), true);
});
},
isRootLink: function(menuitem) {
var submenu = menuitem.closest('ul');
return submenu.parent().hasClass('ui-menu');
}
});
})();
/**
* PrimeUI PanelMenu Widget
*/
(function() {
$.widget("primeui.puipanelmenu", $.primeui.puibasemenu, {
options: {
stateful: false,
enhanced: false
},
_create: function() {
this.id = this.element.attr('id');
if(!this.id) {
this.id = this.element.uniqueId().attr('id');
}
this.panels = this.element.children('div');
this._render();
this.headers = this.element.find('> .ui-panelmenu-panel > div.ui-panelmenu-header:not(.ui-state-disabled)');
this.contents = this.element.find('> .ui-panelmenu-panel > .ui-panelmenu-content');
this.menuitemLinks = this.contents.find('.ui-menuitem-link:not(.ui-state-disabled)');
this.treeLinks = this.contents.find('.ui-menu-parent > .ui-menuitem-link:not(.ui-state-disabled)');
this._bindEvents();
if(this.options.stateful) {
this.stateKey = 'panelMenu-' + this.id;
}
this._restoreState();
},
_render: function() {
var $this = this;
if(!this.options.enhanced) {
this.element.addClass('ui-panelmenu ui-widget');
}
this.panels.addClass('ui-panelmenu-panel');
this.element.find('li').each(function(){
var listItem = $(this),
menuitemLink = listItem.children('a'),
icon = menuitemLink.data('icon');
menuitemLink.addClass('ui-menuitem-link ui-corner-all')
if($this.options.enhanced)
menuitemLink.children('span').addClass('ui-menuitem-text');
else
menuitemLink.contents().wrap('<span class="ui-menuitem-text" />');
if(icon) {
menuitemLink.prepend('<span class="ui-menuitem-icon fa fa-fw ' + icon + '"></span>');
}
if(listItem.children('ul').length) {
listItem.addClass('ui-menu-parent');
menuitemLink.prepend('<span class="ui-panelmenu-icon fa fa-fw fa-caret-right"></span>');
listItem.children('ul').addClass('ui-helper-hidden');
if(icon) {
menuitemLink.addClass('ui-menuitem-link-hasicon');
}
}
listItem.addClass('ui-menuitem ui-widget ui-corner-all');
listItem.parent().addClass('ui-menu-list ui-helper-reset');
});
//headers
this.panels.children(':first-child').attr('tabindex', '0').each(function () {
var header = $(this),
headerLink = header.children('a'),
icon = headerLink.data('icon');
if(icon) {
headerLink.addClass('ui-panelmenu-headerlink-hasicon').prepend('<span class="ui-menuitem-icon fa fa-fw ' + icon + '"></span>');
}
header.addClass('ui-widget ui-panelmenu-header ui-state-default ui-corner-all').prepend('<span class="ui-panelmenu-icon fa fa-fw fa-caret-right"></span>');
});
//contents
this.panels.children(':last-child').attr('tabindex', '0').addClass('ui-panelmenu-content ui-widget-content ui-helper-hidden');
},
_destroy: function() {
var $this = this;
this._unbindEvents();
if(!this.options.enhanced) {
this.element.removeClass('ui-panelmenu ui-widget');
}
this.panels.removeClass('ui-panelmenu-panel');
this.headers.removeClass('ui-widget ui-panelmenu-header ui-state-default ui-state-hover ui-state-active ui-corner-all ui-corner-top').removeAttr('tabindex');
this.contents.removeClass('ui-panelmenu-content ui-widget-content ui-helper-hidden').removeAttr('tabindex')
this.contents.find('ul').removeClass('ui-menu-list ui-helper-reset ui-helper-hidden');
this.headers.each(function () {
var header = $(this),
headerLink = header.children('a');
header.children('.fa').remove();
headerLink.removeClass('ui-panelmenu-headerlink-hasicon');
headerLink.children('.fa').remove();
});
this.element.find('li').each(function(){
var listItem = $(this),
menuitemLink = listItem.children('a');
menuitemLink.removeClass('ui-menuitem-link ui-corner-all ui-menuitem-link-hasicon');
if($this.options.enhanced)
menuitemLink.children('span').removeClass('ui-menuitem-text');
else
menuitemLink.contents().unwrap();
menuitemLink.children('.fa').remove();
listItem.removeClass('ui-menuitem ui-widget ui-corner-all ui-menu-parent')
.parent().removeClass('ui-menu-list ui-helper-reset ui-helper-hidden ');
});
},
_unbindEvents: function() {
this.headers.off('mouseover.ui-panelmenu mouseout.ui-panelmenu click.ui-panelmenu');
this.menuitemLinks.off('mouseover.ui-panelmenu mouseout.ui-panelmenu click.ui-panelmenu');
this.treeLinks.off('click.ui-panelmenu');
this._unbindKeyEvents();
},
_bindEvents: function() {
var $this = this;
this.headers.on('mouseover.ui-panelmenu', function() {
var element = $(this);
if(!element.hasClass('ui-state-active')) {
element.addClass('ui-state-hover');
}
}).on('mouseout.ui-panelmenu', function() {
var element = $(this);
if(!element.hasClass('ui-state-active')) {
element.removeClass('ui-state-hover');
}
}).on('click.ui-panelmenu', function(e) {
var header = $(this);
if(header.hasClass('ui-state-active'))
$this._collapseRootSubmenu($(this));
else
$this._expandRootSubmenu($(this), false);
$this._removeFocusedItem();
header.focus();
e.preventDefault();
});
this.menuitemLinks.on('mouseover.ui-panelmenu', function() {
$(this).addClass('ui-state-hover');
}).on('mouseout.ui-panelmenu', function() {
$(this).removeClass('ui-state-hover');
}).on('click.ui-panelmenu', function(e) {
var currentLink = $(this);
$this._focusItem(currentLink.closest('.ui-menuitem'));
var href = currentLink.attr('href');
if(href && href !== '#') {
window.location.href = href;
}
e.preventDefault();
});
this.treeLinks.on('click.ui-panelmenu', function(e) {
var link = $(this),
submenu = link.parent(),
submenuList = link.next();
if(submenuList.is(':visible')) {
if(link.children('span.fa-caret-down').length) {
link.children('span.fa-caret-down').removeClass('fa-caret-down').addClass('fa-caret-right');
}
$this._collapseTreeItem(submenu);
}
else {
if(link.children('span.fa-caret-right').length) {
link.children('span.fa-caret-right').removeClass('fa-caret-right').addClass('fa-caret-down');
}
$this._expandTreeItem(submenu, false);
}
e.preventDefault();
});
this._bindKeyEvents();
},
_bindKeyEvents: function() {
var $this = this;
if(PUI.isIE()) {
this.focusCheck = false;
}
this.headers.on('focus.panelmenu', function(){
$(this).addClass('ui-menuitem-outline');
})
.on('blur.panelmenu', function(){
$(this).removeClass('ui-menuitem-outline ui-state-hover');
})
.on('keydown.panelmenu', function(e) {
var keyCode = $.ui.keyCode,
key = e.which;
if(key === keyCode.SPACE || key === keyCode.ENTER || key === keyCode.NUMPAD_ENTER) {
$(this).trigger('click');
e.preventDefault();
}
});
this.contents.on('mousedown.panelmenu', function(e) {
if($(e.target).is(':not(:input:enabled)')) {
e.preventDefault();
}
}).on('focus.panelmenu', function(){
if(!$this.focusedItem) {
$this._focusItem($this._getFirstItemOfContent($(this)));
if(PUI.isIE()) {
$this.focusCheck = false;
}
}
}).on('keydown.panelmenu', function(e) {
if(!$this.focusedItem) {
return;
}
var keyCode = $.ui.keyCode;
switch(e.which) {
case keyCode.LEFT:
if($this._isExpanded($this.focusedItem)) {
$this.focusedItem.children('.ui-menuitem-link').trigger('click');
}
else {
var parentListOfItem = $this.focusedItem.closest('ul.ui-menu-list');
if(parentListOfItem.parent().is(':not(.ui-panelmenu-content)')) {
$this._focusItem(parentListOfItem.closest('li.ui-menuitem'));
}
}
e.preventDefault();
break;
case keyCode.RIGHT:
if($this.focusedItem.hasClass('ui-menu-parent') && !$this._isExpanded($this.focusedItem)) {
$this.focusedItem.children('.ui-menuitem-link').trigger('click');
}
e.preventDefault();
break;
case keyCode.UP:
var itemToFocus = null,
prevItem = $this.focusedItem.prev();
if(prevItem.length) {
itemToFocus = prevItem.find('li.ui-menuitem:visible:last');
if(!itemToFocus.length) {
itemToFocus = prevItem;
}
}
else {
itemToFocus = $this.focusedItem.closest('ul').parent('li');
}
if(itemToFocus.length) {
$this._focusItem(itemToFocus);
}
e.preventDefault();
break;
case keyCode.DOWN:
var itemToFocus = null,
firstVisibleChildItem = $this.focusedItem.find('> ul > li:visible:first');
if(firstVisibleChildItem.length) {
itemToFocus = firstVisibleChildItem;
}
else if($this.focusedItem.next().length) {
itemToFocus = $this.focusedItem.next();
}
else {
if($this.focusedItem.next().length === 0) {
itemToFocus = $this._searchDown($this.focusedItem);
}
}
if(itemToFocus && itemToFocus.length) {
$this._focusItem(itemToFocus);
}
e.preventDefault();
break;
case keyCode.ENTER:
case keyCode.NUMPAD_ENTER:
case keyCode.SPACE:
var currentLink = $this.focusedItem.children('.ui-menuitem-link');
//IE fix
setTimeout(function(){
currentLink.trigger('click');
},1);
$this.element.blur();
var href = currentLink.attr('href');
if(href && href !== '#') {
window.location.href = href;
}
e.preventDefault();
break;
case keyCode.TAB:
if($this.focusedItem) {
if(PUI.isIE()) {
$this.focusCheck = true;
}
$(this).focus();
}
break;
}
}).on('blur.panelmenu', function(e) {
if(PUI.isIE() && !$this.focusCheck) {
return;
}
$this._removeFocusedItem();
});
var clickNS = 'click.' + this.id;
//remove focusedItem when document is clicked
$(document.body).off(clickNS).on(clickNS, function(event) {
if(!$(event.target).closest('.ui-panelmenu').length) {
$this._removeFocusedItem();
}
});
},
_unbindKeyEvents: function() {
this.headers.off('focus.panelmenu blur.panelmenu keydown.panelmenu');
this.contents.off('mousedown.panelmenu focus.panelmenu keydown.panelmenu blur.panelmenu');
$(document.body).off('click.' + this.id);
},
_isExpanded: function(item) {
return item.children('ul.ui-menu-list').is(':visible');
},
_searchDown: function(item) {
var nextOfParent = item.closest('ul').parent('li').next(),
itemToFocus = null;
if(nextOfParent.length) {
itemToFocus = nextOfParent;
}
else if(item.closest('ul').parent('li').length === 0){
itemToFocus = item;
}
else {
itemToFocus = this._searchDown(item.closest('ul').parent('li'));
}
return itemToFocus;
},
_getFirstItemOfContent: function(content) {
return content.find('> .ui-menu-list > .ui-menuitem:visible:first-child');
},
_collapseRootSubmenu: function(header) {
var panel = header.next();
header.attr('aria-expanded', false).removeClass('ui-state-active ui-corner-top').addClass('ui-state-hover ui-corner-all');
header.children('span.fa').removeClass('fa-caret-down').addClass('fa-caret-right');
panel.attr('aria-hidden', true).slideUp('normal', 'easeInOutCirc');
this._removeAsExpanded(panel);
},
_expandRootSubmenu: function(header, restoring) {
var panel = header.next();
header.attr('aria-expanded', true).addClass('ui-state-active ui-corner-top').removeClass('ui-state-hover ui-corner-all');
header.children('span.fa').removeClass('fa-caret-right').addClass('fa-caret-down');
if(restoring) {
panel.attr('aria-hidden', false).show();
}
else {
panel.attr('aria-hidden', false).slideDown('normal', 'easeInOutCirc');
this._addAsExpanded(panel);
}
},
_restoreState: function() {
var expandedNodeIds = null;
if(this.options.stateful) {
expandedNodeIds = PUI.getCookie(this.stateKey);
}
if(expandedNodeIds) {
this._collapseAll();
this.expandedNodes = expandedNodeIds.split(',');
for(var i = 0 ; i < this.expandedNodes.length; i++) {
var element = $(PUI.escapeClientId(this.expandedNodes[i]));
if(element.is('div.ui-panelmenu-content'))
this._expandRootSubmenu(element.prev(), true);
else if(element.is('li.ui-menu-parent'))
this._expandTreeItem(element, true);
}
}
else {
this.expandedNodes = [];
var activeHeaders = this.headers.filter('.ui-state-active'),
activeTreeSubmenus = this.element.find('.ui-menu-parent > .ui-menu-list:not(.ui-helper-hidden)');
for(var i = 0; i < activeHeaders.length; i++) {
this.expandedNodes.push(activeHeaders.eq(i).next().attr('id'));
}
for(var i = 0; i < activeTreeSubmenus.length; i++) {
this.expandedNodes.push(activeTreeSubmenus.eq(i).parent().attr('id'));
}
}
},
_collapseAll: function() {
this.headers.filter('.ui-state-active').each(function() {
var header = $(this);
header.removeClass('ui-state-active').next().addClass('ui-helper-hidden');
});
this.element.find('.ui-menu-parent > .ui-menu-list:not(.ui-helper-hidden)').each(function() {
$(this).addClass('ui-helper-hidden');
});
},
_removeAsExpanded: function(element) {
var id = element.attr('id');
this.expandedNodes = $.grep(this.expandedNodes, function(value) {
return value != id;
});
this._saveState();
},
_addAsExpanded: function(element) {
this.expandedNodes.push(element.attr('id'));
this._saveState();
},
_removeFocusedItem: function() {
if(this.focusedItem) {
this._getItemText(this.focusedItem).removeClass('ui-menuitem-outline');
this.focusedItem = null;
}
},
_focusItem: function(item) {
this._removeFocusedItem();
this._getItemText(item).addClass('ui-menuitem-outline').focus();
this.focusedItem = item;
},
_getItemText: function(item) {
return item.find('> .ui-menuitem-link > span.ui-menuitem-text');
},
_expandTreeItem: function(submenu, restoring) {
var submenuLink = submenu.find('> .ui-menuitem-link');
submenuLink.find('> .ui-menuitem-text').attr('aria-expanded', true);
submenu.children('.ui-menu-list').show();
if(!restoring) {
this._addAsExpanded(submenu);
}
},
_collapseTreeItem: function(submenu) {
var submenuLink = submenu.find('> .ui-menuitem-link');
submenuLink.find('> .ui-menuitem-text').attr('aria-expanded', false);
submenu.children('.ui-menu-list').hide();
this._removeAsExpanded(submenu);
},
_removeAsExpanded: function(element) {
var id = element.attr('id');
this.expandedNodes = $.grep(this.expandedNodes, function(value) {
return value != id;
});
this._saveState();
},
_addAsExpanded: function(element) {
this.expandedNodes.push(element.attr('id'));
this._saveState();
},
_saveState: function() {
if(this.options.stateful) {
var expandedNodeIds = this.expandedNodes.join(',');
PUI.setCookie(this.stateKey, expandedNodeIds, {path:'/'});
}
},
_clearState: function() {
if(this.options.stateful) {
PUI.deleteCookie(this.stateKey, {path:'/'});
}
}
});
})();
/**
* PrimeUI Messages widget
*/
(function() {
$.widget("primeui.puimessages", {
options: {
closable: true
},
_create: function() {
this.element.addClass('ui-messages ui-widget ui-corner-all');
if(this.options.closable) {
this.closer = $('<a href="#" class="ui-messages-close"><i class="fa fa-close"></i></a>').appendTo(this.element);
}
this.element.append('<span class="ui-messages-icon fa fa-2x"></span>');
this.msgContainer = $('<ul></ul>').appendTo(this.element);
this._bindEvents();
},
_bindEvents: function() {
var $this = this;
if(this.options.closable) {
this.closer.on('click', function(e) {
$this.element.slideUp();
e.preventDefault();
});
}
},
show: function(severity, msgs) {
this.clear();
this.element.removeClass('ui-messages-info ui-messages-warn ui-messages-error').addClass('ui-messages-' + severity);
this.element.children('.ui-messages-icon').removeClass('fa-info-circle fa-close fa-warning').addClass(this._getIcon(severity));
if($.isArray(msgs)) {
for(var i = 0; i < msgs.length; i++) {
this._showMessage(msgs[i]);
}
}
else {
this._showMessage(msgs);
}
this.element.show();
},
_showMessage: function(msg) {
this.msgContainer.append('<li><span class="ui-messages-summary">' + msg.summary + '</span><span class="ui-messages-detail">' + msg.detail + '</span></li>');
},
clear: function() {
this.msgContainer.children().remove();
this.element.hide();
},
_getIcon: function(severity) {
switch(severity) {
case 'info':
return 'fa-info-circle';
break;
case 'warn':
return 'fa-warning';
break;
case 'error':
return 'fa-close';
break;
default:
return 'fa-info-circle';
break;
}
}
});
})();(function() {
$.widget("primeui.puimultiselectlistbox", {
options: {
caption: null,
choices: null,
effect: false||'fade',
name: null,
value: null
},
_create: function() {
this.element.addClass('ui-multiselectlistbox ui-widget ui-helper-clearfix');
this.element.append('<input type="hidden"></input>');
this.element.append('<div class="ui-multiselectlistbox-listcontainer"></div>');
this.container = this.element.children('div');
this.input = this.element.children('input');
var choices = this.options.choices;
if(this.options.name) {
this.input.attr('name', this.options.name);
}
if(choices) {
if(this.options.caption) {
this.container.append('<div class="ui-multiselectlistbox-header ui-widget-header ui-corner-top">'+ this.options.caption +'</div>');
}
this.container.append('<ul class="ui-multiselectlistbox-list ui-inputfield ui-widget-content ui-corner-bottom"></ul>');
this.rootList = this.container.children('ul');
for(var i = 0; i < choices.length; i++) {
this._createItemNode(choices[i], this.rootList);
}
this.items = this.element.find('li.ui-multiselectlistbox-item');
this._bindEvents();
if(this.options.value !== undefined || this.options.value !== null) {
this.preselect(this.options.value);
}
}
},
_createItemNode: function(choice, parent) {
var listItem = $('<li class="ui-multiselectlistbox-item"><span>'+ choice.label + '</span></li>');
listItem.appendTo(parent);
if(choice.items) {
listItem.append('<ul class="ui-helper-hidden"></ul>');
var sublistContainer = listItem.children('ul');
for(var i = 0; i < choice.items.length; i++) {
this._createItemNode(choice.items[i], sublistContainer);
}
}
else {
listItem.attr('data-value', choice.value);
}
},
_unbindEvents: function() {
this.items.off('mouseover.multiSelectListbox mouseout.multiSelectListbox click.multiSelectListbox');
},
_bindEvents: function() {
var $this = this;
this.items.on('mouseover.multiSelectListbox', function() {
var item = $(this);
if(!item.hasClass('ui-state-highlight'))
$(this).addClass('ui-state-hover');
})
.on('mouseout.multiSelectListbox', function() {
var item = $(this);
if(!item.hasClass('ui-state-highlight'))
$(this).removeClass('ui-state-hover');
})
.on('click.multiSelectListbox', function() {
var item = $(this);
if(!item.hasClass('ui-state-highlight')) {
$this.showOptionGroup(item);
}
});
},
showOptionGroup: function(item) {
item.addClass('ui-state-highlight').removeClass('ui-state-hover').siblings().filter('.ui-state-highlight').removeClass('ui-state-highlight');
item.closest('.ui-multiselectlistbox-listcontainer').nextAll().remove();
var childItemsContainer = item.children('ul'),
itemValue = item.attr('data-value');
if(itemValue) {
this.input.val(itemValue);
}
if(childItemsContainer.length) {
var groupContainer = $('<div class="ui-multiselectlistbox-listcontainer" style="display:none"></div>');
childItemsContainer.clone(true).appendTo(groupContainer).addClass('ui-multiselectlistbox-list ui-inputfield ui-widget-content').removeClass('ui-helper-hidden');
groupContainer.prepend('<div class="ui-multiselectlistbox-header ui-widget-header ui-corner-top">' + item.children('span').text() + '</div>')
.children('.ui-multiselectlistbox-list').addClass('ui-corner-bottom');
this.element.append(groupContainer);
if (this.options.effect)
groupContainer.show(this.options.effect);
else
groupContainer.show();
}
},
disable: function() {
if(!this.options.disabled) {
this.options.disabled = true;
this.element.addClass('ui-state-disabled');
this._unbindEvents();
this.container.nextAll().remove();
}
},
getValue: function() {
return this.input.val();
},
preselect: function(value) {
var $this = this,
item = this.items.filter('[data-value="' + value + '"]');
if(item.length === 0) {
return;
}
var ancestors = item.parentsUntil('.ui-multiselectlistbox-list'),
selectedIndexMap = [];
for(var i = (ancestors.length - 1); i >= 0; i--) {
var ancestor = ancestors.eq(i);
if(ancestor.is('li')) {
selectedIndexMap.push(ancestor.index());
}
else if(ancestor.is('ul')) {
var groupContainer = $('<div class="ui-multiselectlistbox-listcontainer" style="display:none"></div>');
ancestor.clone(true).appendTo(groupContainer).addClass('ui-multiselectlistbox-list ui-widget-content ui-corner-all').removeClass('ui-helper-hidden');
groupContainer.prepend('<div class="ui-multiselectlistbox-header ui-widget-header ui-corner-top">' + ancestor.prev('span').text() + '</div>')
.children('.ui-multiselectlistbox-list').addClass('ui-corner-bottom').removeClass('ui-corner-all');
$this.element.append(groupContainer);
}
}
//highlight item
var lists = this.element.children('div.ui-multiselectlistbox-listcontainer'),
clonedItem = lists.find(' > ul.ui-multiselectlistbox-list > li.ui-multiselectlistbox-item').filter('[data-value="' + value + '"]');
clonedItem.addClass('ui-state-highlight');
//highlight ancestors
for(var i = 0; i < selectedIndexMap.length; i++) {
lists.eq(i).find('> .ui-multiselectlistbox-list > li.ui-multiselectlistbox-item').eq(selectedIndexMap[i]).addClass('ui-state-highlight');
}
$this.element.children('div.ui-multiselectlistbox-listcontainer:hidden').show();
}
});
})();
/**
* PrimeFaces Notify Widget
*/
(function() {
$.widget("primeui.puinotify", {
options: {
position: 'top',
visible: false,
animate: true,
effectSpeed: 'normal',
easing: 'swing'
},
_create: function() {
this.element.addClass('ui-notify ui-notify-' + this.options.position + ' ui-widget ui-widget-content ui-shadow')
.wrapInner('<div class="ui-notify-content" />').appendTo(document.body);
this.content = this.element.children('.ui-notify-content');
this.closeIcon = $('<span class="ui-notify-close fa fa-close"></span>').appendTo(this.element);
this._bindEvents();
if(this.options.visible) {
this.show();
}
},
_bindEvents: function() {
var $this = this;
this.closeIcon.on('click.puinotify', function() {
$this.hide();
});
},
show: function(content) {
var $this = this;
if(content) {
this.update(content);
}
this.element.css('z-index',++PUI.zindex);
this._trigger('beforeShow');
if(this.options.animate) {
this.element.slideDown(this.options.effectSpeed, this.options.easing, function() {
$this._trigger('afterShow');
});
}
else {
this.element.show();
$this._trigger('afterShow');
}
},
hide: function() {
var $this = this;
this._trigger('beforeHide');
if(this.options.animate) {
this.element.slideUp(this.options.effectSpeed, this.options.easing, function() {
$this._trigger('afterHide');
});
}
else {
this.element.hide();
$this._trigger('afterHide');
}
},
update: function(content) {
this.content.html(content);
}
});
})();/**
* PrimeUI picklist widget
*/
(function() {
$.widget("primeui.puiorderlist", {
options: {
controlsLocation: 'none',
dragdrop: true,
effect: 'fade',
caption: null,
responsive: false,
datasource: null,
content: null,
template: null
},
_create: function() {
this._createDom();
if(this.options.datasource) {
if($.isArray(this.options.datasource)) {
this._generateOptionElements(this.options.datasource);
}
else if($.type(this.options.datasource) === 'function') {
this.options.datasource.call(this, this._generateOptionElements);
}
}
this.optionElements = this.element.children('option');
this._createListElement();
this._bindEvents();
},
_createDom: function() {
this.element.addClass('ui-helper-hidden');
if(this.options.controlsLocation !== 'none')
this.element.wrap('<div class="ui-grid-col-10"></div>');
else
this.element.wrap('<div class="ui-grid-col-12"></div>');
this.element.parent().wrap('<div class="ui-orderlist ui-grid ui-widget"><div class="ui-grid-row"></div></div>')
this.container = this.element.closest('.ui-orderlist');
if(this.options.controlsLocation !== 'none') {
this.element.parent().before('<div class="ui-orderlist-controls ui-grid-col-2"></div>');
this._createButtons();
}
if(this.options.responsive) {
this.container.addClass('ui-grid-responsive');
}
},
_generateOptionElements: function(data) {
for(var i = 0; i < data.length; i++) {
var choice = data[i];
if(choice.label)
this.element.append('<option value="' + choice.value + '">' + choice.label + '</option>');
else
this.element.append('<option value="' + choice + '">' + choice + '</option>');
}
},
_createListElement: function() {
this.list = $('<ul class="ui-widget-content ui-orderlist-list"></ul>').insertBefore(this.element);
for(var i = 0; i < this.optionElements.length; i++) {
var optionElement = this.optionElements.eq(i),
itemContent = this._createItemContent(optionElement.get(0)),
listItem = $('<li class="ui-orderlist-item ui-corner-all"></li>');
if($.type(itemContent) === 'string')
listItem.html(itemContent);
else
listItem.append(itemContent);
listItem.data('item-value', optionElement.attr('value')).appendTo(this.list);
}
this.items = this.list.children('.ui-orderlist-item');
if(this.options.caption) {
this.list.addClass('ui-corner-bottom').before('<div class="ui-orderlist-caption ui-widget-header ui-corner-top">' + this.options.caption + '</div>')
} else {
this.list.addClass('ui-corner-all')
}
},
_createButtons: function() {
var $this = this;
this.buttonContainer = this.element.parent().prev();
this.moveUpButton = this._createButton('fa-angle-up', 'ui-orderlist-button-moveup', function(){$this._moveUp();});
this.moveTopButton = this._createButton('fa-angle-double-up', 'ui-orderlist-button-move-top', function(){$this._moveTop();});
this.moveDownButton = this._createButton('fa-angle-down', 'ui-orderlist-button-move-down', function(){$this._moveDown();});
this.moveBottomButton = this._createButton('fa-angle-double-down', 'ui-orderlist-move-bottom', function(){$this._moveBottom();});
this.buttonContainer.append(this.moveUpButton).append(this.moveTopButton).append(this.moveDownButton).append(this.moveBottomButton);
},
_createButton: function(icon, cssClass, fn) {
var btn = $('<button class="' + cssClass + '" type="button"></button>').puibutton({
'icon': icon,
'click': function() {
fn();
$(this).removeClass('ui-state-hover ui-state-focus');
}
});
return btn;
},
_bindEvents: function() {
this._bindButtonEvents();
this._bindItemEvents(this.items);
if(this.options.dragdrop) {
this._initDragDrop();
}
},
_initDragDrop: function() {
var $this = this;
this.list.sortable({
revert: 1,
start: function(event, ui) {
PUI.clearSelection();
}
,update: function(event, ui) {
$this.onDragDrop(event, ui);
}
});
},
_moveUp: function() {
var $this = this,
selectedItems = this.items.filter('.ui-state-highlight'),
itemsToMoveCount = selectedItems.length,
movedItemsCount = 0;
selectedItems.each(function() {
var item = $(this);
if(!item.is(':first-child')) {
item.hide($this.options.effect, {}, 'fast', function() {
item.insertBefore(item.prev()).show($this.options.effect, {}, 'fast', function() {
movedItemsCount++;
if(itemsToMoveCount === movedItemsCount) {
$this._saveState();
$this._fireReorderEvent();
}
});
});
}
else {
itemsToMoveCount--;
}
});
},
_moveTop: function() {
var $this = this,
selectedItems = this.items.filter('.ui-state-highlight'),
itemsToMoveCount = selectedItems.length,
movedItemsCount = 0;
selectedItems.each(function() {
var item = $(this);
if(!item.is(':first-child')) {
item.hide($this.options.effect, {}, 'fast', function() {
item.prependTo(item.parent()).show($this.options.effect, {}, 'fast', function(){
movedItemsCount++;
if(itemsToMoveCount === movedItemsCount) {
$this._saveState();
$this._fireReorderEvent();
}
});
});
}
else {
itemsToMoveCount--;
}
});
},
_moveDown: function() {
var $this = this,
selectedItems = $(this.items.filter('.ui-state-highlight').get().reverse()),
itemsToMoveCount = selectedItems.length,
movedItemsCount = 0;
selectedItems.each(function() {
var item = $(this);
if(!item.is(':last-child')) {
item.hide($this.options.effect, {}, 'fast', function() {
item.insertAfter(item.next()).show($this.options.effect, {}, 'fast', function() {
movedItemsCount++;
if(itemsToMoveCount === movedItemsCount) {
$this._saveState();
$this._fireReorderEvent();
}
});
});
}
else {
itemsToMoveCount--;
}
});
},
_moveBottom: function() {
var $this = this,
selectedItems = this.items.filter('.ui-state-highlight'),
itemsToMoveCount = selectedItems.length,
movedItemsCount = 0;
selectedItems.each(function() {
var item = $(this);
if(!item.is(':last-child')) {
item.hide($this.options.effect, {}, 'fast', function() {
item.appendTo(item.parent()).show($this.options.effect, {}, 'fast', function() {
movedItemsCount++;
if(itemsToMoveCount === movedItemsCount) {
$this._saveState();
$this._fireReorderEvent();
}
});
});
}
else {
itemsToMoveCount--;
}
});
},
_saveState: function() {
this.element.children().remove();
this._generateOptions();
},
_fireReorderEvent: function() {
this._trigger('reorder', null);
},
onDragDrop: function(event, ui) {
ui.item.removeClass('ui-state-highlight');
this._saveState();
this._fireReorderEvent();
},
_generateOptions: function() {
var $this = this;
this.list.children('.ui-orderlist-item').each(function() {
var item = $(this),
itemValue = item.data('item-value');
$this.element.append('<option value="' + itemValue + '" selected="selected">' + itemValue + '</option>');
});
},
_createItemContent: function(choice) {
if(this.options.template) {
var template = this.options.template.html();
Mustache.parse(template);
return Mustache.render(template, choice);
}
else if(this.options.content) {
return this.options.content.call(this, choice);
}
else {
return choice.label;
}
},
addOption: function(value,label) {
var newListItem;
if(this.options.content) {
var option = (label) ? {'label':label,'value':value}: {'label':value,'value':value};
newListItem = $('<li class="ui-orderlist-item ui-corner-all"></li>').append(this.options.content(option)).appendTo(this.list);
}
else {
var listLabel = (label) ? label: value;
newListItem = $('<li class="ui-orderlist-item ui-corner-all">' + listLabel + '</li>').appendTo(this.list);
}
if(label)
this.element.append('<option value="' + value + '">' + label + '</option>');
else
this.element.append('<option value="' + value + '">' + value + '</option>');
this._bindItemEvents(newListItem);
this.optionElements = this.element.children('option');
this.items = this.items.add(newListItem);
if(this.options.dragdrop) {
this.list.sortable('refresh');
}
},
removeOption: function(value) {
for (var i = 0; i < this.optionElements.length; i++) {
if(this.optionElements[i].value == value) {
this.optionElements[i].remove(i);
this._unbindItemEvents(this.items.eq(i));
this.items[i].remove(i);
}
}
this.optionElements = this.element.children('option');
this.items = this.list.children('.ui-orderlist-item');
if(this.options.dragdrop) {
this.list.sortable('refresh');
}
},
_unbindEvents: function() {
this._unbindItemEvents(this.items);
this._unbindButtonEvents();
},
_unbindItemEvents: function(item) {
item.off('mouseover.puiorderlist mouseout.puiorderlist mousedown.puiorderlist');
},
_bindItemEvents: function(item) {
var $this = this;
item.on('mouseover.puiorderlist', function(e) {
var element = $(this);
if(!element.hasClass('ui-state-highlight'))
$(this).addClass('ui-state-hover');
})
.on('mouseout.puiorderlist', function(e) {
var element = $(this);
if(!element.hasClass('ui-state-highlight'))
$(this).removeClass('ui-state-hover');
})
.on('mousedown.puiorderlist', function(e) {
var element = $(this),
metaKey = (e.metaKey||e.ctrlKey);
if(!metaKey) {
element.removeClass('ui-state-hover').addClass('ui-state-highlight')
.siblings('.ui-state-highlight').removeClass('ui-state-highlight');
//$this.fireItemSelectEvent(element, e);
}
else {
if(element.hasClass('ui-state-highlight')) {
element.removeClass('ui-state-highlight');
//$this.fireItemUnselectEvent(element);
}
else {
element.removeClass('ui-state-hover').addClass('ui-state-highlight');
//$this.fireItemSelectEvent(element, e);
}
}
});
},
getSelection: function() {
var selectedItems = [];
this.items.filter('.ui-state-highlight').each(function() {
selectedItems.push($(this).data('item-value'));
});
return selectedItems;
},
setSelection: function(value) {
for (var i = 0; i < this.items.length; i++) {
for (var j = 0; j < value.length; j++) {
if(this.items.eq(i).data('item-value') == value[j]) {
this.items.eq(i).addClass('ui-state-highlight');
}
}
}
},
disable: function() {
this._unbindEvents();
this.items.addClass('ui-state-disabled');
this.container.addClass('ui-state-disabled');
if(this.options.dragdrop) {
this.list.sortable('destroy');
}
},
enable: function() {
this._bindEvents();
this.items.removeClass('ui-state-disabled');
this.container.removeClass('ui-state-disabled');
if(this.options.dragdrop) {
this._initDragDrop();
}
},
_unbindButtonEvents: function() {
if(this.buttonContainer) {
this.moveUpButton.puibutton('disable');
this.moveTopButton.puibutton('disable');
this.moveDownButton.puibutton('disable');
this.moveBottomButton.puibutton('disable');
}
},
_bindButtonEvents: function() {
if(this.buttonContainer) {
this.moveUpButton.puibutton('enable');
this.moveTopButton.puibutton('enable');
this.moveDownButton.puibutton('enable');
this.moveBottomButton.puibutton('enable');
}
}
});
})();/**
* PrimeUI Paginator Widget
*/
(function() {
var ElementHandlers = {
'{FirstPageLink}': {
markup: '<span class="ui-paginator-first ui-paginator-element ui-state-default ui-corner-all"><span class="fa fa-step-backward"></span></span>',
create: function(paginator) {
var element = $(this.markup);
if(paginator.options.page === 0) {
element.addClass('ui-state-disabled');
}
element.on('click.puipaginator', function() {
if(!$(this).hasClass("ui-state-disabled")) {
paginator.option('page', 0);
}
});
return element;
},
update: function(element, state) {
if(state.page === 0) {
element.addClass('ui-state-disabled').removeClass('ui-state-hover ui-state-active');
}
else {
element.removeClass('ui-state-disabled');
}
}
},
'{PreviousPageLink}': {
markup: '<span class="ui-paginator-prev ui-paginator-element ui-state-default ui-corner-all"><span class="fa fa-backward"></span></span>',
create: function(paginator) {
var element = $(this.markup);
if(paginator.options.page === 0) {
element.addClass('ui-state-disabled');
}
element.on('click.puipaginator', function() {
if(!$(this).hasClass("ui-state-disabled")) {
paginator.option('page', paginator.options.page - 1);
}
});
return element;
},
update: function(element, state) {
if(state.page === 0) {
element.addClass('ui-state-disabled').removeClass('ui-state-hover ui-state-active');
}
else {
element.removeClass('ui-state-disabled');
}
}
},
'{NextPageLink}': {
markup: '<span class="ui-paginator-next ui-paginator-element ui-state-default ui-corner-all"><span class="fa fa-forward"></span></span>',
create: function(paginator) {
var element = $(this.markup);
if(paginator.options.page === (paginator.getPageCount() - 1)) {
element.addClass('ui-state-disabled').removeClass('ui-state-hover ui-state-active');
}
element.on('click.puipaginator', function() {
if(!$(this).hasClass("ui-state-disabled")) {
paginator.option('page', paginator.options.page + 1);
}
});
return element;
},
update: function(element, state) {
if(state.page === (state.pageCount - 1)) {
element.addClass('ui-state-disabled').removeClass('ui-state-hover ui-state-active');
}
else {
element.removeClass('ui-state-disabled');
}
}
},
'{LastPageLink}': {
markup: '<span class="ui-paginator-last ui-paginator-element ui-state-default ui-corner-all"><span class="fa fa-step-forward"></span></span>',
create: function(paginator) {
var element = $(this.markup);
if(paginator.options.page === (paginator.getPageCount() - 1)) {
element.addClass('ui-state-disabled').removeClass('ui-state-hover ui-state-active');
}
element.on('click.puipaginator', function() {
if(!$(this).hasClass("ui-state-disabled")) {
paginator.option('page', paginator.getPageCount() - 1);
}
});
return element;
},
update: function(element, state) {
if(state.page === (state.pageCount - 1)) {
element.addClass('ui-state-disabled').removeClass('ui-state-hover ui-state-active');
}
else {
element.removeClass('ui-state-disabled');
}
}
},
'{PageLinks}': {
markup: '<span class="ui-paginator-pages"></span>',
create: function(paginator) {
var element = $(this.markup),
boundaries = this.calculateBoundaries({
page: paginator.options.page,
pageLinks: paginator.options.pageLinks,
pageCount: paginator.getPageCount()
}),
start = boundaries[0],
end = boundaries[1];
for(var i = start; i <= end; i++) {
var pageLinkNumber = (i + 1),
pageLinkElement = $('<span class="ui-paginator-page ui-paginator-element ui-state-default ui-corner-all">' + pageLinkNumber + "</span>");
if(i === paginator.options.page) {
pageLinkElement.addClass('ui-state-active');
}
pageLinkElement.on('click.puipaginator', function(e){
var link = $(this);
if(!link.hasClass('ui-state-disabled')&&!link.hasClass('ui-state-active')) {
paginator.option('page', parseInt(link.text(), 10) - 1);
}
});
element.append(pageLinkElement);
}
return element;
},
update: function(element, state, paginator) {
var pageLinks = element.children(),
boundaries = this.calculateBoundaries({
page: state.page,
pageLinks: state.pageLinks,
pageCount: state.pageCount
}),
start = boundaries[0],
end = boundaries[1];
pageLinks.remove();
for(var i = start; i <= end; i++) {
var pageLinkNumber = (i + 1),
pageLinkElement = $('<span class="ui-paginator-page ui-paginator-element ui-state-default ui-corner-all">' + pageLinkNumber + "</span>");
if(i === state.page) {
pageLinkElement.addClass('ui-state-active');
}
pageLinkElement.on('click.puipaginator', function(e){
var link = $(this);
if(!link.hasClass('ui-state-disabled')&&!link.hasClass('ui-state-active')) {
paginator.option('page', parseInt(link.text(), 10) - 1);
}
});
paginator._bindHover(pageLinkElement);
element.append(pageLinkElement);
}
},
calculateBoundaries: function(config) {
var page = config.page,
pageLinks = config.pageLinks,
pageCount = config.pageCount,
visiblePages = Math.min(pageLinks, pageCount);
//calculate range, keep current in middle if necessary
var start = Math.max(0, parseInt(Math.ceil(page - ((visiblePages) / 2)), 10)),
end = Math.min(pageCount - 1, start + visiblePages - 1);
//check when approaching to last page
var delta = pageLinks - (end - start + 1);
start = Math.max(0, start - delta);
return [start, end];
}
}
};
$.widget("primeui.puipaginator", {
options: {
pageLinks: 5,
totalRecords: 0,
page: 0,
rows: 0,
template: '{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}'
},
_create: function() {
this.element.addClass('ui-paginator ui-widget-header');
this.paginatorElements = [];
var elementKeys = this.options.template.split(/[ ]+/);
for(var i = 0; i < elementKeys.length;i++) {
var elementKey = elementKeys[i],
handler = ElementHandlers[elementKey];
if(handler) {
var paginatorElement = handler.create(this);
this.paginatorElements[elementKey] = paginatorElement;
this.element.append(paginatorElement);
}
}
this._bindEvents();
},
_bindEvents: function() {
this._bindHover(this.element.find('span.ui-paginator-element'));
},
_bindHover: function(elements) {
elements.on('mouseover.puipaginator', function() {
var el = $(this);
if(!el.hasClass('ui-state-active')&&!el.hasClass('ui-state-disabled')) {
el.addClass('ui-state-hover');
}
})
.on('mouseout.puipaginator', function() {
var el = $(this);
if(el.hasClass('ui-state-hover')) {
el.removeClass('ui-state-hover');
}
});
},
_setOption: function(key, value) {
if(key === 'page')
this.setPage(value);
else if(key === 'totalRecords')
this.setTotalRecords(value);
else
$.Widget.prototype._setOption.apply(this, arguments);
},
setPage: function(p, silent) {
var pc = this.getPageCount();
if(p >= 0 && p < pc) {
var newState = {
first: this.options.rows * p,
rows: this.options.rows,
page: p,
pageCount: pc,
pageLinks: this.options.pageLinks
};
this.options.page = p;
if(!silent) {
this._trigger('paginate', null, newState);
}
this.updateUI(newState);
}
},
//state contains page and totalRecords
setState: function(state) {
this.options.totalRecords = state.totalRecords;
this.setPage(state.page, true);
},
updateUI: function(state) {
for(var paginatorElementKey in this.paginatorElements) {
ElementHandlers[paginatorElementKey].update(this.paginatorElements[paginatorElementKey], state, this);
}
},
getPageCount: function() {
return Math.ceil(this.options.totalRecords / this.options.rows)||1;
},
setTotalRecords: function(value) {
this.options.totalRecords = value;
this.setPage(0, true);
}
});
})();/**
* PrimeUI Panel Widget
*/
(function() {
$.widget("primeui.puipanel", {
options: {
toggleable: false,
toggleDuration: 'normal',
toggleOrientation : 'vertical',
collapsed: false,
closable: false,
closeDuration: 'normal',
title: null,
enhanced: false
},
_create: function() {
if(!this.options.enhanced) {
this.element.addClass('ui-panel ui-widget ui-widget-content ui-corner-all')
.contents().wrapAll('<div class="ui-panel-content ui-widget-content" />');
var title = this.element.attr('title')||this.options.title;
if(title) {
this.element.prepend('<div class="ui-panel-titlebar ui-widget-header ui-helper-clearfix ui-corner-all"><span class="ui-panel-title">' +
title + "</span></div>").removeAttr('title');
}
}
this.header = this.element.children('div.ui-panel-titlebar');
this.title = this.header.children('span.ui-panel-title');
this.content = this.element.children('div.ui-panel-content');
var $this = this;
if(this.options.closable) {
if(!this.options.enhanced) {
this.closer = $('<a class="ui-panel-titlebar-icon ui-panel-titlebar-closer ui-corner-all ui-state-default" href="#"><span class="fa fa-fw fa-close"></span></a>')
.appendTo(this.header);
}
else {
this.closer = this.header.children('.ui-panel-titlebar-closer');
}
this.closer.on('click.puipanel', function(e) {
$this.close();
e.preventDefault();
});
}
if(this.options.toggleable) {
var icon = this.options.collapsed ? 'fa-plus' : 'fa-minus';
if(!this.options.enhanced) {
this.toggler = $('<a class="ui-panel-titlebar-icon ui-panel-titlebar-toggler ui-corner-all ui-state-default" href="#"><span class="fa fa-fw ' + icon + '"></span></a>')
.appendTo(this.header);
}
else {
this.toggler = this.header.children('.ui-panel-titlebar-toggler');
this.toggler.children('.fa').addClass(icon);
}
this.toggler.on('click.puipanel', function(e) {
$this.toggle();
e.preventDefault();
});
if(this.options.collapsed) {
this.content.hide();
}
}
this._bindEvents();
},
_bindEvents: function() {
this.header.children('a.ui-panel-titlebar-icon').on('mouseenter.puipanel', function() {
$(this).addClass('ui-state-hover');
})
.on('mouseleave.puipanel', function() {
$(this).removeClass('ui-state-hover');
});
},
_unbindEvents: function() {
this.header.children('a.ui-panel-titlebar-icon').off();
},
close: function() {
var $this = this;
this._trigger('beforeClose', null);
this.element.fadeOut(this.options.closeDuration,
function() {
$this._trigger('afterClose', null);
}
);
},
toggle: function() {
if(this.options.collapsed) {
this.expand();
}
else {
this.collapse();
}
},
expand: function() {
this.toggler.children('.fa').removeClass('fa-plus').addClass('fa-minus');
if(this.options.toggleOrientation === 'vertical') {
this._slideDown();
}
else if(this.options.toggleOrientation === 'horizontal') {
this._slideRight();
}
},
collapse: function() {
this.toggler.children('.fa').removeClass('fa-minus').addClass('fa-plus');
if(this.options.toggleOrientation === 'vertical') {
this._slideUp();
}
else if(this.options.toggleOrientation === 'horizontal') {
this._slideLeft();
}
},
_slideUp: function() {
var $this = this;
this._trigger('beforeCollapse');
this.content.slideUp(this.options.toggleDuration, 'easeInOutCirc', function() {
$this._trigger('afterCollapse');
$this.options.collapsed = !$this.options.collapsed;
});
},
_slideDown: function() {
var $this = this;
this._trigger('beforeExpand');
this.content.slideDown(this.options.toggleDuration, 'easeInOutCirc', function() {
$this._trigger('afterExpand');
$this.options.collapsed = !$this.options.collapsed;
});
},
_slideLeft: function() {
var $this = this;
this.originalWidth = this.element.width();
this.title.hide();
this.toggler.hide();
this.content.hide();
this.element.animate({
width: '42px'
}, this.options.toggleSpeed, 'easeInOutCirc', function() {
$this.toggler.show();
$this.element.addClass('ui-panel-collapsed-h');
$this.options.collapsed = !$this.options.collapsed;
});
},
_slideRight: function() {
var $this = this,
expandWidth = this.originalWidth||'100%';
this.toggler.hide();
this.element.animate({
width: expandWidth
}, this.options.toggleSpeed, 'easeInOutCirc', function() {
$this.element.removeClass('ui-panel-collapsed-h');
$this.title.show();
$this.toggler.show();
$this.options.collapsed = !$this.options.collapsed;
$this.content.css({
'visibility': 'visible',
'display': 'block',
'height': 'auto'
});
});
},
_destroy: function() {
this._unbindEvents();
if(this.toggler) {
this.toggler.children('.fa').removeClass('fa-minus fa-plus');
}
}
});
})();/**
* PrimeUI password widget
*/
(function() {
$.widget("primeui.puipassword", {
options: {
promptLabel: 'Please enter a password',
weakLabel: 'Weak',
mediumLabel: 'Medium',
strongLabel: 'Strong',
inline: false
},
_create: function() {
this.id = this.element.attr('id');
if(!this.id) {
this.id = this.element.uniqueId().attr('id');
}
this.element.puiinputtext().addClass('ui-password');
if(!this.element.prop(':disabled')) {
var panelMarkup = '<div class="ui-password-panel ui-widget ui-state-highlight ui-corner-all ui-helper-hidden">';
panelMarkup += '<div class="ui-password-meter" style="background-position:0pt 0pt"> </div>';
panelMarkup += '<div class="ui-password-info">' + this.options.promptLabel + '</div>';
panelMarkup += '</div>';
this.panel = $(panelMarkup).insertAfter(this.element);
this.meter = this.panel.children('div.ui-password-meter');
this.infoText = this.panel.children('div.ui-password-info');
if(this.options.inline) {
this.panel.addClass('ui-password-panel-inline');
} else {
this.panel.addClass('ui-password-panel-overlay').appendTo('body');
}
this._bindEvents();
}
},
_destroy: function() {
this.element.puiinputtext('destroy').removeClass('ui-password');
this._unbindEvents();
this.panel.remove();
$(window).off('resize.' + this.id);
},
_bindEvents: function() {
var $this = this;
this.element.on('focus.puipassword', function() {
$this.show();
})
.on('blur.puipassword', function() {
$this.hide();
})
.on('keyup.puipassword', function() {
var value = $this.element.val(),
label = null,
meterPos = null;
if(value.length === 0) {
label = $this.options.promptLabel;
meterPos = '0px 0px';
}
else {
var score = $this._testStrength($this.element.val());
if(score < 30) {
label = $this.options.weakLabel;
meterPos = '0px -10px';
}
else if(score >= 30 && score < 80) {
label = $this.options.mediumLabel;
meterPos = '0px -20px';
}
else if(score >= 80) {
label = $this.options.strongLabel;
meterPos = '0px -30px';
}
}
$this.meter.css('background-position', meterPos);
$this.infoText.text(label);
});
if(!this.options.inline) {
var resizeNS = 'resize.' + this.id;
$(window).off(resizeNS).on(resizeNS, function() {
if($this.panel.is(':visible')) {
$this.align();
}
});
}
},
_unbindEvents: function() {
this.element.off('focus.puipassword blur.puipassword keyup.puipassword');
},
_testStrength: function(str) {
var grade = 0,
val = 0,
$this = this;
val = str.match('[0-9]');
grade += $this._normalize(val ? val.length : 1/4, 1) * 25;
val = str.match('[a-zA-Z]');
grade += $this._normalize(val ? val.length : 1/2, 3) * 10;
val = str.match('[!@#$%^&*?_~.,;=]');
grade += $this._normalize(val ? val.length : 1/6, 1) * 35;
val = str.match('[A-Z]');
grade += $this._normalize(val ? val.length : 1/6, 1) * 30;
grade *= str.length / 8;
return grade > 100 ? 100 : grade;
},
_normalize: function(x, y) {
var diff = x - y;
if(diff <= 0) {
return x / y;
}
else {
return 1 + 0.5 * (x / (x + y/4));
}
},
align: function() {
this.panel.css({
left:'',
top:'',
'z-index': ++PUI.zindex
})
.position({
my: 'left top',
at: 'right top',
of: this.element
});
},
show: function() {
if(!this.options.inline) {
this.align();
this.panel.fadeIn();
}
else {
this.panel.slideDown();
}
},
hide: function() {
if(this.options.inline) {
this.panel.slideUp();
}
else {
this.panel.fadeOut();
}
},
disable: function () {
this.element.puiinputtext('disable');
this._unbindEvents();
},
enable: function () {
this.element.puiinputtext('enable');
this._bindEvents();
},
_setOption: function(key, value) {
if(key === 'disabled') {
if(value)
this.disable();
else
this.enable();
}
else {
$.Widget.prototype._setOption.apply(this, arguments);
}
}
});
})();/**
* PrimeUI picklist widget
*/
(function() {
$.widget("primeui.puipicklist", {
options: {
effect: 'fade',
effectSpeed: 'fast',
sourceCaption: null,
targetCaption: null,
filter: false,
filterFunction: null,
filterMatchMode: 'startsWith',
dragdrop: true,
sourceData: null,
targetData: null,
content: null,
template: null,
responsive: false
},
_create: function() {
this.element.uniqueId().addClass('ui-picklist ui-widget ui-helper-clearfix');
if(this.options.responsive) {
this.element.addClass('ui-picklist-responsive');
}
this.inputs = this.element.children('select');
this.items = $();
this.sourceInput = this.inputs.eq(0);
this.targetInput = this.inputs.eq(1);
if(this.options.sourceData) {
this._populateInputFromData(this.sourceInput, this.options.sourceData);
}
if(this.options.targetData) {
this._populateInputFromData(this.targetInput, this.options.targetData);
}
this.sourceList = this._createList(this.sourceInput, 'ui-picklist-source', this.options.sourceCaption);
this._createButtons();
this.targetList = this._createList(this.targetInput, 'ui-picklist-target', this.options.targetCaption);
if(this.options.showSourceControls) {
this.element.prepend(this._createListControls(this.sourceList, 'ui-picklist-source-controls'));
}
if(this.options.showTargetControls) {
this.element.append(this._createListControls(this.targetList, 'ui-picklist-target-controls'));
}
this._bindEvents();
},
_populateInputFromData: function(input, data) {
for(var i = 0; i < data.length; i++) {
var choice = data[i];
if(choice.label)
input.append('<option value="' + choice.value + '">' + choice.label + '</option>');
else
input.append('<option value="' + choice + '">' + choice + '</option>');
}
},
_createList: function(input, cssClass, caption) {
var listWrapper = $('<div class="ui-picklist-listwrapper ' + cssClass + '-wrapper"></div>'),
listContainer = $('<ul class="ui-widget-content ui-picklist-list ' + cssClass + '"></ul>');
if(this.options.filter) {
listWrapper.append('<div class="ui-picklist-filter-container"><input type="text" class="ui-picklist-filter" /><span class="fa fa-fw fa-search"></span></div>');
listWrapper.find('> .ui-picklist-filter-container > input').puiinputtext();
}
if(caption) {
listWrapper.append('<div class="ui-picklist-caption ui-widget-header ui-corner-tl ui-corner-tr">' + caption + '</div>');
listContainer.addClass('ui-corner-bottom');
}
else {
listContainer.addClass('ui-corner-all');
}
this._populateContainerFromOptions(input, listContainer);
listWrapper.append(listContainer);
input.addClass('ui-helper-hidden').appendTo(listWrapper);
listWrapper.appendTo(this.element);
return listContainer;
},
_populateContainerFromOptions: function(input, listContainer, data) {
var choices = input.children('option');
for(var i = 0; i < choices.length; i++) {
var choice = choices.eq(i),
content = this._createItemContent(choice.get(0)),
item = $('<li class="ui-picklist-item ui-corner-all"></li>').data({
'item-label': choice.text(),
'item-value': choice.val()
});
if($.type(content) === 'string')
item.html(content);
else
item.append(content);
this.items = this.items.add(item);
listContainer.append(item);
}
},
_createButtons: function() {
var $this = this,
buttonContainer = $('<div class="ui-picklist-buttons"><div class="ui-picklist-buttons-cell"></div>');
buttonContainer.children('div').append(this._createButton('fa-angle-right', 'ui-picklist-button-add', function(){$this._add();}))
.append(this._createButton('fa-angle-double-right', 'ui-picklist-button-addall', function(){$this._addAll();}))
.append(this._createButton('fa-angle-left', 'ui-picklist-button-remove', function(){$this._remove();}))
.append(this._createButton('fa-angle-double-left', 'ui-picklist-button-removeall', function(){$this._removeAll();}));
this.element.append(buttonContainer);
},
_createListControls: function(list, cssClass) {
var $this = this,
buttonContainer = $('<div class="' + cssClass + ' ui-picklist-buttons"><div class="ui-picklist-buttons-cell"></div>');
buttonContainer.children('div').append(this._createButton('fa-angle-up', 'ui-picklist-button-move-up', function(){$this._moveUp(list);}))
.append(this._createButton('fa-angle-double-up', 'ui-picklist-button-move-top', function(){$this._moveTop(list);}))
.append(this._createButton('fa-angle-down', 'ui-picklist-button-move-down', function(){$this._moveDown(list);}))
.append(this._createButton('fa-angle-double-down', 'ui-picklist-button-move-bottom', function(){$this._moveBottom(list);}));
return buttonContainer;
},
_createButton: function(icon, cssClass, fn) {
var btn = $('<button class="' + cssClass + '" type="button"></button>').puibutton({
'icon': icon,
'click': function() {
fn();
$(this).removeClass('ui-state-hover ui-state-focus');
}
});
return btn;
},
_bindEvents: function() {
var $this = this;
this.items.on('mouseover.puipicklist', function(e) {
var element = $(this);
if(!element.hasClass('ui-state-highlight')) {
$(this).addClass('ui-state-hover');
}
})
.on('mouseout.puipicklist', function(e) {
$(this).removeClass('ui-state-hover');
})
.on('click.puipicklist', function(e) {
var item = $(this),
metaKey = (e.metaKey||e.ctrlKey);
if(!e.shiftKey) {
if(!metaKey) {
$this.unselectAll();
}
if(metaKey && item.hasClass('ui-state-highlight')) {
$this.unselectItem(item);
}
else {
$this.selectItem(item);
$this.cursorItem = item;
}
}
else {
$this.unselectAll();
if($this.cursorItem && ($this.cursorItem.parent().is(item.parent()))) {
var currentItemIndex = item.index(),
cursorItemIndex = $this.cursorItem.index(),
startIndex = (currentItemIndex > cursorItemIndex) ? cursorItemIndex : currentItemIndex,
endIndex = (currentItemIndex > cursorItemIndex) ? (currentItemIndex + 1) : (cursorItemIndex + 1),
parentList = item.parent();
for(var i = startIndex ; i < endIndex; i++) {
$this.selectItem(parentList.children('li.ui-picklist-item').eq(i));
}
}
else {
$this.selectItem(item);
$this.cursorItem = item;
}
}
})
.on('dblclick.pickList', function() {
var item = $(this);
if($(this).closest('.ui-picklist-listwrapper').hasClass('ui-picklist-source-wrapper'))
$this._transfer(item, $this.sourceList, $this.targetList, 'dblclick');
else
$this._transfer(item, $this.targetList, $this.sourceList, 'dblclick');
PUI.clearSelection();
});
if(this.options.filter) {
this._setupFilterMatcher();
this.element.find('> .ui-picklist-source-wrapper > .ui-picklist-filter-container > input').on('keyup', function(e) {
$this._filter(this.value, $this.sourceList);
});
this.element.find('> .ui-picklist-target-wrapper > .ui-picklist-filter-container > input').on('keyup', function(e) {
$this._filter(this.value, $this.targetList);
});
}
if(this.options.dragdrop) {
this.element.find('> .ui-picklist-listwrapper > ul.ui-picklist-list').sortable({
cancel: '.ui-state-disabled',
connectWith: '#' + this.element.attr('id') + ' .ui-picklist-list',
revert: 1,
update: function(event, ui) {
$this.unselectItem(ui.item);
$this._saveState();
},
receive: function(event, ui) {
$this._triggerTransferEvent(ui.item, ui.sender, ui.item.closest('ul.ui-picklist-list'), 'dragdrop');
}
});
}
},
selectItem: function(item) {
item.removeClass('ui-state-hover').addClass('ui-state-highlight');
},
unselectItem: function(item) {
item.removeClass('ui-state-highlight');
},
unselectAll: function() {
var selectedItems = this.items.filter('.ui-state-highlight');
for(var i = 0; i < selectedItems.length; i++) {
this.unselectItem(selectedItems.eq(i));
}
},
_add: function() {
var items = this.sourceList.children('li.ui-picklist-item.ui-state-highlight');
this._transfer(items, this.sourceList, this.targetList, 'command');
},
_addAll: function() {
var items = this.sourceList.children('li.ui-picklist-item:visible:not(.ui-state-disabled)');
this._transfer(items, this.sourceList, this.targetList, 'command');
},
_remove: function() {
var items = this.targetList.children('li.ui-picklist-item.ui-state-highlight');
this._transfer(items, this.targetList, this.sourceList, 'command');
},
_removeAll: function() {
var items = this.targetList.children('li.ui-picklist-item:visible:not(.ui-state-disabled)');
this._transfer(items, this.targetList, this.sourceList, 'command');
},
_moveUp: function(list) {
var $this = this,
animated = $this.options.effect,
items = list.children('.ui-state-highlight'),
itemsCount = items.length,
movedCount = 0;
items.each(function() {
var item = $(this);
if(!item.is(':first-child')) {
if(animated) {
item.hide($this.options.effect, {}, $this.options.effectSpeed, function() {
item.insertBefore(item.prev()).show($this.options.effect, {}, $this.options.effectSpeed, function() {
movedCount++;
if(movedCount === itemsCount) {
$this._saveState();
}
});
});
}
else {
item.hide().insertBefore(item.prev()).show();
}
}
});
if(!animated) {
this._saveState();
}
},
_moveTop: function(list) {
var $this = this,
animated = $this.options.effect,
items = list.children('.ui-state-highlight'),
itemsCount = items.length,
movedCount = 0;
list.children('.ui-state-highlight').each(function() {
var item = $(this);
if(!item.is(':first-child')) {
if(animated) {
item.hide($this.options.effect, {}, $this.options.effectSpeed, function() {
item.prependTo(item.parent()).show($this.options.effect, {}, $this.options.effectSpeed, function(){
movedCount++;
if(movedCount === itemsCount) {
$this._saveState();
}
});
});
}
else {
item.hide().prependTo(item.parent()).show();
}
}
});
if(!animated) {
this._saveState();
}
},
_moveDown: function(list) {
var $this = this,
animated = $this.options.effect,
items = list.children('.ui-state-highlight'),
itemsCount = items.length,
movedCount = 0;
$(list.children('.ui-state-highlight').get().reverse()).each(function() {
var item = $(this);
if(!item.is(':last-child')) {
if(animated) {
item.hide($this.options.effect, {}, $this.options.effectSpeed, function() {
item.insertAfter(item.next()).show($this.options.effect, {}, $this.options.effectSpeed, function() {
movedCount++;
if(movedCount === itemsCount) {
$this._saveState();
}
});
});
}
else {
item.hide().insertAfter(item.next()).show();
}
}
});
if(!animated) {
this._saveState();
}
},
_moveBottom: function(list) {
var $this = this,
animated = $this.options.effect,
items = list.children('.ui-state-highlight'),
itemsCount = items.length,
movedCount = 0;
list.children('.ui-state-highlight').each(function() {
var item = $(this);
if(!item.is(':last-child')) {
if(animated) {
item.hide($this.options.effect, {}, $this.options.effectSpeed, function() {
item.appendTo(item.parent()).show($this.options.effect, {}, $this.options.effectSpeed, function() {
movedCount++;
if(movedCount === itemsCount) {
$this._saveState();
}
});
});
}
else {
item.hide().appendTo(item.parent()).show();
}
}
});
if(!animated) {
this._saveState();
}
},
_transfer: function(items, from, to, type) {
var $this = this,
itemsCount = items.length,
transferCount = 0;
if(this.options.effect) {
items.hide(this.options.effect, {}, this.options.effectSpeed, function() {
var item = $(this);
$this.unselectItem(item);
item.appendTo(to).show($this.options.effect, {}, $this.options.effectSpeed, function() {
transferCount++;
if(transferCount === itemsCount) {
$this._saveState();
$this._triggerTransferEvent(items, from, to, type);
}
});
});
}
else {
items.hide().removeClass('ui-state-highlight ui-state-hover').appendTo(to).show();
this._saveState();
this._triggerTransferEvent(items, from, to, type);
}
},
_triggerTransferEvent: function(items, from, to, type) {
var obj = {};
obj.items = items;
obj.from = from;
obj.to = to;
obj.type = type;
this._trigger('transfer', null, obj);
},
_saveState: function() {
this.sourceInput.children().remove();
this.targetInput.children().remove();
this._generateItems(this.sourceList, this.sourceInput);
this._generateItems(this.targetList, this.targetInput);
this.cursorItem = null;
},
_generateItems: function(list, input) {
list.children('.ui-picklist-item').each(function() {
var item = $(this),
itemValue = item.data('item-value'),
itemLabel = item.data('item-label');
input.append('<option value="' + itemValue + '" selected="selected">' + itemLabel + '</option>');
});
},
_setupFilterMatcher: function() {
this.filterMatchers = {
'startsWith': this._startsWithFilter,
'contains': this._containsFilter,
'endsWith': this._endsWithFilter,
'custom': this.options.filterFunction
};
this.filterMatcher = this.filterMatchers[this.options.filterMatchMode];
},
_filter: function(value, list) {
var filterValue = $.trim(value).toLowerCase(),
items = list.children('li.ui-picklist-item');
if(filterValue === '') {
items.filter(':hidden').show();
}
else {
for(var i = 0; i < items.length; i++) {
var item = items.eq(i),
itemLabel = item.data('item-label');
if(this.filterMatcher(itemLabel, filterValue))
item.show();
else
item.hide();
}
}
},
_startsWithFilter: function(value, filter) {
return value.toLowerCase().indexOf(filter) === 0;
},
_containsFilter: function(value, filter) {
return value.toLowerCase().indexOf(filter) !== -1;
},
_endsWithFilter: function(value, filter) {
return value.indexOf(filter, value.length - filter.length) !== -1;
},
_setOption: function (key, value) {
$.Widget.prototype._setOption.apply(this, arguments);
if (key === 'sourceData') {
this._setOptionData(this.sourceInput, this.sourceList, this.options.sourceData);
}
if (key === 'targetData') {
this._setOptionData(this.targetInput, this.targetList, this.options.targetData);
}
},
_setOptionData: function(input, listContainer, data) {
input.empty();
listContainer.empty();
this._populateInputFromData(input, data);
this._populateContainerFromOptions(input, listContainer, data);
this._bindEvents();
},
_unbindEvents: function() {
this.items.off("mouseover.puipicklist mouseout.puipicklist click.puipicklist dblclick.pickList");
},
disable: function () {
this._unbindEvents();
this.items.addClass('ui-state-disabled');
this.element.find('.ui-picklist-buttons > button').each(function (idx, btn) {
$(btn).puibutton('disable');
});
},
enable: function () {
this._bindEvents();
this.items.removeClass('ui-state-disabled');
this.element.find('.ui-picklist-buttons > button').each(function (idx, btn) {
$(btn).puibutton('enable');
});
},
_createItemContent: function(choice) {
if(this.options.template) {
var template = this.options.template.html();
Mustache.parse(template);
return Mustache.render(template, choice);
}
else if(this.options.content) {
return this.options.content.call(this, choice);
}
else {
return choice.label;
}
}
});
})();/**
* PrimeUI progressbar widget
*/
(function() {
$.widget("primeui.puiprogressbar", {
options: {
value: 0,
labelTemplate: '{value}%',
complete: null,
easing: 'easeInOutCirc',
effectSpeed: 'normal',
showLabel: true
},
_create: function() {
this.element.addClass('ui-progressbar ui-widget ui-widget-content ui-corner-all')
.append('<div class="ui-progressbar-value ui-widget-header ui-corner-all"></div>')
.append('<div class="ui-progressbar-label"></div>');
this.jqValue = this.element.children('.ui-progressbar-value');
this.jqLabel = this.element.children('.ui-progressbar-label');
if(this.options.value !==0) {
this._setValue(this.options.value, false);
}
this.enableARIA();
},
_setValue: function(value, animate) {
var anim = (animate === undefined || animate) ? true : false;
if(value >= 0 && value <= 100) {
if(value === 0) {
this.jqValue.hide().css('width', '0%').removeClass('ui-corner-right');
this.jqLabel.hide();
}
else {
if(anim) {
this.jqValue.show().animate({
'width': value + '%'
}, this.options.effectSpeed, this.options.easing);
}
else {
this.jqValue.show().css('width', value + '%');
}
if(this.options.labelTemplate && this.options.showLabel) {
var formattedLabel = this.options.labelTemplate.replace(/{value}/gi, value);
this.jqLabel.html(formattedLabel).show();
}
if(value === 100) {
this._trigger('complete');
}
}
this.options.value = value;
this.element.attr('aria-valuenow', value);
}
},
_getValue: function() {
return this.options.value;
},
enableARIA: function() {
this.element.attr('role', 'progressbar')
.attr('aria-valuemin', 0)
.attr('aria-valuenow', this.options.value)
.attr('aria-valuemax', 100);
},
_setOption: function(key, value) {
if(key === 'value') {
this._setValue(value);
}
$.Widget.prototype._setOption.apply(this, arguments);
},
_destroy: function() {
}
});
})();/**
* PrimeUI radiobutton widget
*/
(function() {
var checkedRadios = {};
$.widget("primeui.puiradiobutton", {
_create: function() {
this.element.wrap('<div class="ui-radiobutton ui-widget"><div class="ui-helper-hidden-accessible"></div></div>');
this.container = this.element.parent().parent();
this.box = $('<div class="ui-radiobutton-box ui-widget ui-radiobutton-relative ui-state-default">').appendTo(this.container);
this.icon = $('<span class="ui-radiobutton-icon"></span>').appendTo(this.box);
this.disabled = this.element.prop('disabled');
this.label = $('label[for="' + this.element.attr('id') + '"]');
if(this.element.prop('checked')) {
this.box.addClass('ui-state-active');
this.icon.addClass('fa fa-fw fa-circle');
checkedRadios[this.element.attr('name')] = this.box;
}
if(this.disabled) {
this.box.addClass('ui-state-disabled');
} else {
this._bindEvents();
}
},
_bindEvents: function() {
var $this = this;
this.box.on('mouseover.puiradiobutton', function() {
if(!$this._isChecked())
$this.box.addClass('ui-state-hover');
}).on('mouseout.puiradiobutton', function() {
if(!$this._isChecked())
$this.box.removeClass('ui-state-hover');
}).on('click.puiradiobutton', function() {
if(!$this._isChecked()) {
$this.element.trigger('click');
if(PUI.browser.msie && parseInt(PUI.browser.version, 10) < 9) {
$this.element.trigger('change');
}
}
});
if(this.label.length > 0) {
this.label.on('click.puiradiobutton', function(e) {
$this.element.trigger('click');
e.preventDefault();
});
}
this.element.on('focus.puiradiobutton', function() {
if($this._isChecked()) {
$this.box.removeClass('ui-state-active');
}
$this.box.addClass('ui-state-focus');
})
.on('blur.puiradiobutton', function() {
if($this._isChecked()) {
$this.box.addClass('ui-state-active');
}
$this.box.removeClass('ui-state-focus');
})
.on('change.puiradiobutton', function(e) {
var name = $this.element.attr('name');
if(checkedRadios[name]) {
checkedRadios[name].removeClass('ui-state-active ui-state-focus ui-state-hover').children('.ui-radiobutton-icon').removeClass('fa fa-fw fa-circle');
}
$this.icon.addClass('fa fa-fw fa-circle');
if(!$this.element.is(':focus')) {
$this.box.addClass('ui-state-active');
}
checkedRadios[name] = $this.box;
$this._trigger('change', null);
});
},
_isChecked: function() {
return this.element.prop('checked');
},
_unbindEvents: function () {
this.box.off('mouseover.puiradiobutton mouseout.puiradiobutton click.puiradiobutton');
this.element.off('focus.puiradiobutton blur.puiradiobutton change.puiradiobutton');
if (this.label.length) {
this.label.off('click.puiradiobutton');
}
},
enable: function () {
this._bindEvents();
this.box.removeClass('ui-state-disabled');
},
disable: function () {
this._unbindEvents();
this.box.addClass('ui-state-disabled');
},
_destroy: function () {
this._unbindEvents();
this.container.removeClass('ui-radiobutton ui-widget');
this.box.remove();
this.element.unwrap().unwrap();
}
});
})();/**
* PrimeUI rating widget
*/
(function() {
$.widget("primeui.puirating", {
options: {
stars: 5,
cancel: true,
readonly: false,
disabled: false,
value: 0
},
_create: function() {
var input = this.element;
input.wrap('<div />');
this.container = input.parent();
this.container.addClass('ui-rating');
var inputVal = input.val(),
value = inputVal === '' ? this.options.value : parseInt(inputVal, 10);
if(this.options.cancel) {
this.container.append('<div class="ui-rating-cancel"><a></a></div>');
}
for(var i = 0; i < this.options.stars; i++) {
var styleClass = (value > i) ? "ui-rating-star ui-rating-star-on" : "ui-rating-star";
this.container.append('<div class="' + styleClass + '"><a></a></div>');
}
this.stars = this.container.children('.ui-rating-star');
if(input.prop('disabled')||this.options.disabled) {
this.container.addClass('ui-state-disabled');
}
else if(!input.prop('readonly')&&!this.options.readonly){
this._bindEvents();
}
},
_bindEvents: function() {
var $this = this;
this.stars.click(function() {
var value = $this.stars.index(this) + 1; //index starts from zero
$this.setValue(value);
});
this.container.children('.ui-rating-cancel').hover(function() {
$(this).toggleClass('ui-rating-cancel-hover');
})
.click(function() {
$this.cancel();
});
},
cancel: function() {
this.element.val('');
this.stars.filter('.ui-rating-star-on').removeClass('ui-rating-star-on');
this._trigger('oncancel', null);
},
getValue: function() {
var inputVal = this.element.val();
return inputVal === '' ? null : parseInt(inputVal, 10);
},
setValue: function(value) {
this.element.val(value);
//update visuals
this.stars.removeClass('ui-rating-star-on');
for(var i = 0; i < value; i++) {
this.stars.eq(i).addClass('ui-rating-star-on');
}
this._trigger('rate', null, value);
},
enable: function() {
this.container.removeClass('ui-state-disabled');
this._bindEvents();
},
disable: function() {
this.container.addClass('ui-state-disabled');
this._unbindEvents();
},
_unbindEvents: function() {
this.stars.off();
this.container.children('.ui-rating-cancel').off();
},
_updateValue: function(value) {
var stars = this.container.children('div.ui-rating-star');
stars.removeClass('ui-rating-star-on');
for(var i = 0; i < stars.length; i++) {
if(i < value) {
stars.eq(i).addClass('ui-rating-star-on');
}
}
this.element.val(value);
},
_setOption: function(key, value) {
if(key === 'value') {
this.options.value = value;
this._updateValue(value);
}
else {
$.Widget.prototype._setOption.apply(this, arguments);
}
},
_destroy: function() {
this._unbindEvents();
this.stars.remove();
this.container.children('.ui-rating-cancel').remove();
this.element.unwrap();
}
});
})();/**
* PrimeUI SelectButton Widget
*/
(function() {
$.widget("primeui.puiselectbutton", {
options: {
value: null,
choices: null,
formfield: null,
tabindex: '0',
multiple: false,
enhanced: false
},
_create: function() {
if(!this.options.enhanced) {
this.element.addClass('ui-selectbutton ui-buttonset ui-widget ui-corner-all').attr('tabindex');
if(this.options.choices) {
this.element.addClass('ui-buttonset-' + this.options.choices.length);
for(var i = 0; i < this.options.choices.length; i++) {
this.element.append('<div class="ui-button ui-widget ui-state-default ui-button-text-only" tabindex="' + this.options.tabindex + '" data-value="'
+ this.options.choices[i].value + '">' +
'<span class="ui-button-text ui-c">' +
this.options.choices[i].label +
'</span></div>');
}
}
}
else {
var $this = this;
this.options.choices = [];
this.element.children('.ui-button').each(function() {
var btn = $(this),
value = btn.attr('data-value'),
label = btn.children('span').text();
$this.options.choices.push({'label': label, 'value': value});
});
}
//cornering
this.buttons = this.element.children('div.ui-button');
this.buttons.filter(':first-child').addClass('ui-corner-left');
this.buttons.filter(':last-child').addClass('ui-corner-right');
if(!this.options.multiple) {
this.input = $('<input type="hidden" />').appendTo(this.element);
}
else {
this.input = $('<select class="ui-helper-hidden-accessible" multiple></select>').appendTo(this.element);
for (var i = 0; i < this.options.choices.length; i++) {
var selectOption = '<option value = "'+ this.options.choices[i].value +'"></option>';
this.input.append(selectOption);
}
this.selectOptions = this.input.children('option');
}
if(this.options.formfield) {
this.input.attr('name', this.options.formfield);
}
//preselection
if(this.options.value !== null && this.options.value !== undefined) {
this._updateSelection(this.options.value);
}
this._bindEvents();
},
_destroy: function() {
this._unbindEvents();
if(!this.options.enhanced) {
this.buttons.remove();
this.element.removeClass('ui-selectbutton ui-buttonset ui-widget ui-corner-all').removeAttr('tabindex');
}
else {
this.buttons.removeClass('ui-state-focus ui-state-hover ui-state-active ui-corner-left ui-corner-right');
}
this.input.remove();
},
_triggerChangeEvent: function(event) {
var $this = this;
if(this.options.multiple) {
var values = [],
indexes = [];
for(var i = 0; i < $this.buttons.length; i++) {
var btn = $this.buttons.eq(i);
if(btn.hasClass('ui-state-active')) {
values.push(btn.data('value'));
indexes.push(i);
}
}
$this._trigger('change', event, {
value: values,
index: indexes
});
}
else {
for(var i = 0; i < $this.buttons.length; i++) {
var btn = $this.buttons.eq(i);
if(btn.hasClass('ui-state-active')) {
$this._trigger('change', event, {
value: btn.data('value'),
index: i
});
break;
}
}
}
},
_bindEvents: function() {
var $this = this;
this.buttons.on('mouseover.puiselectbutton', function() {
var btn = $(this);
if(!btn.hasClass('ui-state-active')) {
btn.addClass('ui-state-hover');
}
})
.on('mouseout.puiselectbutton', function() {
$(this).removeClass('ui-state-hover');
})
.on('click.puiselectbutton', function(e) {
var btn = $(this);
if($(this).hasClass("ui-state-active")) {
$this.unselectOption(btn);
}
else {
if($this.options.multiple) {
$this.selectOption(btn);
}
else {
$this.unselectOption(btn.siblings('.ui-state-active'));
$this.selectOption(btn);
}
}
$this._triggerChangeEvent(e);
})
.on('focus.puiselectbutton', function() {
$(this).addClass('ui-state-focus');
})
.on('blur.puiselectbutton', function() {
$(this).removeClass('ui-state-focus');
})
.on('keydown.puiselectbutton', function(e) {
var keyCode = $.ui.keyCode;
if(e.which === keyCode.SPACE||e.which === keyCode.ENTER||e.which === keyCode.NUMPAD_ENTER) {
$(this).trigger('click');
e.preventDefault();
}
});
},
_unbindEvents: function() {
this.buttons.off('mouseover.puiselectbutton mouseout.puiselectbutton focus.puiselectbutton blur.puiselectbutton keydown.puiselectbutton click.puiselectbutton');
},
selectOption: function(value) {
var btn = $.isNumeric(value) ? this.element.children('.ui-button').eq(value) : value;
if(this.options.multiple) {
this.selectOptions.eq(btn.index()).prop('selected',true);
}
else
this.input.val(btn.data('value'));
btn.addClass('ui-state-active');
},
unselectOption: function(value){
var btn = $.isNumeric(value) ? this.element.children('.ui-button').eq(value) : value;
if(this.options.multiple)
this.selectOptions.eq(btn.index()).prop('selected',false);
else
this.input.val('');
btn.removeClass('ui-state-active');
btn.removeClass('ui-state-focus');
},
_setOption: function (key, value) {
if (key === 'data') {
this.element.empty();
this._bindEvents();
}
else if (key === 'value') {
this._updateSelection(value);
}
else {
$.Widget.prototype._setOption.apply(this, arguments);
}
},
_updateSelection: function(value) {
this.buttons.removeClass('ui-state-active');
for(var i = 0; i < this.buttons.length; i++) {
var button = this.buttons.eq(i),
buttonValue = button.attr('data-value');
if(this.options.multiple) {
if($.inArray(buttonValue, value) >= 0) {
button.addClass('ui-state-active');
}
}
else {
if(buttonValue == value) {
button.addClass('ui-state-active');
break;
}
}
}
}
});
})();/**
* PrimeUI spinner widget
*/
(function() {
$.widget("primeui.puispinner", {
options: {
step: 1.0,
min: undefined,
max: undefined,
prefix: null,
suffix: null
},
_create: function() {
var input = this.element,
disabled = input.prop('disabled');
input.puiinputtext().addClass('ui-spinner-input').wrap('<span class="ui-spinner ui-widget ui-corner-all" />');
this.wrapper = input.parent();
this.wrapper.append('<a class="ui-spinner-button ui-spinner-up ui-corner-tr ui-button ui-widget ui-state-default ui-button-text-only"><span class="ui-button-text"><span class="fa fa-fw fa-caret-up"></span></span></a><a class="ui-spinner-button ui-spinner-down ui-corner-br ui-button ui-widget ui-state-default ui-button-text-only"><span class="ui-button-text"><span class="fa fa-fw fa-caret-down"></span></span></a>');
this.upButton = this.wrapper.children('a.ui-spinner-up');
this.downButton = this.wrapper.children('a.ui-spinner-down');
this.options.step = this.options.step||1;
if(parseInt(this.options.step, 10) === 0) {
this.options.precision = this.options.step.toString().split(/[,]|[.]/)[1].length;
}
this._initValue();
if(!disabled&&!input.prop('readonly')) {
this._bindEvents();
}
if(disabled) {
this.wrapper.addClass('ui-state-disabled');
}
if(this.options.min !== undefined) {
input.attr('aria-valuemin', this.options.min);
}
if(this.options.max !== undefined){
input.attr('aria-valuemax', this.options.max);
}
},
_destroy: function() {
this.element.puiinputtext('destroy').removeClass('ui-spinner-input').off('keydown.puispinner keyup.puispinner blur.puispinner focus.puispinner mousewheel.puispinner');
this.wrapper.children('.ui-spinner-button').off().remove();
this.element.unwrap();
},
_bindEvents: function() {
var $this = this;
//visuals for spinner buttons
this.wrapper.children('.ui-spinner-button')
.mouseover(function() {
$(this).addClass('ui-state-hover');
}).mouseout(function() {
$(this).removeClass('ui-state-hover ui-state-active');
if($this.timer) {
window.clearInterval($this.timer);
}
}).mouseup(function() {
window.clearInterval($this.timer);
$(this).removeClass('ui-state-active').addClass('ui-state-hover');
}).mousedown(function(e) {
var element = $(this),
dir = element.hasClass('ui-spinner-up') ? 1 : -1;
element.removeClass('ui-state-hover').addClass('ui-state-active');
if($this.element.is(':not(:focus)')) {
$this.element.focus();
}
$this._repeat(null, dir);
//keep focused
e.preventDefault();
});
this.element.on('keydown.puispinner', function (e) {
var keyCode = $.ui.keyCode;
switch(e.which) {
case keyCode.UP:
$this._spin($this.options.step);
break;
case keyCode.DOWN:
$this._spin(-1 * $this.options.step);
break;
default:
//do nothing
break;
}
})
.on('keyup.puispinner', function () {
$this._updateValue();
})
.on('blur.puispinner', function () {
$this._format();
})
.on('focus.puispinner', function () {
//remove formatting
$this.element.val($this.value);
});
//mousewheel
this.element.on('mousewheel.puispinner', function(event, delta) {
if($this.element.is(':focus')) {
if(delta > 0) {
$this._spin($this.options.step);
}
else {
$this._spin(-1 * $this.options.step);
}
return false;
}
});
},
_repeat: function(interval, dir) {
var $this = this,
i = interval || 500;
window.clearTimeout(this.timer);
this.timer = window.setTimeout(function() {
$this._repeat(40, dir);
}, i);
this._spin(this.options.step * dir);
},
_toFixed: function (value, precision) {
var power = Math.pow(10, precision||0);
return String(Math.round(value * power) / power);
},
_spin: function(step) {
var newValue,
currentValue = this.value ? this.value : 0;
if(this.options.precision) {
newValue = parseFloat(this._toFixed(currentValue + step, this.options.precision));
}
else {
newValue = parseInt(currentValue + step, 10);
}
if(this.options.min !== undefined && newValue < this.options.min) {
newValue = this.options.min;
}
if(this.options.max !== undefined && newValue > this.options.max) {
newValue = this.options.max;
}
this.element.val(newValue).attr('aria-valuenow', newValue);
this.value = newValue;
this.element.trigger('change');
},
_updateValue: function() {
var value = this.element.val();
if(value === '') {
if(this.options.min !== undefined) {
this.value = this.options.min;
}
else {
this.value = 0;
}
}
else {
if(this.options.step) {
value = parseFloat(value);
}
else {
value = parseInt(value, 10);
}
if(!isNaN(value)) {
this.value = value;
}
}
},
_initValue: function() {
var value = this.element.val();
if(value === '') {
if(this.options.min !== undefined) {
this.value = this.options.min;
}
else {
this.value = 0;
}
}
else {
if(this.options.prefix) {
value = value.split(this.options.prefix)[1];
}
if(this.options.suffix) {
value = value.split(this.options.suffix)[0];
}
if(this.options.step) {
this.value = parseFloat(value);
}
else {
this.value = parseInt(value, 10);
}
}
},
_format: function() {
var value = this.value;
if(this.options.prefix) {
value = this.options.prefix + value;
}
if(this.options.suffix) {
value = value + this.options.suffix;
}
this.element.val(value);
},
_unbindEvents: function() {
//visuals for spinner buttons
this.wrapper.children('.ui-spinner-button').off();
this.element.off();
},
enable: function() {
this.wrapper.removeClass('ui-state-disabled');
this.element.puiinputtext('enable');
this._bindEvents();
},
disable: function() {
this.wrapper.addClass('ui-state-disabled');
this.element.puiinputtext('disable');
this._unbindEvents();
},
_setOption: function(key, value) {
if(key === 'disabled') {
if(value)
this.disable();
else
this.enable();
}
else {
$.Widget.prototype._setOption.apply(this, arguments);
}
}
});
})();/**
* PrimeFaces SplitButton Widget
*/
(function() {
$.widget("primeui.puisplitbutton", {
options: {
icon: null,
iconPos: 'left',
items: null
},
_create: function() {
this.element.wrap('<div class="ui-splitbutton ui-buttonset ui-widget"></div>');
this.container = this.element.parent().uniqueId();
this.menuButton = this.container.append('<button class="ui-splitbutton-menubutton" type="button"></button>').children('.ui-splitbutton-menubutton');
this.options.disabled = this.element.prop('disabled');
if(this.options.disabled) {
this.menuButton.prop('disabled', true);
}
this.element.puibutton(this.options).removeClass('ui-corner-all').addClass('ui-corner-left');
this.menuButton.puibutton({
icon: 'fa-caret-down'
}).removeClass('ui-corner-all').addClass('ui-corner-right');
if(this.options.items && this.options.items.length) {
this._renderPanel();
this._bindEvents();
}
},
_renderPanel: function() {
this.menu = $('<div class="ui-menu ui-menu-dynamic ui-widget ui-widget-content ui-corner-all ui-helper-clearfix ui-shadow"></div>').
append('<ul class="ui-menu-list ui-helper-reset"></ul>');
this.menuList = this.menu.children('.ui-menu-list');
for(var i = 0; i < this.options.items.length; i++) {
var item = this.options.items[i],
menuitem = $('<li class="ui-menuitem ui-widget ui-corner-all" role="menuitem"></li>'),
link = $('<a class="ui-menuitem-link ui-corner-all"><span class="ui-menuitem-icon fa fa-fw ' + item.icon +'"></span><span class="ui-menuitem-text">' + item.text +'</span></a>');
if(item.url) {
link.attr('href', item.url);
}
if(item.click) {
link.on('click.puisplitbutton', item.click);
}
menuitem.append(link).appendTo(this.menuList);
}
this.menu.appendTo(this.options.appendTo||this.container);
this.options.position = {
my: 'left top',
at: 'left bottom',
of: this.element.parent()
};
},
_bindEvents: function() {
var $this = this;
this.menuButton.on('click.puisplitbutton', function() {
if($this.menu.is(':hidden'))
$this.show();
else
$this.hide();
});
this.menuList.children().on('mouseover.puisplitbutton', function(e) {
$(this).addClass('ui-state-hover');
}).on('mouseout.puisplitbutton', function(e) {
$(this).removeClass('ui-state-hover');
}).on('click.puisplitbutton', function() {
$this.hide();
});
$(document.body).bind('mousedown.' + this.container.attr('id'), function (e) {
if($this.menu.is(":hidden")) {
return;
}
var target = $(e.target);
if(target.is($this.element)||$this.element.has(target).length > 0) {
return;
}
var offset = $this.menu.offset();
if(e.pageX < offset.left ||
e.pageX > offset.left + $this.menu.width() ||
e.pageY < offset.top ||
e.pageY > offset.top + $this.menu.height()) {
$this.element.removeClass('ui-state-focus ui-state-hover');
$this.hide();
}
});
var resizeNS = 'resize.' + this.container.attr('id');
$(window).unbind(resizeNS).bind(resizeNS, function() {
if($this.menu.is(':visible')) {
$this._alignPanel();
}
});
},
show: function() {
this.menuButton.trigger('focus');
this.menu.show();
this._alignPanel();
this._trigger('show', null);
},
hide: function() {
this.menuButton.removeClass('ui-state-focus');
this.menu.fadeOut('fast');
this._trigger('hide', null);
},
_alignPanel: function() {
this.menu.css({left:'', top:'','z-index': ++PUI.zindex}).position(this.options.position);
},
disable: function() {
this.element.puibutton('disable');
this.menuButton.puibutton('disable');
},
enable: function() {
this.element.puibutton('enable');
this.menuButton.puibutton('enable');
}
});
})();/**
* PrimeUI sticky widget
*/
(function() {
$.widget("primeui.puisticky", {
_create: function() {
this.initialState = {
top: this.element.offset().top,
height: this.element.height()
};
this.id = this.element.attr('id');
if(!this.id) {
this.id = this.element.uniqueId().attr('id');
}
this._bindEvents();
},
_bindEvents: function() {
var $this = this,
win = $(window),
scrollNS = 'scroll.' + this.id,
resizeNS = 'resize.' + this.id;
win.off(scrollNS).on(scrollNS, function() {
if(win.scrollTop() > $this.initialState.top)
$this._fix();
else
$this._restore();
})
.off(resizeNS).on(resizeNS, function() {
if($this.fixed) {
$this.element.width($this.ghost.outerWidth() - ($this.element.outerWidth() - $this.element.width()));
}
});
},
_fix: function() {
if(!this.fixed) {
this.element.css({
'position': 'fixed',
'top': 0,
'z-index': 10000
})
.addClass('ui-shadow ui-sticky');
this.ghost = $('<div class="ui-sticky-ghost"></div>').height(this.initialState.height).insertBefore(this.element);
this.element.width(this.ghost.outerWidth() - (this.element.outerWidth() - this.element.width()));
this.fixed = true;
}
},
_restore: function() {
if(this.fixed) {
this.element.css({
position: 'static',
top: 'auto',
width: 'auto'
})
.removeClass('ui-shadow ui-sticky');
this.ghost.remove();
this.fixed = false;
}
}
});
})();/**
* PrimeUI Switch Widget
*/
(function() {
$.widget("primeui.puiswitch", {
options: {
onLabel: 'On',
offLabel: 'Off',
checked: false,
change: null,
enhanced: false
},
_create: function() {
if(!this.options.enhanced) {
this.element.wrap('<div class="ui-inputswitch ui-widget ui-widget-content ui-corner-all"></div>');
this.container = this.element.parent();
this.element.wrap('<div class="ui-helper-hidden-accessible"></div>');
this.container.prepend('<div class="ui-inputswitch-off"></div>' +
'<div class="ui-inputswitch-on ui-state-active"></div>' +
'<div class="ui-inputswitch-handle ui-state-default"></div>');
this.onContainer = this.container.children('.ui-inputswitch-on');
this.offContainer = this.container.children('.ui-inputswitch-off');
this.onContainer.append('<span>'+ this.options.onLabel +'</span>');
this.offContainer.append('<span>'+ this.options.offLabel +'</span>');
}
else {
this.container = this.element.closest('.ui-inputswitch');
this.onContainer = this.container.children('.ui-inputswitch-on');
this.offContainer = this.container.children('.ui-inputswitch-off');
}
this.onLabel = this.onContainer.children('span');
this.offLabel = this.offContainer.children('span');
this.handle = this.container.children('.ui-inputswitch-handle');
var onContainerWidth = this.onContainer.width(),
offContainerWidth = this.offContainer.width(),
spanPadding = this.offLabel.innerWidth() - this.offLabel.width(),
handleMargins = this.handle.outerWidth() - this.handle.innerWidth();
var containerWidth = (onContainerWidth > offContainerWidth) ? onContainerWidth : offContainerWidth,
handleWidth = containerWidth;
this.handle.css({'width':handleWidth});
handleWidth = this.handle.width();
containerWidth = containerWidth + handleWidth + 6;
var labelWidth = containerWidth - handleWidth - spanPadding - handleMargins;
this.container.css({'width': containerWidth });
this.onLabel.width(labelWidth);
this.offLabel.width(labelWidth);
//position
this.offContainer.css({ width: this.container.width() - 5 });
this.offset = this.container.width() - this.handle.outerWidth();
//default value
if(this.element.prop('checked')||this.options.checked) {
this.handle.css({ 'left': this.offset});
this.onContainer.css({ 'width': this.offset});
this.offLabel.css({ 'margin-right': -this.offset});
}
else {
this.onContainer.css({ 'width': 0 });
this.onLabel.css({'margin-left': -this.offset});
}
if(!this.element.prop('disabled')) {
this._bindEvents();
}
},
_bindEvents: function() {
var $this = this;
this.container.on('click.puiswitch', function(e) {
$this.toggle();
$this.element.trigger('focus');
});
this.element.on('focus.puiswitch', function(e) {
$this.handle.addClass('ui-state-focus');
})
.on('blur.puiswitch', function(e) {
$this.handle.removeClass('ui-state-focus');
})
.on('keydown.puiswitch', function(e) {
var keyCode = $.ui.keyCode;
if(e.which === keyCode.SPACE) {
e.preventDefault();
}
})
.on('keyup.puiswitch', function(e) {
var keyCode = $.ui.keyCode;
if(e.which === keyCode.SPACE) {
$this.toggle();
e.preventDefault();
}
})
.on('change.puiswitch', function(e) {
if($this.element.prop('checked')||$this.options.checked)
$this._checkUI();
else
$this._uncheckUI();
$this._trigger('change', e, {checked: $this.options.checked});
});
},
_unbindEvents: function() {
this.container.off('click.puiswitch');
this.element.off('focus.puiswitch blur.puiswitch keydown.puiswitch keyup.puiswitch change.puiswitch');
},
_destroy: function() {
this._unbindEvents();
if(!this.options.enhanced) {
this.onContainer.remove();
this.offContainer.remove();
this.handle.remove();
this.element.unwrap().unwrap();
}
else {
this.container.css('width', 'auto');
this.onContainer.css('width', 'auto');
this.onLabel.css('width', 'auto').css('margin-left', 0);
this.offContainer.css('width', 'auto');
this.offLabel.css('width', 'auto').css('margin-left', 0);
}
},
toggle: function() {
if(this.element.prop('checked')||this.options.checked)
this.uncheck();
else
this.check();
},
check: function() {
this.options.checked = true;
this.element.prop('checked', true).trigger('change');
},
uncheck: function() {
this.options.checked = false;
this.element.prop('checked', false).trigger('change');
},
_checkUI: function() {
this.onContainer.animate({width:this.offset}, 200);
this.onLabel.animate({marginLeft:0}, 200);
this.offLabel.animate({marginRight:-this.offset}, 200);
this.handle.animate({left:this.offset}, 200);
},
_uncheckUI: function() {
this.onContainer.animate({width:0}, 200);
this.onLabel.animate({marginLeft:-this.offset}, 200);
this.offLabel.animate({marginRight:0}, 200);
this.handle.animate({left:0}, 200);
},
_setOption: function(key, value) {
if(key === 'checked') {
if(value)
this.check();
else
this.uncheck();
}
else {
$.Widget.prototype._setOption.apply(this, arguments);
}
},
});
})();/**
* PrimeUI tabview widget
*/
(function() {
$.widget("primeui.puitabview", {
options: {
activeIndex: 0,
orientation:'top'
},
_create: function() {
var element = this.element;
this.navContainer = element.children('ul');
this.tabHeaders = this.navContainer.children('li');
this.panelContainer = element.children('div');
this._resolvePanelMode();
this.panels = this._findPanels();
element.addClass('ui-tabview ui-widget ui-widget-content ui-corner-all ui-hidden-container ui-tabview-' + this.options.orientation);
this.navContainer.addClass('ui-tabview-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all');
this.tabHeaders.addClass('ui-state-default ui-corner-top');
this.panelContainer.addClass('ui-tabview-panels');
this.panels.addClass('ui-tabview-panel ui-widget-content ui-corner-bottom');
this.tabHeaders.eq(this.options.activeIndex).addClass('ui-tabview-selected ui-state-active');
this.panels.filter(':not(:eq(' + this.options.activeIndex + '))').addClass('ui-helper-hidden');
this._bindEvents();
},
_destroy: function() {
this.element.removeClass('ui-tabview ui-widget ui-widget-content ui-corner-all ui-hidden-container ui-tabview-' + this.options.orientation);
this.navContainer.removeClass('ui-tabview-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all');
this.tabHeaders.removeClass('ui-state-default ui-corner-top ui-tabview-selected ui-state-active');
this.panelContainer.removeClass('ui-tabview-panels');
this.panels.removeClass('ui-tabview-panel ui-widget-content ui-corner-bottom ui-helper-hidden').removeData('loaded');
this._unbindEvents();
},
_bindEvents: function() {
var $this = this;
//Tab header events
this.tabHeaders.on('mouseover.puitabview', function(e) {
var element = $(this);
if(!element.hasClass('ui-state-disabled')&&!element.hasClass('ui-state-active')) {
element.addClass('ui-state-hover');
}
})
.on('mouseout.puitabview', function(e) {
var element = $(this);
if(!element.hasClass('ui-state-disabled')&&!element.hasClass('ui-state-active')) {
element.removeClass('ui-state-hover');
}
})
.on('click.puitabview', function(e) {
var element = $(this);
if($(e.target).is(':not(.fa-close)')) {
var index = element.index();
if(!element.hasClass('ui-state-disabled') && !element.hasClass('ui-state-active')) {
$this.select(index);
}
}
e.preventDefault();
});
//Closable tabs
this.navContainer.find('li .fa-close')
.on('click.puitabview', function(e) {
var index = $(this).parent().index();
$this.remove(index);
e.preventDefault();
});
},
_unbindEvents: function() {
this.tabHeaders.off('mouseover.puitabview mouseout.puitabview click.puitabview');
this.navContainer.find('li .fa-close').off('click.puitabview');
},
select: function(index) {
this.options.activeIndex = index;
var newPanel = this.panels.eq(index),
oldHeader = this.tabHeaders.filter('.ui-state-active'),
newHeader = this._getHeaderOfPanel(newPanel),
oldPanel = this.panels.filter('.ui-tabview-panel:visible'),
$this = this;
//aria
oldPanel.attr('aria-hidden', true);
oldHeader.attr('aria-expanded', false);
newPanel.attr('aria-hidden', false);
newHeader.attr('aria-expanded', true);
if(this.options.effect) {
oldPanel.hide(this.options.effect.name, null, this.options.effect.duration, function() {
oldHeader.removeClass('ui-tabview-selected ui-state-active');
newHeader.removeClass('ui-state-hover').addClass('ui-tabview-selected ui-state-active');
newPanel.show($this.options.name, null, $this.options.effect.duration, function() {
$this._trigger('change', null, {'index':index});
});
});
}
else {
oldHeader.removeClass('ui-tabview-selected ui-state-active');
oldPanel.hide();
newHeader.removeClass('ui-state-hover').addClass('ui-tabview-selected ui-state-active');
newPanel.show();
$this._trigger('change', null, {'index':index});
}
},
remove: function(index) {
var header = this.tabHeaders.eq(index),
panel = this.panels.eq(index);
this._trigger('close', null, {'index':index});
header.remove();
panel.remove();
this.tabHeaders = this.navContainer.children('li');
this.panels = this._findPanels();
if(index < this.options.activeIndex) {
this.options.activeIndex--;
}
else if(index == this.options.activeIndex) {
var newIndex = (this.options.activeIndex == this.getLength()) ? this.options.activeIndex - 1: this.options.activeIndex,
newHeader = this.tabHeaders.eq(newIndex),
newPanel = this.panels.eq(newIndex);
newHeader.removeClass('ui-state-hover').addClass('ui-tabview-selected ui-state-active');
newPanel.show();
}
},
getLength: function() {
return this.tabHeaders.length;
},
getActiveIndex: function() {
return this.options.activeIndex;
},
_markAsLoaded: function(panel) {
panel.data('loaded', true);
},
_isLoaded: function(panel) {
return panel.data('loaded') === true;
},
disable: function(index) {
this.tabHeaders.eq(index).addClass('ui-state-disabled');
},
enable: function(index) {
this.tabHeaders.eq(index).removeClass('ui-state-disabled');
},
_findPanels: function() {
var containers = this.panelContainer.children();
//primeui
if(this.panelMode === 'native') {
return containers;
}
//primeng
else if(this.panelMode === 'wrapped') {
return containers.children(':first-child');
}
},
_resolvePanelMode: function() {
var containers = this.panelContainer.children();
this.panelMode = containers.is('div') ? 'native' : 'wrapped';
},
_getHeaderOfPanel: function(panel) {
if(this.panelMode === 'native')
return this.tabHeaders.eq(panel.index());
else if(this.panelMode === 'wrapped')
return this.tabHeaders.eq(panel.parent().index());
},
_setOption: function(key, value) {
if(key === 'activeIndex') {
this.select(value);
}
else {
$.Widget.prototype._setOption.apply(this, arguments);
}
}
});
})();/**
* PrimeUI Terminal widget
*/
(function() {
$.widget("primeui.puiterminal", {
options: {
welcomeMessage: '',
prompt:'prime $',
handler: null
},
_create: function() {
this.element.addClass('ui-terminal ui-widget ui-widget-content ui-corner-all')
.append('<div>' + this.options.welcomeMessage + '</div>')
.append('<div class="ui-terminal-content"></div>')
.append('<div><span class="ui-terminal-prompt">' + this.options.prompt + '</span>' +
'<input type="text" class="ui-terminal-input" autocomplete="off"></div>' );
this.promptContainer = this.element.find('> div:last-child > span.ui-terminal-prompt');
this.content = this.element.children('.ui-terminal-content');
this.input = this.promptContainer.next();
this.commands = [];
this.commandIndex = 0;
this._bindEvents();
},
_bindEvents: function() {
var $this = this;
this.input.on('keydown.terminal', function(e) {
var keyCode = $.ui.keyCode;
switch(e.which) {
case keyCode.UP:
if($this.commandIndex > 0) {
$this.input.val($this.commands[--$this.commandIndex]);
}
e.preventDefault();
break;
case keyCode.DOWN:
if($this.commandIndex < ($this.commands.length - 1)) {
$this.input.val($this.commands[++$this.commandIndex]);
}
else {
$this.commandIndex = $this.commands.length;
$this.input.val('');
}
e.preventDefault();
break;
case keyCode.ENTER:
case keyCode.NUMPAD_ENTER:
$this._processCommand();
e.preventDefault();
break;
}
});
this.element.on('click', function() {
$this.input.trigger('focus');
});
},
_processCommand: function() {
var command = this.input.val();
this.commands.push();
this.commandIndex++;
if(this.options.handler && $.type(this.options.handler) === 'function') {
this.options.handler.call(this, command, this._updateContent);
}
},
_updateContent: function(content) {
var commandResponseContainer = $('<div></div>');
commandResponseContainer.append('<span>' + this.options.prompt + '</span><span class="ui-terminal-command">' + this.input.val() + '</span>')
.append('<div>' + content + '</div>').appendTo(this.content);
this.input.val('');
this.element.scrollTop(this.content.height());
},
clear: function() {
this.content.html('');
this.input.val('');
}
});
})();/**
* PrimeUI togglebutton widget
*/
(function() {
$.widget("primeui.puitogglebutton", {
options: {
onLabel: 'Yes',
offLabel: 'No',
onIcon: null,
offIcon: null,
checked: false
},
_create: function() {
this.element.wrap('<div class="ui-button ui-togglebutton ui-widget ui-state-default ui-corner-all" />');
this.container = this.element.parent();
this.element.addClass('ui-helper-hidden-accessible');
if(this.options.onIcon && this.options.offIcon) {
this.container.addClass('ui-button-text-icon-left');
this.container.append('<span class="ui-button-icon-left fa fa-fw"></span>');
}
else {
this.container.addClass('ui-button-text-only');
}
this.container.append('<span class="ui-button-text"></span>');
if(this.options.style) {
this.container.attr('style', this.options.style);
}
if(this.options.styleClass) {
this.container.attr('class', this.options.styleClass);
}
this.label = this.container.children('.ui-button-text');
this.icon = this.container.children('.fa');
//initial state
if(this.element.prop('checked')||this.options.checked) {
this.check(true);
} else {
this.uncheck(true);
}
if(!this.element.prop('disabled')) {
this._bindEvents();
}
},
_bindEvents: function() {
var $this = this;
this.container.on('mouseover.puitogglebutton', function() {
if(!$this.container.hasClass('ui-state-active')) {
$this.container.addClass('ui-state-hover');
}
}).on('mouseout.puitogglebutton', function() {
$this.container.removeClass('ui-state-hover');
})
.on('click.puitogglebutton', function() {
$this.toggle();
$this.element.trigger('focus');
});
this.element.on('focus.puitogglebutton', function() {
$this.container.addClass('ui-state-focus');
})
.on('blur.puitogglebutton', function() {
$this.container.removeClass('ui-state-focus');
})
.on('keydown.puitogglebutton', function(e) {
var keyCode = $.ui.keyCode;
if(e.which === keyCode.SPACE) {
e.preventDefault();
}
})
.on('keyup.puitogglebutton', function(e) {
var keyCode = $.ui.keyCode;
if(e.which === keyCode.SPACE) {
$this.toggle();
e.preventDefault();
}
});
},
_unbindEvents: function() {
this.container.off('mouseover.puitogglebutton mouseout.puitogglebutton click.puitogglebutton');
this.element.off('focus.puitogglebutton blur.puitogglebutton keydown.puitogglebutton keyup.puitogglebutton');
},
toggle: function() {
if(this.element.prop('checked'))
this.uncheck();
else
this.check();
},
check: function(silent) {
this.container.addClass('ui-state-active');
this.label.text(this.options.onLabel);
this.element.prop('checked', true);
if(this.options.onIcon) {
this.icon.removeClass(this.options.offIcon).addClass(this.options.onIcon);
}
if(!silent) {
this._trigger('change', null, {checked: true});
}
},
uncheck: function(silent) {
this.container.removeClass('ui-state-active')
this.label.text(this.options.offLabel);
this.element.prop('checked', false);
if(this.options.offIcon) {
this.icon.removeClass(this.options.onIcon).addClass(this.options.offIcon);
}
if(!silent) {
this._trigger('change', null, {checked: false});
}
},
disable: function () {
this.element.prop('disabled', true);
this.container.attr('aria-disabled', true);
this.container.addClass('ui-state-disabled').removeClass('ui-state-focus ui-state-hover');
this._unbindEvents();
},
enable: function () {
this.element.prop('disabled', false);
this.container.attr('aria-disabled', false);
this.container.removeClass('ui-state-disabled');
this._bindEvents();
},
isChecked: function() {
return this.element.prop('checked');
},
_setOption: function(key, value) {
if(key === 'checked') {
this.options.checked = value;
if(value)
this.check(true);
else
this.uncheck(true);
}
else if(key === 'disabled') {
if(value)
this.disable();
else
this.enable();
}
else {
$.Widget.prototype._setOption.apply(this, arguments);
}
},
_destroy: function() {
this._unbindEvents();
this.container.children('span').remove();
this.element.removeClass('ui-helper-hidden-accessible').unwrap();
}
});
})();/**
* PrimeFaces Tooltip Widget
*/
(function() {
$.widget("primeui.puitooltip", {
options: {
showEvent: 'mouseover',
hideEvent: 'mouseout',
showEffect: 'fade',
hideEffect: null,
showEffectSpeed: 'normal',
hideEffectSpeed: 'normal',
my: 'left top',
at: 'right bottom',
showDelay: 150,
content: null
},
_create: function() {
this.options.showEvent = this.options.showEvent + '.puitooltip';
this.options.hideEvent = this.options.hideEvent + '.puitooltip';
if(this.element.get(0) === document) {
this._bindGlobal();
}
else {
this._bindTarget();
}
},
_bindGlobal: function() {
this.container = $('<div class="ui-tooltip ui-tooltip-global ui-widget ui-widget-content ui-corner-all ui-shadow" />').appendTo(document.body);
this.globalSelector = 'a,:input,:button,img';
var $this = this;
$(document).off(this.options.showEvent + ' ' + this.options.hideEvent, this.globalSelector)
.on(this.options.showEvent, this.globalSelector, null, function() {
var target = $(this),
title = target.attr('title');
if(title) {
$this.container.text(title);
$this.globalTitle = title;
$this.target = target;
target.attr('title', '');
$this.show();
}
})
.on(this.options.hideEvent, this.globalSelector, null, function() {
var target = $(this);
if($this.globalTitle) {
$this.container.hide();
target.attr('title', $this.globalTitle);
$this.globalTitle = null;
$this.target = null;
}
});
var resizeNS = 'resize.puitooltip';
$(window).unbind(resizeNS).bind(resizeNS, function() {
if($this.container.is(':visible')) {
$this._align();
}
});
},
_bindTarget: function() {
this.container = $('<div class="ui-tooltip ui-widget ui-widget-content ui-corner-all ui-shadow" />').appendTo(document.body);
var $this = this;
this.element.off(this.options.showEvent + ' ' + this.options.hideEvent)
.on(this.options.showEvent, function() {
$this.show();
})
.on(this.options.hideEvent, function() {
$this.hide();
});
this.container.html(this.options.content);
this.element.removeAttr('title');
this.target = this.element;
var resizeNS = 'resize.' + this.element.attr('id');
$(window).unbind(resizeNS).bind(resizeNS, function() {
if($this.container.is(':visible')) {
$this._align();
}
});
},
_align: function() {
this.container.css({
left:'',
top:'',
'z-index': ++PUI.zindex
})
.position({
my: this.options.my,
at: this.options.at,
of: this.target
});
},
show: function() {
var $this = this;
this.timeout = window.setTimeout(function() {
$this._align();
$this.container.show($this.options.showEffect, {}, $this.options.showEffectSpeed);
}, this.options.showDelay);
},
hide: function() {
window.clearTimeout(this.timeout);
this.container.hide(this.options.hideEffect, {}, this.options.hideEffectSpeed, function() {
$(this).css('z-index', '');
});
}
});
})();/**
* PrimeUI Tree widget
*/
(function() {
$.widget("primeui.puitree", {
options: {
nodes: null,
lazy: false,
animate: false,
selectionMode: null,
icons: null
},
_create: function() {
this.element.uniqueId().addClass('ui-tree ui-widget ui-widget-content ui-corner-all')
.append('<ul class="ui-tree-container"></ul>');
this.rootContainer = this.element.children('.ui-tree-container');
if(this.options.selectionMode) {
this.selection = [];
}
this._bindEvents();
if($.type(this.options.nodes) === 'array') {
this._renderNodes(this.options.nodes, this.rootContainer);
}
else if($.type(this.options.nodes) === 'function') {
this.options.nodes.call(this, {}, this._initData);
}
else {
throw 'Unsupported type. nodes option can be either an array or a function';
}
},
_renderNodes: function(nodes, container) {
for(var i = 0; i < nodes.length; i++) {
this._renderNode(nodes[i], container);
}
},
_renderNode: function(node, container) {
var leaf = this.options.lazy ? node.leaf : !(node.children && node.children.length),
iconType = node.iconType||'def',
expanded = node.expanded,
selectable = this.options.selectionMode ? (node.selectable === false ? false : true) : false,
toggleIcon = leaf ? 'ui-treenode-leaf-icon' :
(node.expanded ? 'ui-tree-toggler fa fa-fw fa-caret-down' : 'ui-tree-toggler fa fa-fw fa-caret-right'),
styleClass = leaf ? 'ui-treenode ui-treenode-leaf' : 'ui-treenode ui-treenode-parent',
nodeElement = $('<li class="' + styleClass + '"></li>'),
contentElement = $('<span class="ui-treenode-content"></span>');
nodeElement.data('puidata', node.data).appendTo(container);
if(selectable) {
contentElement.addClass('ui-treenode-selectable');
}
contentElement.append('<span class="' + toggleIcon + '"></span>')
.append('<span class="ui-treenode-icon"></span>')
.append('<span class="ui-treenode-label ui-corner-all">' + node.label + '</span>')
.appendTo(nodeElement);
var iconConfig = this.options.icons && this.options.icons[iconType];
if(iconConfig) {
var iconContainer = contentElement.children('.ui-treenode-icon'),
icon = ($.type(iconConfig) === 'string') ? iconConfig : (expanded ? iconConfig.expanded : iconConfig.collapsed);
iconContainer.addClass('fa fa-fw ' + icon);
}
if(!leaf) {
var childrenContainer = $('<ul class="ui-treenode-children"></ul>');
if(!node.expanded) {
childrenContainer.hide();
}
childrenContainer.appendTo(nodeElement);
if(node.children) {
for(var i = 0; i < node.children.length; i++) {
this._renderNode(node.children[i], childrenContainer);
}
}
}
},
_initData: function(data) {
this._renderNodes(data, this.rootContainer);
},
_handleNodeData: function(data, node) {
this._renderNodes(data, node.children('.ui-treenode-children'));
this._showNodeChildren(node);
node.data('puiloaded', true);
},
_bindEvents: function() {
var $this = this,
elementId = this.element.attr('id'),
togglerSelector = '#' + elementId + ' .ui-tree-toggler';
$(document).off('click.puitree-' + elementId, togglerSelector)
.on('click.puitree-' + elementId, togglerSelector, null, function(e) {
var toggleIcon = $(this),
node = toggleIcon.closest('li');
if(node.hasClass('ui-treenode-expanded'))
$this.collapseNode(node);
else
$this.expandNode(node);
});
if(this.options.selectionMode) {
var nodeLabelSelector = '#' + elementId + ' .ui-treenode-selectable .ui-treenode-label',
nodeContentSelector = '#' + elementId + ' .ui-treenode-selectable.ui-treenode-content';
$(document).off('mouseout.puitree-' + elementId + ' mouseover.puitree-' + elementId, nodeLabelSelector)
.on('mouseout.puitree-' + elementId, nodeLabelSelector, null, function() {
$(this).removeClass('ui-state-hover');
})
.on('mouseover.puitree-' + elementId, nodeLabelSelector, null, function() {
$(this).addClass('ui-state-hover');
})
.off('click.puitree-' + elementId, nodeContentSelector)
.on('click.puitree-' + elementId, nodeContentSelector, null, function(e) {
$this._nodeClick(e, $(this));
});
}
},
expandNode: function(node) {
this._trigger('beforeExpand', null, {'node': node, 'data': node.data('puidata')});
if(this.options.lazy && !node.data('puiloaded')) {
this.options.nodes.call(this, {
'node': node,
'data': node.data('puidata')
}, this._handleNodeData);
}
else {
this._showNodeChildren(node);
}
},
collapseNode: function(node) {
this._trigger('beforeCollapse', null, {'node': node, 'data': node.data('puidata')});
node.removeClass('ui-treenode-expanded');
var iconType = node.iconType||'def',
iconConfig = this.options.icons && this.options.icons[iconType];
if(iconConfig && $.type(iconConfig) !== 'string') {
node.find('> .ui-treenode-content > .ui-treenode-icon').removeClass(iconConfig.expanded).addClass(iconConfig.collapsed);
}
var toggleIcon = node.find('> .ui-treenode-content > .ui-tree-toggler'),
childrenContainer = node.children('.ui-treenode-children');
toggleIcon.addClass('fa-caret-right').removeClass('fa-caret-down');
if(this.options.animate) {
childrenContainer.slideUp('fast');
}
else {
childrenContainer.hide();
}
this._trigger('afterCollapse', null, {'node': node, 'data': node.data('puidata')});
},
_showNodeChildren: function(node) {
node.addClass('ui-treenode-expanded').attr('aria-expanded', true);
var iconType = node.iconType||'def',
iconConfig = this.options.icons && this.options.icons[iconType];
if(iconConfig && $.type(iconConfig) !== 'string') {
node.find('> .ui-treenode-content > .ui-treenode-icon').removeClass(iconConfig.collapsed).addClass(iconConfig.expanded);
}
var toggleIcon = node.find('> .ui-treenode-content > .ui-tree-toggler');
toggleIcon.addClass('fa-caret-down').removeClass('fa-caret-right');
if(this.options.animate) {
node.children('.ui-treenode-children').slideDown('fast');
}
else {
node.children('.ui-treenode-children').show();
}
this._trigger('afterExpand', null, {'node': node, 'data': node.data('puidata')});
},
_nodeClick: function(event, nodeContent) {
PUI.clearSelection();
if($(event.target).is(':not(.ui-tree-toggler)')) {
var node = nodeContent.parent();
var selected = this._isNodeSelected(node.data('puidata')),
metaKey = event.metaKey||event.ctrlKey;
if(selected && metaKey) {
this.unselectNode(node);
}
else {
if(this._isSingleSelection()||(this._isMultipleSelection() && !metaKey)) {
this.unselectAllNodes();
}
this.selectNode(node);
}
}
},
selectNode: function(node) {
node.attr('aria-selected', true).find('> .ui-treenode-content > .ui-treenode-label').removeClass('ui-state-hover').addClass('ui-state-highlight');
this._addToSelection(node.data('puidata'));
this._trigger('nodeSelect', null, {'node': node, 'data': node.data('puidata')});
},
unselectNode: function(node) {
node.attr('aria-selected', false).find('> .ui-treenode-content > .ui-treenode-label').removeClass('ui-state-highlight ui-state-hover');
this._removeFromSelection(node.data('puidata'));
this._trigger('nodeUnselect', null, {'node': node, 'data': node.data('puidata')});
},
unselectAllNodes: function() {
this.selection = [];
this.element.find('.ui-treenode-label.ui-state-highlight').each(function() {
$(this).removeClass('ui-state-highlight').closest('.ui-treenode').attr('aria-selected', false);
});
},
_addToSelection: function(nodedata) {
if(nodedata) {
var selected = this._isNodeSelected(nodedata);
if(!selected) {
this.selection.push(nodedata);
}
}
},
_removeFromSelection: function(nodedata) {
if(nodedata) {
var index = -1;
for(var i = 0; i < this.selection.length; i++) {
var data = this.selection[i];
if(data && (JSON.stringify(data) === JSON.stringify(nodedata))) {
index = i;
break;
}
}
if(index >= 0) {
this.selection.splice(index, 1);
}
}
},
_isNodeSelected: function(nodedata) {
var selected = false;
if(nodedata) {
for(var i = 0; i < this.selection.length; i++) {
var data = this.selection[i];
if(data && (JSON.stringify(data) === JSON.stringify(nodedata))) {
selected = true;
break;
}
}
}
return selected;
},
_isSingleSelection: function() {
return this.options.selectionMode && this.options.selectionMode === 'single';
},
_isMultipleSelection: function() {
return this.options.selectionMode && this.options.selectionMode === 'multiple';
}
});
})();/**
* PrimeUI TreeTable widget
*/
(function() {
$.widget("primeui.puitreetable", {
options: {
nodes: null,
lazy: false,
selectionMode: null,
header: null
},
_create: function() {
this.id = this.element.attr('id');
if(!this.id) {
this.id = this.element.uniqueId().attr('id');
}
this.element.addClass('ui-treetable ui-widget');
this.tableWrapper = $('<div class="ui-treetable-tablewrapper" />').appendTo(this.element);
this.table = $('<table><thead></thead><tbody></tbody></table>').appendTo(this.tableWrapper);
this.thead = this.table.children('thead');
this.tbody = this.table.children('tbody').addClass('ui-treetable-data');
var $this = this;
if(this.options.columns) {
var headerRow = $('<tr></tr>').appendTo(this.thead);
$.each(this.options.columns, function(i, col) {
var header = $('<th class="ui-state-default"></th>').data('field', col.field).appendTo(headerRow);
if(col.headerClass) {
header.addClass(col.headerClass);
}
if(col.headerStyle) {
header.attr('style', col.headerStyle);
}
if(col.headerText) {
header.text(col.headerText);
}
});
}
if(this.options.header) {
this.element.prepend('<div class="ui-treetable-header ui-widget-header ui-corner-top">' + this.options.header + '</div>');
}
if(this.options.footer) {
this.element.append('<div class="ui-treetable-footer ui-widget-header ui-corner-bottom">' + this.options.footer + '</div>');
}
if($.isArray(this.options.nodes)) {
this._renderNodes(this.options.nodes, null, true);
}
else if($.type(this.options.nodes) === 'function') {
this.options.nodes.call(this, {}, this._initData);
}
else {
throw 'Unsupported type. nodes option can be either an array or a function';
}
this._bindEvents();
},
_initData: function(data) {
this._renderNodes(data, null, true);
},
_renderNodes: function(nodes, rootRow, expanded) {
for(var i = 0; i < nodes.length; i++) {
var node = nodes[i],
nodeData = node.data,
leaf = this.options.lazy ? node.leaf : !(node.children && node.children.length),
row = $('<tr class="ui-widget-content"></tr>'),
depth = rootRow ? rootRow.data('depth') + 1 : 0,
parentRowkey = rootRow ? rootRow.data('rowkey'): null,
rowkey = parentRowkey ? parentRowkey + '_' + i : i.toString();
row.data({
'depth': depth,
'rowkey': rowkey,
'parentrowkey': parentRowkey,
'puidata': nodeData
});
if(!expanded) {
row.addClass('ui-helper-hidden');
}
for(var j = 0; j < this.options.columns.length; j++) {
var column = $('<td />').appendTo(row),
columnOptions = this.options.columns[j];
if(columnOptions.bodyClass) {
column.addClass(columnOptions.bodyClass);
}
if(columnOptions.bodyStyle) {
column.attr('style', columnOptions.bodyStyle);
}
if(j === 0) {
var toggler = $('<span class="ui-treetable-toggler fa fa-fw fa-caret-right ui-c"></span>');
toggler.css('margin-left', depth * 16 + 'px');
if(leaf) {
toggler.css('visibility', 'hidden');
}
toggler.appendTo(column);
}
if(columnOptions.content) {
var content = columnOptions.content.call(this, nodeData);
if($.type(content) === 'string')
column.text(content);
else
column.append(content);
}
else {
column.append(nodeData[columnOptions.field]);
}
}
if(rootRow)
row.insertAfter(rootRow);
else
row.appendTo(this.tbody);
if(!leaf) {
this._renderNodes(node.children, row, node.expanded);
}
}
},
_bindEvents: function() {
var $this = this,
togglerSelector = '> tr > td:first-child > .ui-treetable-toggler';
//expand and collapse
this.tbody.off('click.puitreetable', togglerSelector)
.on('click.puitreetable', togglerSelector, null, function(e) {
var toggler = $(this),
row = toggler.closest('tr');
if(!row.data('processing')) {
row.data('processing', true);
if(toggler.hasClass('fa-caret-right'))
$this.expandNode(row);
else
$this.collapseNode(row);
}
});
//selection
if(this.options.selectionMode) {
this.selection = [];
var rowSelector = '> tr';
this.tbody.off('mouseover.puitreetable mouseout.puitreetable click.puitreetable', rowSelector)
.on('mouseover.puitreetable', rowSelector, null, function(e) {
var element = $(this);
if(!element.hasClass('ui-state-highlight')) {
element.addClass('ui-state-hover');
}
})
.on('mouseout.puitreetable', rowSelector, null, function(e) {
var element = $(this);
if(!element.hasClass('ui-state-highlight')) {
element.removeClass('ui-state-hover');
}
})
.on('click.puitreetable', rowSelector, null, function(e) {
$this.onRowClick(e, $(this));
});
}
},
expandNode: function(row) {
this._trigger('beforeExpand', null, {'node': row, 'data': row.data('puidata')});
if(this.options.lazy && !row.data('puiloaded')) {
this.options.nodes.call(this, {
'node': row,
'data': row.data('puidata')
}, this._handleNodeData);
}
else {
this._showNodeChildren(row, false);
this._trigger('afterExpand', null, {'node': row, 'data': row.data('puidata')});
}
},
_handleNodeData: function(data, node) {
this._renderNodes(data, node, true);
this._showNodeChildren(node, false);
node.data('puiloaded', true);
this._trigger('afterExpand', null, {'node': node, 'data': node.data('puidata')});
},
_showNodeChildren: function(row, showOnly) {
if(!showOnly) {
row.data('expanded', true).attr('aria-expanded', true)
.find('.ui-treetable-toggler:first').addClass('fa-caret-down').removeClass('fa-caret-right');
}
var children = this._getChildren(row);
for(var i = 0; i < children.length; i++) {
var child = children[i];
child.removeClass('ui-helper-hidden');
if(child.data('expanded')) {
this._showNodeChildren(child, true);
}
}
row.data('processing', false);
},
collapseNode: function(row) {
this._trigger('beforeCollapse', null, {'node': row, 'data': row.data('puidata')});
this._hideNodeChildren(row, false);
row.data('processing', false);
this._trigger('afterCollapse', null, {'node': row, 'data': row.data('puidata')});
},
_hideNodeChildren: function(row, hideOnly) {
if(!hideOnly) {
row.data('expanded', false).attr('aria-expanded', false)
.find('.ui-treetable-toggler:first').addClass('fa-caret-right').removeClass('fa-caret-down');
}
var children = this._getChildren(row);
for(var i = 0; i < children.length; i++) {
var child = children[i];
child.addClass('ui-helper-hidden');
if(child.data('expanded')) {
this._hideNodeChildren(child, true);
}
}
},
onRowClick: function(event, row) {
if(!$(event.target).is(':input,:button,a,.ui-c')) {
var selected = row.hasClass('ui-state-highlight'),
metaKey = event.metaKey||event.ctrlKey;
if(selected && metaKey) {
this.unselectNode(row);
}
else {
if(this.isSingleSelection()||(this.isMultipleSelection() && !metaKey)) {
this.unselectAllNodes();
}
this.selectNode(row);
}
PUI.clearSelection();
}
},
selectNode: function(row, silent) {
row.removeClass('ui-state-hover').addClass('ui-state-highlight').attr('aria-selected', true);
if(!silent) {
this._trigger('nodeSelect', {}, {'node': row, 'data': row.data('puidata')});
}
},
unselectNode: function(row, silent) {
row.removeClass('ui-state-highlight').attr('aria-selected', false);
if(!silent) {
this._trigger('nodeUnselect', {}, {'node': row, 'data': row.data('puidata')});
}
},
unselectAllNodes: function() {
var selectedNodes = this.tbody.children('tr.ui-state-highlight');
for(var i = 0; i < selectedNodes.length; i++) {
this.unselectNode(selectedNodes.eq(i), true);
}
},
isSingleSelection: function() {
return this.options.selectionMode === 'single';
},
isMultipleSelection: function() {
return this.options.selectionMode === 'multiple';
},
_getChildren: function(node) {
var nodeKey = node.data('rowkey'),
nextNodes = node.nextAll(),
children = [];
for(var i = 0; i < nextNodes.length; i++) {
var nextNode = nextNodes.eq(i),
nextNodeParentKey = nextNode.data('parentrowkey');
if(nextNodeParentKey === nodeKey) {
children.push(nextNode);
}
}
return children;
}
});
})();
/**
* PrimeUI ColResize widget
*/
(function() {
$.widget("primeui.puicolresize", {
options: {
mode: 'fit'
},
_create: function() {
this.element.addClass('ui-datatable-resizable');
this.thead = this.element.find('> .ui-datatable-tablewrapper > table > thead');
this.thead.find('> tr > th').addClass('ui-resizable-column');
this.resizerHelper = $('<div class="ui-column-resizer-helper ui-state-highlight"></div>').appendTo(this.element);
this.addResizers();
var resizers = this.thead.find('> tr > th > span.ui-column-resizer'),
$this = this;
setTimeout(function() {
$this.fixColumnWidths();
}, 5);
resizers.draggable({
axis: 'x',
start: function(event, ui) {
ui.helper.data('originalposition', ui.helper.offset());
var height = $this.options.scrollable ? $this.scrollBody.height() : $this.thead.parent().height() - $this.thead.height() - 1;
$this.resizerHelper.height(height);
$this.resizerHelper.show();
},
drag: function(event, ui) {
$this.resizerHelper.offset({
left: ui.helper.offset().left + ui.helper.width() / 2,
top: $this.thead.offset().top + $this.thead.height()
});
},
stop: function(event, ui) {
ui.helper.css({
'left': '',
'top': '0px',
'right': '0px'
});
$this.resize(event, ui);
$this.resizerHelper.hide();
if($this.options.mode === 'expand') {
setTimeout(function() {
$this._trigger('colResize', null, {element: ui.helper.parent().get(0)});
}, 5);
}
else {
$this._trigger('colResize', null, {element: ui.helper.parent().get(0)});
}
},
containment: this.element
});
},
resize: function(event, ui) {
var columnHeader, nextColumnHeader, change = null, newWidth = null, nextColumnWidth = null,
expandMode = (this.options.mode === 'expand'),
table = this.thead.parent(),
columnHeader = ui.helper.parent(),
nextColumnHeader = columnHeader.next();
change = (ui.position.left - ui.originalPosition.left),
newWidth = (columnHeader.width() + change),
nextColumnWidth = (nextColumnHeader.width() - change);
if((newWidth > 15 && nextColumnWidth > 15) || (expandMode && newWidth > 15)) {
if(expandMode) {
table.width(table.width() + change);
setTimeout(function() {
columnHeader.width(newWidth);
}, 1);
}
else {
columnHeader.width(newWidth);
nextColumnHeader.width(nextColumnWidth);
}
}
},
addResizers: function() {
var resizableColumns = this.thead.find('> tr > th.ui-resizable-column');
resizableColumns.prepend('<span class="ui-column-resizer"> </span>');
if(this.options.columnResizeMode === 'fit') {
resizableColumns.filter(':last-child').children('span.ui-column-resizer').hide();
}
},
fixColumnWidths: function() {
if(!this.columnWidthsFixed) {
this.element.find('> .ui-datatable-tablewrapper > table > thead > tr > th').each(function() {
var col = $(this);
col.width(col.width());
});
this.columnWidthsFixed = true;
}
},
_destroy: function() {
this.element.removeClass('ui-datatable-resizable');
this.thead.find('> tr > th').removeClass('ui-resizable-column');
this.resizerHelper.remove();
this.thead.find('> tr > th > span.ui-column-resizer').draggable('destroy').remove();
}
});
})();
/**
* PrimeUI ColReorder widget
*/
(function() {
$.widget("primeui.puicolreorder", {
_create: function() {
var $this = this;
this.thead = this.element.find('> .ui-datatable-tablewrapper > table > thead');
this.tbody = this.element.find('> .ui-datatable-tablewrapper > table > tbody');
this.dragIndicatorTop = $('<span class="fa fa-arrow-down" style="position:absolute"/></span>').hide().appendTo(this.element);
this.dragIndicatorBottom = $('<span class="fa fa-arrow-up" style="position:absolute"/></span>').hide().appendTo(this.element);
this.thead.find('> tr > th').draggable({
appendTo: 'body',
opacity: 0.75,
cursor: 'move',
scope: this.id,
cancel: ':input,.ui-column-resizer',
drag: function(event, ui) {
var droppable = ui.helper.data('droppable-column');
if(droppable) {
var droppableOffset = droppable.offset(),
topArrowY = droppableOffset.top - 10,
bottomArrowY = droppableOffset.top + droppable.height() + 8,
arrowX = null;
//calculate coordinates of arrow depending on mouse location
if(event.originalEvent.pageX >= droppableOffset.left + (droppable.width() / 2)) {
var nextDroppable = droppable.next();
if(nextDroppable.length == 1)
arrowX = nextDroppable.offset().left - 9;
else
arrowX = droppable.offset().left + droppable.innerWidth() - 9;
ui.helper.data('drop-location', 1); //right
}
else {
arrowX = droppableOffset.left - 9;
ui.helper.data('drop-location', -1); //left
}
$this.dragIndicatorTop.offset({
'left': arrowX,
'top': topArrowY - 3
}).show();
$this.dragIndicatorBottom.offset({
'left': arrowX,
'top': bottomArrowY - 3
}).show();
}
},
stop: function(event, ui) {
//hide dnd arrows
$this.dragIndicatorTop.css({
'left':0,
'top':0
}).hide();
$this.dragIndicatorBottom.css({
'left':0,
'top':0
}).hide();
},
helper: function() {
var header = $(this),
helper = $('<div class="ui-widget ui-state-default" style="padding:4px 10px;text-align:center;"></div>');
helper.width(header.width());
helper.height(header.height());
helper.html(header.html());
return helper.get(0);
}
})
.droppable({
hoverClass:'ui-state-highlight',
tolerance:'pointer',
scope: this.id,
over: function(event, ui) {
ui.helper.data('droppable-column', $(this));
},
drop: function(event, ui) {
var draggedColumnHeader = ui.draggable,
droppedColumnHeader = $(this),
dropLocation = ui.helper.data('drop-location');
$this._trigger('colReorder', null, {
dragIndex: draggedColumnHeader.index(),
dropIndex: droppedColumnHeader.index(),
dropSide: dropLocation
});
}
});
},
_destroy: function() {
this.dragIndicatorTop.remove();
this.dragIndicatorBottom.remove();
this.thead.find('> tr > th').draggable('destroy').droppable('destroy');
}
});
})();
/**
* PrimeUI TableScroll widget
*/
(function() {
$.widget("primeui.puitablescroll", {
options: {
scrollHeight: null,
scrollWidth: null
},
_create: function() {
this.id = PUI.generateRandomId();
this.scrollHeader = this.element.children('.ui-datatable-scrollable-header');
this.scrollBody = this.element.children('.ui-datatable-scrollable-body');
this.scrollHeaderBox = this.scrollHeader.children('.ui-datatable-scrollable-header-box');
this.bodyTable = this.scrollBody.children('table');
this.percentageScrollHeight = this.options.scrollHeight && (this.options.scrollHeight.indexOf('%') !== -1);
this.percentageScrollWidth = this.options.scrollWidth && (this.options.scrollWidth.indexOf('%') !== -1);
var $this = this,
scrollBarWidth = this.getScrollbarWidth() + 'px';
if(this.options.scrollHeight) {
if(this.percentageScrollHeight)
this.adjustScrollHeight();
else
this.scrollBody.css('max-height', this.options.scrollHeight + 'px');
this.scrollHeaderBox.css('margin-right', scrollBarWidth);
}
if(this.options.scrollWidth) {
if(this.percentageScrollWidth)
this.adjustScrollWidth();
else
this.setScrollWidth(parseInt(this.options.scrollWidth));
}
this.scrollBody.on('scroll.dataTable', function() {
var scrollLeft = $this.scrollBody.scrollLeft();
$this.scrollHeaderBox.css('margin-left', -scrollLeft);
});
this.scrollHeader.on('scroll.dataTable', function() {
$this.scrollHeader.scrollLeft(0);
});
$(window).on('resize.' + this.id, function() {
if($this.element.is(':visible')) {
if($this.percentageScrollHeight)
$this.adjustScrollHeight();
if($this.percentageScrollWidth)
$this.adjustScrollWidth();
}
});
},
_destroy: function() {
$(window).off('resize.' + this.id);
this.scrollHeader.off('scroll.dataTable');
this.scrollBody.off('scroll.dataTable');
},
adjustScrollHeight: function() {
var relativeHeight = this.element.parent().parent().innerHeight() * (parseInt(this.options.scrollHeight) / 100),
tableHeaderHeight = this.element.children('.ui-datatable-header').outerHeight(true),
tableFooterHeight = this.element.children('.ui-datatable-footer').outerHeight(true),
scrollersHeight = (this.scrollHeader.outerHeight(true) + this.scrollFooter.outerHeight(true)),
paginatorsHeight = this.paginator ? this.paginator.getContainerHeight(true) : 0,
height = (relativeHeight - (scrollersHeight + paginatorsHeight + tableHeaderHeight + tableFooterHeight));
this.scrollBody.css('max-height', height + 'px');
},
adjustScrollWidth: function() {
var width = parseInt((this.element.parent().parent().innerWidth() * (parseInt(this.options.scrollWidth) / 100)));
this.setScrollWidth(width);
},
setOuterWidth: function(element, width) {
var diff = element.outerWidth() - element.width();
element.width(width - diff);
},
setScrollWidth: function(width) {
var $this = this;
this.element.children('.ui-widget-header').each(function() {
$this.setOuterWidth($(this), width);
});
this.scrollHeader.width(width);
this.scrollBody.css('margin-right', 0).width(width);
},
getScrollbarWidth: function() {
if(!this.scrollbarWidth) {
this.scrollbarWidth = PUI.calculateScrollbarWidth();
}
return this.scrollbarWidth;
}
});
})(); |
/**
* @author TatumCreative (Greg Tatum) / http://gregtatum.com/
*/
var constants = {
combine: {
"THREE.MultiplyOperation" : THREE.MultiplyOperation,
"THREE.MixOperation" : THREE.MixOperation,
"THREE.AddOperation" : THREE.AddOperation
},
side : {
"THREE.FrontSide" : THREE.FrontSide,
"THREE.BackSide" : THREE.BackSide,
"THREE.DoubleSide" : THREE.DoubleSide
},
shading : {
"THREE.FlatShading" : THREE.FlatShading,
"THREE.SmoothShading" : THREE.SmoothShading
},
colors : {
"THREE.NoColors" : THREE.NoColors,
"THREE.FaceColors" : THREE.FaceColors,
"THREE.VertexColors" : THREE.VertexColors
},
blendingMode : {
"THREE.NoBlending" : THREE.NoBlending,
"THREE.NormalBlending" : THREE.NormalBlending,
"THREE.AdditiveBlending" : THREE.AdditiveBlending,
"THREE.SubtractiveBlending" : THREE.SubtractiveBlending,
"THREE.MultiplyBlending" : THREE.MultiplyBlending,
"THREE.CustomBlending" : THREE.CustomBlending
},
equations : {
"THREE.AddEquation" : THREE.AddEquation,
"THREE.SubtractEquation" : THREE.SubtractEquation,
"THREE.ReverseSubtractEquation" : THREE.ReverseSubtractEquation
},
destinationFactors : {
"THREE.ZeroFactor" : THREE.ZeroFactor,
"THREE.OneFactor" : THREE.OneFactor,
"THREE.SrcColorFactor" : THREE.SrcColorFactor,
"THREE.OneMinusSrcColorFactor" : THREE.OneMinusSrcColorFactor,
"THREE.SrcAlphaFactor" : THREE.SrcAlphaFactor,
"THREE.OneMinusSrcAlphaFactor" : THREE.OneMinusSrcAlphaFactor,
"THREE.DstAlphaFactor" : THREE.DstAlphaFactor,
"THREE.OneMinusDstAlphaFactor" : THREE.OneMinusDstAlphaFactor
},
sourceFactors : {
"THREE.DstColorFactor" : THREE.DstColorFactor,
"THREE.OneMinusDstColorFactor" : THREE.OneMinusDstColorFactor,
"THREE.SrcAlphaSaturateFactor" : THREE.SrcAlphaSaturateFactor
}
}
function getObjectsKeys( obj ) {
var keys = [];
for ( var key in obj ) {
if ( obj.hasOwnProperty( key ) ) {
keys.push( key );
}
}
return keys;
}
var envMaps = (function () {
var path = "../../examples/textures/cube/SwedishRoyalCastle/";
var format = '.jpg';
var urls = [
path + 'px' + format, path + 'nx' + format,
path + 'py' + format, path + 'ny' + format,
path + 'pz' + format, path + 'nz' + format
];
var reflectionCube = THREE.ImageUtils.loadTextureCube( urls );
reflectionCube.format = THREE.RGBFormat;
var refractionCube = THREE.ImageUtils.loadTextureCube( urls );
refractionCube.mapping = THREE.CubeRefractionMapping;
refractionCube.format = THREE.RGBFormat;
return {
none : null,
reflection : reflectionCube,
refraction : refractionCube
};
})();
var envMapKeys = getObjectsKeys( envMaps );
var textureMaps = (function () {
return {
none : null,
grass : THREE.ImageUtils.loadTexture( "../../examples/textures/terrain/grasslight-thin.jpg" )
};
})();
var textureMapKeys = getObjectsKeys( textureMaps );
function generateVertexColors ( geometry ) {
for ( var i=0, il = geometry.faces.length; i < il; i++ ) {
geometry.faces[i].vertexColors.push( new THREE.Color().setHSL(
i / il * Math.random(),
0.5,
0.5
) );
geometry.faces[i].vertexColors.push( new THREE.Color().setHSL(
i / il * Math.random(),
0.5,
0.5
) );
geometry.faces[i].vertexColors.push( new THREE.Color().setHSL(
i / il * Math.random(),
0.5,
0.5
) );
geometry.faces[i].color = new THREE.Color().setHSL(
i / il * Math.random(),
0.5,
0.5
);
}
}
function generateMorphTargets ( mesh, geometry ) {
var vertices = [], scale;
for ( var i = 0; i < geometry.vertices.length; i++ ) {
vertices.push( geometry.vertices[ i ].clone() );
scale = 1 + Math.random() * 0.3;
vertices[ vertices.length - 1 ].x *= scale;
vertices[ vertices.length - 1 ].y *= scale;
vertices[ vertices.length - 1 ].z *= scale;
}
geometry.morphTargets.push( { name: "target1", vertices: vertices } );
geometry.update
}
function handleColorChange ( color ) {
return function ( value ){
if (typeof value === "string") {
value = value.replace('#', '0x');
}
color.setHex( value );
};
}
function needsUpdate ( material, geometry ) {
return function () {
material.shading = +material.shading; //Ensure number
material.vertexColors = +material.vertexColors; //Ensure number
material.side = +material.side; //Ensure number
material.needsUpdate = true;
geometry.verticesNeedUpdate = true;
geometry.normalsNeedUpdate = true;
geometry.colorsNeedUpdate = true;
};
};
function updateMorphs ( torus, material ) {
return function () {
torus.updateMorphTargets();
material.needsUpdate = true;
};
}
function updateTexture ( material, materialKey, textures ) {
return function ( key ) {
material[materialKey] = textures[key];
material.needsUpdate = true;
};
}
function guiScene ( gui, scene ) {
var folder = gui.addFolder('Scene');
var data = {
background : "#000000",
"ambient light" : ambientLight.color.getHex()
}
var color = new THREE.Color();
var colorConvert = handleColorChange( color );
folder.addColor( data, "background" ).onChange( function ( value ) {
colorConvert( value );
renderer.setClearColor( color.getHex() );
} );
folder.addColor( data, "ambient light" ).onChange( handleColorChange( ambientLight.color ) )
guiSceneFog( folder, scene );
}
function guiSceneFog ( folder, scene ) {
var fogFolder = folder.addFolder('scene.fog');
var fog = new THREE.Fog( 0x3f7b9d, 0, 60 );
var data = {
fog : {
"THREE.Fog()" : false,
"scene.fog.color" : fog.color.getHex()
}
};
fogFolder.add( data.fog, 'THREE.Fog()' ).onChange( function ( useFog ) {
if ( useFog ) {
scene.fog = fog;
} else {
scene.fog = null;
}
} );
fogFolder.addColor( data.fog, 'scene.fog.color').onChange( handleColorChange( fog.color ) );
}
function guiMaterial ( gui, mesh, material, geometry ) {
var folder = gui.addFolder('THREE.Material');
folder.add( material, 'transparent' );
folder.add( material, 'opacity', 0, 1 );
// folder.add( material, 'blending', constants.blendingMode );
// folder.add( material, 'blendSrc', constants.destinationFactors );
// folder.add( material, 'blendDst', constants.destinationFactors );
// folder.add( material, 'blendEquation', constants.equations );
folder.add( material, 'depthTest' );
folder.add( material, 'depthWrite' );
// folder.add( material, 'polygonOffset' );
// folder.add( material, 'polygonOffsetFactor' );
// folder.add( material, 'polygonOffsetUnits' );
folder.add( material, 'alphaTest', 0, 1 );
// folder.add( material, 'overdraw', 0, 5 );
folder.add( material, 'visible' );
folder.add( material, 'side', constants.side ).onChange( needsUpdate( material, geometry ) );
}
function guiMeshBasicMaterial ( gui, mesh, material, geometry ) {
var data = {
color : material.color.getHex(),
envMaps : envMapKeys,
map : textureMapKeys,
specularMap : textureMapKeys,
alphaMap : textureMapKeys
};
var folder = gui.addFolder('THREE.MeshBasicMaterial');
folder.addColor( data, 'color' ).onChange( handleColorChange( material.color ) );
folder.add( material, 'wireframe' );
folder.add( material, 'wireframeLinewidth', 0, 10 );
folder.add( material, 'shading', constants.shading);
folder.add( material, 'vertexColors', constants.colors).onChange( needsUpdate( material, geometry ) );
folder.add( material, 'fog' );
folder.add( data, 'envMaps', envMapKeys ).onChange( updateTexture( material, 'envMap', envMaps ) );
folder.add( data, 'map', textureMapKeys ).onChange( updateTexture( material, 'map', textureMaps ) );
folder.add( data, 'specularMap', textureMapKeys ).onChange( updateTexture( material, 'specularMap', textureMaps ) );
folder.add( data, 'alphaMap', textureMapKeys ).onChange( updateTexture( material, 'alphaMap', textureMaps ) );
folder.add( material, 'morphTargets' ).onChange( updateMorphs( mesh, material ) );
folder.add( material, 'combine', constants.combine ).onChange( updateMorphs( mesh, material ) );
folder.add( material, 'reflectivity', 0, 1 );
folder.add( material, 'refractionRatio', 0, 1 );
//folder.add( material, 'skinning' );
}
function guiMeshDepthMaterial ( gui, mesh, material, geometry ) {
var folder = gui.addFolder('THREE.MeshDepthMaterial');
folder.add( material, 'wireframe' );
folder.add( material, 'wireframeLinewidth', 0, 10 );
folder.add( material, 'morphTargets' ).onChange( updateMorphs( mesh, material ) );
}
function guiMeshNormalMaterial ( gui, mesh, material, geometry ) {
var folder = gui.addFolder('THREE.MeshNormalMaterial');
folder.add( material, 'wireframe' );
folder.add( material, 'wireframeLinewidth', 0, 10 );
folder.add( material, 'morphTargets' ).onChange( updateMorphs( mesh, material ) );
}
function guiLineBasicMaterial ( gui, mesh, material, geometry ) {
var data = {
color : material.color.getHex()
};
var folder = gui.addFolder('THREE.LineBasicMaterial');
folder.addColor( data, 'color' ).onChange( handleColorChange( material.color ) );
folder.add( material, 'linewidth', 0, 10 );
folder.add( material, 'linecap', ["butt", "round", "square"] );
folder.add( material, 'linejoin', ["round", "bevel", "miter"] );
folder.add( material, 'vertexColors', constants.colors).onChange( needsUpdate( material, geometry ) );
folder.add( material, 'fog' );
}
function guiMeshLambertMaterial ( gui, mesh, material, geometry ) {
var data = {
color : material.color.getHex(),
emissive : material.emissive.getHex(),
envMaps : envMapKeys,
map : textureMapKeys,
specularMap : textureMapKeys,
alphaMap : textureMapKeys
};
var envObj = {};
var folder = gui.addFolder('THREE.MeshLambertMaterial');
folder.addColor( data, 'color' ).onChange( handleColorChange( material.color ) );
folder.addColor( data, 'emissive' ).onChange( handleColorChange( material.emissive ) );
folder.add( material, 'wireframe' );
folder.add( material, 'wireframeLinewidth', 0, 10 );
folder.add( material, 'vertexColors', constants.colors ).onChange( needsUpdate( material, geometry ) );
folder.add( material, 'fog' );
folder.add( data, 'envMaps', envMapKeys ).onChange( updateTexture( material, 'envMap', envMaps ) );
folder.add( data, 'map', textureMapKeys ).onChange( updateTexture( material, 'map', textureMaps ) );
folder.add( data, 'specularMap', textureMapKeys ).onChange( updateTexture( material, 'specularMap', textureMaps ) );
folder.add( data, 'alphaMap', textureMapKeys ).onChange( updateTexture( material, 'alphaMap', textureMaps ) );
folder.add( material, 'morphTargets' ).onChange( updateMorphs( mesh, material ) );
folder.add( material, 'combine', constants.combine ).onChange( updateMorphs( mesh, material ) );
folder.add( material, 'reflectivity', 0, 1 );
folder.add( material, 'refractionRatio', 0, 1 );
//folder.add( material, 'skinning' );
}
function guiMeshPhongMaterial ( gui, mesh, material, geometry ) {
var data = {
color : material.color.getHex(),
emissive : material.emissive.getHex(),
specular : material.specular.getHex(),
envMaps : envMapKeys,
map : textureMapKeys,
lightMap : textureMapKeys,
specularMap : textureMapKeys,
alphaMap : textureMapKeys
};
var folder = gui.addFolder('THREE.MeshPhongMaterial');
folder.addColor( data, 'color' ).onChange( handleColorChange( material.color ) );
folder.addColor( data, 'emissive' ).onChange( handleColorChange( material.emissive ) );
folder.addColor( data, 'specular' ).onChange( handleColorChange( material.specular ) );
folder.add( material, 'shininess', 1, 100);
folder.add( material, 'shading', constants.shading).onChange( needsUpdate( material, geometry ) );
folder.add( material, 'wireframe' );
folder.add( material, 'wireframeLinewidth', 0, 10 );
folder.add( material, 'vertexColors', constants.colors);
folder.add( material, 'fog' );
folder.add( data, 'envMaps', envMapKeys ).onChange( updateTexture( material, 'envMap', envMaps ) );
folder.add( data, 'map', textureMapKeys ).onChange( updateTexture( material, 'map', textureMaps ) );
folder.add( data, 'lightMap', textureMapKeys ).onChange( updateTexture( material, 'lightMap', textureMaps ) );
folder.add( data, 'specularMap', textureMapKeys ).onChange( updateTexture( material, 'specularMap', textureMaps ) );
folder.add( data, 'alphaMap', textureMapKeys ).onChange( updateTexture( material, 'alphaMap', textureMaps ) );
}
function chooseFromHash ( gui, mesh, geometry ) {
var selectedMaterial = window.location.hash.substring(1) || "MeshBasicMaterial";
var material;
switch (selectedMaterial) {
case "MeshBasicMaterial" :
material = new THREE.MeshBasicMaterial({color: 0x2194CE});
guiMaterial( gui, mesh, material, geometry );
guiMeshBasicMaterial( gui, mesh, material, geometry );
return material;
break;
case "MeshLambertMaterial" :
material = new THREE.MeshLambertMaterial({color: 0x2194CE});
guiMaterial( gui, mesh, material, geometry );
guiMeshLambertMaterial( gui, mesh, material, geometry );
return material;
break;
case "MeshPhongMaterial" :
material = new THREE.MeshPhongMaterial({color: 0x2194CE});
guiMaterial( gui, mesh, material, geometry );
guiMeshPhongMaterial( gui, mesh, material, geometry );
return material;
break;
case "MeshDepthMaterial" :
material = new THREE.MeshDepthMaterial({color: 0x2194CE});
guiMaterial( gui, mesh, material, geometry );
guiMeshDepthMaterial( gui, mesh, material, geometry );
return material;
break;
case "MeshNormalMaterial" :
material = new THREE.MeshNormalMaterial();
guiMaterial( gui, mesh, material, geometry );
guiMeshNormalMaterial( gui, mesh, material, geometry );
return material;
break;
case "LineBasicMaterial" :
material = new THREE.LineBasicMaterial({color: 0x2194CE});
guiMaterial( gui, mesh, material, geometry );
guiLineBasicMaterial( gui, mesh, material, geometry );
return material;
break;
}
}
|
/*
* A simple reusable store that loads static calendar field definitions into memory
* and can be bound to the CalendarCombo widget and used for calendar color selection.
*/
Ext.define('Ext.calendar.data.MemoryCalendarStore', {
extend: 'Ext.data.Store',
model: 'Ext.calendar.data.CalendarModel',
requires: [
'Ext.data.proxy.Memory',
'Ext.data.reader.Json',
'Ext.data.writer.Json',
'Ext.calendar.data.CalendarModel',
'Ext.calendar.data.CalendarMappings'
],
proxy: {
type: 'memory',
reader: {
type: 'json',
root: 'calendars'
},
writer: {
type: 'json'
}
},
autoLoad: true,
initComponent: function() {
var me = this,
calendarData = Ext.calendar.data;
me.sorters = me.sorters || [{
property: calendarData.CalendarMappings.Title.name,
direction: 'ASC'
}];
me.idProperty = me.idProperty || calendarData.CalendarMappings.CalendarId.name || 'id';
me.fields = calendarData.CalendarModel.prototype.fields.getRange();
me.callParent(arguments);
}
}); |
(function(pangu) {
'use strict';
var ignore_tags = /^(code|pre|textarea)$/i;
var space_sensitive_tags = /^(a|del|pre|s|strike|u)$/i;
var space_like_tags = /^(br|hr|i|img|pangu)$/i;
var block_tags = /^(div|h1|h2|h3|h4|h5|h6|p)$/i;
function can_ignore_node(node) {
var parent_node = node.parentNode;
while (parent_node && parent_node.nodeName && parent_node.nodeName.search(/^(html|head|body|#document)$/i) === -1) {
if ((parent_node.getAttribute('contenteditable') === 'true') || (parent_node.getAttribute('g_editable') === 'true') || (parent_node.nodeName.search(ignore_tags) >= 0)) {
return true;
}
else {
parent_node = parent_node.parentNode;
}
}
return false;
}
function is_first_text_child(parent_node, target_node) {
var child_nodes = parent_node.childNodes;
for (var i = 0; i < child_nodes.length; i++) {
var child_node = child_nodes[i];
if (child_node.nodeType !== 8 && child_node.textContent) {
return child_node === target_node;
}
}
}
function is_last_text_child(parent_node, target_node) {
var child_nodes = parent_node.childNodes;
for (var i = child_nodes.length - 1; i > -1; i--) {
var child_node = child_nodes[i];
if (child_node.nodeType !== 8 && child_node.textContent) {
return child_node === target_node;
}
}
}
function insert_space(text) {
var old_text = text;
var new_text;
text = text.replace(/([\u2e80-\u2eff\u2f00-\u2fdf\u3040-\u309f\u30a0-\u30ff\u3100-\u312f\u3200-\u32ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff])(["])/g, '$1 $2');
text = text.replace(/(["])([\u2e80-\u2eff\u2f00-\u2fdf\u3040-\u309f\u30a0-\u30ff\u3100-\u312f\u3200-\u32ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff])/g, '$1 $2');
text = text.replace(/(["'\(\[\{<\u201c]+)(\s*)(.+?)(\s*)(["'\)\]\}>\u201d]+)/g, '$1$3$5');
text = text.replace(/([\u2e80-\u2eff\u2f00-\u2fdf\u3040-\u309f\u30a0-\u30ff\u3100-\u312f\u3200-\u32ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff])( )(')([A-Za-z])/g, '$1$3$4');
text = text.replace(/([\u2e80-\u2eff\u2f00-\u2fdf\u3040-\u309f\u30a0-\u30ff\u3100-\u312f\u3200-\u32ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff])(#(\S+))/g, '$1 $2');
text = text.replace(/((\S+)#)([\u2e80-\u2eff\u2f00-\u2fdf\u3040-\u309f\u30a0-\u30ff\u3100-\u312f\u3200-\u32ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff])/g, '$1 $3');
text = text.replace(/([\u2e80-\u2eff\u2f00-\u2fdf\u3040-\u309f\u30a0-\u30ff\u3100-\u312f\u3200-\u32ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff])([\+\-\*\/=&\\|<>])([A-Za-z0-9])/g, '$1 $2 $3');
text = text.replace(/([A-Za-z0-9])([\+\-\*\/=&\\|<>])([\u2e80-\u2eff\u2f00-\u2fdf\u3040-\u309f\u30a0-\u30ff\u3100-\u312f\u3200-\u32ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff])/g, '$1 $2 $3');
old_text = text;
new_text = old_text.replace(/([\u2e80-\u2eff\u2f00-\u2fdf\u3040-\u309f\u30a0-\u30ff\u3100-\u312f\u3200-\u32ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff])([\(\[\{<\u201c]+(.*?)[\)\]\}>\u201d]+)([\u2e80-\u2eff\u2f00-\u2fdf\u3040-\u309f\u30a0-\u30ff\u3100-\u312f\u3200-\u32ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff])/g, '$1 $2 $4');
text = new_text;
if (old_text === new_text) {
text = text.replace(/([\u2e80-\u2eff\u2f00-\u2fdf\u3040-\u309f\u30a0-\u30ff\u3100-\u312f\u3200-\u32ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff])([\(\[\{<\u201c>])/g, '$1 $2');
text = text.replace(/([\)\]\}>\u201d<])([\u2e80-\u2eff\u2f00-\u2fdf\u3040-\u309f\u30a0-\u30ff\u3100-\u312f\u3200-\u32ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff])/g, '$1 $2');
}
text = text.replace(/([\(\[\{<\u201c]+)(\s*)(.+?)(\s*)([\)\]\}>\u201d]+)/g, '$1$3$5');
text = text.replace(/([\u2e80-\u2eff\u2f00-\u2fdf\u3040-\u309f\u30a0-\u30ff\u3100-\u312f\u3200-\u32ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff])([~!;:,\.\?\u2026])([A-Za-z0-9])/g, '$1$2 $3');
text = text.replace(/([\u2e80-\u2eff\u2f00-\u2fdf\u3040-\u309f\u30a0-\u30ff\u3100-\u312f\u3200-\u32ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff])([A-Za-z0-9`\$%\^&\*\-=\+\\\|/@\u00a1-\u00ff\u2022\u2027\u2150-\u218f])/g, '$1 $2');
text = text.replace(/([A-Za-z0-9`~\$%\^&\*\-=\+\\\|/!;:,\.\?\u00a1-\u00ff\u2022\u2026\u2027\u2150-\u218f])([\u2e80-\u2eff\u2f00-\u2fdf\u3040-\u309f\u30a0-\u30ff\u3100-\u312f\u3200-\u32ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff])/g, '$1 $2');
text = text.replace(/(Taipei)(,)(China)/g, '$1$2 $3');
return text;
}
function spacing(xpath_query, context_node) {
context_node = context_node || document;
var had_spacing = false;
var text_nodes = document.evaluate(xpath_query, context_node, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var nodes_length = text_nodes.snapshotLength;
var next_text_node;
for (var i = nodes_length - 1; i > -1; --i) {
var current_text_node = text_nodes.snapshotItem(i);
if (can_ignore_node(current_text_node)) {
next_text_node = current_text_node;
continue;
}
var new_data = insert_space(current_text_node.data);
if (current_text_node.data !== new_data) {
had_spacing = true;
current_text_node.data = new_data;
}
if (next_text_node) {
if (current_text_node.nextSibling) {
if (current_text_node.nextSibling.nodeName.search(space_like_tags) >= 0) {
next_text_node = current_text_node;
continue;
}
}
var text = current_text_node.data.toString().substr(-1) + next_text_node.data.toString().substr(0, 1);
var new_text = insert_space(text);
if (text !== new_text) {
had_spacing = true;
var next_node = next_text_node;
while (next_node.parentNode &&
next_node.nodeName.search(space_sensitive_tags) === -1 &&
is_first_text_child(next_node.parentNode, next_node)) {
next_node = next_node.parentNode;
}
var current_node = current_text_node;
while (current_node.parentNode &&
current_node.nodeName.search(space_sensitive_tags) === -1 &&
is_last_text_child(current_node.parentNode, current_node)) {
current_node = current_node.parentNode;
}
if (current_node.nextSibling) {
if (current_node.nextSibling.nodeName.search(space_like_tags) >= 0) {
next_text_node = current_text_node;
continue;
}
}
if (current_node.nodeName.search(block_tags) === -1) {
if (next_node.nodeName.search(space_sensitive_tags) === -1) {
if ((next_node.nodeName.search(ignore_tags) === -1) && (next_node.nodeName.search(block_tags) === -1)) {
if (next_text_node.previousSibling) {
if (next_text_node.previousSibling.nodeName.search(space_like_tags) === -1) {
next_text_node.data = ' ' + next_text_node.data;
}
}
else {
if (!can_ignore_node(next_text_node)) {
next_text_node.data = ' ' + next_text_node.data;
}
}
}
}
else if (current_node.nodeName.search(space_sensitive_tags) === -1) {
current_text_node.data = current_text_node.data + ' ';
}
else {
var pangu_space = document.createElement('pangu');
pangu_space.innerHTML = ' ';
if (next_node.previousSibling) {
if (next_node.previousSibling.nodeName.search(space_like_tags) === -1) {
next_node.parentNode.insertBefore(pangu_space, next_node);
}
}
else {
next_node.parentNode.insertBefore(pangu_space, next_node);
}
if (!pangu_space.previousElementSibling) {
if (pangu_space.parentNode) {
pangu_space.parentNode.removeChild(pangu_space);
}
}
}
}
}
}
next_text_node = current_text_node;
}
return had_spacing;
}
pangu.text_spacing = function(text) {
return insert_space(text);
};
pangu.page_title_spacing = function() {
var title_query = '/html/head/title/text()';
var had_spacing = spacing(title_query);
return had_spacing;
};
pangu.page_spacing = function() {
var had_spacing_title = pangu.page_title_spacing();
var body_query = '/html/body//*/text()[normalize-space(.)]';
['script', 'style', 'textarea'].forEach(function(tag) {
body_query += '[translate(name(..),"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")!="' + tag + '"]';
});
var had_spacing_body = spacing(body_query);
return had_spacing_title || had_spacing_body;
};
pangu.node_spacing = function(context_node) {
var inserted_query = './/*/text()[normalize-space(.)]';
['script', 'style', 'textarea'].forEach(function(tag) {
inserted_query += '[translate(name(..),"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")!="' + tag + '"]';
});
var had_spacing = spacing(inserted_query, context_node);
return had_spacing;
};
pangu.element_spacing = function(selector_string) {
var xpath_query;
if (selector_string.indexOf('#') === 0) {
var target_id = selector_string.slice(1);
xpath_query = 'id("' + target_id + '")//text()';
}
else if (selector_string.indexOf('.') === 0) {
var target_class = selector_string.slice(1);
xpath_query = '//*[contains(concat(" ", normalize-space(@class), " "), "' + target_class + '")]//text()';
}
else {
var target_tag = selector_string;
xpath_query = '//' + target_tag + '//text()';
}
var had_spacing = spacing(xpath_query);
return had_spacing;
};
}(window.pangu = window.pangu || {}));
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
* @format
* @preventMunge
*/
'use strict';
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
import { AnimatedEvent, attachNativeEvent } from './AnimatedEvent';
import AnimatedAddition from './nodes/AnimatedAddition';
import AnimatedDiffClamp from './nodes/AnimatedDiffClamp';
import AnimatedDivision from './nodes/AnimatedDivision';
import AnimatedInterpolation from './nodes/AnimatedInterpolation';
import AnimatedModulo from './nodes/AnimatedModulo';
import AnimatedMultiplication from './nodes/AnimatedMultiplication';
import AnimatedNode from './nodes/AnimatedNode';
import AnimatedProps from './nodes/AnimatedProps';
import AnimatedSubtraction from './nodes/AnimatedSubtraction';
import AnimatedTracking from './nodes/AnimatedTracking';
import AnimatedValue from './nodes/AnimatedValue';
import AnimatedValueXY from './nodes/AnimatedValueXY';
import DecayAnimation from './animations/DecayAnimation';
import SpringAnimation from './animations/SpringAnimation';
import TimingAnimation from './animations/TimingAnimation';
import createAnimatedComponent from './createAnimatedComponent';
var add = function add(a, b) {
return new AnimatedAddition(a, b);
};
var subtract = function subtract(a, b) {
return new AnimatedSubtraction(a, b);
};
var divide = function divide(a, b) {
return new AnimatedDivision(a, b);
};
var multiply = function multiply(a, b) {
return new AnimatedMultiplication(a, b);
};
var modulo = function modulo(a, modulus) {
return new AnimatedModulo(a, modulus);
};
var diffClamp = function diffClamp(a, min, max) {
return new AnimatedDiffClamp(a, min, max);
};
var _combineCallbacks = function _combineCallbacks(callback, config) {
if (callback && config.onComplete) {
return function () {
config.onComplete && config.onComplete.apply(config, arguments);
callback && callback.apply(void 0, arguments);
};
} else {
return callback || config.onComplete;
}
};
var maybeVectorAnim = function maybeVectorAnim(value, config, anim) {
if (value instanceof AnimatedValueXY) {
var configX = _objectSpread({}, config);
var configY = _objectSpread({}, config);
for (var key in config) {
var _config$key = config[key],
x = _config$key.x,
y = _config$key.y;
if (x !== undefined && y !== undefined) {
configX[key] = x;
configY[key] = y;
}
}
var aX = anim(value.x, configX);
var aY = anim(value.y, configY); // We use `stopTogether: false` here because otherwise tracking will break
// because the second animation will get stopped before it can update.
return parallel([aX, aY], {
stopTogether: false
});
}
return null;
};
var spring = function spring(value, config) {
var _start = function start(animatedValue, configuration, callback) {
callback = _combineCallbacks(callback, configuration);
var singleValue = animatedValue;
var singleConfig = configuration;
singleValue.stopTracking();
if (configuration.toValue instanceof AnimatedNode) {
singleValue.track(new AnimatedTracking(singleValue, configuration.toValue, SpringAnimation, singleConfig, callback));
} else {
singleValue.animate(new SpringAnimation(singleConfig), callback);
}
};
return maybeVectorAnim(value, config, spring) || {
start: function start(callback) {
_start(value, config, callback);
},
stop: function stop() {
value.stopAnimation();
},
reset: function reset() {
value.resetAnimation();
},
_startNativeLoop: function _startNativeLoop(iterations) {
var singleConfig = _objectSpread({}, config, {
iterations: iterations
});
_start(value, singleConfig);
},
_isUsingNativeDriver: function _isUsingNativeDriver() {
return config.useNativeDriver || false;
}
};
};
var timing = function timing(value, config) {
var _start2 = function start(animatedValue, configuration, callback) {
callback = _combineCallbacks(callback, configuration);
var singleValue = animatedValue;
var singleConfig = configuration;
singleValue.stopTracking();
if (configuration.toValue instanceof AnimatedNode) {
singleValue.track(new AnimatedTracking(singleValue, configuration.toValue, TimingAnimation, singleConfig, callback));
} else {
singleValue.animate(new TimingAnimation(singleConfig), callback);
}
};
return maybeVectorAnim(value, config, timing) || {
start: function start(callback) {
_start2(value, config, callback);
},
stop: function stop() {
value.stopAnimation();
},
reset: function reset() {
value.resetAnimation();
},
_startNativeLoop: function _startNativeLoop(iterations) {
var singleConfig = _objectSpread({}, config, {
iterations: iterations
});
_start2(value, singleConfig);
},
_isUsingNativeDriver: function _isUsingNativeDriver() {
return config.useNativeDriver || false;
}
};
};
var decay = function decay(value, config) {
var _start3 = function start(animatedValue, configuration, callback) {
callback = _combineCallbacks(callback, configuration);
var singleValue = animatedValue;
var singleConfig = configuration;
singleValue.stopTracking();
singleValue.animate(new DecayAnimation(singleConfig), callback);
};
return maybeVectorAnim(value, config, decay) || {
start: function start(callback) {
_start3(value, config, callback);
},
stop: function stop() {
value.stopAnimation();
},
reset: function reset() {
value.resetAnimation();
},
_startNativeLoop: function _startNativeLoop(iterations) {
var singleConfig = _objectSpread({}, config, {
iterations: iterations
});
_start3(value, singleConfig);
},
_isUsingNativeDriver: function _isUsingNativeDriver() {
return config.useNativeDriver || false;
}
};
};
var sequence = function sequence(animations) {
var current = 0;
return {
start: function start(callback) {
var onComplete = function onComplete(result) {
if (!result.finished) {
callback && callback(result);
return;
}
current++;
if (current === animations.length) {
callback && callback(result);
return;
}
animations[current].start(onComplete);
};
if (animations.length === 0) {
callback && callback({
finished: true
});
} else {
animations[current].start(onComplete);
}
},
stop: function stop() {
if (current < animations.length) {
animations[current].stop();
}
},
reset: function reset() {
animations.forEach(function (animation, idx) {
if (idx <= current) {
animation.reset();
}
});
current = 0;
},
_startNativeLoop: function _startNativeLoop() {
throw new Error('Loops run using the native driver cannot contain Animated.sequence animations');
},
_isUsingNativeDriver: function _isUsingNativeDriver() {
return false;
}
};
};
var parallel = function parallel(animations, config) {
var doneCount = 0; // Make sure we only call stop() at most once for each animation
var hasEnded = {};
var stopTogether = !(config && config.stopTogether === false);
var result = {
start: function start(callback) {
if (doneCount === animations.length) {
callback && callback({
finished: true
});
return;
}
animations.forEach(function (animation, idx) {
var cb = function cb(endResult) {
hasEnded[idx] = true;
doneCount++;
if (doneCount === animations.length) {
doneCount = 0;
callback && callback(endResult);
return;
}
if (!endResult.finished && stopTogether) {
result.stop();
}
};
if (!animation) {
cb({
finished: true
});
} else {
animation.start(cb);
}
});
},
stop: function stop() {
animations.forEach(function (animation, idx) {
!hasEnded[idx] && animation.stop();
hasEnded[idx] = true;
});
},
reset: function reset() {
animations.forEach(function (animation, idx) {
animation.reset();
hasEnded[idx] = false;
doneCount = 0;
});
},
_startNativeLoop: function _startNativeLoop() {
throw new Error('Loops run using the native driver cannot contain Animated.parallel animations');
},
_isUsingNativeDriver: function _isUsingNativeDriver() {
return false;
}
};
return result;
};
var delay = function delay(time) {
// Would be nice to make a specialized implementation
return timing(new AnimatedValue(0), {
toValue: 0,
delay: time,
duration: 0
});
};
var stagger = function stagger(time, animations) {
return parallel(animations.map(function (animation, i) {
return sequence([delay(time * i), animation]);
}));
};
var loop = function loop(animation, _temp) {
var _ref = _temp === void 0 ? {} : _temp,
_ref$iterations = _ref.iterations,
iterations = _ref$iterations === void 0 ? -1 : _ref$iterations,
_ref$resetBeforeItera = _ref.resetBeforeIteration,
resetBeforeIteration = _ref$resetBeforeItera === void 0 ? true : _ref$resetBeforeItera;
var isFinished = false;
var iterationsSoFar = 0;
return {
start: function start(callback) {
var restart = function restart(result) {
if (result === void 0) {
result = {
finished: true
};
}
if (isFinished || iterationsSoFar === iterations || result.finished === false) {
callback && callback(result);
} else {
iterationsSoFar++;
resetBeforeIteration && animation.reset();
animation.start(restart);
}
};
if (!animation || iterations === 0) {
callback && callback({
finished: true
});
} else {
if (animation._isUsingNativeDriver()) {
animation._startNativeLoop(iterations);
} else {
restart(); // Start looping recursively on the js thread
}
}
},
stop: function stop() {
isFinished = true;
animation.stop();
},
reset: function reset() {
iterationsSoFar = 0;
isFinished = false;
animation.reset();
},
_startNativeLoop: function _startNativeLoop() {
throw new Error('Loops run using the native driver cannot contain Animated.loop animations');
},
_isUsingNativeDriver: function _isUsingNativeDriver() {
return animation._isUsingNativeDriver();
}
};
};
function forkEvent(event, listener) {
if (!event) {
return listener;
} else if (event instanceof AnimatedEvent) {
event.__addListener(listener);
return event;
} else {
return function () {
typeof event === 'function' && event.apply(void 0, arguments);
listener.apply(void 0, arguments);
};
}
}
function unforkEvent(event, listener) {
if (event && event instanceof AnimatedEvent) {
event.__removeListener(listener);
}
}
var event = function event(argMapping, config) {
var animatedEvent = new AnimatedEvent(argMapping, config);
if (animatedEvent.__isNative) {
return animatedEvent;
} else {
return animatedEvent.__getHandler();
}
};
/**
* The `Animated` library is designed to make animations fluid, powerful, and
* easy to build and maintain. `Animated` focuses on declarative relationships
* between inputs and outputs, with configurable transforms in between, and
* simple `start`/`stop` methods to control time-based animation execution.
* If additional transforms are added, be sure to include them in
* AnimatedMock.js as well.
*
* See http://facebook.github.io/react-native/docs/animated.html
*/
var AnimatedImplementation = {
/**
* Standard value class for driving animations. Typically initialized with
* `new Animated.Value(0);`
*
* See http://facebook.github.io/react-native/docs/animated.html#value
*/
Value: AnimatedValue,
/**
* 2D value class for driving 2D animations, such as pan gestures.
*
* See https://facebook.github.io/react-native/docs/animatedvaluexy.html
*/
ValueXY: AnimatedValueXY,
/**
* Exported to use the Interpolation type in flow.
*
* See http://facebook.github.io/react-native/docs/animated.html#interpolation
*/
Interpolation: AnimatedInterpolation,
/**
* Exported for ease of type checking. All animated values derive from this
* class.
*
* See http://facebook.github.io/react-native/docs/animated.html#node
*/
Node: AnimatedNode,
/**
* Animates a value from an initial velocity to zero based on a decay
* coefficient.
*
* See http://facebook.github.io/react-native/docs/animated.html#decay
*/
decay: decay,
/**
* Animates a value along a timed easing curve. The Easing module has tons of
* predefined curves, or you can use your own function.
*
* See http://facebook.github.io/react-native/docs/animated.html#timing
*/
timing: timing,
/**
* Animates a value according to an analytical spring model based on
* damped harmonic oscillation.
*
* See http://facebook.github.io/react-native/docs/animated.html#spring
*/
spring: spring,
/**
* Creates a new Animated value composed from two Animated values added
* together.
*
* See http://facebook.github.io/react-native/docs/animated.html#add
*/
add: add,
/**
* Creates a new Animated value composed by subtracting the second Animated
* value from the first Animated value.
*
* See http://facebook.github.io/react-native/docs/animated.html#subtract
*/
subtract: subtract,
/**
* Creates a new Animated value composed by dividing the first Animated value
* by the second Animated value.
*
* See http://facebook.github.io/react-native/docs/animated.html#divide
*/
divide: divide,
/**
* Creates a new Animated value composed from two Animated values multiplied
* together.
*
* See http://facebook.github.io/react-native/docs/animated.html#multiply
*/
multiply: multiply,
/**
* Creates a new Animated value that is the (non-negative) modulo of the
* provided Animated value.
*
* See http://facebook.github.io/react-native/docs/animated.html#modulo
*/
modulo: modulo,
/**
* Create a new Animated value that is limited between 2 values. It uses the
* difference between the last value so even if the value is far from the
* bounds it will start changing when the value starts getting closer again.
*
* See http://facebook.github.io/react-native/docs/animated.html#diffclamp
*/
diffClamp: diffClamp,
/**
* Starts an animation after the given delay.
*
* See http://facebook.github.io/react-native/docs/animated.html#delay
*/
delay: delay,
/**
* Starts an array of animations in order, waiting for each to complete
* before starting the next. If the current running animation is stopped, no
* following animations will be started.
*
* See http://facebook.github.io/react-native/docs/animated.html#sequence
*/
sequence: sequence,
/**
* Starts an array of animations all at the same time. By default, if one
* of the animations is stopped, they will all be stopped. You can override
* this with the `stopTogether` flag.
*
* See http://facebook.github.io/react-native/docs/animated.html#parallel
*/
parallel: parallel,
/**
* Array of animations may run in parallel (overlap), but are started in
* sequence with successive delays. Nice for doing trailing effects.
*
* See http://facebook.github.io/react-native/docs/animated.html#stagger
*/
stagger: stagger,
/**
* Loops a given animation continuously, so that each time it reaches the
* end, it resets and begins again from the start.
*
* See http://facebook.github.io/react-native/docs/animated.html#loop
*/
loop: loop,
/**
* Takes an array of mappings and extracts values from each arg accordingly,
* then calls `setValue` on the mapped outputs.
*
* See http://facebook.github.io/react-native/docs/animated.html#event
*/
event: event,
/**
* Make any React component Animatable. Used to create `Animated.View`, etc.
*
* See http://facebook.github.io/react-native/docs/animated.html#createanimatedcomponent
*/
createAnimatedComponent: createAnimatedComponent,
/**
* Imperative API to attach an animated value to an event on a view. Prefer
* using `Animated.event` with `useNativeDrive: true` if possible.
*
* See http://facebook.github.io/react-native/docs/animated.html#attachnativeevent
*/
attachNativeEvent: attachNativeEvent,
/**
* Advanced imperative API for snooping on animated events that are passed in
* through props. Use values directly where possible.
*
* See http://facebook.github.io/react-native/docs/animated.html#forkevent
*/
forkEvent: forkEvent,
unforkEvent: unforkEvent,
/**
* Expose Event class, so it can be used as a type for type checkers.
*/
Event: AnimatedEvent,
__PropsOnlyForTests: AnimatedProps
};
export default AnimatedImplementation; |
import { camelize, hasOwn, defineReactive } from '../../util/index'
import { EL } from '../priorities'
export default {
priority: EL,
bind () {
/* istanbul ignore if */
if (!this.arg) {
return
}
var id = this.id = camelize(this.arg)
var refs = (this._scope || this.vm).$els
if (hasOwn(refs, id)) {
refs[id] = this.el
} else {
defineReactive(refs, id, this.el)
}
},
unbind () {
var refs = (this._scope || this.vm).$els
if (refs[this.id] === this.el) {
refs[this.id] = null
}
}
}
|
var RELANG = {};
RELANG['sr-lat'] = {
html: 'HTML',
video: 'Ubaci video',
image: 'Ubaci fotografiju',
table: 'Tabela',
link: 'Veza',
link_insert: 'Ubaci vezu ...',
unlink: 'Ukloni vezu',
formatting: 'Stilovi',
paragraph: 'Paragraf',
quote: 'Citat',
code: 'Izvorni kod',
header1: 'Zaglavlje 1',
header2: 'Zaglavlje 2',
header3: 'Zaglavlje 3',
header4: 'Zaglavlje 4',
bold: 'Podebljaj',
italic: 'Nakosi',
fontcolor: 'Boja slova',
backcolor: 'Boja pozadine',
unorderedlist: 'Nesortirana lista',
orderedlist: 'Sortirana lista',
outdent: 'Izvuci',
indent: 'Uvuci',
redo: 'Korak napred',
undo: 'Korak nazad',
cut: 'Izreži',
cancel: 'Odustani',
insert: 'Ubaci',
save: 'Sačuvaj',
_delete: 'Izbriši',
insert_table: 'Ubaci tabelu',
insert_row_above: 'Dodaj red iznad',
insert_row_below: 'Dodaj red ispod',
insert_column_left: 'Dodaj kolonu levo',
insert_column_right: 'Dodaj kolonu desno',
delete_column: 'Izbriši kolonu',
delete_row: 'Izbriši red',
delete_table: 'Izbriši tabelu',
rows: 'Red',
columns: 'Kolona',
add_head: 'Dodaj zaglavlje',
delete_head: 'Ukloni zaglavlje',
title: 'Naslov',
image_position: 'Pozicija',
none: 'Bez',
left: 'Levo',
right: 'Desno',
image_web_link: 'Web adresa fotografije',
text: 'Tekst',
mailto: 'Email',
web: 'Web adresa',
video_html_code: 'Video kod',
file: 'Datoteka',
upload: 'Pošalji',
download: 'Preuzmi',
choose: 'Odaberi',
or_choose: 'Ili odaberi',
drop_file_here: 'Prevuci datoteku ovde',
align_left: 'Poravnaj levo',
align_center: 'Centriraj',
align_right: 'Poravnaj desno',
align_justify: 'Od ruba do ruba',
horizontalrule: 'Ubaci horizontalnu liniju',
fullscreen: 'Prikaz preko čitavog ekrana',
deleted: 'Izbrisano',
anchor: 'Sidro',
link_new_tab: 'Open link in new tab',
underline: 'Underline',
alignment: 'Alignment'
};
|
ace.define('ace/mode/golang', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/golang_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var GolangHighlightRules = require("./golang_highlight_rules").GolangHighlightRules;
var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent;
var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour;
var CStyleFoldMode = require("./folding/cstyle").FoldMode;
var Mode = function() {
this.$tokenizer = new Tokenizer(new GolangHighlightRules().getRules());
this.$outdent = new MatchingBraceOutdent();
this.foldingRules = new CStyleFoldMode();
};
oop.inherits(Mode, TextMode);
(function() {
this.lineCommentStart = "//";
this.blockComment = {start: "/*", end: "*/"};
this.getNextLineIndent = function(state, line, tab) {
var indent = this.$getIndent(line);
var tokenizedLine = this.$tokenizer.getLineTokens(line, state);
var tokens = tokenizedLine.tokens;
var endState = tokenizedLine.state;
if (tokens.length && tokens[tokens.length-1].type == "comment") {
return indent;
}
if (state == "start") {
var match = line.match(/^.*[\{\(\[]\s*$/);
if (match) {
indent += tab;
}
}
return indent;
};//end getNextLineIndent
this.checkOutdent = function(state, line, input) {
return this.$outdent.checkOutdent(line, input);
};
this.autoOutdent = function(state, doc, row) {
this.$outdent.autoOutdent(doc, row);
};
}).call(Mode.prototype);
exports.Mode = Mode;
});
ace.define('ace/mode/golang_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
var oop = require("../lib/oop");
var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules;
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var GolangHighlightRules = function() {
var keywords = (
"true|else|false|break|case|return|goto|if|const|" +
"continue|struct|default|switch|for|" +
"func|import|package|chan|defer|fallthrough|go|interface|map|range" +
"select|type|var"
);
var buildinConstants = ("nil|true|false|iota");
var keywordMapper = this.createKeywordMapper({
"variable.language": "this",
"keyword": keywords,
"constant.language": buildinConstants
}, "identifier");
this.$rules = {
"start" : [
{
token : "comment",
regex : "\\/\\/.*$"
},
DocCommentHighlightRules.getStartRule("doc-start"),
{
token : "comment", // multi line comment
regex : "\\/\\*",
next : "comment"
}, {
token : "string", // single line
regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'
}, {
token : "string", // multi line string start
regex : '["].*\\\\$',
next : "qqstring"
}, {
token : "string", // single line
regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"
}, {
token : "string", // multi line string start
regex : "['].*\\\\$",
next : "qstring"
}, {
token : "constant.numeric", // hex
regex : "0[xX][0-9a-fA-F]+\\b"
}, {
token : "constant.numeric", // float
regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
}, {
token : "constant", // <CONSTANT>
regex : "<[a-zA-Z0-9.]+>"
}, {
token : "keyword", // pre-compiler directivs
regex : "(?:#include|#pragma|#line|#define|#undef|#ifdef|#else|#elif|#endif|#ifndef)"
}, {
token : keywordMapper,
regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
}, {
token : "keyword.operator",
regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|==|=|!=|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|new|delete|typeof|void)"
}, {
token : "punctuation.operator",
regex : "\\?|\\:|\\,|\\;|\\."
}, {
token : "paren.lparen",
regex : "[[({]"
}, {
token : "paren.rparen",
regex : "[\\])}]"
}, {
token : "text",
regex : "\\s+"
}
],
"comment" : [
{
token : "comment", // closing comment
regex : ".*?\\*\\/",
next : "start"
}, {
token : "comment", // comment spanning whole line
regex : ".+"
}
],
"qqstring" : [
{
token : "string",
regex : '(?:(?:\\\\.)|(?:[^"\\\\]))*?"',
next : "start"
}, {
token : "string",
regex : '.+'
}
],
"qstring" : [
{
token : "string",
regex : "(?:(?:\\\\.)|(?:[^'\\\\]))*?'",
next : "start"
}, {
token : "string",
regex : '.+'
}
]
};
this.embedRules(DocCommentHighlightRules, "doc-",
[ DocCommentHighlightRules.getEndRule("start") ]);
}
oop.inherits(GolangHighlightRules, TextHighlightRules);
exports.GolangHighlightRules = GolangHighlightRules;
});
ace.define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var DocCommentHighlightRules = function() {
this.$rules = {
"start" : [ {
token : "comment.doc.tag",
regex : "@[\\w\\d_]+" // TODO: fix email addresses
}, {
token : "comment.doc.tag",
regex : "\\bTODO\\b"
}, {
defaultToken : "comment.doc"
}]
};
};
oop.inherits(DocCommentHighlightRules, TextHighlightRules);
DocCommentHighlightRules.getStartRule = function(start) {
return {
token : "comment.doc", // doc comment
regex : "\\/\\*(?=\\*)",
next : start
};
};
DocCommentHighlightRules.getEndRule = function (start) {
return {
token : "comment.doc", // closing comment
regex : "\\*\\/",
next : start
};
};
exports.DocCommentHighlightRules = DocCommentHighlightRules;
});
ace.define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) {
var Range = require("../range").Range;
var MatchingBraceOutdent = function() {};
(function() {
this.checkOutdent = function(line, input) {
if (! /^\s+$/.test(line))
return false;
return /^\s*\}/.test(input);
};
this.autoOutdent = function(doc, row) {
var line = doc.getLine(row);
var match = line.match(/^(\s*\})/);
if (!match) return 0;
var column = match[1].length;
var openBracePos = doc.findMatchingBracket({row: row, column: column});
if (!openBracePos || openBracePos.row == row) return 0;
var indent = this.$getIndent(doc.getLine(openBracePos.row));
doc.replace(new Range(row, 0, row, column-1), indent);
};
this.$getIndent = function(line) {
return line.match(/^\s*/)[0];
};
}).call(MatchingBraceOutdent.prototype);
exports.MatchingBraceOutdent = MatchingBraceOutdent;
});
ace.define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour', 'ace/token_iterator', 'ace/lib/lang'], function(require, exports, module) {
var oop = require("../../lib/oop");
var Behaviour = require("../behaviour").Behaviour;
var TokenIterator = require("../../token_iterator").TokenIterator;
var lang = require("../../lib/lang");
var SAFE_INSERT_IN_TOKENS =
["text", "paren.rparen", "punctuation.operator"];
var SAFE_INSERT_BEFORE_TOKENS =
["text", "paren.rparen", "punctuation.operator", "comment"];
var autoInsertedBrackets = 0;
var autoInsertedRow = -1;
var autoInsertedLineEnd = "";
var maybeInsertedBrackets = 0;
var maybeInsertedRow = -1;
var maybeInsertedLineStart = "";
var maybeInsertedLineEnd = "";
var CstyleBehaviour = function () {
CstyleBehaviour.isSaneInsertion = function(editor, session) {
var cursor = editor.getCursorPosition();
var iterator = new TokenIterator(session, cursor.row, cursor.column);
if (!this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) {
var iterator2 = new TokenIterator(session, cursor.row, cursor.column + 1);
if (!this.$matchTokenType(iterator2.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS))
return false;
}
iterator.stepForward();
return iterator.getCurrentTokenRow() !== cursor.row ||
this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_BEFORE_TOKENS);
};
CstyleBehaviour.$matchTokenType = function(token, types) {
return types.indexOf(token.type || token) > -1;
};
CstyleBehaviour.recordAutoInsert = function(editor, session, bracket) {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
if (!this.isAutoInsertedClosing(cursor, line, autoInsertedLineEnd[0]))
autoInsertedBrackets = 0;
autoInsertedRow = cursor.row;
autoInsertedLineEnd = bracket + line.substr(cursor.column);
autoInsertedBrackets++;
};
CstyleBehaviour.recordMaybeInsert = function(editor, session, bracket) {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
if (!this.isMaybeInsertedClosing(cursor, line))
maybeInsertedBrackets = 0;
maybeInsertedRow = cursor.row;
maybeInsertedLineStart = line.substr(0, cursor.column) + bracket;
maybeInsertedLineEnd = line.substr(cursor.column);
maybeInsertedBrackets++;
};
CstyleBehaviour.isAutoInsertedClosing = function(cursor, line, bracket) {
return autoInsertedBrackets > 0 &&
cursor.row === autoInsertedRow &&
bracket === autoInsertedLineEnd[0] &&
line.substr(cursor.column) === autoInsertedLineEnd;
};
CstyleBehaviour.isMaybeInsertedClosing = function(cursor, line) {
return maybeInsertedBrackets > 0 &&
cursor.row === maybeInsertedRow &&
line.substr(cursor.column) === maybeInsertedLineEnd &&
line.substr(0, cursor.column) == maybeInsertedLineStart;
};
CstyleBehaviour.popAutoInsertedClosing = function() {
autoInsertedLineEnd = autoInsertedLineEnd.substr(1);
autoInsertedBrackets--;
};
CstyleBehaviour.clearMaybeInsertedClosing = function() {
maybeInsertedBrackets = 0;
maybeInsertedRow = -1;
};
this.add("braces", "insertion", function (state, action, editor, session, text) {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
if (text == '{') {
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && selected !== "{" && editor.getWrapBehavioursEnabled()) {
return {
text: '{' + selected + '}',
selection: false
};
} else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
if (/[\]\}\)]/.test(line[cursor.column])) {
CstyleBehaviour.recordAutoInsert(editor, session, "}");
return {
text: '{}',
selection: [1, 1]
};
} else {
CstyleBehaviour.recordMaybeInsert(editor, session, "{");
return {
text: '{',
selection: [1, 1]
};
}
}
} else if (text == '}') {
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == '}') {
var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row});
if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
CstyleBehaviour.popAutoInsertedClosing();
return {
text: '',
selection: [1, 1]
};
}
}
} else if (text == "\n" || text == "\r\n") {
var closing = "";
if (CstyleBehaviour.isMaybeInsertedClosing(cursor, line)) {
closing = lang.stringRepeat("}", maybeInsertedBrackets);
CstyleBehaviour.clearMaybeInsertedClosing();
}
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == '}' || closing !== "") {
var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column}, '}');
if (!openBracePos)
return null;
var indent = this.getNextLineIndent(state, line.substring(0, cursor.column), session.getTabString());
var next_indent = this.$getIndent(line);
return {
text: '\n' + indent + '\n' + next_indent + closing,
selection: [1, indent.length, 1, indent.length]
};
}
}
});
this.add("braces", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '{') {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.end.column, range.end.column + 1);
if (rightChar == '}') {
range.end.column++;
return range;
} else {
maybeInsertedBrackets--;
}
}
});
this.add("parens", "insertion", function (state, action, editor, session, text) {
if (text == '(') {
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && editor.getWrapBehavioursEnabled()) {
return {
text: '(' + selected + ')',
selection: false
};
} else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
CstyleBehaviour.recordAutoInsert(editor, session, ")");
return {
text: '()',
selection: [1, 1]
};
}
} else if (text == ')') {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == ')') {
var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row});
if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
CstyleBehaviour.popAutoInsertedClosing();
return {
text: '',
selection: [1, 1]
};
}
}
}
});
this.add("parens", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '(') {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == ')') {
range.end.column++;
return range;
}
}
});
this.add("brackets", "insertion", function (state, action, editor, session, text) {
if (text == '[') {
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && editor.getWrapBehavioursEnabled()) {
return {
text: '[' + selected + ']',
selection: false
};
} else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
CstyleBehaviour.recordAutoInsert(editor, session, "]");
return {
text: '[]',
selection: [1, 1]
};
}
} else if (text == ']') {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == ']') {
var matching = session.$findOpeningBracket(']', {column: cursor.column + 1, row: cursor.row});
if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
CstyleBehaviour.popAutoInsertedClosing();
return {
text: '',
selection: [1, 1]
};
}
}
}
});
this.add("brackets", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '[') {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == ']') {
range.end.column++;
return range;
}
}
});
this.add("string_dquotes", "insertion", function (state, action, editor, session, text) {
if (text == '"' || text == "'") {
var quote = text;
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) {
return {
text: quote + selected + quote,
selection: false
};
} else {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var leftChar = line.substring(cursor.column-1, cursor.column);
if (leftChar == '\\') {
return null;
}
var tokens = session.getTokens(selection.start.row);
var col = 0, token;
var quotepos = -1; // Track whether we're inside an open quote.
for (var x = 0; x < tokens.length; x++) {
token = tokens[x];
if (token.type == "string") {
quotepos = -1;
} else if (quotepos < 0) {
quotepos = token.value.indexOf(quote);
}
if ((token.value.length + col) > selection.start.column) {
break;
}
col += tokens[x].value.length;
}
if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) {
if (!CstyleBehaviour.isSaneInsertion(editor, session))
return;
return {
text: quote + quote,
selection: [1,1]
};
} else if (token && token.type === "string") {
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == quote) {
return {
text: '',
selection: [1, 1]
};
}
}
}
}
});
this.add("string_dquotes", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && (selected == '"' || selected == "'")) {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == selected) {
range.end.column++;
return range;
}
}
});
};
oop.inherits(CstyleBehaviour, Behaviour);
exports.CstyleBehaviour = CstyleBehaviour;
});
ace.define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) {
var oop = require("../../lib/oop");
var Range = require("../../range").Range;
var BaseFoldMode = require("./fold_mode").FoldMode;
var FoldMode = exports.FoldMode = function(commentRegex) {
if (commentRegex) {
this.foldingStartMarker = new RegExp(
this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start)
);
this.foldingStopMarker = new RegExp(
this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end)
);
}
};
oop.inherits(FoldMode, BaseFoldMode);
(function() {
this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/;
this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/;
this.getFoldWidgetRange = function(session, foldStyle, row) {
var line = session.getLine(row);
var match = line.match(this.foldingStartMarker);
if (match) {
var i = match.index;
if (match[1])
return this.openingBracketBlock(session, match[1], row, i);
return session.getCommentFoldRange(row, i + match[0].length, 1);
}
if (foldStyle !== "markbeginend")
return;
var match = line.match(this.foldingStopMarker);
if (match) {
var i = match.index + match[0].length;
if (match[1])
return this.closingBracketBlock(session, match[1], row, i);
return session.getCommentFoldRange(row, i, -1);
}
};
}).call(FoldMode.prototype);
});
|
var assert = require('assert');
var program = require('../../');
var valueFactory = require('../../lib/factory/value.js');
var ObjectExpression = require('../../lib/nodes/ObjectExpression.js');
var ArrayExpression = require('../../lib/nodes/ArrayExpression.js');
var Literal = require('../../lib/nodes/Literal.js');
describe('ArrayExpression objects', function () {
beforeEach(function () {
this.arr = new ArrayExpression(valueFactory.create('[1, [2, 3], "a", {"foo":"bar"}, ]'));
});
it('#type equal ArrayExpression', function () {
assert.equal(this.arr.type, 'ArrayExpression');
});
describe('#push()', function () {
it('adds a new value to the end of the array', function () {
this.arr.at(1).push('"a"');
assert.equal(this.arr.at(1).at(1).value(), 3);
assert.equal(this.arr.at(1).at(2).value(), 'a');
});
});
describe('#unshift()', function () {
it('adds a new value to the start of the array', function () {
this.arr.at(1).unshift('"a"');
assert.equal(this.arr.at(1).at(0).value(), 'a');
assert.equal(this.arr.at(1).at(2).value(), 3);
});
});
describe('#at()', function () {
it('returns a wrapped value', function () {
assert(this.arr.at(0) instanceof Literal);
assert(this.arr.at(1) instanceof ArrayExpression);
assert(this.arr.at(1).at(0) instanceof Literal);
assert(this.arr.at(2) instanceof Literal);
assert(this.arr.at(3) instanceof ObjectExpression);
assert.equal(this.arr.at(0).value(), 1);
assert.equal(this.arr.at(1).at(0).value(), 2);
assert.equal(this.arr.at(2).value(), 'a');
});
});
describe('#value()', function () {
it('replace itself with new value', function () {
var tree = program('var b = ["a"];');
tree.var('b').value('[1]');
assert.equal(tree.toString(), 'var b = [1];');
});
it('replaces itself with a different type of node', function () {
var tree = program('var b = ["a"];');
tree.var('b').value('"this is literal"');
assert.equal(tree.toString(), 'var b = \'this is literal\';');
});
it('return the new value', function () {
var val = this.arr.at(1).value('"a"');
assert(val instanceof Literal);
assert.equal(val.value(), 'a');
});
});
});
|
/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'scayt', 'el', {
btn_about: 'About SCAYT',
btn_dictionaries: 'Λεξικά',
btn_disable: 'Disable SCAYT',
btn_enable: 'Enable SCAYT',
btn_langs:'Γλώσσες',
btn_options: 'Επιλογές',
text_title: 'Spell Check As You Type'
}); |
var moment = require('../../moment');
/**************************************************
Dutch
*************************************************/
exports['locale:nl'] = {
setUp : function (cb) {
moment.locale('nl');
moment.createFromInputFallback = function () {
throw new Error('input not handled by moment');
};
cb();
},
tearDown : function (cb) {
moment.locale('en');
cb();
},
'parse' : function (test) {
var tests = 'januari jan._februari feb._maart mrt._april apr._mei mei._juni jun._juli jul._augustus aug._september sep._oktober okt._november nov._december dec.'.split('_'), i;
function equalTest(input, mmm, i) {
test.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1));
}
for (i = 0; i < 12; i++) {
tests[i] = tests[i].split(' ');
equalTest(tests[i][0], 'MMM', i);
equalTest(tests[i][1], 'MMM', i);
equalTest(tests[i][0], 'MMMM', i);
equalTest(tests[i][1], 'MMMM', i);
equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i);
equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i);
equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i);
equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i);
}
test.done();
},
'format' : function (test) {
var a = [
['dddd, MMMM Do YYYY, HH:mm:ss', 'zondag, februari 14de 2010, 15:25:50'],
['ddd, HH', 'zo., 15'],
['M Mo MM MMMM MMM', '2 2de 02 februari feb.'],
['YYYY YY', '2010 10'],
['D Do DD', '14 14de 14'],
['d do dddd ddd dd', '0 0de zondag zo. Zo'],
['DDD DDDo DDDD', '45 45ste 045'],
['w wo ww', '6 6de 06'],
['h hh', '3 03'],
['H HH', '15 15'],
['m mm', '25 25'],
['s ss', '50 50'],
['a A', 'pm PM'],
['[the] DDDo [day of the year]', 'the 45ste day of the year'],
['L', '14-02-2010'],
['LL', '14 februari 2010'],
['LLL', '14 februari 2010 15:25'],
['LLLL', 'zondag 14 februari 2010 15:25'],
['l', '14-2-2010'],
['ll', '14 feb. 2010'],
['lll', '14 feb. 2010 15:25'],
['llll', 'zo. 14 feb. 2010 15:25']
],
b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)),
i;
for (i = 0; i < a.length; i++) {
test.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]);
}
test.done();
},
'format ordinal' : function (test) {
test.equal(moment([2011, 0, 1]).format('DDDo'), '1ste', '1ste');
test.equal(moment([2011, 0, 2]).format('DDDo'), '2de', '2de');
test.equal(moment([2011, 0, 3]).format('DDDo'), '3de', '3de');
test.equal(moment([2011, 0, 4]).format('DDDo'), '4de', '4de');
test.equal(moment([2011, 0, 5]).format('DDDo'), '5de', '5de');
test.equal(moment([2011, 0, 6]).format('DDDo'), '6de', '6de');
test.equal(moment([2011, 0, 7]).format('DDDo'), '7de', '7de');
test.equal(moment([2011, 0, 8]).format('DDDo'), '8ste', '8ste');
test.equal(moment([2011, 0, 9]).format('DDDo'), '9de', '9de');
test.equal(moment([2011, 0, 10]).format('DDDo'), '10de', '10de');
test.equal(moment([2011, 0, 11]).format('DDDo'), '11de', '11de');
test.equal(moment([2011, 0, 12]).format('DDDo'), '12de', '12de');
test.equal(moment([2011, 0, 13]).format('DDDo'), '13de', '13de');
test.equal(moment([2011, 0, 14]).format('DDDo'), '14de', '14de');
test.equal(moment([2011, 0, 15]).format('DDDo'), '15de', '15de');
test.equal(moment([2011, 0, 16]).format('DDDo'), '16de', '16de');
test.equal(moment([2011, 0, 17]).format('DDDo'), '17de', '17de');
test.equal(moment([2011, 0, 18]).format('DDDo'), '18de', '18de');
test.equal(moment([2011, 0, 19]).format('DDDo'), '19de', '19de');
test.equal(moment([2011, 0, 20]).format('DDDo'), '20ste', '20ste');
test.equal(moment([2011, 0, 21]).format('DDDo'), '21ste', '21ste');
test.equal(moment([2011, 0, 22]).format('DDDo'), '22ste', '22ste');
test.equal(moment([2011, 0, 23]).format('DDDo'), '23ste', '23ste');
test.equal(moment([2011, 0, 24]).format('DDDo'), '24ste', '24ste');
test.equal(moment([2011, 0, 25]).format('DDDo'), '25ste', '25ste');
test.equal(moment([2011, 0, 26]).format('DDDo'), '26ste', '26ste');
test.equal(moment([2011, 0, 27]).format('DDDo'), '27ste', '27ste');
test.equal(moment([2011, 0, 28]).format('DDDo'), '28ste', '28ste');
test.equal(moment([2011, 0, 29]).format('DDDo'), '29ste', '29ste');
test.equal(moment([2011, 0, 30]).format('DDDo'), '30ste', '30ste');
test.equal(moment([2011, 0, 31]).format('DDDo'), '31ste', '31ste');
test.done();
},
'format month' : function (test) {
var expected = 'januari jan._februari feb._maart mrt._april apr._mei mei_juni jun._juli jul._augustus aug._september sep._oktober okt._november nov._december dec.'.split('_'), i;
for (i = 0; i < expected.length; i++) {
test.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]);
}
test.done();
},
'format week' : function (test) {
var expected = 'zondag zo. Zo_maandag ma. Ma_dinsdag di. Di_woensdag wo. Wo_donderdag do. Do_vrijdag vr. Vr_zaterdag za. Za'.split('_'), i;
for (i = 0; i < expected.length; i++) {
test.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]);
}
test.done();
},
'from' : function (test) {
var start = moment([2007, 1, 28]);
test.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'een paar seconden', '44 seconds = a few seconds');
test.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'één minuut', '45 seconds = a minute');
test.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'één minuut', '89 seconds = a minute');
test.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minuten', '90 seconds = 2 minutes');
test.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minuten', '44 minutes = 44 minutes');
test.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'één uur', '45 minutes = an hour');
test.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'één uur', '89 minutes = an hour');
test.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 uur', '90 minutes = 2 hours');
test.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 uur', '5 hours = 5 hours');
test.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 uur', '21 hours = 21 hours');
test.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'één dag', '22 hours = a day');
test.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'één dag', '35 hours = a day');
test.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 dagen', '36 hours = 2 days');
test.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'één dag', '1 day = a day');
test.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 dagen', '5 days = 5 days');
test.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 dagen', '25 days = 25 days');
test.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'één maand', '26 days = a month');
test.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'één maand', '30 days = a month');
test.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'één maand', '43 days = a month');
test.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 maanden', '46 days = 2 months');
test.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 maanden', '75 days = 2 months');
test.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 maanden', '76 days = 3 months');
test.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'één maand', '1 month = a month');
test.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 maanden', '5 months = 5 months');
test.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'één jaar', '345 days = a year');
test.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 jaar', '548 days = 2 years');
test.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'één jaar', '1 year = a year');
test.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 jaar', '5 years = 5 years');
test.done();
},
'suffix' : function (test) {
test.equal(moment(30000).from(0), 'over een paar seconden', 'prefix');
test.equal(moment(0).from(30000), 'een paar seconden geleden', 'suffix');
test.done();
},
'now from now' : function (test) {
test.equal(moment().fromNow(), 'een paar seconden geleden', 'now from now should display as in the past');
test.done();
},
'fromNow' : function (test) {
test.equal(moment().add({s: 30}).fromNow(), 'over een paar seconden', 'in a few seconds');
test.equal(moment().add({d: 5}).fromNow(), 'over 5 dagen', 'in 5 days');
test.done();
},
'calendar day' : function (test) {
var a = moment().hours(2).minutes(0).seconds(0);
test.equal(moment(a).calendar(), 'vandaag om 02:00', 'today at the same time');
test.equal(moment(a).add({m: 25}).calendar(), 'vandaag om 02:25', 'Now plus 25 min');
test.equal(moment(a).add({h: 1}).calendar(), 'vandaag om 03:00', 'Now plus 1 hour');
test.equal(moment(a).add({d: 1}).calendar(), 'morgen om 02:00', 'tomorrow at the same time');
test.equal(moment(a).subtract({h: 1}).calendar(), 'vandaag om 01:00', 'Now minus 1 hour');
test.equal(moment(a).subtract({d: 1}).calendar(), 'gisteren om 02:00', 'yesterday at the same time');
test.done();
},
'calendar next week' : function (test) {
var i, m;
for (i = 2; i < 7; i++) {
m = moment().add({d: i});
test.equal(m.calendar(), m.format('dddd [om] LT'), 'Today + ' + i + ' days current time');
m.hours(0).minutes(0).seconds(0).milliseconds(0);
test.equal(m.calendar(), m.format('dddd [om] LT'), 'Today + ' + i + ' days beginning of day');
m.hours(23).minutes(59).seconds(59).milliseconds(999);
test.equal(m.calendar(), m.format('dddd [om] LT'), 'Today + ' + i + ' days end of day');
}
test.done();
},
'calendar last week' : function (test) {
var i, m;
for (i = 2; i < 7; i++) {
m = moment().subtract({d: i});
test.equal(m.calendar(), m.format('[afgelopen] dddd [om] LT'), 'Today - ' + i + ' days current time');
m.hours(0).minutes(0).seconds(0).milliseconds(0);
test.equal(m.calendar(), m.format('[afgelopen] dddd [om] LT'), 'Today - ' + i + ' days beginning of day');
m.hours(23).minutes(59).seconds(59).milliseconds(999);
test.equal(m.calendar(), m.format('[afgelopen] dddd [om] LT'), 'Today - ' + i + ' days end of day');
}
test.done();
},
'calendar all else' : function (test) {
var weeksAgo = moment().subtract({w: 1}),
weeksFromNow = moment().add({w: 1});
test.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago');
test.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week');
weeksAgo = moment().subtract({w: 2});
weeksFromNow = moment().add({w: 2});
test.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago');
test.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks');
test.done();
},
'month abbreviation' : function (test) {
test.equal(moment([2012, 5, 23]).format('D-MMM-YYYY'), '23-jun-2012', 'format month abbreviation surrounded by dashes should not include a dot');
test.equal(moment([2012, 5, 23]).format('D MMM YYYY'), '23 jun. 2012', 'format month abbreviation not surrounded by dashes should include a dot');
test.done();
},
// Monday is the first day of the week.
// The week that contains Jan 4th is the first week of the year.
'weeks year starting sunday' : function (test) {
test.equal(moment([2012, 0, 1]).week(), 52, 'Jan 1 2012 should be week 52');
test.equal(moment([2012, 0, 2]).week(), 1, 'Jan 2 2012 should be week 1');
test.equal(moment([2012, 0, 8]).week(), 1, 'Jan 8 2012 should be week 1');
test.equal(moment([2012, 0, 9]).week(), 2, 'Jan 9 2012 should be week 2');
test.equal(moment([2012, 0, 15]).week(), 2, 'Jan 15 2012 should be week 2');
test.done();
},
'weeks year starting monday' : function (test) {
test.equal(moment([2007, 0, 1]).week(), 1, 'Jan 1 2007 should be week 1');
test.equal(moment([2007, 0, 7]).week(), 1, 'Jan 7 2007 should be week 1');
test.equal(moment([2007, 0, 8]).week(), 2, 'Jan 8 2007 should be week 2');
test.equal(moment([2007, 0, 14]).week(), 2, 'Jan 14 2007 should be week 2');
test.equal(moment([2007, 0, 15]).week(), 3, 'Jan 15 2007 should be week 3');
test.done();
},
'weeks year starting tuesday' : function (test) {
test.equal(moment([2007, 11, 31]).week(), 1, 'Dec 31 2007 should be week 1');
test.equal(moment([2008, 0, 1]).week(), 1, 'Jan 1 2008 should be week 1');
test.equal(moment([2008, 0, 6]).week(), 1, 'Jan 6 2008 should be week 1');
test.equal(moment([2008, 0, 7]).week(), 2, 'Jan 7 2008 should be week 2');
test.equal(moment([2008, 0, 13]).week(), 2, 'Jan 13 2008 should be week 2');
test.equal(moment([2008, 0, 14]).week(), 3, 'Jan 14 2008 should be week 3');
test.done();
},
'weeks year starting wednesday' : function (test) {
test.equal(moment([2002, 11, 30]).week(), 1, 'Dec 30 2002 should be week 1');
test.equal(moment([2003, 0, 1]).week(), 1, 'Jan 1 2003 should be week 1');
test.equal(moment([2003, 0, 5]).week(), 1, 'Jan 5 2003 should be week 1');
test.equal(moment([2003, 0, 6]).week(), 2, 'Jan 6 2003 should be week 2');
test.equal(moment([2003, 0, 12]).week(), 2, 'Jan 12 2003 should be week 2');
test.equal(moment([2003, 0, 13]).week(), 3, 'Jan 13 2003 should be week 3');
test.done();
},
'weeks year starting thursday' : function (test) {
test.equal(moment([2008, 11, 29]).week(), 1, 'Dec 29 2008 should be week 1');
test.equal(moment([2009, 0, 1]).week(), 1, 'Jan 1 2009 should be week 1');
test.equal(moment([2009, 0, 4]).week(), 1, 'Jan 4 2009 should be week 1');
test.equal(moment([2009, 0, 5]).week(), 2, 'Jan 5 2009 should be week 2');
test.equal(moment([2009, 0, 11]).week(), 2, 'Jan 11 2009 should be week 2');
test.equal(moment([2009, 0, 13]).week(), 3, 'Jan 12 2009 should be week 3');
test.done();
},
'weeks year starting friday' : function (test) {
test.equal(moment([2009, 11, 28]).week(), 53, 'Dec 28 2009 should be week 53');
test.equal(moment([2010, 0, 1]).week(), 53, 'Jan 1 2010 should be week 53');
test.equal(moment([2010, 0, 3]).week(), 53, 'Jan 3 2010 should be week 53');
test.equal(moment([2010, 0, 4]).week(), 1, 'Jan 4 2010 should be week 1');
test.equal(moment([2010, 0, 10]).week(), 1, 'Jan 10 2010 should be week 1');
test.equal(moment([2010, 0, 11]).week(), 2, 'Jan 11 2010 should be week 2');
test.done();
},
'weeks year starting saturday' : function (test) {
test.equal(moment([2010, 11, 27]).week(), 52, 'Dec 27 2010 should be week 52');
test.equal(moment([2011, 0, 1]).week(), 52, 'Jan 1 2011 should be week 52');
test.equal(moment([2011, 0, 2]).week(), 52, 'Jan 2 2011 should be week 52');
test.equal(moment([2011, 0, 3]).week(), 1, 'Jan 3 2011 should be week 1');
test.equal(moment([2011, 0, 9]).week(), 1, 'Jan 9 2011 should be week 1');
test.equal(moment([2011, 0, 10]).week(), 2, 'Jan 10 2011 should be week 2');
test.done();
},
'weeks year starting sunday formatted' : function (test) {
test.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52ste', 'Jan 1 2012 should be week 52');
test.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1ste', 'Jan 2 2012 should be week 1');
test.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1ste', 'Jan 8 2012 should be week 1');
test.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2de', 'Jan 9 2012 should be week 2');
test.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2de', 'Jan 15 2012 should be week 2');
test.done();
}
};
|
/*
* ----------------------------- JSTORAGE -------------------------------------
* Simple local storage wrapper to save data on the browser side, supporting
* all major browsers - IE6+, Firefox2+, Safari4+, Chrome4+ and Opera 10.5+
*
* Copyright (c) 2010 - 2012 Andris Reinman, andris.reinman@gmail.com
* Project homepage: www.jstorage.info
*
* Licensed under MIT-style 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 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.
*/
(function(){
var
/* jStorage version */
JSTORAGE_VERSION = "0.4.2",
/* detect a dollar object or create one if not found */
$ = window.jQuery || window.$ || (window.$ = {}),
/* check for a JSON handling support */
JSON = {
parse:
window.JSON && (window.JSON.parse || window.JSON.decode) ||
String.prototype.evalJSON && function(str){return String(str).evalJSON();} ||
$.parseJSON ||
$.evalJSON,
stringify:
Object.toJSON ||
window.JSON && (window.JSON.stringify || window.JSON.encode) ||
$.toJSON
};
// Break if no JSON support was found
if(!JSON.parse || !JSON.stringify){
throw new Error("No JSON support found, include //cdnjs.cloudflare.com/ajax/libs/json2/20110223/json2.js to page");
}
var
/* This is the object, that holds the cached values */
_storage = {__jstorage_meta:{CRC32:{}}},
/* Actual browser storage (localStorage or globalStorage['domain']) */
_storage_service = {jStorage:"{}"},
/* DOM element for older IE versions, holds userData behavior */
_storage_elm = null,
/* How much space does the storage take */
_storage_size = 0,
/* which backend is currently used */
_backend = false,
/* onchange observers */
_observers = {},
/* timeout to wait after onchange event */
_observer_timeout = false,
/* last update time */
_observer_update = 0,
/* pubsub observers */
_pubsub_observers = {},
/* skip published items older than current timestamp */
_pubsub_last = +new Date(),
/* Next check for TTL */
_ttl_timeout,
/**
* XML encoding and decoding as XML nodes can't be JSON'ized
* XML nodes are encoded and decoded if the node is the value to be saved
* but not if it's as a property of another object
* Eg. -
* $.jStorage.set("key", xmlNode); // IS OK
* $.jStorage.set("key", {xml: xmlNode}); // NOT OK
*/
_XMLService = {
/**
* Validates a XML node to be XML
* based on jQuery.isXML function
*/
isXML: function(elm){
var documentElement = (elm ? elm.ownerDocument || elm : 0).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
},
/**
* Encodes a XML node to string
* based on http://www.mercurytide.co.uk/news/article/issues-when-working-ajax/
*/
encode: function(xmlNode) {
if(!this.isXML(xmlNode)){
return false;
}
try{ // Mozilla, Webkit, Opera
return new XMLSerializer().serializeToString(xmlNode);
}catch(E1) {
try { // IE
return xmlNode.xml;
}catch(E2){}
}
return false;
},
/**
* Decodes a XML node from string
* loosely based on http://outwestmedia.com/jquery-plugins/xmldom/
*/
decode: function(xmlString){
var dom_parser = ("DOMParser" in window && (new DOMParser()).parseFromString) ||
(window.ActiveXObject && function(_xmlString) {
var xml_doc = new ActiveXObject('Microsoft.XMLDOM');
xml_doc.async = 'false';
xml_doc.loadXML(_xmlString);
return xml_doc;
}),
resultXML;
if(!dom_parser){
return false;
}
resultXML = dom_parser.call("DOMParser" in window && (new DOMParser()) || window, xmlString, 'text/xml');
return this.isXML(resultXML)?resultXML:false;
}
};
////////////////////////// PRIVATE METHODS ////////////////////////
/**
* Initialization function. Detects if the browser supports DOM Storage
* or userData behavior and behaves accordingly.
*/
function _init(){
/* Check if browser supports localStorage */
var localStorageReallyWorks = false;
if("localStorage" in window){
try {
window.localStorage.setItem('_tmptest', 'tmpval');
localStorageReallyWorks = true;
window.localStorage.removeItem('_tmptest');
} catch(BogusQuotaExceededErrorOnIos5) {
// Thanks be to iOS5 Private Browsing mode which throws
// QUOTA_EXCEEDED_ERRROR DOM Exception 22.
}
}
if(localStorageReallyWorks){
try {
if(window.localStorage) {
_storage_service = window.localStorage;
_backend = "localStorage";
_observer_update = _storage_service.jStorage_update;
}
} catch(E3) {/* Firefox fails when touching localStorage and cookies are disabled */}
}
/* Check if browser supports globalStorage */
else if("globalStorage" in window){
try {
if(window.globalStorage) {
_storage_service = window.globalStorage[window.location.hostname];
_backend = "globalStorage";
_observer_update = _storage_service.jStorage_update;
}
} catch(E4) {/* Firefox fails when touching localStorage and cookies are disabled */}
}
/* Check if browser supports userData behavior */
else {
_storage_elm = document.createElement('link');
if(_storage_elm.addBehavior){
/* Use a DOM element to act as userData storage */
_storage_elm.style.behavior = 'url(#default#userData)';
/* userData element needs to be inserted into the DOM! */
document.getElementsByTagName('head')[0].appendChild(_storage_elm);
try{
_storage_elm.load("jStorage");
}catch(E){
// try to reset cache
_storage_elm.setAttribute("jStorage", "{}");
_storage_elm.save("jStorage");
_storage_elm.load("jStorage");
}
var data = "{}";
try{
data = _storage_elm.getAttribute("jStorage");
}catch(E5){}
try{
_observer_update = _storage_elm.getAttribute("jStorage_update");
}catch(E6){}
_storage_service.jStorage = data;
_backend = "userDataBehavior";
}else{
_storage_elm = null;
return;
}
}
// Load data from storage
_load_storage();
// remove dead keys
_handleTTL();
// start listening for changes
_setupObserver();
// initialize publish-subscribe service
_handlePubSub();
// handle cached navigation
if("addEventListener" in window){
window.addEventListener("pageshow", function(event){
if(event.persisted){
_storageObserver();
}
}, false);
}
}
/**
* Reload data from storage when needed
*/
function _reloadData(){
var data = "{}";
if(_backend == "userDataBehavior"){
_storage_elm.load("jStorage");
try{
data = _storage_elm.getAttribute("jStorage");
}catch(E5){}
try{
_observer_update = _storage_elm.getAttribute("jStorage_update");
}catch(E6){}
_storage_service.jStorage = data;
}
_load_storage();
// remove dead keys
_handleTTL();
_handlePubSub();
}
/**
* Sets up a storage change observer
*/
function _setupObserver(){
if(_backend == "localStorage" || _backend == "globalStorage"){
if("addEventListener" in window){
window.addEventListener("storage", _storageObserver, false);
}else{
document.attachEvent("onstorage", _storageObserver);
}
}else if(_backend == "userDataBehavior"){
setInterval(_storageObserver, 1000);
}
}
/**
* Fired on any kind of data change, needs to check if anything has
* really been changed
*/
function _storageObserver(){
var updateTime;
// cumulate change notifications with timeout
clearTimeout(_observer_timeout);
_observer_timeout = setTimeout(function(){
if(_backend == "localStorage" || _backend == "globalStorage"){
updateTime = _storage_service.jStorage_update;
}else if(_backend == "userDataBehavior"){
_storage_elm.load("jStorage");
try{
updateTime = _storage_elm.getAttribute("jStorage_update");
}catch(E5){}
}
if(updateTime && updateTime != _observer_update){
_observer_update = updateTime;
_checkUpdatedKeys();
}
}, 25);
}
/**
* Reloads the data and checks if any keys are changed
*/
function _checkUpdatedKeys(){
var oldCrc32List = JSON.parse(JSON.stringify(_storage.__jstorage_meta.CRC32)),
newCrc32List;
_reloadData();
newCrc32List = JSON.parse(JSON.stringify(_storage.__jstorage_meta.CRC32));
var key,
updated = [],
removed = [];
for(key in oldCrc32List){
if(oldCrc32List.hasOwnProperty(key)){
if(!newCrc32List[key]){
removed.push(key);
continue;
}
if(oldCrc32List[key] != newCrc32List[key] && String(oldCrc32List[key]).substr(0,2) == "2."){
updated.push(key);
}
}
}
for(key in newCrc32List){
if(newCrc32List.hasOwnProperty(key)){
if(!oldCrc32List[key]){
updated.push(key);
}
}
}
_fireObservers(updated, "updated");
_fireObservers(removed, "deleted");
}
/**
* Fires observers for updated keys
*
* @param {Array|String} keys Array of key names or a key
* @param {String} action What happened with the value (updated, deleted, flushed)
*/
function _fireObservers(keys, action){
keys = [].concat(keys || []);
if(action == "flushed"){
keys = [];
for(var key in _observers){
if(_observers.hasOwnProperty(key)){
keys.push(key);
}
}
action = "deleted";
}
for(var i=0, len = keys.length; i<len; i++){
if(_observers[keys[i]]){
for(var j=0, jlen = _observers[keys[i]].length; j<jlen; j++){
_observers[keys[i]][j](keys[i], action);
}
}
}
}
/**
* Publishes key change to listeners
*/
function _publishChange(){
var updateTime = (+new Date()).toString();
if(_backend == "localStorage" || _backend == "globalStorage"){
_storage_service.jStorage_update = updateTime;
}else if(_backend == "userDataBehavior"){
_storage_elm.setAttribute("jStorage_update", updateTime);
_storage_elm.save("jStorage");
}
_storageObserver();
}
/**
* Loads the data from the storage based on the supported mechanism
*/
function _load_storage(){
/* if jStorage string is retrieved, then decode it */
if(_storage_service.jStorage){
try{
_storage = JSON.parse(String(_storage_service.jStorage));
}catch(E6){_storage_service.jStorage = "{}";}
}else{
_storage_service.jStorage = "{}";
}
_storage_size = _storage_service.jStorage?String(_storage_service.jStorage).length:0;
if(!_storage.__jstorage_meta){
_storage.__jstorage_meta = {};
}
if(!_storage.__jstorage_meta.CRC32){
_storage.__jstorage_meta.CRC32 = {};
}
}
/**
* This functions provides the "save" mechanism to store the jStorage object
*/
function _save(){
_dropOldEvents(); // remove expired events
try{
_storage_service.jStorage = JSON.stringify(_storage);
// If userData is used as the storage engine, additional
if(_storage_elm) {
_storage_elm.setAttribute("jStorage",_storage_service.jStorage);
_storage_elm.save("jStorage");
}
_storage_size = _storage_service.jStorage?String(_storage_service.jStorage).length:0;
}catch(E7){/* probably cache is full, nothing is saved this way*/}
}
/**
* Function checks if a key is set and is string or numberic
*
* @param {String} key Key name
*/
function _checkKey(key){
if(!key || (typeof key != "string" && typeof key != "number")){
throw new TypeError('Key name must be string or numeric');
}
if(key == "__jstorage_meta"){
throw new TypeError('Reserved key name');
}
return true;
}
/**
* Removes expired keys
*/
function _handleTTL(){
var curtime, i, TTL, CRC32, nextExpire = Infinity, changed = false, deleted = [];
clearTimeout(_ttl_timeout);
if(!_storage.__jstorage_meta || typeof _storage.__jstorage_meta.TTL != "object"){
// nothing to do here
return;
}
curtime = +new Date();
TTL = _storage.__jstorage_meta.TTL;
CRC32 = _storage.__jstorage_meta.CRC32;
for(i in TTL){
if(TTL.hasOwnProperty(i)){
if(TTL[i] <= curtime){
delete TTL[i];
delete CRC32[i];
delete _storage[i];
changed = true;
deleted.push(i);
}else if(TTL[i] < nextExpire){
nextExpire = TTL[i];
}
}
}
// set next check
if(nextExpire != Infinity){
_ttl_timeout = setTimeout(_handleTTL, nextExpire - curtime);
}
// save changes
if(changed){
_save();
_publishChange();
_fireObservers(deleted, "deleted");
}
}
/**
* Checks if there's any events on hold to be fired to listeners
*/
function _handlePubSub(){
var i, len;
if(!_storage.__jstorage_meta.PubSub){
return;
}
var pubelm,
_pubsubCurrent = _pubsub_last;
for(i=len=_storage.__jstorage_meta.PubSub.length-1; i>=0; i--){
pubelm = _storage.__jstorage_meta.PubSub[i];
if(pubelm[0] > _pubsub_last){
_pubsubCurrent = pubelm[0];
_fireSubscribers(pubelm[1], pubelm[2]);
}
}
_pubsub_last = _pubsubCurrent;
}
/**
* Fires all subscriber listeners for a pubsub channel
*
* @param {String} channel Channel name
* @param {Mixed} payload Payload data to deliver
*/
function _fireSubscribers(channel, payload){
if(_pubsub_observers[channel]){
for(var i=0, len = _pubsub_observers[channel].length; i<len; i++){
// send immutable data that can't be modified by listeners
_pubsub_observers[channel][i](channel, JSON.parse(JSON.stringify(payload)));
}
}
}
/**
* Remove old events from the publish stream (at least 2sec old)
*/
function _dropOldEvents(){
if(!_storage.__jstorage_meta.PubSub){
return;
}
var retire = +new Date() - 2000;
for(var i=0, len = _storage.__jstorage_meta.PubSub.length; i<len; i++){
if(_storage.__jstorage_meta.PubSub[i][0] <= retire){
// deleteCount is needed for IE6
_storage.__jstorage_meta.PubSub.splice(i, _storage.__jstorage_meta.PubSub.length - i);
break;
}
}
if(!_storage.__jstorage_meta.PubSub.length){
delete _storage.__jstorage_meta.PubSub;
}
}
/**
* Publish payload to a channel
*
* @param {String} channel Channel name
* @param {Mixed} payload Payload to send to the subscribers
*/
function _publish(channel, payload){
if(!_storage.__jstorage_meta){
_storage.__jstorage_meta = {};
}
if(!_storage.__jstorage_meta.PubSub){
_storage.__jstorage_meta.PubSub = [];
}
_storage.__jstorage_meta.PubSub.unshift([+new Date, channel, payload]);
_save();
_publishChange();
}
/**
* JS Implementation of MurmurHash2
*
* SOURCE: https://github.com/garycourt/murmurhash-js (MIT licensed)
*
* @author <a href="mailto:gary.court@gmail.com">Gary Court</a>
* @see http://github.com/garycourt/murmurhash-js
* @author <a href="mailto:aappleby@gmail.com">Austin Appleby</a>
* @see http://sites.google.com/site/murmurhash/
*
* @param {string} str ASCII only
* @param {number} seed Positive integer only
* @return {number} 32-bit positive integer hash
*/
function murmurhash2_32_gc(str, seed) {
var
l = str.length,
h = seed ^ l,
i = 0,
k;
while (l >= 4) {
k =
((str.charCodeAt(i) & 0xff)) |
((str.charCodeAt(++i) & 0xff) << 8) |
((str.charCodeAt(++i) & 0xff) << 16) |
((str.charCodeAt(++i) & 0xff) << 24);
k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16));
k ^= k >>> 24;
k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16));
h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)) ^ k;
l -= 4;
++i;
}
switch (l) {
case 3: h ^= (str.charCodeAt(i + 2) & 0xff) << 16;
case 2: h ^= (str.charCodeAt(i + 1) & 0xff) << 8;
case 1: h ^= (str.charCodeAt(i) & 0xff);
h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16));
}
h ^= h >>> 13;
h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16));
h ^= h >>> 15;
return h >>> 0;
}
////////////////////////// PUBLIC INTERFACE /////////////////////////
$.jStorage = {
/* Version number */
version: JSTORAGE_VERSION,
/**
* Sets a key's value.
*
* @param {String} key Key to set. If this value is not set or not
* a string an exception is raised.
* @param {Mixed} value Value to set. This can be any value that is JSON
* compatible (Numbers, Strings, Objects etc.).
* @param {Object} [options] - possible options to use
* @param {Number} [options.TTL] - optional TTL value
* @return {Mixed} the used value
*/
set: function(key, value, options){
_checkKey(key);
options = options || {};
// undefined values are deleted automatically
if(typeof value == "undefined"){
this.deleteKey(key);
return value;
}
if(_XMLService.isXML(value)){
value = {_is_xml:true,xml:_XMLService.encode(value)};
}else if(typeof value == "function"){
return undefined; // functions can't be saved!
}else if(value && typeof value == "object"){
// clone the object before saving to _storage tree
value = JSON.parse(JSON.stringify(value));
}
_storage[key] = value;
_storage.__jstorage_meta.CRC32[key] = "2." + murmurhash2_32_gc(JSON.stringify(value), 0x9747b28c);
this.setTTL(key, options.TTL || 0); // also handles saving and _publishChange
_fireObservers(key, "updated");
return value;
},
/**
* Looks up a key in cache
*
* @param {String} key - Key to look up.
* @param {mixed} def - Default value to return, if key didn't exist.
* @return {Mixed} the key value, default value or null
*/
get: function(key, def){
_checkKey(key);
if(key in _storage){
if(_storage[key] && typeof _storage[key] == "object" && _storage[key]._is_xml) {
return _XMLService.decode(_storage[key].xml);
}else{
return _storage[key];
}
}
return typeof(def) == 'undefined' ? null : def;
},
/**
* Deletes a key from cache.
*
* @param {String} key - Key to delete.
* @return {Boolean} true if key existed or false if it didn't
*/
deleteKey: function(key){
_checkKey(key);
if(key in _storage){
delete _storage[key];
// remove from TTL list
if(typeof _storage.__jstorage_meta.TTL == "object" &&
key in _storage.__jstorage_meta.TTL){
delete _storage.__jstorage_meta.TTL[key];
}
delete _storage.__jstorage_meta.CRC32[key];
_save();
_publishChange();
_fireObservers(key, "deleted");
return true;
}
return false;
},
/**
* Sets a TTL for a key, or remove it if ttl value is 0 or below
*
* @param {String} key - key to set the TTL for
* @param {Number} ttl - TTL timeout in milliseconds
* @return {Boolean} true if key existed or false if it didn't
*/
setTTL: function(key, ttl){
var curtime = +new Date();
_checkKey(key);
ttl = Number(ttl) || 0;
if(key in _storage){
if(!_storage.__jstorage_meta.TTL){
_storage.__jstorage_meta.TTL = {};
}
// Set TTL value for the key
if(ttl>0){
_storage.__jstorage_meta.TTL[key] = curtime + ttl;
}else{
delete _storage.__jstorage_meta.TTL[key];
}
_save();
_handleTTL();
_publishChange();
return true;
}
return false;
},
/**
* Gets remaining TTL (in milliseconds) for a key or 0 when no TTL has been set
*
* @param {String} key Key to check
* @return {Number} Remaining TTL in milliseconds
*/
getTTL: function(key){
var curtime = +new Date(), ttl;
_checkKey(key);
if(key in _storage && _storage.__jstorage_meta.TTL && _storage.__jstorage_meta.TTL[key]){
ttl = _storage.__jstorage_meta.TTL[key] - curtime;
return ttl || 0;
}
return 0;
},
/**
* Deletes everything in cache.
*
* @return {Boolean} Always true
*/
flush: function(){
_storage = {__jstorage_meta:{CRC32:{}}};
_save();
_publishChange();
_fireObservers(null, "flushed");
return true;
},
/**
* Returns a read-only copy of _storage
*
* @return {Object} Read-only copy of _storage
*/
storageObj: function(){
function F() {}
F.prototype = _storage;
return new F();
},
/**
* Returns an index of all used keys as an array
* ['key1', 'key2',..'keyN']
*
* @return {Array} Used keys
*/
index: function(){
var index = [], i;
for(i in _storage){
if(_storage.hasOwnProperty(i) && i != "__jstorage_meta"){
index.push(i);
}
}
return index;
},
/**
* How much space in bytes does the storage take?
*
* @return {Number} Storage size in chars (not the same as in bytes,
* since some chars may take several bytes)
*/
storageSize: function(){
return _storage_size;
},
/**
* Which backend is currently in use?
*
* @return {String} Backend name
*/
currentBackend: function(){
return _backend;
},
/**
* Test if storage is available
*
* @return {Boolean} True if storage can be used
*/
storageAvailable: function(){
return !!_backend;
},
/**
* Register change listeners
*
* @param {String} key Key name
* @param {Function} callback Function to run when the key changes
*/
listenKeyChange: function(key, callback){
_checkKey(key);
if(!_observers[key]){
_observers[key] = [];
}
_observers[key].push(callback);
},
/**
* Remove change listeners
*
* @param {String} key Key name to unregister listeners against
* @param {Function} [callback] If set, unregister the callback, if not - unregister all
*/
stopListening: function(key, callback){
_checkKey(key);
if(!_observers[key]){
return;
}
if(!callback){
delete _observers[key];
return;
}
for(var i = _observers[key].length - 1; i>=0; i--){
if(_observers[key][i] == callback){
_observers[key].splice(i,1);
}
}
},
/**
* Subscribe to a Publish/Subscribe event stream
*
* @param {String} channel Channel name
* @param {Function} callback Function to run when the something is published to the channel
*/
subscribe: function(channel, callback){
channel = (channel || "").toString();
if(!channel){
throw new TypeError('Channel not defined');
}
if(!_pubsub_observers[channel]){
_pubsub_observers[channel] = [];
}
_pubsub_observers[channel].push(callback);
},
/**
* Publish data to an event stream
*
* @param {String} channel Channel name
* @param {Mixed} payload Payload to deliver
*/
publish: function(channel, payload){
channel = (channel || "").toString();
if(!channel){
throw new TypeError('Channel not defined');
}
_publish(channel, payload);
},
/**
* Reloads the data from browser storage
*/
reInit: function(){
_reloadData();
}
};
// Initialize jStorage
_init();
})(); |
/* @preserve
* The MIT License (MIT)
*
* Copyright (c) 2014 Petka Antonov
*
* 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:</p>
*
* 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.
*
*/
/**
* bluebird build version 2.9.20
* Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, cancel, using, filter, any, each, timers
*/
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise) {
var SomePromiseArray = Promise._SomePromiseArray;
function any(promises) {
var ret = new SomePromiseArray(promises);
var promise = ret.promise();
ret.setHowMany(1);
ret.setUnwrap();
ret.init();
return promise;
}
Promise.any = function (promises) {
return any(promises);
};
Promise.prototype.any = function () {
return any(this);
};
};
},{}],2:[function(_dereq_,module,exports){
"use strict";
var firstLineError;
try {throw new Error(); } catch (e) {firstLineError = e;}
var schedule = _dereq_("./schedule.js");
var Queue = _dereq_("./queue.js");
var _process = typeof process !== "undefined" ? process : undefined;
var util = _dereq_("./util.js");
function Async() {
this._isTickUsed = false;
this._lateQueue = new Queue(16);
this._normalQueue = new Queue(16);
this._trampolineEnabled = true;
var self = this;
this.drainQueues = function () {
self._drainQueues();
};
this._schedule =
schedule.isStatic ? schedule(this.drainQueues) : schedule;
}
Async.prototype.disableTrampolineIfNecessary = function() {
if (util.hasDevTools) {
this._trampolineEnabled = false;
}
};
Async.prototype.enableTrampoline = function() {
if (!this._trampolineEnabled) {
this._trampolineEnabled = true;
this._schedule = function(fn) {
setTimeout(fn, 0);
};
}
};
Async.prototype.haveItemsQueued = function () {
return this._normalQueue.length() > 0;
};
Async.prototype._withDomain = function(fn) {
if (_process !== undefined &&
_process.domain != null &&
!fn.domain) {
fn = _process.domain.bind(fn);
}
return fn;
};
Async.prototype.throwLater = function(fn, arg) {
if (arguments.length === 1) {
arg = fn;
fn = function () { throw arg; };
}
fn = this._withDomain(fn);
if (typeof setTimeout !== "undefined") {
setTimeout(function() {
fn(arg);
}, 0);
} else try {
this._schedule(function() {
fn(arg);
});
} catch (e) {
throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/m3OTXk\u000a");
}
};
function AsyncInvokeLater(fn, receiver, arg) {
fn = this._withDomain(fn);
this._lateQueue.push(fn, receiver, arg);
this._queueTick();
}
function AsyncInvoke(fn, receiver, arg) {
fn = this._withDomain(fn);
this._normalQueue.push(fn, receiver, arg);
this._queueTick();
}
function AsyncSettlePromises(promise) {
this._normalQueue._pushOne(promise);
this._queueTick();
}
if (!util.hasDevTools) {
Async.prototype.invokeLater = AsyncInvokeLater;
Async.prototype.invoke = AsyncInvoke;
Async.prototype.settlePromises = AsyncSettlePromises;
} else {
Async.prototype.invokeLater = function (fn, receiver, arg) {
if (this._trampolineEnabled) {
AsyncInvokeLater.call(this, fn, receiver, arg);
} else {
setTimeout(function() {
fn.call(receiver, arg);
}, 100);
}
};
Async.prototype.invoke = function (fn, receiver, arg) {
if (this._trampolineEnabled) {
AsyncInvoke.call(this, fn, receiver, arg);
} else {
setTimeout(function() {
fn.call(receiver, arg);
}, 0);
}
};
Async.prototype.settlePromises = function(promise) {
if (this._trampolineEnabled) {
AsyncSettlePromises.call(this, promise);
} else {
setTimeout(function() {
promise._settlePromises();
}, 0);
}
};
}
Async.prototype.invokeFirst = function (fn, receiver, arg) {
fn = this._withDomain(fn);
this._normalQueue.unshift(fn, receiver, arg);
this._queueTick();
};
Async.prototype._drainQueue = function(queue) {
while (queue.length() > 0) {
var fn = queue.shift();
if (typeof fn !== "function") {
fn._settlePromises();
continue;
}
var receiver = queue.shift();
var arg = queue.shift();
fn.call(receiver, arg);
}
};
Async.prototype._drainQueues = function () {
this._drainQueue(this._normalQueue);
this._reset();
this._drainQueue(this._lateQueue);
};
Async.prototype._queueTick = function () {
if (!this._isTickUsed) {
this._isTickUsed = true;
this._schedule(this.drainQueues);
}
};
Async.prototype._reset = function () {
this._isTickUsed = false;
};
module.exports = new Async();
module.exports.firstLineError = firstLineError;
},{"./queue.js":28,"./schedule.js":31,"./util.js":38}],3:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, INTERNAL, tryConvertToPromise) {
var rejectThis = function(_, e) {
this._reject(e);
};
var targetRejected = function(e, context) {
context.promiseRejectionQueued = true;
context.bindingPromise._then(rejectThis, rejectThis, null, this, e);
};
var bindingResolved = function(thisArg, context) {
this._setBoundTo(thisArg);
if (this._isPending()) {
this._resolveCallback(context.target);
}
};
var bindingRejected = function(e, context) {
if (!context.promiseRejectionQueued) this._reject(e);
};
Promise.prototype.bind = function (thisArg) {
var maybePromise = tryConvertToPromise(thisArg);
var ret = new Promise(INTERNAL);
ret._propagateFrom(this, 1);
var target = this._target();
if (maybePromise instanceof Promise) {
var context = {
promiseRejectionQueued: false,
promise: ret,
target: target,
bindingPromise: maybePromise
};
target._then(INTERNAL, targetRejected, ret._progress, ret, context);
maybePromise._then(
bindingResolved, bindingRejected, ret._progress, ret, context);
} else {
ret._setBoundTo(thisArg);
ret._resolveCallback(target);
}
return ret;
};
Promise.prototype._setBoundTo = function (obj) {
if (obj !== undefined) {
this._bitField = this._bitField | 131072;
this._boundTo = obj;
} else {
this._bitField = this._bitField & (~131072);
}
};
Promise.prototype._isBound = function () {
return (this._bitField & 131072) === 131072;
};
Promise.bind = function (thisArg, value) {
var maybePromise = tryConvertToPromise(thisArg);
var ret = new Promise(INTERNAL);
if (maybePromise instanceof Promise) {
maybePromise._then(function(thisArg) {
ret._setBoundTo(thisArg);
ret._resolveCallback(value);
}, ret._reject, ret._progress, ret, null);
} else {
ret._setBoundTo(thisArg);
ret._resolveCallback(value);
}
return ret;
};
};
},{}],4:[function(_dereq_,module,exports){
"use strict";
var old;
if (typeof Promise !== "undefined") old = Promise;
function noConflict() {
try { if (Promise === bluebird) Promise = old; }
catch (e) {}
return bluebird;
}
var bluebird = _dereq_("./promise.js")();
bluebird.noConflict = noConflict;
module.exports = bluebird;
},{"./promise.js":23}],5:[function(_dereq_,module,exports){
"use strict";
var cr = Object.create;
if (cr) {
var callerCache = cr(null);
var getterCache = cr(null);
callerCache[" size"] = getterCache[" size"] = 0;
}
module.exports = function(Promise) {
var util = _dereq_("./util.js");
var canEvaluate = util.canEvaluate;
var isIdentifier = util.isIdentifier;
var getMethodCaller;
var getGetter;
if (!true) {
var makeMethodCaller = function (methodName) {
return new Function("ensureMethod", " \n\
return function(obj) { \n\
'use strict' \n\
var len = this.length; \n\
ensureMethod(obj, 'methodName'); \n\
switch(len) { \n\
case 1: return obj.methodName(this[0]); \n\
case 2: return obj.methodName(this[0], this[1]); \n\
case 3: return obj.methodName(this[0], this[1], this[2]); \n\
case 0: return obj.methodName(); \n\
default: \n\
return obj.methodName.apply(obj, this); \n\
} \n\
}; \n\
".replace(/methodName/g, methodName))(ensureMethod);
};
var makeGetter = function (propertyName) {
return new Function("obj", " \n\
'use strict'; \n\
return obj.propertyName; \n\
".replace("propertyName", propertyName));
};
var getCompiled = function(name, compiler, cache) {
var ret = cache[name];
if (typeof ret !== "function") {
if (!isIdentifier(name)) {
return null;
}
ret = compiler(name);
cache[name] = ret;
cache[" size"]++;
if (cache[" size"] > 512) {
var keys = Object.keys(cache);
for (var i = 0; i < 256; ++i) delete cache[keys[i]];
cache[" size"] = keys.length - 256;
}
}
return ret;
};
getMethodCaller = function(name) {
return getCompiled(name, makeMethodCaller, callerCache);
};
getGetter = function(name) {
return getCompiled(name, makeGetter, getterCache);
};
}
function ensureMethod(obj, methodName) {
var fn;
if (obj != null) fn = obj[methodName];
if (typeof fn !== "function") {
var message = "Object " + util.classString(obj) + " has no method '" +
util.toString(methodName) + "'";
throw new Promise.TypeError(message);
}
return fn;
}
function caller(obj) {
var methodName = this.pop();
var fn = ensureMethod(obj, methodName);
return fn.apply(obj, this);
}
Promise.prototype.call = function (methodName) {
var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];}
if (!true) {
if (canEvaluate) {
var maybeCaller = getMethodCaller(methodName);
if (maybeCaller !== null) {
return this._then(
maybeCaller, undefined, undefined, args, undefined);
}
}
}
args.push(methodName);
return this._then(caller, undefined, undefined, args, undefined);
};
function namedGetter(obj) {
return obj[this];
}
function indexedGetter(obj) {
var index = +this;
if (index < 0) index = Math.max(0, index + obj.length);
return obj[index];
}
Promise.prototype.get = function (propertyName) {
var isIndex = (typeof propertyName === "number");
var getter;
if (!isIndex) {
if (canEvaluate) {
var maybeGetter = getGetter(propertyName);
getter = maybeGetter !== null ? maybeGetter : namedGetter;
} else {
getter = namedGetter;
}
} else {
getter = indexedGetter;
}
return this._then(getter, undefined, undefined, propertyName, undefined);
};
};
},{"./util.js":38}],6:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise) {
var errors = _dereq_("./errors.js");
var async = _dereq_("./async.js");
var CancellationError = errors.CancellationError;
Promise.prototype._cancel = function (reason) {
if (!this.isCancellable()) return this;
var parent;
var promiseToReject = this;
while ((parent = promiseToReject._cancellationParent) !== undefined &&
parent.isCancellable()) {
promiseToReject = parent;
}
this._unsetCancellable();
promiseToReject._target()._rejectCallback(reason, false, true);
};
Promise.prototype.cancel = function (reason) {
if (!this.isCancellable()) return this;
if (reason === undefined) reason = new CancellationError();
async.invokeLater(this._cancel, this, reason);
return this;
};
Promise.prototype.cancellable = function () {
if (this._cancellable()) return this;
async.enableTrampoline();
this._setCancellable();
this._cancellationParent = undefined;
return this;
};
Promise.prototype.uncancellable = function () {
var ret = this.then();
ret._unsetCancellable();
return ret;
};
Promise.prototype.fork = function (didFulfill, didReject, didProgress) {
var ret = this._then(didFulfill, didReject, didProgress,
undefined, undefined);
ret._setCancellable();
ret._cancellationParent = undefined;
return ret;
};
};
},{"./async.js":2,"./errors.js":13}],7:[function(_dereq_,module,exports){
"use strict";
module.exports = function() {
var async = _dereq_("./async.js");
var util = _dereq_("./util.js");
var bluebirdFramePattern =
/[\\\/]bluebird[\\\/]js[\\\/](main|debug|zalgo|instrumented)/;
var stackFramePattern = null;
var formatStack = null;
var indentStackFrames = false;
var warn;
function CapturedTrace(parent) {
this._parent = parent;
var length = this._length = 1 + (parent === undefined ? 0 : parent._length);
captureStackTrace(this, CapturedTrace);
if (length > 32) this.uncycle();
}
util.inherits(CapturedTrace, Error);
CapturedTrace.prototype.uncycle = function() {
var length = this._length;
if (length < 2) return;
var nodes = [];
var stackToIndex = {};
for (var i = 0, node = this; node !== undefined; ++i) {
nodes.push(node);
node = node._parent;
}
length = this._length = i;
for (var i = length - 1; i >= 0; --i) {
var stack = nodes[i].stack;
if (stackToIndex[stack] === undefined) {
stackToIndex[stack] = i;
}
}
for (var i = 0; i < length; ++i) {
var currentStack = nodes[i].stack;
var index = stackToIndex[currentStack];
if (index !== undefined && index !== i) {
if (index > 0) {
nodes[index - 1]._parent = undefined;
nodes[index - 1]._length = 1;
}
nodes[i]._parent = undefined;
nodes[i]._length = 1;
var cycleEdgeNode = i > 0 ? nodes[i - 1] : this;
if (index < length - 1) {
cycleEdgeNode._parent = nodes[index + 1];
cycleEdgeNode._parent.uncycle();
cycleEdgeNode._length =
cycleEdgeNode._parent._length + 1;
} else {
cycleEdgeNode._parent = undefined;
cycleEdgeNode._length = 1;
}
var currentChildLength = cycleEdgeNode._length + 1;
for (var j = i - 2; j >= 0; --j) {
nodes[j]._length = currentChildLength;
currentChildLength++;
}
return;
}
}
};
CapturedTrace.prototype.parent = function() {
return this._parent;
};
CapturedTrace.prototype.hasParent = function() {
return this._parent !== undefined;
};
CapturedTrace.prototype.attachExtraTrace = function(error) {
if (error.__stackCleaned__) return;
this.uncycle();
var parsed = CapturedTrace.parseStackAndMessage(error);
var message = parsed.message;
var stacks = [parsed.stack];
var trace = this;
while (trace !== undefined) {
stacks.push(cleanStack(trace.stack.split("\n")));
trace = trace._parent;
}
removeCommonRoots(stacks);
removeDuplicateOrEmptyJumps(stacks);
error.stack = reconstructStack(message, stacks);
util.notEnumerableProp(error, "__stackCleaned__", true);
};
function reconstructStack(message, stacks) {
for (var i = 0; i < stacks.length - 1; ++i) {
stacks[i].push("From previous event:");
stacks[i] = stacks[i].join("\n");
}
if (i < stacks.length) {
stacks[i] = stacks[i].join("\n");
}
return message + "\n" + stacks.join("\n");
}
function removeDuplicateOrEmptyJumps(stacks) {
for (var i = 0; i < stacks.length; ++i) {
if (stacks[i].length === 0 ||
((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) {
stacks.splice(i, 1);
i--;
}
}
}
function removeCommonRoots(stacks) {
var current = stacks[0];
for (var i = 1; i < stacks.length; ++i) {
var prev = stacks[i];
var currentLastIndex = current.length - 1;
var currentLastLine = current[currentLastIndex];
var commonRootMeetPoint = -1;
for (var j = prev.length - 1; j >= 0; --j) {
if (prev[j] === currentLastLine) {
commonRootMeetPoint = j;
break;
}
}
for (var j = commonRootMeetPoint; j >= 0; --j) {
var line = prev[j];
if (current[currentLastIndex] === line) {
current.pop();
currentLastIndex--;
} else {
break;
}
}
current = prev;
}
}
function cleanStack(stack) {
var ret = [];
for (var i = 0; i < stack.length; ++i) {
var line = stack[i];
var isTraceLine = stackFramePattern.test(line) ||
" (No stack trace)" === line;
var isInternalFrame = isTraceLine && shouldIgnore(line);
if (isTraceLine && !isInternalFrame) {
if (indentStackFrames && line.charAt(0) !== " ") {
line = " " + line;
}
ret.push(line);
}
}
return ret;
}
function stackFramesAsArray(error) {
var stack = error.stack.replace(/\s+$/g, "").split("\n");
for (var i = 0; i < stack.length; ++i) {
var line = stack[i];
if (" (No stack trace)" === line || stackFramePattern.test(line)) {
break;
}
}
if (i > 0) {
stack = stack.slice(i);
}
return stack;
}
CapturedTrace.parseStackAndMessage = function(error) {
var stack = error.stack;
var message = error.toString();
stack = typeof stack === "string" && stack.length > 0
? stackFramesAsArray(error) : [" (No stack trace)"];
return {
message: message,
stack: cleanStack(stack)
};
};
CapturedTrace.formatAndLogError = function(error, title) {
if (typeof console !== "undefined") {
var message;
if (typeof error === "object" || typeof error === "function") {
var stack = error.stack;
message = title + formatStack(stack, error);
} else {
message = title + String(error);
}
if (typeof warn === "function") {
warn(message);
} else if (typeof console.log === "function" ||
typeof console.log === "object") {
console.log(message);
}
}
};
CapturedTrace.unhandledRejection = function (reason) {
CapturedTrace.formatAndLogError(reason, "^--- With additional stack trace: ");
};
CapturedTrace.isSupported = function () {
return typeof captureStackTrace === "function";
};
CapturedTrace.fireRejectionEvent =
function(name, localHandler, reason, promise) {
var localEventFired = false;
try {
if (typeof localHandler === "function") {
localEventFired = true;
if (name === "rejectionHandled") {
localHandler(promise);
} else {
localHandler(reason, promise);
}
}
} catch (e) {
async.throwLater(e);
}
var globalEventFired = false;
try {
globalEventFired = fireGlobalEvent(name, reason, promise);
} catch (e) {
globalEventFired = true;
async.throwLater(e);
}
var domEventFired = false;
if (fireDomEvent) {
try {
domEventFired = fireDomEvent(name.toLowerCase(), {
reason: reason,
promise: promise
});
} catch (e) {
domEventFired = true;
async.throwLater(e);
}
}
if (!globalEventFired && !localEventFired && !domEventFired &&
name === "unhandledRejection") {
CapturedTrace.formatAndLogError(reason, "Unhandled rejection ");
}
};
function formatNonError(obj) {
var str;
if (typeof obj === "function") {
str = "[function " +
(obj.name || "anonymous") +
"]";
} else {
str = obj.toString();
var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/;
if (ruselessToString.test(str)) {
try {
var newStr = JSON.stringify(obj);
str = newStr;
}
catch(e) {
}
}
if (str.length === 0) {
str = "(empty array)";
}
}
return ("(<" + snip(str) + ">, no stack trace)");
}
function snip(str) {
var maxChars = 41;
if (str.length < maxChars) {
return str;
}
return str.substr(0, maxChars - 3) + "...";
}
var shouldIgnore = function() { return false; };
var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;
function parseLineInfo(line) {
var matches = line.match(parseLineInfoRegex);
if (matches) {
return {
fileName: matches[1],
line: parseInt(matches[2], 10)
};
}
}
CapturedTrace.setBounds = function(firstLineError, lastLineError) {
if (!CapturedTrace.isSupported()) return;
var firstStackLines = firstLineError.stack.split("\n");
var lastStackLines = lastLineError.stack.split("\n");
var firstIndex = -1;
var lastIndex = -1;
var firstFileName;
var lastFileName;
for (var i = 0; i < firstStackLines.length; ++i) {
var result = parseLineInfo(firstStackLines[i]);
if (result) {
firstFileName = result.fileName;
firstIndex = result.line;
break;
}
}
for (var i = 0; i < lastStackLines.length; ++i) {
var result = parseLineInfo(lastStackLines[i]);
if (result) {
lastFileName = result.fileName;
lastIndex = result.line;
break;
}
}
if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName ||
firstFileName !== lastFileName || firstIndex >= lastIndex) {
return;
}
shouldIgnore = function(line) {
if (bluebirdFramePattern.test(line)) return true;
var info = parseLineInfo(line);
if (info) {
if (info.fileName === firstFileName &&
(firstIndex <= info.line && info.line <= lastIndex)) {
return true;
}
}
return false;
};
};
var captureStackTrace = (function stackDetection() {
var v8stackFramePattern = /^\s*at\s*/;
var v8stackFormatter = function(stack, error) {
if (typeof stack === "string") return stack;
if (error.name !== undefined &&
error.message !== undefined) {
return error.toString();
}
return formatNonError(error);
};
if (typeof Error.stackTraceLimit === "number" &&
typeof Error.captureStackTrace === "function") {
Error.stackTraceLimit = Error.stackTraceLimit + 6;
stackFramePattern = v8stackFramePattern;
formatStack = v8stackFormatter;
var captureStackTrace = Error.captureStackTrace;
shouldIgnore = function(line) {
return bluebirdFramePattern.test(line);
};
return function(receiver, ignoreUntil) {
Error.stackTraceLimit = Error.stackTraceLimit + 6;
captureStackTrace(receiver, ignoreUntil);
Error.stackTraceLimit = Error.stackTraceLimit - 6;
};
}
var err = new Error();
if (typeof err.stack === "string" &&
err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) {
stackFramePattern = /@/;
formatStack = v8stackFormatter;
indentStackFrames = true;
return function captureStackTrace(o) {
o.stack = new Error().stack;
};
}
var hasStackAfterThrow;
try { throw new Error(); }
catch(e) {
hasStackAfterThrow = ("stack" in e);
}
if (!("stack" in err) && hasStackAfterThrow) {
stackFramePattern = v8stackFramePattern;
formatStack = v8stackFormatter;
return function captureStackTrace(o) {
Error.stackTraceLimit = Error.stackTraceLimit + 6;
try { throw new Error(); }
catch(e) { o.stack = e.stack; }
Error.stackTraceLimit = Error.stackTraceLimit - 6;
};
}
formatStack = function(stack, error) {
if (typeof stack === "string") return stack;
if ((typeof error === "object" ||
typeof error === "function") &&
error.name !== undefined &&
error.message !== undefined) {
return error.toString();
}
return formatNonError(error);
};
return null;
})([]);
var fireDomEvent;
var fireGlobalEvent = (function() {
if (util.isNode) {
return function(name, reason, promise) {
if (name === "rejectionHandled") {
return process.emit(name, promise);
} else {
return process.emit(name, reason, promise);
}
};
} else {
var customEventWorks = false;
var anyEventWorks = true;
try {
var ev = new self.CustomEvent("test");
customEventWorks = ev instanceof CustomEvent;
} catch (e) {}
if (!customEventWorks) {
try {
var event = document.createEvent("CustomEvent");
event.initCustomEvent("testingtheevent", false, true, {});
self.dispatchEvent(event);
} catch (e) {
anyEventWorks = false;
}
}
if (anyEventWorks) {
fireDomEvent = function(type, detail) {
var event;
if (customEventWorks) {
event = new self.CustomEvent(type, {
detail: detail,
bubbles: false,
cancelable: true
});
} else if (self.dispatchEvent) {
event = document.createEvent("CustomEvent");
event.initCustomEvent(type, false, true, detail);
}
return event ? !self.dispatchEvent(event) : false;
};
}
var toWindowMethodNameMap = {};
toWindowMethodNameMap["unhandledRejection"] = ("on" +
"unhandledRejection").toLowerCase();
toWindowMethodNameMap["rejectionHandled"] = ("on" +
"rejectionHandled").toLowerCase();
return function(name, reason, promise) {
var methodName = toWindowMethodNameMap[name];
var method = self[methodName];
if (!method) return false;
if (name === "rejectionHandled") {
method.call(self, promise);
} else {
method.call(self, reason, promise);
}
return true;
};
}
})();
if (typeof console !== "undefined" && typeof console.warn !== "undefined") {
warn = function (message) {
console.warn(message);
};
if (util.isNode && process.stderr.isTTY) {
warn = function(message) {
process.stderr.write("\u001b[31m" + message + "\u001b[39m\n");
};
} else if (!util.isNode && typeof (new Error().stack) === "string") {
warn = function(message) {
console.warn("%c" + message, "color: red");
};
}
}
return CapturedTrace;
};
},{"./async.js":2,"./util.js":38}],8:[function(_dereq_,module,exports){
"use strict";
module.exports = function(NEXT_FILTER) {
var util = _dereq_("./util.js");
var errors = _dereq_("./errors.js");
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
var keys = _dereq_("./es5.js").keys;
var TypeError = errors.TypeError;
function CatchFilter(instances, callback, promise) {
this._instances = instances;
this._callback = callback;
this._promise = promise;
}
function safePredicate(predicate, e) {
var safeObject = {};
var retfilter = tryCatch(predicate).call(safeObject, e);
if (retfilter === errorObj) return retfilter;
var safeKeys = keys(safeObject);
if (safeKeys.length) {
errorObj.e = new TypeError("Catch filter must inherit from Error or be a simple predicate function\u000a\u000a See http://goo.gl/o84o68\u000a");
return errorObj;
}
return retfilter;
}
CatchFilter.prototype.doFilter = function (e) {
var cb = this._callback;
var promise = this._promise;
var boundTo = promise._boundTo;
for (var i = 0, len = this._instances.length; i < len; ++i) {
var item = this._instances[i];
var itemIsErrorType = item === Error ||
(item != null && item.prototype instanceof Error);
if (itemIsErrorType && e instanceof item) {
var ret = tryCatch(cb).call(boundTo, e);
if (ret === errorObj) {
NEXT_FILTER.e = ret.e;
return NEXT_FILTER;
}
return ret;
} else if (typeof item === "function" && !itemIsErrorType) {
var shouldHandle = safePredicate(item, e);
if (shouldHandle === errorObj) {
e = errorObj.e;
break;
} else if (shouldHandle) {
var ret = tryCatch(cb).call(boundTo, e);
if (ret === errorObj) {
NEXT_FILTER.e = ret.e;
return NEXT_FILTER;
}
return ret;
}
}
}
NEXT_FILTER.e = e;
return NEXT_FILTER;
};
return CatchFilter;
};
},{"./errors.js":13,"./es5.js":14,"./util.js":38}],9:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, CapturedTrace, isDebugging) {
var contextStack = [];
function Context() {
this._trace = new CapturedTrace(peekContext());
}
Context.prototype._pushContext = function () {
if (!isDebugging()) return;
if (this._trace !== undefined) {
contextStack.push(this._trace);
}
};
Context.prototype._popContext = function () {
if (!isDebugging()) return;
if (this._trace !== undefined) {
contextStack.pop();
}
};
function createContext() {
if (isDebugging()) return new Context();
}
function peekContext() {
var lastIndex = contextStack.length - 1;
if (lastIndex >= 0) {
return contextStack[lastIndex];
}
return undefined;
}
Promise.prototype._peekContext = peekContext;
Promise.prototype._pushContext = Context.prototype._pushContext;
Promise.prototype._popContext = Context.prototype._popContext;
return createContext;
};
},{}],10:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, CapturedTrace) {
var async = _dereq_("./async.js");
var Warning = _dereq_("./errors.js").Warning;
var util = _dereq_("./util.js");
var canAttachTrace = util.canAttachTrace;
var unhandledRejectionHandled;
var possiblyUnhandledRejection;
var debugging = false || (util.isNode &&
(!!process.env["BLUEBIRD_DEBUG"] ||
process.env["NODE_ENV"] === "development"));
if (debugging) {
async.disableTrampolineIfNecessary();
}
Promise.prototype._ensurePossibleRejectionHandled = function () {
this._setRejectionIsUnhandled();
async.invokeLater(this._notifyUnhandledRejection, this, undefined);
};
Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
CapturedTrace.fireRejectionEvent("rejectionHandled",
unhandledRejectionHandled, undefined, this);
};
Promise.prototype._notifyUnhandledRejection = function () {
if (this._isRejectionUnhandled()) {
var reason = this._getCarriedStackTrace() || this._settledValue;
this._setUnhandledRejectionIsNotified();
CapturedTrace.fireRejectionEvent("unhandledRejection",
possiblyUnhandledRejection, reason, this);
}
};
Promise.prototype._setUnhandledRejectionIsNotified = function () {
this._bitField = this._bitField | 524288;
};
Promise.prototype._unsetUnhandledRejectionIsNotified = function () {
this._bitField = this._bitField & (~524288);
};
Promise.prototype._isUnhandledRejectionNotified = function () {
return (this._bitField & 524288) > 0;
};
Promise.prototype._setRejectionIsUnhandled = function () {
this._bitField = this._bitField | 2097152;
};
Promise.prototype._unsetRejectionIsUnhandled = function () {
this._bitField = this._bitField & (~2097152);
if (this._isUnhandledRejectionNotified()) {
this._unsetUnhandledRejectionIsNotified();
this._notifyUnhandledRejectionIsHandled();
}
};
Promise.prototype._isRejectionUnhandled = function () {
return (this._bitField & 2097152) > 0;
};
Promise.prototype._setCarriedStackTrace = function (capturedTrace) {
this._bitField = this._bitField | 1048576;
this._fulfillmentHandler0 = capturedTrace;
};
Promise.prototype._isCarryingStackTrace = function () {
return (this._bitField & 1048576) > 0;
};
Promise.prototype._getCarriedStackTrace = function () {
return this._isCarryingStackTrace()
? this._fulfillmentHandler0
: undefined;
};
Promise.prototype._captureStackTrace = function () {
if (debugging) {
this._trace = new CapturedTrace(this._peekContext());
}
return this;
};
Promise.prototype._attachExtraTrace = function (error, ignoreSelf) {
if (debugging && canAttachTrace(error)) {
var trace = this._trace;
if (trace !== undefined) {
if (ignoreSelf) trace = trace._parent;
}
if (trace !== undefined) {
trace.attachExtraTrace(error);
} else if (!error.__stackCleaned__) {
var parsed = CapturedTrace.parseStackAndMessage(error);
error.stack = parsed.message + "\n" + parsed.stack.join("\n");
util.notEnumerableProp(error, "__stackCleaned__", true);
}
}
};
Promise.prototype._warn = function(message) {
var warning = new Warning(message);
var ctx = this._peekContext();
if (ctx) {
ctx.attachExtraTrace(warning);
} else {
var parsed = CapturedTrace.parseStackAndMessage(warning);
warning.stack = parsed.message + "\n" + parsed.stack.join("\n");
}
CapturedTrace.formatAndLogError(warning, "");
};
Promise.onPossiblyUnhandledRejection = function (fn) {
possiblyUnhandledRejection = typeof fn === "function" ? fn : undefined;
};
Promise.onUnhandledRejectionHandled = function (fn) {
unhandledRejectionHandled = typeof fn === "function" ? fn : undefined;
};
Promise.longStackTraces = function () {
if (async.haveItemsQueued() &&
debugging === false
) {
throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/DT1qyG\u000a");
}
debugging = CapturedTrace.isSupported();
if (debugging) {
async.disableTrampolineIfNecessary();
}
};
Promise.hasLongStackTraces = function () {
return debugging && CapturedTrace.isSupported();
};
if (!CapturedTrace.isSupported()) {
Promise.longStackTraces = function(){};
debugging = false;
}
return function() {
return debugging;
};
};
},{"./async.js":2,"./errors.js":13,"./util.js":38}],11:[function(_dereq_,module,exports){
"use strict";
var util = _dereq_("./util.js");
var isPrimitive = util.isPrimitive;
var wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver;
module.exports = function(Promise) {
var returner = function () {
return this;
};
var thrower = function () {
throw this;
};
var wrapper = function (value, action) {
if (action === 1) {
return function () {
throw value;
};
} else if (action === 2) {
return function () {
return value;
};
}
};
Promise.prototype["return"] =
Promise.prototype.thenReturn = function (value) {
if (wrapsPrimitiveReceiver && isPrimitive(value)) {
return this._then(
wrapper(value, 2),
undefined,
undefined,
undefined,
undefined
);
}
return this._then(returner, undefined, undefined, value, undefined);
};
Promise.prototype["throw"] =
Promise.prototype.thenThrow = function (reason) {
if (wrapsPrimitiveReceiver && isPrimitive(reason)) {
return this._then(
wrapper(reason, 1),
undefined,
undefined,
undefined,
undefined
);
}
return this._then(thrower, undefined, undefined, reason, undefined);
};
};
},{"./util.js":38}],12:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, INTERNAL) {
var PromiseReduce = Promise.reduce;
Promise.prototype.each = function (fn) {
return PromiseReduce(this, fn, null, INTERNAL);
};
Promise.each = function (promises, fn) {
return PromiseReduce(promises, fn, null, INTERNAL);
};
};
},{}],13:[function(_dereq_,module,exports){
"use strict";
var es5 = _dereq_("./es5.js");
var Objectfreeze = es5.freeze;
var util = _dereq_("./util.js");
var inherits = util.inherits;
var notEnumerableProp = util.notEnumerableProp;
function subError(nameProperty, defaultMessage) {
function SubError(message) {
if (!(this instanceof SubError)) return new SubError(message);
notEnumerableProp(this, "message",
typeof message === "string" ? message : defaultMessage);
notEnumerableProp(this, "name", nameProperty);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
} else {
Error.call(this);
}
}
inherits(SubError, Error);
return SubError;
}
var _TypeError, _RangeError;
var Warning = subError("Warning", "warning");
var CancellationError = subError("CancellationError", "cancellation error");
var TimeoutError = subError("TimeoutError", "timeout error");
var AggregateError = subError("AggregateError", "aggregate error");
try {
_TypeError = TypeError;
_RangeError = RangeError;
} catch(e) {
_TypeError = subError("TypeError", "type error");
_RangeError = subError("RangeError", "range error");
}
var methods = ("join pop push shift unshift slice filter forEach some " +
"every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" ");
for (var i = 0; i < methods.length; ++i) {
if (typeof Array.prototype[methods[i]] === "function") {
AggregateError.prototype[methods[i]] = Array.prototype[methods[i]];
}
}
es5.defineProperty(AggregateError.prototype, "length", {
value: 0,
configurable: false,
writable: true,
enumerable: true
});
AggregateError.prototype["isOperational"] = true;
var level = 0;
AggregateError.prototype.toString = function() {
var indent = Array(level * 4 + 1).join(" ");
var ret = "\n" + indent + "AggregateError of:" + "\n";
level++;
indent = Array(level * 4 + 1).join(" ");
for (var i = 0; i < this.length; ++i) {
var str = this[i] === this ? "[Circular AggregateError]" : this[i] + "";
var lines = str.split("\n");
for (var j = 0; j < lines.length; ++j) {
lines[j] = indent + lines[j];
}
str = lines.join("\n");
ret += str + "\n";
}
level--;
return ret;
};
function OperationalError(message) {
if (!(this instanceof OperationalError))
return new OperationalError(message);
notEnumerableProp(this, "name", "OperationalError");
notEnumerableProp(this, "message", message);
this.cause = message;
this["isOperational"] = true;
if (message instanceof Error) {
notEnumerableProp(this, "message", message.message);
notEnumerableProp(this, "stack", message.stack);
} else if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}
inherits(OperationalError, Error);
var errorTypes = Error["__BluebirdErrorTypes__"];
if (!errorTypes) {
errorTypes = Objectfreeze({
CancellationError: CancellationError,
TimeoutError: TimeoutError,
OperationalError: OperationalError,
RejectionError: OperationalError,
AggregateError: AggregateError
});
notEnumerableProp(Error, "__BluebirdErrorTypes__", errorTypes);
}
module.exports = {
Error: Error,
TypeError: _TypeError,
RangeError: _RangeError,
CancellationError: errorTypes.CancellationError,
OperationalError: errorTypes.OperationalError,
TimeoutError: errorTypes.TimeoutError,
AggregateError: errorTypes.AggregateError,
Warning: Warning
};
},{"./es5.js":14,"./util.js":38}],14:[function(_dereq_,module,exports){
var isES5 = (function(){
"use strict";
return this === undefined;
})();
if (isES5) {
module.exports = {
freeze: Object.freeze,
defineProperty: Object.defineProperty,
getDescriptor: Object.getOwnPropertyDescriptor,
keys: Object.keys,
names: Object.getOwnPropertyNames,
getPrototypeOf: Object.getPrototypeOf,
isArray: Array.isArray,
isES5: isES5,
propertyIsWritable: function(obj, prop) {
var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
return !!(!descriptor || descriptor.writable || descriptor.set);
}
};
} else {
var has = {}.hasOwnProperty;
var str = {}.toString;
var proto = {}.constructor.prototype;
var ObjectKeys = function (o) {
var ret = [];
for (var key in o) {
if (has.call(o, key)) {
ret.push(key);
}
}
return ret;
};
var ObjectGetDescriptor = function(o, key) {
return {value: o[key]};
};
var ObjectDefineProperty = function (o, key, desc) {
o[key] = desc.value;
return o;
};
var ObjectFreeze = function (obj) {
return obj;
};
var ObjectGetPrototypeOf = function (obj) {
try {
return Object(obj).constructor.prototype;
}
catch (e) {
return proto;
}
};
var ArrayIsArray = function (obj) {
try {
return str.call(obj) === "[object Array]";
}
catch(e) {
return false;
}
};
module.exports = {
isArray: ArrayIsArray,
keys: ObjectKeys,
names: ObjectKeys,
defineProperty: ObjectDefineProperty,
getDescriptor: ObjectGetDescriptor,
freeze: ObjectFreeze,
getPrototypeOf: ObjectGetPrototypeOf,
isES5: isES5,
propertyIsWritable: function() {
return true;
}
};
}
},{}],15:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, INTERNAL) {
var PromiseMap = Promise.map;
Promise.prototype.filter = function (fn, options) {
return PromiseMap(this, fn, options, INTERNAL);
};
Promise.filter = function (promises, fn, options) {
return PromiseMap(promises, fn, options, INTERNAL);
};
};
},{}],16:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, NEXT_FILTER, tryConvertToPromise) {
var util = _dereq_("./util.js");
var wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver;
var isPrimitive = util.isPrimitive;
var thrower = util.thrower;
function returnThis() {
return this;
}
function throwThis() {
throw this;
}
function return$(r) {
return function() {
return r;
};
}
function throw$(r) {
return function() {
throw r;
};
}
function promisedFinally(ret, reasonOrValue, isFulfilled) {
var then;
if (wrapsPrimitiveReceiver && isPrimitive(reasonOrValue)) {
then = isFulfilled ? return$(reasonOrValue) : throw$(reasonOrValue);
} else {
then = isFulfilled ? returnThis : throwThis;
}
return ret._then(then, thrower, undefined, reasonOrValue, undefined);
}
function finallyHandler(reasonOrValue) {
var promise = this.promise;
var handler = this.handler;
var ret = promise._isBound()
? handler.call(promise._boundTo)
: handler();
if (ret !== undefined) {
var maybePromise = tryConvertToPromise(ret, promise);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
return promisedFinally(maybePromise, reasonOrValue,
promise.isFulfilled());
}
}
if (promise.isRejected()) {
NEXT_FILTER.e = reasonOrValue;
return NEXT_FILTER;
} else {
return reasonOrValue;
}
}
function tapHandler(value) {
var promise = this.promise;
var handler = this.handler;
var ret = promise._isBound()
? handler.call(promise._boundTo, value)
: handler(value);
if (ret !== undefined) {
var maybePromise = tryConvertToPromise(ret, promise);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
return promisedFinally(maybePromise, value, true);
}
}
return value;
}
Promise.prototype._passThroughHandler = function (handler, isFinally) {
if (typeof handler !== "function") return this.then();
var promiseAndHandler = {
promise: this,
handler: handler
};
return this._then(
isFinally ? finallyHandler : tapHandler,
isFinally ? finallyHandler : undefined, undefined,
promiseAndHandler, undefined);
};
Promise.prototype.lastly =
Promise.prototype["finally"] = function (handler) {
return this._passThroughHandler(handler, true);
};
Promise.prototype.tap = function (handler) {
return this._passThroughHandler(handler, false);
};
};
},{"./util.js":38}],17:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise,
apiRejection,
INTERNAL,
tryConvertToPromise) {
var errors = _dereq_("./errors.js");
var TypeError = errors.TypeError;
var util = _dereq_("./util.js");
var errorObj = util.errorObj;
var tryCatch = util.tryCatch;
var yieldHandlers = [];
function promiseFromYieldHandler(value, yieldHandlers, traceParent) {
for (var i = 0; i < yieldHandlers.length; ++i) {
traceParent._pushContext();
var result = tryCatch(yieldHandlers[i])(value);
traceParent._popContext();
if (result === errorObj) {
traceParent._pushContext();
var ret = Promise.reject(errorObj.e);
traceParent._popContext();
return ret;
}
var maybePromise = tryConvertToPromise(result, traceParent);
if (maybePromise instanceof Promise) return maybePromise;
}
return null;
}
function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) {
var promise = this._promise = new Promise(INTERNAL);
promise._captureStackTrace();
this._stack = stack;
this._generatorFunction = generatorFunction;
this._receiver = receiver;
this._generator = undefined;
this._yieldHandlers = typeof yieldHandler === "function"
? [yieldHandler].concat(yieldHandlers)
: yieldHandlers;
}
PromiseSpawn.prototype.promise = function () {
return this._promise;
};
PromiseSpawn.prototype._run = function () {
this._generator = this._generatorFunction.call(this._receiver);
this._receiver =
this._generatorFunction = undefined;
this._next(undefined);
};
PromiseSpawn.prototype._continue = function (result) {
if (result === errorObj) {
return this._promise._rejectCallback(result.e, false, true);
}
var value = result.value;
if (result.done === true) {
this._promise._resolveCallback(value);
} else {
var maybePromise = tryConvertToPromise(value, this._promise);
if (!(maybePromise instanceof Promise)) {
maybePromise =
promiseFromYieldHandler(maybePromise,
this._yieldHandlers,
this._promise);
if (maybePromise === null) {
this._throw(
new TypeError(
"A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/4Y4pDk\u000a\u000a".replace("%s", value) +
"From coroutine:\u000a" +
this._stack.split("\n").slice(1, -7).join("\n")
)
);
return;
}
}
maybePromise._then(
this._next,
this._throw,
undefined,
this,
null
);
}
};
PromiseSpawn.prototype._throw = function (reason) {
this._promise._attachExtraTrace(reason);
this._promise._pushContext();
var result = tryCatch(this._generator["throw"])
.call(this._generator, reason);
this._promise._popContext();
this._continue(result);
};
PromiseSpawn.prototype._next = function (value) {
this._promise._pushContext();
var result = tryCatch(this._generator.next).call(this._generator, value);
this._promise._popContext();
this._continue(result);
};
Promise.coroutine = function (generatorFunction, options) {
if (typeof generatorFunction !== "function") {
throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/6Vqhm0\u000a");
}
var yieldHandler = Object(options).yieldHandler;
var PromiseSpawn$ = PromiseSpawn;
var stack = new Error().stack;
return function () {
var generator = generatorFunction.apply(this, arguments);
var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler,
stack);
spawn._generator = generator;
spawn._next(undefined);
return spawn.promise();
};
};
Promise.coroutine.addYieldHandler = function(fn) {
if (typeof fn !== "function") throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
yieldHandlers.push(fn);
};
Promise.spawn = function (generatorFunction) {
if (typeof generatorFunction !== "function") {
return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/6Vqhm0\u000a");
}
var spawn = new PromiseSpawn(generatorFunction, this);
var ret = spawn.promise();
spawn._run(Promise.spawn);
return ret;
};
};
},{"./errors.js":13,"./util.js":38}],18:[function(_dereq_,module,exports){
"use strict";
module.exports =
function(Promise, PromiseArray, tryConvertToPromise, INTERNAL) {
var util = _dereq_("./util.js");
var canEvaluate = util.canEvaluate;
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
var reject;
if (!true) {
if (canEvaluate) {
var thenCallback = function(i) {
return new Function("value", "holder", " \n\
'use strict'; \n\
holder.pIndex = value; \n\
holder.checkFulfillment(this); \n\
".replace(/Index/g, i));
};
var caller = function(count) {
var values = [];
for (var i = 1; i <= count; ++i) values.push("holder.p" + i);
return new Function("holder", " \n\
'use strict'; \n\
var callback = holder.fn; \n\
return callback(values); \n\
".replace(/values/g, values.join(", ")));
};
var thenCallbacks = [];
var callers = [undefined];
for (var i = 1; i <= 5; ++i) {
thenCallbacks.push(thenCallback(i));
callers.push(caller(i));
}
var Holder = function(total, fn) {
this.p1 = this.p2 = this.p3 = this.p4 = this.p5 = null;
this.fn = fn;
this.total = total;
this.now = 0;
};
Holder.prototype.callers = callers;
Holder.prototype.checkFulfillment = function(promise) {
var now = this.now;
now++;
var total = this.total;
if (now >= total) {
var handler = this.callers[total];
promise._pushContext();
var ret = tryCatch(handler)(this);
promise._popContext();
if (ret === errorObj) {
promise._rejectCallback(ret.e, false, true);
} else {
promise._resolveCallback(ret);
}
} else {
this.now = now;
}
};
var reject = function (reason) {
this._reject(reason);
};
}
}
Promise.join = function () {
var last = arguments.length - 1;
var fn;
if (last > 0 && typeof arguments[last] === "function") {
fn = arguments[last];
if (!true) {
if (last < 6 && canEvaluate) {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
var holder = new Holder(last, fn);
var callbacks = thenCallbacks;
for (var i = 0; i < last; ++i) {
var maybePromise = tryConvertToPromise(arguments[i], ret);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
if (maybePromise._isPending()) {
maybePromise._then(callbacks[i], reject,
undefined, ret, holder);
} else if (maybePromise._isFulfilled()) {
callbacks[i].call(ret,
maybePromise._value(), holder);
} else {
ret._reject(maybePromise._reason());
}
} else {
callbacks[i].call(ret, maybePromise, holder);
}
}
return ret;
}
}
}
var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];}
if (fn) args.pop();
var ret = new PromiseArray(args).promise();
return fn !== undefined ? ret.spread(fn) : ret;
};
};
},{"./util.js":38}],19:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise,
PromiseArray,
apiRejection,
tryConvertToPromise,
INTERNAL) {
var async = _dereq_("./async.js");
var util = _dereq_("./util.js");
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
var PENDING = {};
var EMPTY_ARRAY = [];
function MappingPromiseArray(promises, fn, limit, _filter) {
this.constructor$(promises);
this._promise._captureStackTrace();
this._callback = fn;
this._preservedValues = _filter === INTERNAL
? new Array(this.length())
: null;
this._limit = limit;
this._inFlight = 0;
this._queue = limit >= 1 ? [] : EMPTY_ARRAY;
async.invoke(init, this, undefined);
}
util.inherits(MappingPromiseArray, PromiseArray);
function init() {this._init$(undefined, -2);}
MappingPromiseArray.prototype._init = function () {};
MappingPromiseArray.prototype._promiseFulfilled = function (value, index) {
var values = this._values;
var length = this.length();
var preservedValues = this._preservedValues;
var limit = this._limit;
if (values[index] === PENDING) {
values[index] = value;
if (limit >= 1) {
this._inFlight--;
this._drainQueue();
if (this._isResolved()) return;
}
} else {
if (limit >= 1 && this._inFlight >= limit) {
values[index] = value;
this._queue.push(index);
return;
}
if (preservedValues !== null) preservedValues[index] = value;
var callback = this._callback;
var receiver = this._promise._boundTo;
this._promise._pushContext();
var ret = tryCatch(callback).call(receiver, value, index, length);
this._promise._popContext();
if (ret === errorObj) return this._reject(ret.e);
var maybePromise = tryConvertToPromise(ret, this._promise);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
if (maybePromise._isPending()) {
if (limit >= 1) this._inFlight++;
values[index] = PENDING;
return maybePromise._proxyPromiseArray(this, index);
} else if (maybePromise._isFulfilled()) {
ret = maybePromise._value();
} else {
return this._reject(maybePromise._reason());
}
}
values[index] = ret;
}
var totalResolved = ++this._totalResolved;
if (totalResolved >= length) {
if (preservedValues !== null) {
this._filter(values, preservedValues);
} else {
this._resolve(values);
}
}
};
MappingPromiseArray.prototype._drainQueue = function () {
var queue = this._queue;
var limit = this._limit;
var values = this._values;
while (queue.length > 0 && this._inFlight < limit) {
if (this._isResolved()) return;
var index = queue.pop();
this._promiseFulfilled(values[index], index);
}
};
MappingPromiseArray.prototype._filter = function (booleans, values) {
var len = values.length;
var ret = new Array(len);
var j = 0;
for (var i = 0; i < len; ++i) {
if (booleans[i]) ret[j++] = values[i];
}
ret.length = j;
this._resolve(ret);
};
MappingPromiseArray.prototype.preservedValues = function () {
return this._preservedValues;
};
function map(promises, fn, options, _filter) {
var limit = typeof options === "object" && options !== null
? options.concurrency
: 0;
limit = typeof limit === "number" &&
isFinite(limit) && limit >= 1 ? limit : 0;
return new MappingPromiseArray(promises, fn, limit, _filter);
}
Promise.prototype.map = function (fn, options) {
if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
return map(this, fn, options, null).promise();
};
Promise.map = function (promises, fn, options, _filter) {
if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
return map(promises, fn, options, _filter).promise();
};
};
},{"./async.js":2,"./util.js":38}],20:[function(_dereq_,module,exports){
"use strict";
module.exports =
function(Promise, INTERNAL, tryConvertToPromise, apiRejection) {
var util = _dereq_("./util.js");
var tryCatch = util.tryCatch;
Promise.method = function (fn) {
if (typeof fn !== "function") {
throw new Promise.TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
}
return function () {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._pushContext();
var value = tryCatch(fn).apply(this, arguments);
ret._popContext();
ret._resolveFromSyncValue(value);
return ret;
};
};
Promise.attempt = Promise["try"] = function (fn, args, ctx) {
if (typeof fn !== "function") {
return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
}
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._pushContext();
var value = util.isArray(args)
? tryCatch(fn).apply(ctx, args)
: tryCatch(fn).call(ctx, args);
ret._popContext();
ret._resolveFromSyncValue(value);
return ret;
};
Promise.prototype._resolveFromSyncValue = function (value) {
if (value === util.errorObj) {
this._rejectCallback(value.e, false, true);
} else {
this._resolveCallback(value, true);
}
};
};
},{"./util.js":38}],21:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise) {
var util = _dereq_("./util.js");
var async = _dereq_("./async.js");
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
function spreadAdapter(val, nodeback) {
var promise = this;
if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback);
var ret = tryCatch(nodeback).apply(promise._boundTo, [null].concat(val));
if (ret === errorObj) {
async.throwLater(ret.e);
}
}
function successAdapter(val, nodeback) {
var promise = this;
var receiver = promise._boundTo;
var ret = val === undefined
? tryCatch(nodeback).call(receiver, null)
: tryCatch(nodeback).call(receiver, null, val);
if (ret === errorObj) {
async.throwLater(ret.e);
}
}
function errorAdapter(reason, nodeback) {
var promise = this;
if (!reason) {
var target = promise._target();
var newReason = target._getCarriedStackTrace();
newReason.cause = reason;
reason = newReason;
}
var ret = tryCatch(nodeback).call(promise._boundTo, reason);
if (ret === errorObj) {
async.throwLater(ret.e);
}
}
Promise.prototype.asCallback =
Promise.prototype.nodeify = function (nodeback, options) {
if (typeof nodeback == "function") {
var adapter = successAdapter;
if (options !== undefined && Object(options).spread) {
adapter = spreadAdapter;
}
this._then(
adapter,
errorAdapter,
undefined,
this,
nodeback
);
}
return this;
};
};
},{"./async.js":2,"./util.js":38}],22:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, PromiseArray) {
var util = _dereq_("./util.js");
var async = _dereq_("./async.js");
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
Promise.prototype.progressed = function (handler) {
return this._then(undefined, undefined, handler, undefined, undefined);
};
Promise.prototype._progress = function (progressValue) {
if (this._isFollowingOrFulfilledOrRejected()) return;
this._target()._progressUnchecked(progressValue);
};
Promise.prototype._progressHandlerAt = function (index) {
return index === 0
? this._progressHandler0
: this[(index << 2) + index - 5 + 2];
};
Promise.prototype._doProgressWith = function (progression) {
var progressValue = progression.value;
var handler = progression.handler;
var promise = progression.promise;
var receiver = progression.receiver;
var ret = tryCatch(handler).call(receiver, progressValue);
if (ret === errorObj) {
if (ret.e != null &&
ret.e.name !== "StopProgressPropagation") {
var trace = util.canAttachTrace(ret.e)
? ret.e : new Error(util.toString(ret.e));
promise._attachExtraTrace(trace);
promise._progress(ret.e);
}
} else if (ret instanceof Promise) {
ret._then(promise._progress, null, null, promise, undefined);
} else {
promise._progress(ret);
}
};
Promise.prototype._progressUnchecked = function (progressValue) {
var len = this._length();
var progress = this._progress;
for (var i = 0; i < len; i++) {
var handler = this._progressHandlerAt(i);
var promise = this._promiseAt(i);
if (!(promise instanceof Promise)) {
var receiver = this._receiverAt(i);
if (typeof handler === "function") {
handler.call(receiver, progressValue, promise);
} else if (receiver instanceof PromiseArray &&
!receiver._isResolved()) {
receiver._promiseProgressed(progressValue, promise);
}
continue;
}
if (typeof handler === "function") {
async.invoke(this._doProgressWith, this, {
handler: handler,
promise: promise,
receiver: this._receiverAt(i),
value: progressValue
});
} else {
async.invoke(progress, promise, progressValue);
}
}
};
};
},{"./async.js":2,"./util.js":38}],23:[function(_dereq_,module,exports){
"use strict";
module.exports = function() {
var makeSelfResolutionError = function () {
return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/LhFpo0\u000a");
};
var reflect = function() {
return new Promise.PromiseInspection(this._target());
};
var apiRejection = function(msg) {
return Promise.reject(new TypeError(msg));
};
var util = _dereq_("./util.js");
var async = _dereq_("./async.js");
var errors = _dereq_("./errors.js");
var TypeError = Promise.TypeError = errors.TypeError;
Promise.RangeError = errors.RangeError;
Promise.CancellationError = errors.CancellationError;
Promise.TimeoutError = errors.TimeoutError;
Promise.OperationalError = errors.OperationalError;
Promise.RejectionError = errors.OperationalError;
Promise.AggregateError = errors.AggregateError;
var INTERNAL = function(){};
var APPLY = {};
var NEXT_FILTER = {e: null};
var tryConvertToPromise = _dereq_("./thenables.js")(Promise, INTERNAL);
var PromiseArray =
_dereq_("./promise_array.js")(Promise, INTERNAL,
tryConvertToPromise, apiRejection);
var CapturedTrace = _dereq_("./captured_trace.js")();
var isDebugging = _dereq_("./debuggability.js")(Promise, CapturedTrace);
/*jshint unused:false*/
var createContext =
_dereq_("./context.js")(Promise, CapturedTrace, isDebugging);
var CatchFilter = _dereq_("./catch_filter.js")(NEXT_FILTER);
var PromiseResolver = _dereq_("./promise_resolver.js");
var nodebackForPromise = PromiseResolver._nodebackForPromise;
var errorObj = util.errorObj;
var tryCatch = util.tryCatch;
function Promise(resolver) {
if (typeof resolver !== "function") {
throw new TypeError("the promise constructor requires a resolver function\u000a\u000a See http://goo.gl/EC22Yn\u000a");
}
if (this.constructor !== Promise) {
throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/KsIlge\u000a");
}
this._bitField = 0;
this._fulfillmentHandler0 = undefined;
this._rejectionHandler0 = undefined;
this._progressHandler0 = undefined;
this._promise0 = undefined;
this._receiver0 = undefined;
this._settledValue = undefined;
if (resolver !== INTERNAL) this._resolveFromResolver(resolver);
}
Promise.prototype.toString = function () {
return "[object Promise]";
};
Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
var len = arguments.length;
if (len > 1) {
var catchInstances = new Array(len - 1),
j = 0, i;
for (i = 0; i < len - 1; ++i) {
var item = arguments[i];
if (typeof item === "function") {
catchInstances[j++] = item;
} else {
return Promise.reject(
new TypeError("Catch filter must inherit from Error or be a simple predicate function\u000a\u000a See http://goo.gl/o84o68\u000a"));
}
}
catchInstances.length = j;
fn = arguments[i];
var catchFilter = new CatchFilter(catchInstances, fn, this);
return this._then(undefined, catchFilter.doFilter, undefined,
catchFilter, undefined);
}
return this._then(undefined, fn, undefined, undefined, undefined);
};
Promise.prototype.reflect = function () {
return this._then(reflect, reflect, undefined, this, undefined);
};
Promise.prototype.then = function (didFulfill, didReject, didProgress) {
if (isDebugging() && arguments.length > 0 &&
typeof didFulfill !== "function" &&
typeof didReject !== "function") {
var msg = ".then() only accepts functions but was passed: " +
util.classString(didFulfill);
if (arguments.length > 1) {
msg += ", " + util.classString(didReject);
}
this._warn(msg);
}
return this._then(didFulfill, didReject, didProgress,
undefined, undefined);
};
Promise.prototype.done = function (didFulfill, didReject, didProgress) {
var promise = this._then(didFulfill, didReject, didProgress,
undefined, undefined);
promise._setIsFinal();
};
Promise.prototype.spread = function (didFulfill, didReject) {
return this.all()._then(didFulfill, didReject, undefined, APPLY, undefined);
};
Promise.prototype.isCancellable = function () {
return !this.isResolved() &&
this._cancellable();
};
Promise.prototype.toJSON = function () {
var ret = {
isFulfilled: false,
isRejected: false,
fulfillmentValue: undefined,
rejectionReason: undefined
};
if (this.isFulfilled()) {
ret.fulfillmentValue = this.value();
ret.isFulfilled = true;
} else if (this.isRejected()) {
ret.rejectionReason = this.reason();
ret.isRejected = true;
}
return ret;
};
Promise.prototype.all = function () {
return new PromiseArray(this).promise();
};
Promise.prototype.error = function (fn) {
return this.caught(util.originatesFromRejection, fn);
};
Promise.is = function (val) {
return val instanceof Promise;
};
Promise.fromNode = function(fn) {
var ret = new Promise(INTERNAL);
var result = tryCatch(fn)(nodebackForPromise(ret));
if (result === errorObj) {
ret._rejectCallback(result.e, true, true);
}
return ret;
};
Promise.all = function (promises) {
return new PromiseArray(promises).promise();
};
Promise.defer = Promise.pending = function () {
var promise = new Promise(INTERNAL);
return new PromiseResolver(promise);
};
Promise.cast = function (obj) {
var ret = tryConvertToPromise(obj);
if (!(ret instanceof Promise)) {
var val = ret;
ret = new Promise(INTERNAL);
ret._fulfillUnchecked(val);
}
return ret;
};
Promise.resolve = Promise.fulfilled = Promise.cast;
Promise.reject = Promise.rejected = function (reason) {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._rejectCallback(reason, true);
return ret;
};
Promise.setScheduler = function(fn) {
if (typeof fn !== "function") throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
var prev = async._schedule;
async._schedule = fn;
return prev;
};
Promise.prototype._then = function (
didFulfill,
didReject,
didProgress,
receiver,
internalData
) {
var haveInternalData = internalData !== undefined;
var ret = haveInternalData ? internalData : new Promise(INTERNAL);
if (!haveInternalData) {
ret._propagateFrom(this, 4 | 1);
ret._captureStackTrace();
}
var target = this._target();
if (target !== this) {
if (receiver === undefined) receiver = this._boundTo;
if (!haveInternalData) ret._setIsMigrated();
}
var callbackIndex =
target._addCallbacks(didFulfill, didReject, didProgress, ret, receiver);
if (target._isResolved() && !target._isSettlePromisesQueued()) {
async.invoke(
target._settlePromiseAtPostResolution, target, callbackIndex);
}
return ret;
};
Promise.prototype._settlePromiseAtPostResolution = function (index) {
if (this._isRejectionUnhandled()) this._unsetRejectionIsUnhandled();
this._settlePromiseAt(index);
};
Promise.prototype._length = function () {
return this._bitField & 131071;
};
Promise.prototype._isFollowingOrFulfilledOrRejected = function () {
return (this._bitField & 939524096) > 0;
};
Promise.prototype._isFollowing = function () {
return (this._bitField & 536870912) === 536870912;
};
Promise.prototype._setLength = function (len) {
this._bitField = (this._bitField & -131072) |
(len & 131071);
};
Promise.prototype._setFulfilled = function () {
this._bitField = this._bitField | 268435456;
};
Promise.prototype._setRejected = function () {
this._bitField = this._bitField | 134217728;
};
Promise.prototype._setFollowing = function () {
this._bitField = this._bitField | 536870912;
};
Promise.prototype._setIsFinal = function () {
this._bitField = this._bitField | 33554432;
};
Promise.prototype._isFinal = function () {
return (this._bitField & 33554432) > 0;
};
Promise.prototype._cancellable = function () {
return (this._bitField & 67108864) > 0;
};
Promise.prototype._setCancellable = function () {
this._bitField = this._bitField | 67108864;
};
Promise.prototype._unsetCancellable = function () {
this._bitField = this._bitField & (~67108864);
};
Promise.prototype._setIsMigrated = function () {
this._bitField = this._bitField | 4194304;
};
Promise.prototype._unsetIsMigrated = function () {
this._bitField = this._bitField & (~4194304);
};
Promise.prototype._isMigrated = function () {
return (this._bitField & 4194304) > 0;
};
Promise.prototype._receiverAt = function (index) {
var ret = index === 0
? this._receiver0
: this[
index * 5 - 5 + 4];
if (ret === undefined && this._isBound()) {
return this._boundTo;
}
return ret;
};
Promise.prototype._promiseAt = function (index) {
return index === 0
? this._promise0
: this[index * 5 - 5 + 3];
};
Promise.prototype._fulfillmentHandlerAt = function (index) {
return index === 0
? this._fulfillmentHandler0
: this[index * 5 - 5 + 0];
};
Promise.prototype._rejectionHandlerAt = function (index) {
return index === 0
? this._rejectionHandler0
: this[index * 5 - 5 + 1];
};
Promise.prototype._migrateCallbacks = function (follower, index) {
var fulfill = follower._fulfillmentHandlerAt(index);
var reject = follower._rejectionHandlerAt(index);
var progress = follower._progressHandlerAt(index);
var promise = follower._promiseAt(index);
var receiver = follower._receiverAt(index);
if (promise instanceof Promise) promise._setIsMigrated();
this._addCallbacks(fulfill, reject, progress, promise, receiver);
};
Promise.prototype._addCallbacks = function (
fulfill,
reject,
progress,
promise,
receiver
) {
var index = this._length();
if (index >= 131071 - 5) {
index = 0;
this._setLength(0);
}
if (index === 0) {
this._promise0 = promise;
if (receiver !== undefined) this._receiver0 = receiver;
if (typeof fulfill === "function" && !this._isCarryingStackTrace())
this._fulfillmentHandler0 = fulfill;
if (typeof reject === "function") this._rejectionHandler0 = reject;
if (typeof progress === "function") this._progressHandler0 = progress;
} else {
var base = index * 5 - 5;
this[base + 3] = promise;
this[base + 4] = receiver;
if (typeof fulfill === "function")
this[base + 0] = fulfill;
if (typeof reject === "function")
this[base + 1] = reject;
if (typeof progress === "function")
this[base + 2] = progress;
}
this._setLength(index + 1);
return index;
};
Promise.prototype._setProxyHandlers = function (receiver, promiseSlotValue) {
var index = this._length();
if (index >= 131071 - 5) {
index = 0;
this._setLength(0);
}
if (index === 0) {
this._promise0 = promiseSlotValue;
this._receiver0 = receiver;
} else {
var base = index * 5 - 5;
this[base + 3] = promiseSlotValue;
this[base + 4] = receiver;
}
this._setLength(index + 1);
};
Promise.prototype._proxyPromiseArray = function (promiseArray, index) {
this._setProxyHandlers(promiseArray, index);
};
Promise.prototype._resolveCallback = function(value, shouldBind) {
if (this._isFollowingOrFulfilledOrRejected()) return;
if (value === this)
return this._rejectCallback(makeSelfResolutionError(), false, true);
var maybePromise = tryConvertToPromise(value, this);
if (!(maybePromise instanceof Promise)) return this._fulfill(value);
var propagationFlags = 1 | (shouldBind ? 4 : 0);
this._propagateFrom(maybePromise, propagationFlags);
var promise = maybePromise._target();
if (promise._isPending()) {
var len = this._length();
for (var i = 0; i < len; ++i) {
promise._migrateCallbacks(this, i);
}
this._setFollowing();
this._setLength(0);
this._setFollowee(promise);
} else if (promise._isFulfilled()) {
this._fulfillUnchecked(promise._value());
} else {
this._rejectUnchecked(promise._reason(),
promise._getCarriedStackTrace());
}
};
Promise.prototype._rejectCallback =
function(reason, synchronous, shouldNotMarkOriginatingFromRejection) {
if (!shouldNotMarkOriginatingFromRejection) {
util.markAsOriginatingFromRejection(reason);
}
var trace = util.ensureErrorObject(reason);
var hasStack = trace === reason;
this._attachExtraTrace(trace, synchronous ? hasStack : false);
this._reject(reason, hasStack ? undefined : trace);
};
Promise.prototype._resolveFromResolver = function (resolver) {
var promise = this;
this._captureStackTrace();
this._pushContext();
var synchronous = true;
var r = tryCatch(resolver)(function(value) {
if (promise === null) return;
promise._resolveCallback(value);
promise = null;
}, function (reason) {
if (promise === null) return;
promise._rejectCallback(reason, synchronous);
promise = null;
});
synchronous = false;
this._popContext();
if (r !== undefined && r === errorObj && promise !== null) {
promise._rejectCallback(r.e, true, true);
promise = null;
}
};
Promise.prototype._settlePromiseFromHandler = function (
handler, receiver, value, promise
) {
if (promise._isRejected()) return;
promise._pushContext();
var x;
if (receiver === APPLY && !this._isRejected()) {
x = tryCatch(handler).apply(this._boundTo, value);
} else {
x = tryCatch(handler).call(receiver, value);
}
promise._popContext();
if (x === errorObj || x === promise || x === NEXT_FILTER) {
var err = x === promise ? makeSelfResolutionError() : x.e;
promise._rejectCallback(err, false, true);
} else {
promise._resolveCallback(x);
}
};
Promise.prototype._target = function() {
var ret = this;
while (ret._isFollowing()) ret = ret._followee();
return ret;
};
Promise.prototype._followee = function() {
return this._rejectionHandler0;
};
Promise.prototype._setFollowee = function(promise) {
this._rejectionHandler0 = promise;
};
Promise.prototype._cleanValues = function () {
if (this._cancellable()) {
this._cancellationParent = undefined;
}
};
Promise.prototype._propagateFrom = function (parent, flags) {
if ((flags & 1) > 0 && parent._cancellable()) {
this._setCancellable();
this._cancellationParent = parent;
}
if ((flags & 4) > 0 && parent._isBound()) {
this._setBoundTo(parent._boundTo);
}
};
Promise.prototype._fulfill = function (value) {
if (this._isFollowingOrFulfilledOrRejected()) return;
this._fulfillUnchecked(value);
};
Promise.prototype._reject = function (reason, carriedStackTrace) {
if (this._isFollowingOrFulfilledOrRejected()) return;
this._rejectUnchecked(reason, carriedStackTrace);
};
Promise.prototype._settlePromiseAt = function (index) {
var promise = this._promiseAt(index);
var isPromise = promise instanceof Promise;
if (isPromise && promise._isMigrated()) {
promise._unsetIsMigrated();
return async.invoke(this._settlePromiseAt, this, index);
}
var handler = this._isFulfilled()
? this._fulfillmentHandlerAt(index)
: this._rejectionHandlerAt(index);
var carriedStackTrace =
this._isCarryingStackTrace() ? this._getCarriedStackTrace() : undefined;
var value = this._settledValue;
var receiver = this._receiverAt(index);
this._clearCallbackDataAtIndex(index);
if (typeof handler === "function") {
if (!isPromise) {
handler.call(receiver, value, promise);
} else {
this._settlePromiseFromHandler(handler, receiver, value, promise);
}
} else if (receiver instanceof PromiseArray) {
if (!receiver._isResolved()) {
if (this._isFulfilled()) {
receiver._promiseFulfilled(value, promise);
}
else {
receiver._promiseRejected(value, promise);
}
}
} else if (isPromise) {
if (this._isFulfilled()) {
promise._fulfill(value);
} else {
promise._reject(value, carriedStackTrace);
}
}
if (index >= 4 && (index & 31) === 4)
async.invokeLater(this._setLength, this, 0);
};
Promise.prototype._clearCallbackDataAtIndex = function(index) {
if (index === 0) {
if (!this._isCarryingStackTrace()) {
this._fulfillmentHandler0 = undefined;
}
this._rejectionHandler0 =
this._progressHandler0 =
this._receiver0 =
this._promise0 = undefined;
} else {
var base = index * 5 - 5;
this[base + 3] =
this[base + 4] =
this[base + 0] =
this[base + 1] =
this[base + 2] = undefined;
}
};
Promise.prototype._isSettlePromisesQueued = function () {
return (this._bitField &
-1073741824) === -1073741824;
};
Promise.prototype._setSettlePromisesQueued = function () {
this._bitField = this._bitField | -1073741824;
};
Promise.prototype._unsetSettlePromisesQueued = function () {
this._bitField = this._bitField & (~-1073741824);
};
Promise.prototype._queueSettlePromises = function() {
async.settlePromises(this);
this._setSettlePromisesQueued();
};
Promise.prototype._fulfillUnchecked = function (value) {
if (value === this) {
var err = makeSelfResolutionError();
this._attachExtraTrace(err);
return this._rejectUnchecked(err, undefined);
}
this._setFulfilled();
this._settledValue = value;
this._cleanValues();
if (this._length() > 0) {
this._queueSettlePromises();
}
};
Promise.prototype._rejectUncheckedCheckError = function (reason) {
var trace = util.ensureErrorObject(reason);
this._rejectUnchecked(reason, trace === reason ? undefined : trace);
};
Promise.prototype._rejectUnchecked = function (reason, trace) {
if (reason === this) {
var err = makeSelfResolutionError();
this._attachExtraTrace(err);
return this._rejectUnchecked(err);
}
this._setRejected();
this._settledValue = reason;
this._cleanValues();
if (this._isFinal()) {
async.throwLater(function(e) {
if ("stack" in e) {
async.invokeFirst(
CapturedTrace.unhandledRejection, undefined, e);
}
throw e;
}, trace === undefined ? reason : trace);
return;
}
if (trace !== undefined && trace !== reason) {
this._setCarriedStackTrace(trace);
}
if (this._length() > 0) {
this._queueSettlePromises();
} else {
this._ensurePossibleRejectionHandled();
}
};
Promise.prototype._settlePromises = function () {
this._unsetSettlePromisesQueued();
var len = this._length();
for (var i = 0; i < len; i++) {
this._settlePromiseAt(i);
}
};
Promise._makeSelfResolutionError = makeSelfResolutionError;
_dereq_("./progress.js")(Promise, PromiseArray);
_dereq_("./method.js")(Promise, INTERNAL, tryConvertToPromise, apiRejection);
_dereq_("./bind.js")(Promise, INTERNAL, tryConvertToPromise);
_dereq_("./finally.js")(Promise, NEXT_FILTER, tryConvertToPromise);
_dereq_("./direct_resolve.js")(Promise);
_dereq_("./synchronous_inspection.js")(Promise);
_dereq_("./join.js")(Promise, PromiseArray, tryConvertToPromise, INTERNAL);
Promise.Promise = Promise;
_dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL);
_dereq_('./cancel.js')(Promise);
_dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext);
_dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise);
_dereq_('./nodeify.js')(Promise);
_dereq_('./call_get.js')(Promise);
_dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection);
_dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection);
_dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL);
_dereq_('./settle.js')(Promise, PromiseArray);
_dereq_('./some.js')(Promise, PromiseArray, apiRejection);
_dereq_('./promisify.js')(Promise, INTERNAL);
_dereq_('./any.js')(Promise);
_dereq_('./each.js')(Promise, INTERNAL);
_dereq_('./timers.js')(Promise, INTERNAL);
_dereq_('./filter.js')(Promise, INTERNAL);
util.toFastProperties(Promise);
util.toFastProperties(Promise.prototype);
function fillTypes(value) {
var p = new Promise(INTERNAL);
p._fulfillmentHandler0 = value;
p._rejectionHandler0 = value;
p._progressHandler0 = value;
p._promise0 = value;
p._receiver0 = value;
p._settledValue = value;
}
// Complete slack tracking, opt out of field-type tracking and
// stabilize map
fillTypes({a: 1});
fillTypes({b: 2});
fillTypes({c: 3});
fillTypes(1);
fillTypes(function(){});
fillTypes(undefined);
fillTypes(false);
fillTypes(new Promise(INTERNAL));
CapturedTrace.setBounds(async.firstLineError, util.lastLineError);
return Promise;
};
},{"./any.js":1,"./async.js":2,"./bind.js":3,"./call_get.js":5,"./cancel.js":6,"./captured_trace.js":7,"./catch_filter.js":8,"./context.js":9,"./debuggability.js":10,"./direct_resolve.js":11,"./each.js":12,"./errors.js":13,"./filter.js":15,"./finally.js":16,"./generators.js":17,"./join.js":18,"./map.js":19,"./method.js":20,"./nodeify.js":21,"./progress.js":22,"./promise_array.js":24,"./promise_resolver.js":25,"./promisify.js":26,"./props.js":27,"./race.js":29,"./reduce.js":30,"./settle.js":32,"./some.js":33,"./synchronous_inspection.js":34,"./thenables.js":35,"./timers.js":36,"./using.js":37,"./util.js":38}],24:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, INTERNAL, tryConvertToPromise,
apiRejection) {
var util = _dereq_("./util.js");
var isArray = util.isArray;
function toResolutionValue(val) {
switch(val) {
case -2: return [];
case -3: return {};
}
}
function PromiseArray(values) {
var promise = this._promise = new Promise(INTERNAL);
var parent;
if (values instanceof Promise) {
parent = values;
promise._propagateFrom(parent, 1 | 4);
}
this._values = values;
this._length = 0;
this._totalResolved = 0;
this._init(undefined, -2);
}
PromiseArray.prototype.length = function () {
return this._length;
};
PromiseArray.prototype.promise = function () {
return this._promise;
};
PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) {
var values = tryConvertToPromise(this._values, this._promise);
if (values instanceof Promise) {
values = values._target();
this._values = values;
if (values._isFulfilled()) {
values = values._value();
if (!isArray(values)) {
var err = new Promise.TypeError("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a");
this.__hardReject__(err);
return;
}
} else if (values._isPending()) {
values._then(
init,
this._reject,
undefined,
this,
resolveValueIfEmpty
);
return;
} else {
this._reject(values._reason());
return;
}
} else if (!isArray(values)) {
this._promise._reject(apiRejection("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a")._reason());
return;
}
if (values.length === 0) {
if (resolveValueIfEmpty === -5) {
this._resolveEmptyArray();
}
else {
this._resolve(toResolutionValue(resolveValueIfEmpty));
}
return;
}
var len = this.getActualLength(values.length);
this._length = len;
this._values = this.shouldCopyValues() ? new Array(len) : this._values;
var promise = this._promise;
for (var i = 0; i < len; ++i) {
var isResolved = this._isResolved();
var maybePromise = tryConvertToPromise(values[i], promise);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
if (isResolved) {
maybePromise._unsetRejectionIsUnhandled();
} else if (maybePromise._isPending()) {
maybePromise._proxyPromiseArray(this, i);
} else if (maybePromise._isFulfilled()) {
this._promiseFulfilled(maybePromise._value(), i);
} else {
this._promiseRejected(maybePromise._reason(), i);
}
} else if (!isResolved) {
this._promiseFulfilled(maybePromise, i);
}
}
};
PromiseArray.prototype._isResolved = function () {
return this._values === null;
};
PromiseArray.prototype._resolve = function (value) {
this._values = null;
this._promise._fulfill(value);
};
PromiseArray.prototype.__hardReject__ =
PromiseArray.prototype._reject = function (reason) {
this._values = null;
this._promise._rejectCallback(reason, false, true);
};
PromiseArray.prototype._promiseProgressed = function (progressValue, index) {
this._promise._progress({
index: index,
value: progressValue
});
};
PromiseArray.prototype._promiseFulfilled = function (value, index) {
this._values[index] = value;
var totalResolved = ++this._totalResolved;
if (totalResolved >= this._length) {
this._resolve(this._values);
}
};
PromiseArray.prototype._promiseRejected = function (reason, index) {
this._totalResolved++;
this._reject(reason);
};
PromiseArray.prototype.shouldCopyValues = function () {
return true;
};
PromiseArray.prototype.getActualLength = function (len) {
return len;
};
return PromiseArray;
};
},{"./util.js":38}],25:[function(_dereq_,module,exports){
"use strict";
var util = _dereq_("./util.js");
var maybeWrapAsError = util.maybeWrapAsError;
var errors = _dereq_("./errors.js");
var TimeoutError = errors.TimeoutError;
var OperationalError = errors.OperationalError;
var haveGetters = util.haveGetters;
var es5 = _dereq_("./es5.js");
function isUntypedError(obj) {
return obj instanceof Error &&
es5.getPrototypeOf(obj) === Error.prototype;
}
var rErrorKey = /^(?:name|message|stack|cause)$/;
function wrapAsOperationalError(obj) {
var ret;
if (isUntypedError(obj)) {
ret = new OperationalError(obj);
ret.name = obj.name;
ret.message = obj.message;
ret.stack = obj.stack;
var keys = es5.keys(obj);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (!rErrorKey.test(key)) {
ret[key] = obj[key];
}
}
return ret;
}
util.markAsOriginatingFromRejection(obj);
return obj;
}
function nodebackForPromise(promise) {
return function(err, value) {
if (promise === null) return;
if (err) {
var wrapped = wrapAsOperationalError(maybeWrapAsError(err));
promise._attachExtraTrace(wrapped);
promise._reject(wrapped);
} else if (arguments.length > 2) {
var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];}
promise._fulfill(args);
} else {
promise._fulfill(value);
}
promise = null;
};
}
var PromiseResolver;
if (!haveGetters) {
PromiseResolver = function (promise) {
this.promise = promise;
this.asCallback = nodebackForPromise(promise);
this.callback = this.asCallback;
};
}
else {
PromiseResolver = function (promise) {
this.promise = promise;
};
}
if (haveGetters) {
var prop = {
get: function() {
return nodebackForPromise(this.promise);
}
};
es5.defineProperty(PromiseResolver.prototype, "asCallback", prop);
es5.defineProperty(PromiseResolver.prototype, "callback", prop);
}
PromiseResolver._nodebackForPromise = nodebackForPromise;
PromiseResolver.prototype.toString = function () {
return "[object PromiseResolver]";
};
PromiseResolver.prototype.resolve =
PromiseResolver.prototype.fulfill = function (value) {
if (!(this instanceof PromiseResolver)) {
throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a");
}
this.promise._resolveCallback(value);
};
PromiseResolver.prototype.reject = function (reason) {
if (!(this instanceof PromiseResolver)) {
throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a");
}
this.promise._rejectCallback(reason);
};
PromiseResolver.prototype.progress = function (value) {
if (!(this instanceof PromiseResolver)) {
throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a");
}
this.promise._progress(value);
};
PromiseResolver.prototype.cancel = function (err) {
this.promise.cancel(err);
};
PromiseResolver.prototype.timeout = function () {
this.reject(new TimeoutError("timeout"));
};
PromiseResolver.prototype.isResolved = function () {
return this.promise.isResolved();
};
PromiseResolver.prototype.toJSON = function () {
return this.promise.toJSON();
};
module.exports = PromiseResolver;
},{"./errors.js":13,"./es5.js":14,"./util.js":38}],26:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, INTERNAL) {
var THIS = {};
var util = _dereq_("./util.js");
var nodebackForPromise = _dereq_("./promise_resolver.js")
._nodebackForPromise;
var withAppended = util.withAppended;
var maybeWrapAsError = util.maybeWrapAsError;
var canEvaluate = util.canEvaluate;
var TypeError = _dereq_("./errors").TypeError;
var defaultSuffix = "Async";
var defaultPromisified = {__isPromisified__: true};
var noCopyPropsPattern =
/^(?:length|name|arguments|caller|prototype|__isPromisified__)$/;
var defaultFilter = function(name, func) {
return util.isIdentifier(name) &&
name.charAt(0) !== "_" &&
!util.isClass(func);
};
function propsFilter(key) {
return !noCopyPropsPattern.test(key);
}
function isPromisified(fn) {
try {
return fn.__isPromisified__ === true;
}
catch (e) {
return false;
}
}
function hasPromisified(obj, key, suffix) {
var val = util.getDataPropertyOrDefault(obj, key + suffix,
defaultPromisified);
return val ? isPromisified(val) : false;
}
function checkValid(ret, suffix, suffixRegexp) {
for (var i = 0; i < ret.length; i += 2) {
var key = ret[i];
if (suffixRegexp.test(key)) {
var keyWithoutAsyncSuffix = key.replace(suffixRegexp, "");
for (var j = 0; j < ret.length; j += 2) {
if (ret[j] === keyWithoutAsyncSuffix) {
throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/iWrZbw\u000a"
.replace("%s", suffix));
}
}
}
}
}
function promisifiableMethods(obj, suffix, suffixRegexp, filter) {
var keys = util.inheritedDataKeys(obj);
var ret = [];
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
var value = obj[key];
var passesDefaultFilter = filter === defaultFilter
? true : defaultFilter(key, value, obj);
if (typeof value === "function" &&
!isPromisified(value) &&
!hasPromisified(obj, key, suffix) &&
filter(key, value, obj, passesDefaultFilter)) {
ret.push(key, value);
}
}
checkValid(ret, suffix, suffixRegexp);
return ret;
}
var escapeIdentRegex = function(str) {
return str.replace(/([$])/, "\\$");
};
var makeNodePromisifiedEval;
if (!true) {
var switchCaseArgumentOrder = function(likelyArgumentCount) {
var ret = [likelyArgumentCount];
var min = Math.max(0, likelyArgumentCount - 1 - 3);
for(var i = likelyArgumentCount - 1; i >= min; --i) {
ret.push(i);
}
for(var i = likelyArgumentCount + 1; i <= 3; ++i) {
ret.push(i);
}
return ret;
};
var argumentSequence = function(argumentCount) {
return util.filledRange(argumentCount, "_arg", "");
};
var parameterDeclaration = function(parameterCount) {
return util.filledRange(
Math.max(parameterCount, 3), "_arg", "");
};
var parameterCount = function(fn) {
if (typeof fn.length === "number") {
return Math.max(Math.min(fn.length, 1023 + 1), 0);
}
return 0;
};
makeNodePromisifiedEval =
function(callback, receiver, originalName, fn) {
var newParameterCount = Math.max(0, parameterCount(fn) - 1);
var argumentOrder = switchCaseArgumentOrder(newParameterCount);
var shouldProxyThis = typeof callback === "string" || receiver === THIS;
function generateCallForArgumentCount(count) {
var args = argumentSequence(count).join(", ");
var comma = count > 0 ? ", " : "";
var ret;
if (shouldProxyThis) {
ret = "ret = callback.call(this, {{args}}, nodeback); break;\n";
} else {
ret = receiver === undefined
? "ret = callback({{args}}, nodeback); break;\n"
: "ret = callback.call(receiver, {{args}}, nodeback); break;\n";
}
return ret.replace("{{args}}", args).replace(", ", comma);
}
function generateArgumentSwitchCase() {
var ret = "";
for (var i = 0; i < argumentOrder.length; ++i) {
ret += "case " + argumentOrder[i] +":" +
generateCallForArgumentCount(argumentOrder[i]);
}
ret += " \n\
default: \n\
var args = new Array(len + 1); \n\
var i = 0; \n\
for (var i = 0; i < len; ++i) { \n\
args[i] = arguments[i]; \n\
} \n\
args[i] = nodeback; \n\
[CodeForCall] \n\
break; \n\
".replace("[CodeForCall]", (shouldProxyThis
? "ret = callback.apply(this, args);\n"
: "ret = callback.apply(receiver, args);\n"));
return ret;
}
var getFunctionCode = typeof callback === "string"
? ("this != null ? this['"+callback+"'] : fn")
: "fn";
return new Function("Promise",
"fn",
"receiver",
"withAppended",
"maybeWrapAsError",
"nodebackForPromise",
"tryCatch",
"errorObj",
"INTERNAL","'use strict'; \n\
var ret = function (Parameters) { \n\
'use strict'; \n\
var len = arguments.length; \n\
var promise = new Promise(INTERNAL); \n\
promise._captureStackTrace(); \n\
var nodeback = nodebackForPromise(promise); \n\
var ret; \n\
var callback = tryCatch([GetFunctionCode]); \n\
switch(len) { \n\
[CodeForSwitchCase] \n\
} \n\
if (ret === errorObj) { \n\
promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\
} \n\
return promise; \n\
}; \n\
ret.__isPromisified__ = true; \n\
return ret; \n\
"
.replace("Parameters", parameterDeclaration(newParameterCount))
.replace("[CodeForSwitchCase]", generateArgumentSwitchCase())
.replace("[GetFunctionCode]", getFunctionCode))(
Promise,
fn,
receiver,
withAppended,
maybeWrapAsError,
nodebackForPromise,
util.tryCatch,
util.errorObj,
INTERNAL
);
};
}
function makeNodePromisifiedClosure(callback, receiver, _, fn) {
var defaultThis = (function() {return this;})();
var method = callback;
if (typeof method === "string") {
callback = fn;
}
function promisified() {
var _receiver = receiver;
if (receiver === THIS) _receiver = this;
var promise = new Promise(INTERNAL);
promise._captureStackTrace();
var cb = typeof method === "string" && this !== defaultThis
? this[method] : callback;
var fn = nodebackForPromise(promise);
try {
cb.apply(_receiver, withAppended(arguments, fn));
} catch(e) {
promise._rejectCallback(maybeWrapAsError(e), true, true);
}
return promise;
}
promisified.__isPromisified__ = true;
return promisified;
}
var makeNodePromisified = canEvaluate
? makeNodePromisifiedEval
: makeNodePromisifiedClosure;
function promisifyAll(obj, suffix, filter, promisifier) {
var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$");
var methods =
promisifiableMethods(obj, suffix, suffixRegexp, filter);
for (var i = 0, len = methods.length; i < len; i+= 2) {
var key = methods[i];
var fn = methods[i+1];
var promisifiedKey = key + suffix;
obj[promisifiedKey] = promisifier === makeNodePromisified
? makeNodePromisified(key, THIS, key, fn, suffix)
: promisifier(fn, function() {
return makeNodePromisified(key, THIS, key, fn, suffix);
});
}
util.toFastProperties(obj);
return obj;
}
function promisify(callback, receiver) {
return makeNodePromisified(callback, receiver, undefined, callback);
}
Promise.promisify = function (fn, receiver) {
if (typeof fn !== "function") {
throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
}
if (isPromisified(fn)) {
return fn;
}
var ret = promisify(fn, arguments.length < 2 ? THIS : receiver);
util.copyDescriptors(fn, ret, propsFilter);
return ret;
};
Promise.promisifyAll = function (target, options) {
if (typeof target !== "function" && typeof target !== "object") {
throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/9ITlV0\u000a");
}
options = Object(options);
var suffix = options.suffix;
if (typeof suffix !== "string") suffix = defaultSuffix;
var filter = options.filter;
if (typeof filter !== "function") filter = defaultFilter;
var promisifier = options.promisifier;
if (typeof promisifier !== "function") promisifier = makeNodePromisified;
if (!util.isIdentifier(suffix)) {
throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/8FZo5V\u000a");
}
var keys = util.inheritedDataKeys(target);
for (var i = 0; i < keys.length; ++i) {
var value = target[keys[i]];
if (keys[i] !== "constructor" &&
util.isClass(value)) {
promisifyAll(value.prototype, suffix, filter, promisifier);
promisifyAll(value, suffix, filter, promisifier);
}
}
return promisifyAll(target, suffix, filter, promisifier);
};
};
},{"./errors":13,"./promise_resolver.js":25,"./util.js":38}],27:[function(_dereq_,module,exports){
"use strict";
module.exports = function(
Promise, PromiseArray, tryConvertToPromise, apiRejection) {
var util = _dereq_("./util.js");
var isObject = util.isObject;
var es5 = _dereq_("./es5.js");
function PropertiesPromiseArray(obj) {
var keys = es5.keys(obj);
var len = keys.length;
var values = new Array(len * 2);
for (var i = 0; i < len; ++i) {
var key = keys[i];
values[i] = obj[key];
values[i + len] = key;
}
this.constructor$(values);
}
util.inherits(PropertiesPromiseArray, PromiseArray);
PropertiesPromiseArray.prototype._init = function () {
this._init$(undefined, -3) ;
};
PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) {
this._values[index] = value;
var totalResolved = ++this._totalResolved;
if (totalResolved >= this._length) {
var val = {};
var keyOffset = this.length();
for (var i = 0, len = this.length(); i < len; ++i) {
val[this._values[i + keyOffset]] = this._values[i];
}
this._resolve(val);
}
};
PropertiesPromiseArray.prototype._promiseProgressed = function (value, index) {
this._promise._progress({
key: this._values[index + this.length()],
value: value
});
};
PropertiesPromiseArray.prototype.shouldCopyValues = function () {
return false;
};
PropertiesPromiseArray.prototype.getActualLength = function (len) {
return len >> 1;
};
function props(promises) {
var ret;
var castValue = tryConvertToPromise(promises);
if (!isObject(castValue)) {
return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/OsFKC8\u000a");
} else if (castValue instanceof Promise) {
ret = castValue._then(
Promise.props, undefined, undefined, undefined, undefined);
} else {
ret = new PropertiesPromiseArray(castValue).promise();
}
if (castValue instanceof Promise) {
ret._propagateFrom(castValue, 4);
}
return ret;
}
Promise.prototype.props = function () {
return props(this);
};
Promise.props = function (promises) {
return props(promises);
};
};
},{"./es5.js":14,"./util.js":38}],28:[function(_dereq_,module,exports){
"use strict";
function arrayMove(src, srcIndex, dst, dstIndex, len) {
for (var j = 0; j < len; ++j) {
dst[j + dstIndex] = src[j + srcIndex];
src[j + srcIndex] = void 0;
}
}
function Queue(capacity) {
this._capacity = capacity;
this._length = 0;
this._front = 0;
}
Queue.prototype._willBeOverCapacity = function (size) {
return this._capacity < size;
};
Queue.prototype._pushOne = function (arg) {
var length = this.length();
this._checkCapacity(length + 1);
var i = (this._front + length) & (this._capacity - 1);
this[i] = arg;
this._length = length + 1;
};
Queue.prototype._unshiftOne = function(value) {
var capacity = this._capacity;
this._checkCapacity(this.length() + 1);
var front = this._front;
var i = (((( front - 1 ) &
( capacity - 1) ) ^ capacity ) - capacity );
this[i] = value;
this._front = i;
this._length = this.length() + 1;
};
Queue.prototype.unshift = function(fn, receiver, arg) {
this._unshiftOne(arg);
this._unshiftOne(receiver);
this._unshiftOne(fn);
};
Queue.prototype.push = function (fn, receiver, arg) {
var length = this.length() + 3;
if (this._willBeOverCapacity(length)) {
this._pushOne(fn);
this._pushOne(receiver);
this._pushOne(arg);
return;
}
var j = this._front + length - 3;
this._checkCapacity(length);
var wrapMask = this._capacity - 1;
this[(j + 0) & wrapMask] = fn;
this[(j + 1) & wrapMask] = receiver;
this[(j + 2) & wrapMask] = arg;
this._length = length;
};
Queue.prototype.shift = function () {
var front = this._front,
ret = this[front];
this[front] = undefined;
this._front = (front + 1) & (this._capacity - 1);
this._length--;
return ret;
};
Queue.prototype.length = function () {
return this._length;
};
Queue.prototype._checkCapacity = function (size) {
if (this._capacity < size) {
this._resizeTo(this._capacity << 1);
}
};
Queue.prototype._resizeTo = function (capacity) {
var oldCapacity = this._capacity;
this._capacity = capacity;
var front = this._front;
var length = this._length;
var moveItemsCount = (front + length) & (oldCapacity - 1);
arrayMove(this, 0, this, oldCapacity, moveItemsCount);
};
module.exports = Queue;
},{}],29:[function(_dereq_,module,exports){
"use strict";
module.exports = function(
Promise, INTERNAL, tryConvertToPromise, apiRejection) {
var isArray = _dereq_("./util.js").isArray;
var raceLater = function (promise) {
return promise.then(function(array) {
return race(array, promise);
});
};
function race(promises, parent) {
var maybePromise = tryConvertToPromise(promises);
if (maybePromise instanceof Promise) {
return raceLater(maybePromise);
} else if (!isArray(promises)) {
return apiRejection("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a");
}
var ret = new Promise(INTERNAL);
if (parent !== undefined) {
ret._propagateFrom(parent, 4 | 1);
}
var fulfill = ret._fulfill;
var reject = ret._reject;
for (var i = 0, len = promises.length; i < len; ++i) {
var val = promises[i];
if (val === undefined && !(i in promises)) {
continue;
}
Promise.cast(val)._then(fulfill, reject, undefined, ret, null);
}
return ret;
}
Promise.race = function (promises) {
return race(promises, undefined);
};
Promise.prototype.race = function () {
return race(this, undefined);
};
};
},{"./util.js":38}],30:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise,
PromiseArray,
apiRejection,
tryConvertToPromise,
INTERNAL) {
var async = _dereq_("./async.js");
var util = _dereq_("./util.js");
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
function ReductionPromiseArray(promises, fn, accum, _each) {
this.constructor$(promises);
this._promise._captureStackTrace();
this._preservedValues = _each === INTERNAL ? [] : null;
this._zerothIsAccum = (accum === undefined);
this._gotAccum = false;
this._reducingIndex = (this._zerothIsAccum ? 1 : 0);
this._valuesPhase = undefined;
var maybePromise = tryConvertToPromise(accum, this._promise);
var rejected = false;
var isPromise = maybePromise instanceof Promise;
if (isPromise) {
maybePromise = maybePromise._target();
if (maybePromise._isPending()) {
maybePromise._proxyPromiseArray(this, -1);
} else if (maybePromise._isFulfilled()) {
accum = maybePromise._value();
this._gotAccum = true;
} else {
this._reject(maybePromise._reason());
rejected = true;
}
}
if (!(isPromise || this._zerothIsAccum)) this._gotAccum = true;
this._callback = fn;
this._accum = accum;
if (!rejected) async.invoke(init, this, undefined);
}
function init() {
this._init$(undefined, -5);
}
util.inherits(ReductionPromiseArray, PromiseArray);
ReductionPromiseArray.prototype._init = function () {};
ReductionPromiseArray.prototype._resolveEmptyArray = function () {
if (this._gotAccum || this._zerothIsAccum) {
this._resolve(this._preservedValues !== null
? [] : this._accum);
}
};
ReductionPromiseArray.prototype._promiseFulfilled = function (value, index) {
var values = this._values;
values[index] = value;
var length = this.length();
var preservedValues = this._preservedValues;
var isEach = preservedValues !== null;
var gotAccum = this._gotAccum;
var valuesPhase = this._valuesPhase;
var valuesPhaseIndex;
if (!valuesPhase) {
valuesPhase = this._valuesPhase = new Array(length);
for (valuesPhaseIndex=0; valuesPhaseIndex<length; ++valuesPhaseIndex) {
valuesPhase[valuesPhaseIndex] = 0;
}
}
valuesPhaseIndex = valuesPhase[index];
if (index === 0 && this._zerothIsAccum) {
this._accum = value;
this._gotAccum = gotAccum = true;
valuesPhase[index] = ((valuesPhaseIndex === 0)
? 1 : 2);
} else if (index === -1) {
this._accum = value;
this._gotAccum = gotAccum = true;
} else {
if (valuesPhaseIndex === 0) {
valuesPhase[index] = 1;
} else {
valuesPhase[index] = 2;
this._accum = value;
}
}
if (!gotAccum) return;
var callback = this._callback;
var receiver = this._promise._boundTo;
var ret;
for (var i = this._reducingIndex; i < length; ++i) {
valuesPhaseIndex = valuesPhase[i];
if (valuesPhaseIndex === 2) {
this._reducingIndex = i + 1;
continue;
}
if (valuesPhaseIndex !== 1) return;
value = values[i];
this._promise._pushContext();
if (isEach) {
preservedValues.push(value);
ret = tryCatch(callback).call(receiver, value, i, length);
}
else {
ret = tryCatch(callback)
.call(receiver, this._accum, value, i, length);
}
this._promise._popContext();
if (ret === errorObj) return this._reject(ret.e);
var maybePromise = tryConvertToPromise(ret, this._promise);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
if (maybePromise._isPending()) {
valuesPhase[i] = 4;
return maybePromise._proxyPromiseArray(this, i);
} else if (maybePromise._isFulfilled()) {
ret = maybePromise._value();
} else {
return this._reject(maybePromise._reason());
}
}
this._reducingIndex = i + 1;
this._accum = ret;
}
this._resolve(isEach ? preservedValues : this._accum);
};
function reduce(promises, fn, initialValue, _each) {
if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
var array = new ReductionPromiseArray(promises, fn, initialValue, _each);
return array.promise();
}
Promise.prototype.reduce = function (fn, initialValue) {
return reduce(this, fn, initialValue, null);
};
Promise.reduce = function (promises, fn, initialValue, _each) {
return reduce(promises, fn, initialValue, _each);
};
};
},{"./async.js":2,"./util.js":38}],31:[function(_dereq_,module,exports){
"use strict";
var schedule;
var noAsyncScheduler = function() {
throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/m3OTXk\u000a");
};
if (_dereq_("./util.js").isNode) {
var version = process.versions.node.split(".").map(Number);
schedule = (version[0] === 0 && version[1] > 10) || (version[0] > 0)
? global.setImmediate : process.nextTick;
if (!schedule) {
if (typeof setImmediate !== "undefined") {
schedule = setImmediate;
} else if (typeof setTimeout !== "undefined") {
schedule = setTimeout;
} else {
schedule = noAsyncScheduler;
}
}
} else if (typeof MutationObserver !== "undefined") {
schedule = function(fn) {
var div = document.createElement("div");
var observer = new MutationObserver(fn);
observer.observe(div, {attributes: true});
return function() { div.classList.toggle("foo"); };
};
schedule.isStatic = true;
} else if (typeof setImmediate !== "undefined") {
schedule = function (fn) {
setImmediate(fn);
};
} else if (typeof setTimeout !== "undefined") {
schedule = function (fn) {
setTimeout(fn, 0);
};
} else {
schedule = noAsyncScheduler;
}
module.exports = schedule;
},{"./util.js":38}],32:[function(_dereq_,module,exports){
"use strict";
module.exports =
function(Promise, PromiseArray) {
var PromiseInspection = Promise.PromiseInspection;
var util = _dereq_("./util.js");
function SettledPromiseArray(values) {
this.constructor$(values);
}
util.inherits(SettledPromiseArray, PromiseArray);
SettledPromiseArray.prototype._promiseResolved = function (index, inspection) {
this._values[index] = inspection;
var totalResolved = ++this._totalResolved;
if (totalResolved >= this._length) {
this._resolve(this._values);
}
};
SettledPromiseArray.prototype._promiseFulfilled = function (value, index) {
var ret = new PromiseInspection();
ret._bitField = 268435456;
ret._settledValue = value;
this._promiseResolved(index, ret);
};
SettledPromiseArray.prototype._promiseRejected = function (reason, index) {
var ret = new PromiseInspection();
ret._bitField = 134217728;
ret._settledValue = reason;
this._promiseResolved(index, ret);
};
Promise.settle = function (promises) {
return new SettledPromiseArray(promises).promise();
};
Promise.prototype.settle = function () {
return new SettledPromiseArray(this).promise();
};
};
},{"./util.js":38}],33:[function(_dereq_,module,exports){
"use strict";
module.exports =
function(Promise, PromiseArray, apiRejection) {
var util = _dereq_("./util.js");
var RangeError = _dereq_("./errors.js").RangeError;
var AggregateError = _dereq_("./errors.js").AggregateError;
var isArray = util.isArray;
function SomePromiseArray(values) {
this.constructor$(values);
this._howMany = 0;
this._unwrap = false;
this._initialized = false;
}
util.inherits(SomePromiseArray, PromiseArray);
SomePromiseArray.prototype._init = function () {
if (!this._initialized) {
return;
}
if (this._howMany === 0) {
this._resolve([]);
return;
}
this._init$(undefined, -5);
var isArrayResolved = isArray(this._values);
if (!this._isResolved() &&
isArrayResolved &&
this._howMany > this._canPossiblyFulfill()) {
this._reject(this._getRangeError(this.length()));
}
};
SomePromiseArray.prototype.init = function () {
this._initialized = true;
this._init();
};
SomePromiseArray.prototype.setUnwrap = function () {
this._unwrap = true;
};
SomePromiseArray.prototype.howMany = function () {
return this._howMany;
};
SomePromiseArray.prototype.setHowMany = function (count) {
this._howMany = count;
};
SomePromiseArray.prototype._promiseFulfilled = function (value) {
this._addFulfilled(value);
if (this._fulfilled() === this.howMany()) {
this._values.length = this.howMany();
if (this.howMany() === 1 && this._unwrap) {
this._resolve(this._values[0]);
} else {
this._resolve(this._values);
}
}
};
SomePromiseArray.prototype._promiseRejected = function (reason) {
this._addRejected(reason);
if (this.howMany() > this._canPossiblyFulfill()) {
var e = new AggregateError();
for (var i = this.length(); i < this._values.length; ++i) {
e.push(this._values[i]);
}
this._reject(e);
}
};
SomePromiseArray.prototype._fulfilled = function () {
return this._totalResolved;
};
SomePromiseArray.prototype._rejected = function () {
return this._values.length - this.length();
};
SomePromiseArray.prototype._addRejected = function (reason) {
this._values.push(reason);
};
SomePromiseArray.prototype._addFulfilled = function (value) {
this._values[this._totalResolved++] = value;
};
SomePromiseArray.prototype._canPossiblyFulfill = function () {
return this.length() - this._rejected();
};
SomePromiseArray.prototype._getRangeError = function (count) {
var message = "Input array must contain at least " +
this._howMany + " items but contains only " + count + " items";
return new RangeError(message);
};
SomePromiseArray.prototype._resolveEmptyArray = function () {
this._reject(this._getRangeError(0));
};
function some(promises, howMany) {
if ((howMany | 0) !== howMany || howMany < 0) {
return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/1wAmHx\u000a");
}
var ret = new SomePromiseArray(promises);
var promise = ret.promise();
ret.setHowMany(howMany);
ret.init();
return promise;
}
Promise.some = function (promises, howMany) {
return some(promises, howMany);
};
Promise.prototype.some = function (howMany) {
return some(this, howMany);
};
Promise._SomePromiseArray = SomePromiseArray;
};
},{"./errors.js":13,"./util.js":38}],34:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise) {
function PromiseInspection(promise) {
if (promise !== undefined) {
promise = promise._target();
this._bitField = promise._bitField;
this._settledValue = promise._settledValue;
}
else {
this._bitField = 0;
this._settledValue = undefined;
}
}
PromiseInspection.prototype.value = function () {
if (!this.isFulfilled()) {
throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/hc1DLj\u000a");
}
return this._settledValue;
};
PromiseInspection.prototype.error =
PromiseInspection.prototype.reason = function () {
if (!this.isRejected()) {
throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/hPuiwB\u000a");
}
return this._settledValue;
};
PromiseInspection.prototype.isFulfilled =
Promise.prototype._isFulfilled = function () {
return (this._bitField & 268435456) > 0;
};
PromiseInspection.prototype.isRejected =
Promise.prototype._isRejected = function () {
return (this._bitField & 134217728) > 0;
};
PromiseInspection.prototype.isPending =
Promise.prototype._isPending = function () {
return (this._bitField & 402653184) === 0;
};
PromiseInspection.prototype.isResolved =
Promise.prototype._isResolved = function () {
return (this._bitField & 402653184) > 0;
};
Promise.prototype.isPending = function() {
return this._target()._isPending();
};
Promise.prototype.isRejected = function() {
return this._target()._isRejected();
};
Promise.prototype.isFulfilled = function() {
return this._target()._isFulfilled();
};
Promise.prototype.isResolved = function() {
return this._target()._isResolved();
};
Promise.prototype._value = function() {
return this._settledValue;
};
Promise.prototype._reason = function() {
this._unsetRejectionIsUnhandled();
return this._settledValue;
};
Promise.prototype.value = function() {
var target = this._target();
if (!target.isFulfilled()) {
throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/hc1DLj\u000a");
}
return target._settledValue;
};
Promise.prototype.reason = function() {
var target = this._target();
if (!target.isRejected()) {
throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/hPuiwB\u000a");
}
target._unsetRejectionIsUnhandled();
return target._settledValue;
};
Promise.PromiseInspection = PromiseInspection;
};
},{}],35:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, INTERNAL) {
var util = _dereq_("./util.js");
var errorObj = util.errorObj;
var isObject = util.isObject;
function tryConvertToPromise(obj, context) {
if (isObject(obj)) {
if (obj instanceof Promise) {
return obj;
}
else if (isAnyBluebirdPromise(obj)) {
var ret = new Promise(INTERNAL);
obj._then(
ret._fulfillUnchecked,
ret._rejectUncheckedCheckError,
ret._progressUnchecked,
ret,
null
);
return ret;
}
var then = util.tryCatch(getThen)(obj);
if (then === errorObj) {
if (context) context._pushContext();
var ret = Promise.reject(then.e);
if (context) context._popContext();
return ret;
} else if (typeof then === "function") {
return doThenable(obj, then, context);
}
}
return obj;
}
function getThen(obj) {
return obj.then;
}
var hasProp = {}.hasOwnProperty;
function isAnyBluebirdPromise(obj) {
return hasProp.call(obj, "_promise0");
}
function doThenable(x, then, context) {
var promise = new Promise(INTERNAL);
var ret = promise;
if (context) context._pushContext();
promise._captureStackTrace();
if (context) context._popContext();
var synchronous = true;
var result = util.tryCatch(then).call(x,
resolveFromThenable,
rejectFromThenable,
progressFromThenable);
synchronous = false;
if (promise && result === errorObj) {
promise._rejectCallback(result.e, true, true);
promise = null;
}
function resolveFromThenable(value) {
if (!promise) return;
if (x === value) {
promise._rejectCallback(
Promise._makeSelfResolutionError(), false, true);
} else {
promise._resolveCallback(value);
}
promise = null;
}
function rejectFromThenable(reason) {
if (!promise) return;
promise._rejectCallback(reason, synchronous, true);
promise = null;
}
function progressFromThenable(value) {
if (!promise) return;
if (typeof promise._progress === "function") {
promise._progress(value);
}
}
return ret;
}
return tryConvertToPromise;
};
},{"./util.js":38}],36:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, INTERNAL) {
var util = _dereq_("./util.js");
var TimeoutError = Promise.TimeoutError;
var afterTimeout = function (promise, message) {
if (!promise.isPending()) return;
if (typeof message !== "string") {
message = "operation timed out";
}
var err = new TimeoutError(message);
util.markAsOriginatingFromRejection(err);
promise._attachExtraTrace(err);
promise._cancel(err);
};
var afterValue = function(value) { return delay(+this).thenReturn(value); };
var delay = Promise.delay = function (value, ms) {
if (ms === undefined) {
ms = value;
value = undefined;
var ret = new Promise(INTERNAL);
setTimeout(function() { ret._fulfill(); }, ms);
return ret;
}
ms = +ms;
return Promise.resolve(value)._then(afterValue, null, null, ms, undefined);
};
Promise.prototype.delay = function (ms) {
return delay(this, ms);
};
function successClear(value) {
var handle = this;
if (handle instanceof Number) handle = +handle;
clearTimeout(handle);
return value;
}
function failureClear(reason) {
var handle = this;
if (handle instanceof Number) handle = +handle;
clearTimeout(handle);
throw reason;
}
Promise.prototype.timeout = function (ms, message) {
ms = +ms;
var ret = this.then().cancellable();
ret._cancellationParent = this;
var handle = setTimeout(function timeoutTimeout() {
afterTimeout(ret, message);
}, ms);
return ret._then(successClear, failureClear, undefined, handle, undefined);
};
};
},{"./util.js":38}],37:[function(_dereq_,module,exports){
"use strict";
module.exports = function (Promise, apiRejection, tryConvertToPromise,
createContext) {
var TypeError = _dereq_("./errors.js").TypeError;
var inherits = _dereq_("./util.js").inherits;
var PromiseInspection = Promise.PromiseInspection;
function inspectionMapper(inspections) {
var len = inspections.length;
for (var i = 0; i < len; ++i) {
var inspection = inspections[i];
if (inspection.isRejected()) {
return Promise.reject(inspection.error());
}
inspections[i] = inspection._settledValue;
}
return inspections;
}
function thrower(e) {
setTimeout(function(){throw e;}, 0);
}
function castPreservingDisposable(thenable) {
var maybePromise = tryConvertToPromise(thenable);
if (maybePromise !== thenable &&
typeof thenable._isDisposable === "function" &&
typeof thenable._getDisposer === "function" &&
thenable._isDisposable()) {
maybePromise._setDisposable(thenable._getDisposer());
}
return maybePromise;
}
function dispose(resources, inspection) {
var i = 0;
var len = resources.length;
var ret = Promise.defer();
function iterator() {
if (i >= len) return ret.resolve();
var maybePromise = castPreservingDisposable(resources[i++]);
if (maybePromise instanceof Promise &&
maybePromise._isDisposable()) {
try {
maybePromise = tryConvertToPromise(
maybePromise._getDisposer().tryDispose(inspection),
resources.promise);
} catch (e) {
return thrower(e);
}
if (maybePromise instanceof Promise) {
return maybePromise._then(iterator, thrower,
null, null, null);
}
}
iterator();
}
iterator();
return ret.promise;
}
function disposerSuccess(value) {
var inspection = new PromiseInspection();
inspection._settledValue = value;
inspection._bitField = 268435456;
return dispose(this, inspection).thenReturn(value);
}
function disposerFail(reason) {
var inspection = new PromiseInspection();
inspection._settledValue = reason;
inspection._bitField = 134217728;
return dispose(this, inspection).thenThrow(reason);
}
function Disposer(data, promise, context) {
this._data = data;
this._promise = promise;
this._context = context;
}
Disposer.prototype.data = function () {
return this._data;
};
Disposer.prototype.promise = function () {
return this._promise;
};
Disposer.prototype.resource = function () {
if (this.promise().isFulfilled()) {
return this.promise().value();
}
return null;
};
Disposer.prototype.tryDispose = function(inspection) {
var resource = this.resource();
var context = this._context;
if (context !== undefined) context._pushContext();
var ret = resource !== null
? this.doDispose(resource, inspection) : null;
if (context !== undefined) context._popContext();
this._promise._unsetDisposable();
this._data = null;
return ret;
};
Disposer.isDisposer = function (d) {
return (d != null &&
typeof d.resource === "function" &&
typeof d.tryDispose === "function");
};
function FunctionDisposer(fn, promise, context) {
this.constructor$(fn, promise, context);
}
inherits(FunctionDisposer, Disposer);
FunctionDisposer.prototype.doDispose = function (resource, inspection) {
var fn = this.data();
return fn.call(resource, resource, inspection);
};
function maybeUnwrapDisposer(value) {
if (Disposer.isDisposer(value)) {
this.resources[this.index]._setDisposable(value);
return value.promise();
}
return value;
}
Promise.using = function () {
var len = arguments.length;
if (len < 2) return apiRejection(
"you must pass at least 2 arguments to Promise.using");
var fn = arguments[len - 1];
if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
len--;
var resources = new Array(len);
for (var i = 0; i < len; ++i) {
var resource = arguments[i];
if (Disposer.isDisposer(resource)) {
var disposer = resource;
resource = resource.promise();
resource._setDisposable(disposer);
} else {
var maybePromise = tryConvertToPromise(resource);
if (maybePromise instanceof Promise) {
resource =
maybePromise._then(maybeUnwrapDisposer, null, null, {
resources: resources,
index: i
}, undefined);
}
}
resources[i] = resource;
}
var promise = Promise.settle(resources)
.then(inspectionMapper)
.then(function(vals) {
promise._pushContext();
var ret;
try {
ret = fn.apply(undefined, vals);
} finally {
promise._popContext();
}
return ret;
})
._then(
disposerSuccess, disposerFail, undefined, resources, undefined);
resources.promise = promise;
return promise;
};
Promise.prototype._setDisposable = function (disposer) {
this._bitField = this._bitField | 262144;
this._disposer = disposer;
};
Promise.prototype._isDisposable = function () {
return (this._bitField & 262144) > 0;
};
Promise.prototype._getDisposer = function () {
return this._disposer;
};
Promise.prototype._unsetDisposable = function () {
this._bitField = this._bitField & (~262144);
this._disposer = undefined;
};
Promise.prototype.disposer = function (fn) {
if (typeof fn === "function") {
return new FunctionDisposer(fn, this, createContext());
}
throw new TypeError();
};
};
},{"./errors.js":13,"./util.js":38}],38:[function(_dereq_,module,exports){
"use strict";
var es5 = _dereq_("./es5.js");
var canEvaluate = typeof navigator == "undefined";
var haveGetters = (function(){
try {
var o = {};
es5.defineProperty(o, "f", {
get: function () {
return 3;
}
});
return o.f === 3;
}
catch (e) {
return false;
}
})();
var errorObj = {e: {}};
var tryCatchTarget;
function tryCatcher() {
try {
return tryCatchTarget.apply(this, arguments);
} catch (e) {
errorObj.e = e;
return errorObj;
}
}
function tryCatch(fn) {
tryCatchTarget = fn;
return tryCatcher;
}
var inherits = function(Child, Parent) {
var hasProp = {}.hasOwnProperty;
function T() {
this.constructor = Child;
this.constructor$ = Parent;
for (var propertyName in Parent.prototype) {
if (hasProp.call(Parent.prototype, propertyName) &&
propertyName.charAt(propertyName.length-1) !== "$"
) {
this[propertyName + "$"] = Parent.prototype[propertyName];
}
}
}
T.prototype = Parent.prototype;
Child.prototype = new T();
return Child.prototype;
};
function isPrimitive(val) {
return val == null || val === true || val === false ||
typeof val === "string" || typeof val === "number";
}
function isObject(value) {
return !isPrimitive(value);
}
function maybeWrapAsError(maybeError) {
if (!isPrimitive(maybeError)) return maybeError;
return new Error(safeToString(maybeError));
}
function withAppended(target, appendee) {
var len = target.length;
var ret = new Array(len + 1);
var i;
for (i = 0; i < len; ++i) {
ret[i] = target[i];
}
ret[i] = appendee;
return ret;
}
function getDataPropertyOrDefault(obj, key, defaultValue) {
if (es5.isES5) {
var desc = Object.getOwnPropertyDescriptor(obj, key);
if (desc != null) {
return desc.get == null && desc.set == null
? desc.value
: defaultValue;
}
} else {
return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
}
}
function notEnumerableProp(obj, name, value) {
if (isPrimitive(obj)) return obj;
var descriptor = {
value: value,
configurable: true,
enumerable: false,
writable: true
};
es5.defineProperty(obj, name, descriptor);
return obj;
}
var wrapsPrimitiveReceiver = (function() {
return this !== "string";
}).call("string");
function thrower(r) {
throw r;
}
var inheritedDataKeys = (function() {
if (es5.isES5) {
var oProto = Object.prototype;
var getKeys = Object.getOwnPropertyNames;
return function(obj) {
var ret = [];
var visitedKeys = Object.create(null);
while (obj != null && obj !== oProto) {
var keys;
try {
keys = getKeys(obj);
} catch (e) {
return ret;
}
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (visitedKeys[key]) continue;
visitedKeys[key] = true;
var desc = Object.getOwnPropertyDescriptor(obj, key);
if (desc != null && desc.get == null && desc.set == null) {
ret.push(key);
}
}
obj = es5.getPrototypeOf(obj);
}
return ret;
};
} else {
return function(obj) {
var ret = [];
/*jshint forin:false */
for (var key in obj) {
ret.push(key);
}
return ret;
};
}
})();
function isClass(fn) {
try {
if (typeof fn === "function") {
var keys = es5.names(fn.prototype);
if (es5.isES5) return keys.length > 1;
return keys.length > 0 &&
!(keys.length === 1 && keys[0] === "constructor");
}
return false;
} catch (e) {
return false;
}
}
function toFastProperties(obj) {
/*jshint -W027*/
function f() {}
f.prototype = obj;
return f;
eval(obj);
}
var rident = /^[a-z$_][a-z$_0-9]*$/i;
function isIdentifier(str) {
return rident.test(str);
}
function filledRange(count, prefix, suffix) {
var ret = new Array(count);
for(var i = 0; i < count; ++i) {
ret[i] = prefix + i + suffix;
}
return ret;
}
function safeToString(obj) {
try {
return obj + "";
} catch (e) {
return "[no string representation]";
}
}
function markAsOriginatingFromRejection(e) {
try {
notEnumerableProp(e, "isOperational", true);
}
catch(ignore) {}
}
function originatesFromRejection(e) {
if (e == null) return false;
return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) ||
e["isOperational"] === true);
}
function canAttachTrace(obj) {
return obj instanceof Error && es5.propertyIsWritable(obj, "stack");
}
var ensureErrorObject = (function() {
if (!("stack" in new Error())) {
return function(value) {
if (canAttachTrace(value)) return value;
try {throw new Error(safeToString(value));}
catch(err) {return err;}
};
} else {
return function(value) {
if (canAttachTrace(value)) return value;
return new Error(safeToString(value));
};
}
})();
function classString(obj) {
return {}.toString.call(obj);
}
function copyDescriptors(from, to, filter) {
var keys = es5.names(from);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (filter(key)) {
es5.defineProperty(to, key, es5.getDescriptor(from, key));
}
}
}
var ret = {
isClass: isClass,
isIdentifier: isIdentifier,
inheritedDataKeys: inheritedDataKeys,
getDataPropertyOrDefault: getDataPropertyOrDefault,
thrower: thrower,
isArray: es5.isArray,
haveGetters: haveGetters,
notEnumerableProp: notEnumerableProp,
isPrimitive: isPrimitive,
isObject: isObject,
canEvaluate: canEvaluate,
errorObj: errorObj,
tryCatch: tryCatch,
inherits: inherits,
withAppended: withAppended,
maybeWrapAsError: maybeWrapAsError,
wrapsPrimitiveReceiver: wrapsPrimitiveReceiver,
toFastProperties: toFastProperties,
filledRange: filledRange,
toString: safeToString,
canAttachTrace: canAttachTrace,
ensureErrorObject: ensureErrorObject,
originatesFromRejection: originatesFromRejection,
markAsOriginatingFromRejection: markAsOriginatingFromRejection,
classString: classString,
copyDescriptors: copyDescriptors,
hasDevTools: typeof chrome !== "undefined" && chrome &&
typeof chrome.loadTimes === "function",
isNode: typeof process !== "undefined" &&
classString(process).toLowerCase() === "[object process]"
};
try {throw new Error(); } catch (e) {ret.lastLineError = e;}
module.exports = ret;
},{"./es5.js":14}]},{},[4])(4)
}); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; } |
import Reflux from 'reflux';
import ActorClient from 'utils/ActorClient';
import JoinGroupActions from 'actions/JoinGroupActions';
const urlBase = 'https://quit.email';
export default Reflux.createStore({
init () {
this.listenTo(JoinGroupActions.joinGroup, this.onJoin);
},
onJoin (token) {
let url = urlBase + '/join/' + token;
return JoinGroupActions.joinGroup.promise(ActorClient.joinGroup(url));
},
getUrlBase () {
return urlBase;
}
});
|
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'basicstyles', 'es', {
bold: 'Negrita',
italic: 'Cursiva',
strike: 'Tachado',
subscript: 'Subíndice',
superscript: 'Superíndice',
underline: 'Subrayado'
});
|
cordova.define("org.apache.cordova.geolocation.PositionError", function(require, exports, module) { /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
/**
* Position error object
*
* @constructor
* @param code
* @param message
*/
var PositionError = function(code, message) {
this.code = code || null;
this.message = message || '';
};
PositionError.PERMISSION_DENIED = 1;
PositionError.POSITION_UNAVAILABLE = 2;
PositionError.TIMEOUT = 3;
module.exports = PositionError;
});
|
(function* () { yield v }) |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'image', 'cy', {
alertUrl: 'Rhowch URL y ddelwedd',
alt: 'Testun Amgen',
border: 'Ymyl',
btnUpload: 'Anfon i\'r Gweinydd',
button2Img: 'Ydych am drawsffurfio\'r botwm ddelwedd hwn ar ddelwedd syml?',
hSpace: 'BwlchLl',
img2Button: 'Ydych am drawsffurfio\'r ddelwedd hon ar fotwm delwedd?',
infoTab: 'Gwyb Delwedd',
linkTab: 'Dolen',
lockRatio: 'Cloi Cymhareb',
menu: 'Priodweddau Delwedd',
resetSize: 'Ailosod Maint',
title: 'Priodweddau Delwedd',
titleButton: 'Priodweddau Botwm Delwedd',
upload: 'lanlwytho',
urlMissing: 'URL gwreiddiol y ddelwedd ar goll.',
vSpace: 'BwlchF',
validateBorder: 'Rhaid i\'r ymyl fod yn gyfanrif.',
validateHSpace: 'Rhaid i\'r HSpace fod yn gyfanrif.',
validateVSpace: 'Rhaid i\'r VSpace fod yn gyfanrif.'
});
|
YUI.add("lang/datatype-date-format_en-US",function(a){a.Intl.add("datatype-date-format","en-US",{"a":["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],"A":["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],"b":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],"B":["January","February","March","April","May","June","July","August","September","October","November","December"],"c":"%a, %b %d, %Y %l:%M:%S %p %Z","p":["AM","PM"],"P":["am","pm"],"x":"%m/%d/%y","X":"%l:%M:%S %p"});},"@VERSION@"); |
/*! jQuery UI - v1.9.2 - 2012-11-23
* http://jqueryui.com
* Includes: jquery.ui.datepicker-sl.js
* Copyright 2012 jQuery Foundation and other contributors; Licensed MIT */
jQuery(function(e){e.datepicker.regional.sl={closeText:"Zapri",prevText:"<Prejšnji",nextText:"Naslednji>",currentText:"Trenutni",monthNames:["Januar","Februar","Marec","April","Maj","Junij","Julij","Avgust","September","Oktober","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","Maj","Jun","Jul","Avg","Sep","Okt","Nov","Dec"],dayNames:["Nedelja","Ponedeljek","Torek","Sreda","Četrtek","Petek","Sobota"],dayNamesShort:["Ned","Pon","Tor","Sre","Čet","Pet","Sob"],dayNamesMin:["Ne","Po","To","Sr","Če","Pe","So"],weekHeader:"Teden",dateFormat:"dd.mm.yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},e.datepicker.setDefaults(e.datepicker.regional.sl)}); |
YUI.add("lang/datatype-date-format_zh-Hant-HK",function(e){e.Intl.add("datatype-date-format","zh-Hant-HK",{a:["\u9031\u65e5","\u9031\u4e00","\u9031\u4e8c","\u9031\u4e09","\u9031\u56db","\u9031\u4e94","\u9031\u516d"],A:["\u661f\u671f\u65e5","\u661f\u671f\u4e00","\u661f\u671f\u4e8c","\u661f\u671f\u4e09","\u661f\u671f\u56db","\u661f\u671f\u4e94","\u661f\u671f\u516d"],b:["1\u6708","2\u6708","3\u6708","4\u6708","5\u6708","6\u6708","7\u6708","8\u6708","9\u6708","10\u6708","11\u6708","12\u6708"],B:["1\u6708","2\u6708","3\u6708","4\u6708","5\u6708","6\u6708","7\u6708","8\u6708","9\u6708","10\u6708","11\u6708","12\u6708"],c:"%Y\u5e74%b%d\u65e5%a%Z%p%l\u6642%M\u5206%S\u79d2",p:["\u4e0a\u5348","\u4e0b\u5348"],P:["\u4e0a\u5348","\u4e0b\u5348"],x:"%y\u5e74%m\u6708%d\u65e5",X:"%p%l\u6642%M\u5206%S\u79d2"})},"3.18.0");
|
/*!
handlebars v4.0.2
Copyright (C) 2011-2015 by Yehuda Katz
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.
@license
*/
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define(factory);
else if(typeof exports === 'object')
exports["Handlebars"] = factory();
else
root["Handlebars"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _interopRequireWildcard = __webpack_require__(7)['default'];
var _interopRequireDefault = __webpack_require__(8)['default'];
exports.__esModule = true;
var _handlebarsBase = __webpack_require__(1);
// Each of these augment the Handlebars object. No need to setup here.
// (This is done to easily share code between commonjs and browse envs)
var base = _interopRequireWildcard(_handlebarsBase);
var _handlebarsSafeString = __webpack_require__(2);
var _handlebarsSafeString2 = _interopRequireDefault(_handlebarsSafeString);
var _handlebarsException = __webpack_require__(3);
var _handlebarsException2 = _interopRequireDefault(_handlebarsException);
var _handlebarsUtils = __webpack_require__(4);
var Utils = _interopRequireWildcard(_handlebarsUtils);
var _handlebarsRuntime = __webpack_require__(5);
var runtime = _interopRequireWildcard(_handlebarsRuntime);
var _handlebarsNoConflict = __webpack_require__(6);
// For compatibility and usage outside of module systems, make the Handlebars object a namespace
var _handlebarsNoConflict2 = _interopRequireDefault(_handlebarsNoConflict);
function create() {
var hb = new base.HandlebarsEnvironment();
Utils.extend(hb, base);
hb.SafeString = _handlebarsSafeString2['default'];
hb.Exception = _handlebarsException2['default'];
hb.Utils = Utils;
hb.escapeExpression = Utils.escapeExpression;
hb.VM = runtime;
hb.template = function (spec) {
return runtime.template(spec, hb);
};
return hb;
}
var inst = create();
inst.create = create;
_handlebarsNoConflict2['default'](inst);
inst['default'] = inst;
exports['default'] = inst;
module.exports = exports['default'];
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _interopRequireDefault = __webpack_require__(8)['default'];
exports.__esModule = true;
exports.HandlebarsEnvironment = HandlebarsEnvironment;
var _utils = __webpack_require__(4);
var _exception = __webpack_require__(3);
var _exception2 = _interopRequireDefault(_exception);
var _helpers = __webpack_require__(9);
var _decorators = __webpack_require__(10);
var _logger = __webpack_require__(11);
var _logger2 = _interopRequireDefault(_logger);
var VERSION = '4.0.2';
exports.VERSION = VERSION;
var COMPILER_REVISION = 7;
exports.COMPILER_REVISION = COMPILER_REVISION;
var REVISION_CHANGES = {
1: '<= 1.0.rc.2', // 1.0.rc.2 is actually rev2 but doesn't report it
2: '== 1.0.0-rc.3',
3: '== 1.0.0-rc.4',
4: '== 1.x.x',
5: '== 2.0.0-alpha.x',
6: '>= 2.0.0-beta.1',
7: '>= 4.0.0'
};
exports.REVISION_CHANGES = REVISION_CHANGES;
var objectType = '[object Object]';
function HandlebarsEnvironment(helpers, partials, decorators) {
this.helpers = helpers || {};
this.partials = partials || {};
this.decorators = decorators || {};
_helpers.registerDefaultHelpers(this);
_decorators.registerDefaultDecorators(this);
}
HandlebarsEnvironment.prototype = {
constructor: HandlebarsEnvironment,
logger: _logger2['default'],
log: _logger2['default'].log,
registerHelper: function registerHelper(name, fn) {
if (_utils.toString.call(name) === objectType) {
if (fn) {
throw new _exception2['default']('Arg not supported with multiple helpers');
}
_utils.extend(this.helpers, name);
} else {
this.helpers[name] = fn;
}
},
unregisterHelper: function unregisterHelper(name) {
delete this.helpers[name];
},
registerPartial: function registerPartial(name, partial) {
if (_utils.toString.call(name) === objectType) {
_utils.extend(this.partials, name);
} else {
if (typeof partial === 'undefined') {
throw new _exception2['default']('Attempting to register a partial as undefined');
}
this.partials[name] = partial;
}
},
unregisterPartial: function unregisterPartial(name) {
delete this.partials[name];
},
registerDecorator: function registerDecorator(name, fn) {
if (_utils.toString.call(name) === objectType) {
if (fn) {
throw new _exception2['default']('Arg not supported with multiple decorators');
}
_utils.extend(this.decorators, name);
} else {
this.decorators[name] = fn;
}
},
unregisterDecorator: function unregisterDecorator(name) {
delete this.decorators[name];
}
};
var log = _logger2['default'].log;
exports.log = log;
exports.createFrame = _utils.createFrame;
exports.logger = _logger2['default'];
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
// Build out our basic SafeString type
'use strict';
exports.__esModule = true;
function SafeString(string) {
this.string = string;
}
SafeString.prototype.toString = SafeString.prototype.toHTML = function () {
return '' + this.string;
};
exports['default'] = SafeString;
module.exports = exports['default'];
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack'];
function Exception(message, node) {
var loc = node && node.loc,
line = undefined,
column = undefined;
if (loc) {
line = loc.start.line;
column = loc.start.column;
message += ' - ' + line + ':' + column;
}
var tmp = Error.prototype.constructor.call(this, message);
// Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work.
for (var idx = 0; idx < errorProps.length; idx++) {
this[errorProps[idx]] = tmp[errorProps[idx]];
}
/* istanbul ignore else */
if (Error.captureStackTrace) {
Error.captureStackTrace(this, Exception);
}
if (loc) {
this.lineNumber = line;
this.column = column;
}
}
Exception.prototype = new Error();
exports['default'] = Exception;
module.exports = exports['default'];
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.extend = extend;
exports.indexOf = indexOf;
exports.escapeExpression = escapeExpression;
exports.isEmpty = isEmpty;
exports.createFrame = createFrame;
exports.blockParams = blockParams;
exports.appendContextPath = appendContextPath;
var escape = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'`': '`',
'=': '='
};
var badChars = /[&<>"'`=]/g,
possible = /[&<>"'`=]/;
function escapeChar(chr) {
return escape[chr];
}
function extend(obj /* , ...source */) {
for (var i = 1; i < arguments.length; i++) {
for (var key in arguments[i]) {
if (Object.prototype.hasOwnProperty.call(arguments[i], key)) {
obj[key] = arguments[i][key];
}
}
}
return obj;
}
var toString = Object.prototype.toString;
// Sourced from lodash
// https://github.com/bestiejs/lodash/blob/master/LICENSE.txt
/* eslint-disable func-style */
exports.toString = toString;
var isFunction = function isFunction(value) {
return typeof value === 'function';
};
// fallback for older versions of Chrome and Safari
/* istanbul ignore next */
if (isFunction(/x/)) {
exports.isFunction = isFunction = function (value) {
return typeof value === 'function' && toString.call(value) === '[object Function]';
};
}
exports.isFunction = isFunction;
/* eslint-enable func-style */
/* istanbul ignore next */
var isArray = Array.isArray || function (value) {
return value && typeof value === 'object' ? toString.call(value) === '[object Array]' : false;
};
// Older IE versions do not directly support indexOf so we must implement our own, sadly.
exports.isArray = isArray;
function indexOf(array, value) {
for (var i = 0, len = array.length; i < len; i++) {
if (array[i] === value) {
return i;
}
}
return -1;
}
function escapeExpression(string) {
if (typeof string !== 'string') {
// don't escape SafeStrings, since they're already safe
if (string && string.toHTML) {
return string.toHTML();
} else if (string == null) {
return '';
} else if (!string) {
return string + '';
}
// Force a string conversion as this will be done by the append regardless and
// the regex test will do this transparently behind the scenes, causing issues if
// an object's to string has escaped characters in it.
string = '' + string;
}
if (!possible.test(string)) {
return string;
}
return string.replace(badChars, escapeChar);
}
function isEmpty(value) {
if (!value && value !== 0) {
return true;
} else if (isArray(value) && value.length === 0) {
return true;
} else {
return false;
}
}
function createFrame(object) {
var frame = extend({}, object);
frame._parent = object;
return frame;
}
function blockParams(params, ids) {
params.path = ids;
return params;
}
function appendContextPath(contextPath, id) {
return (contextPath ? contextPath + '.' : '') + id;
}
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _interopRequireWildcard = __webpack_require__(7)['default'];
var _interopRequireDefault = __webpack_require__(8)['default'];
exports.__esModule = true;
exports.checkRevision = checkRevision;
exports.template = template;
exports.wrapProgram = wrapProgram;
exports.resolvePartial = resolvePartial;
exports.invokePartial = invokePartial;
exports.noop = noop;
var _utils = __webpack_require__(4);
var Utils = _interopRequireWildcard(_utils);
var _exception = __webpack_require__(3);
var _exception2 = _interopRequireDefault(_exception);
var _base = __webpack_require__(1);
function checkRevision(compilerInfo) {
var compilerRevision = compilerInfo && compilerInfo[0] || 1,
currentRevision = _base.COMPILER_REVISION;
if (compilerRevision !== currentRevision) {
if (compilerRevision < currentRevision) {
var runtimeVersions = _base.REVISION_CHANGES[currentRevision],
compilerVersions = _base.REVISION_CHANGES[compilerRevision];
throw new _exception2['default']('Template was precompiled with an older version of Handlebars than the current runtime. ' + 'Please update your precompiler to a newer version (' + runtimeVersions + ') or downgrade your runtime to an older version (' + compilerVersions + ').');
} else {
// Use the embedded version info since the runtime doesn't know about this revision yet
throw new _exception2['default']('Template was precompiled with a newer version of Handlebars than the current runtime. ' + 'Please update your runtime to a newer version (' + compilerInfo[1] + ').');
}
}
}
function template(templateSpec, env) {
/* istanbul ignore next */
if (!env) {
throw new _exception2['default']('No environment passed to template');
}
if (!templateSpec || !templateSpec.main) {
throw new _exception2['default']('Unknown template object: ' + typeof templateSpec);
}
templateSpec.main.decorator = templateSpec.main_d;
// Note: Using env.VM references rather than local var references throughout this section to allow
// for external users to override these as psuedo-supported APIs.
env.VM.checkRevision(templateSpec.compiler);
function invokePartialWrapper(partial, context, options) {
if (options.hash) {
context = Utils.extend({}, context, options.hash);
if (options.ids) {
options.ids[0] = true;
}
}
partial = env.VM.resolvePartial.call(this, partial, context, options);
var result = env.VM.invokePartial.call(this, partial, context, options);
if (result == null && env.compile) {
options.partials[options.name] = env.compile(partial, templateSpec.compilerOptions, env);
result = options.partials[options.name](context, options);
}
if (result != null) {
if (options.indent) {
var lines = result.split('\n');
for (var i = 0, l = lines.length; i < l; i++) {
if (!lines[i] && i + 1 === l) {
break;
}
lines[i] = options.indent + lines[i];
}
result = lines.join('\n');
}
return result;
} else {
throw new _exception2['default']('The partial ' + options.name + ' could not be compiled when running in runtime-only mode');
}
}
// Just add water
var container = {
strict: function strict(obj, name) {
if (!(name in obj)) {
throw new _exception2['default']('"' + name + '" not defined in ' + obj);
}
return obj[name];
},
lookup: function lookup(depths, name) {
var len = depths.length;
for (var i = 0; i < len; i++) {
if (depths[i] && depths[i][name] != null) {
return depths[i][name];
}
}
},
lambda: function lambda(current, context) {
return typeof current === 'function' ? current.call(context) : current;
},
escapeExpression: Utils.escapeExpression,
invokePartial: invokePartialWrapper,
fn: function fn(i) {
var ret = templateSpec[i];
ret.decorator = templateSpec[i + '_d'];
return ret;
},
programs: [],
program: function program(i, data, declaredBlockParams, blockParams, depths) {
var programWrapper = this.programs[i],
fn = this.fn(i);
if (data || depths || blockParams || declaredBlockParams) {
programWrapper = wrapProgram(this, i, fn, data, declaredBlockParams, blockParams, depths);
} else if (!programWrapper) {
programWrapper = this.programs[i] = wrapProgram(this, i, fn);
}
return programWrapper;
},
data: function data(value, depth) {
while (value && depth--) {
value = value._parent;
}
return value;
},
merge: function merge(param, common) {
var obj = param || common;
if (param && common && param !== common) {
obj = Utils.extend({}, common, param);
}
return obj;
},
noop: env.VM.noop,
compilerInfo: templateSpec.compiler
};
function ret(context) {
var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var data = options.data;
ret._setup(options);
if (!options.partial && templateSpec.useData) {
data = initData(context, data);
}
var depths = undefined,
blockParams = templateSpec.useBlockParams ? [] : undefined;
if (templateSpec.useDepths) {
if (options.depths) {
depths = context !== options.depths[0] ? [context].concat(options.depths) : options.depths;
} else {
depths = [context];
}
}
function main(context /*, options*/) {
return '' + templateSpec.main(container, context, container.helpers, container.partials, data, blockParams, depths);
}
main = executeDecorators(templateSpec.main, main, container, options.depths || [], data, blockParams);
return main(context, options);
}
ret.isTop = true;
ret._setup = function (options) {
if (!options.partial) {
container.helpers = container.merge(options.helpers, env.helpers);
if (templateSpec.usePartial) {
container.partials = container.merge(options.partials, env.partials);
}
if (templateSpec.usePartial || templateSpec.useDecorators) {
container.decorators = container.merge(options.decorators, env.decorators);
}
} else {
container.helpers = options.helpers;
container.partials = options.partials;
container.decorators = options.decorators;
}
};
ret._child = function (i, data, blockParams, depths) {
if (templateSpec.useBlockParams && !blockParams) {
throw new _exception2['default']('must pass block params');
}
if (templateSpec.useDepths && !depths) {
throw new _exception2['default']('must pass parent depths');
}
return wrapProgram(container, i, templateSpec[i], data, 0, blockParams, depths);
};
return ret;
}
function wrapProgram(container, i, fn, data, declaredBlockParams, blockParams, depths) {
function prog(context) {
var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var currentDepths = depths;
if (depths && context !== depths[0]) {
currentDepths = [context].concat(depths);
}
return fn(container, context, container.helpers, container.partials, options.data || data, blockParams && [options.blockParams].concat(blockParams), currentDepths);
}
prog = executeDecorators(fn, prog, container, depths, data, blockParams);
prog.program = i;
prog.depth = depths ? depths.length : 0;
prog.blockParams = declaredBlockParams || 0;
return prog;
}
function resolvePartial(partial, context, options) {
if (!partial) {
if (options.name === '@partial-block') {
partial = options.data['partial-block'];
} else {
partial = options.partials[options.name];
}
} else if (!partial.call && !options.name) {
// This is a dynamic partial that returned a string
options.name = partial;
partial = options.partials[partial];
}
return partial;
}
function invokePartial(partial, context, options) {
options.partial = true;
if (options.ids) {
options.data.contextPath = options.ids[0] || options.data.contextPath;
}
var partialBlock = undefined;
if (options.fn && options.fn !== noop) {
partialBlock = options.data['partial-block'] = options.fn;
if (partialBlock.partials) {
options.partials = Utils.extend({}, options.partials, partialBlock.partials);
}
}
if (partial === undefined && partialBlock) {
partial = partialBlock;
}
if (partial === undefined) {
throw new _exception2['default']('The partial ' + options.name + ' could not be found');
} else if (partial instanceof Function) {
return partial(context, options);
}
}
function noop() {
return '';
}
function initData(context, data) {
if (!data || !('root' in data)) {
data = data ? _base.createFrame(data) : {};
data.root = context;
}
return data;
}
function executeDecorators(fn, prog, container, depths, data, blockParams) {
if (fn.decorator) {
var props = {};
prog = fn.decorator(prog, props, container, depths && depths[0], data, blockParams, depths);
Utils.extend(prog, props);
}
return prog;
}
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {/* global window */
'use strict';
exports.__esModule = true;
exports['default'] = function (Handlebars) {
/* istanbul ignore next */
var root = typeof global !== 'undefined' ? global : window,
$Handlebars = root.Handlebars;
/* istanbul ignore next */
Handlebars.noConflict = function () {
if (root.Handlebars === Handlebars) {
root.Handlebars = $Handlebars;
}
};
};
module.exports = exports['default'];
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
/***/ },
/* 7 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
exports["default"] = function (obj) {
if (obj && obj.__esModule) {
return obj;
} else {
var newObj = {};
if (obj != null) {
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
}
}
newObj["default"] = obj;
return newObj;
}
};
exports.__esModule = true;
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
exports["default"] = function (obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
};
exports.__esModule = true;
/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _interopRequireDefault = __webpack_require__(8)['default'];
exports.__esModule = true;
exports.registerDefaultHelpers = registerDefaultHelpers;
var _helpersBlockHelperMissing = __webpack_require__(12);
var _helpersBlockHelperMissing2 = _interopRequireDefault(_helpersBlockHelperMissing);
var _helpersEach = __webpack_require__(13);
var _helpersEach2 = _interopRequireDefault(_helpersEach);
var _helpersHelperMissing = __webpack_require__(14);
var _helpersHelperMissing2 = _interopRequireDefault(_helpersHelperMissing);
var _helpersIf = __webpack_require__(15);
var _helpersIf2 = _interopRequireDefault(_helpersIf);
var _helpersLog = __webpack_require__(16);
var _helpersLog2 = _interopRequireDefault(_helpersLog);
var _helpersLookup = __webpack_require__(17);
var _helpersLookup2 = _interopRequireDefault(_helpersLookup);
var _helpersWith = __webpack_require__(18);
var _helpersWith2 = _interopRequireDefault(_helpersWith);
function registerDefaultHelpers(instance) {
_helpersBlockHelperMissing2['default'](instance);
_helpersEach2['default'](instance);
_helpersHelperMissing2['default'](instance);
_helpersIf2['default'](instance);
_helpersLog2['default'](instance);
_helpersLookup2['default'](instance);
_helpersWith2['default'](instance);
}
/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _interopRequireDefault = __webpack_require__(8)['default'];
exports.__esModule = true;
exports.registerDefaultDecorators = registerDefaultDecorators;
var _decoratorsInline = __webpack_require__(19);
var _decoratorsInline2 = _interopRequireDefault(_decoratorsInline);
function registerDefaultDecorators(instance) {
_decoratorsInline2['default'](instance);
}
/***/ },
/* 11 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var logger = {
methodMap: ['debug', 'info', 'warn', 'error'],
level: 'info',
// Maps a given level value to the `methodMap` indexes above.
lookupLevel: function lookupLevel(level) {
if (typeof level === 'string') {
var levelMap = logger.methodMap.indexOf(level.toLowerCase());
if (levelMap >= 0) {
level = levelMap;
} else {
level = parseInt(level, 10);
}
}
return level;
},
// Can be overridden in the host environment
log: function log(level) {
level = logger.lookupLevel(level);
if (typeof console !== 'undefined' && logger.lookupLevel(logger.level) <= level) {
var method = logger.methodMap[level];
if (!console[method]) {
// eslint-disable-line no-console
method = 'log';
}
for (var _len = arguments.length, message = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
message[_key - 1] = arguments[_key];
}
console[method].apply(console, message); // eslint-disable-line no-console
}
}
};
exports['default'] = logger;
module.exports = exports['default'];
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _utils = __webpack_require__(4);
exports['default'] = function (instance) {
instance.registerHelper('blockHelperMissing', function (context, options) {
var inverse = options.inverse,
fn = options.fn;
if (context === true) {
return fn(this);
} else if (context === false || context == null) {
return inverse(this);
} else if (_utils.isArray(context)) {
if (context.length > 0) {
if (options.ids) {
options.ids = [options.name];
}
return instance.helpers.each(context, options);
} else {
return inverse(this);
}
} else {
if (options.data && options.ids) {
var data = _utils.createFrame(options.data);
data.contextPath = _utils.appendContextPath(options.data.contextPath, options.name);
options = { data: data };
}
return fn(context, options);
}
});
};
module.exports = exports['default'];
/***/ },
/* 13 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _interopRequireDefault = __webpack_require__(8)['default'];
exports.__esModule = true;
var _utils = __webpack_require__(4);
var _exception = __webpack_require__(3);
var _exception2 = _interopRequireDefault(_exception);
exports['default'] = function (instance) {
instance.registerHelper('each', function (context, options) {
if (!options) {
throw new _exception2['default']('Must pass iterator to #each');
}
var fn = options.fn,
inverse = options.inverse,
i = 0,
ret = '',
data = undefined,
contextPath = undefined;
if (options.data && options.ids) {
contextPath = _utils.appendContextPath(options.data.contextPath, options.ids[0]) + '.';
}
if (_utils.isFunction(context)) {
context = context.call(this);
}
if (options.data) {
data = _utils.createFrame(options.data);
}
function execIteration(field, index, last) {
// Don't iterate over undefined values since we can't execute blocks against them
// in non-strict (js) mode.
if (context[field] == null) {
return;
}
if (data) {
data.key = field;
data.index = index;
data.first = index === 0;
data.last = !!last;
if (contextPath) {
data.contextPath = contextPath + field;
}
}
ret = ret + fn(context[field], {
data: data,
blockParams: _utils.blockParams([context[field], field], [contextPath + field, null])
});
}
if (context && typeof context === 'object') {
if (_utils.isArray(context)) {
for (var j = context.length; i < j; i++) {
execIteration(i, i, i === context.length - 1);
}
} else {
var priorKey = undefined;
for (var key in context) {
if (context.hasOwnProperty(key)) {
// We're running the iterations one step out of sync so we can detect
// the last iteration without have to scan the object twice and create
// an itermediate keys array.
if (priorKey !== undefined) {
execIteration(priorKey, i - 1);
}
priorKey = key;
i++;
}
}
if (priorKey !== undefined) {
execIteration(priorKey, i - 1, true);
}
}
}
if (i === 0) {
ret = inverse(this);
}
return ret;
});
};
module.exports = exports['default'];
/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _interopRequireDefault = __webpack_require__(8)['default'];
exports.__esModule = true;
var _exception = __webpack_require__(3);
var _exception2 = _interopRequireDefault(_exception);
exports['default'] = function (instance) {
instance.registerHelper('helperMissing', function () /* [args, ]options */{
if (arguments.length === 1) {
// A missing field in a {{foo}} construct.
return undefined;
} else {
// Someone is actually trying to call something, blow up.
throw new _exception2['default']('Missing helper: "' + arguments[arguments.length - 1].name + '"');
}
});
};
module.exports = exports['default'];
/***/ },
/* 15 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _utils = __webpack_require__(4);
exports['default'] = function (instance) {
instance.registerHelper('if', function (conditional, options) {
if (_utils.isFunction(conditional)) {
conditional = conditional.call(this);
}
// Default behavior is to render the positive path if the value is truthy and not empty.
// The `includeZero` option may be set to treat the condtional as purely not empty based on the
// behavior of isEmpty. Effectively this determines if 0 is handled by the positive path or negative.
if (!options.hash.includeZero && !conditional || _utils.isEmpty(conditional)) {
return options.inverse(this);
} else {
return options.fn(this);
}
});
instance.registerHelper('unless', function (conditional, options) {
return instance.helpers['if'].call(this, conditional, { fn: options.inverse, inverse: options.fn, hash: options.hash });
});
};
module.exports = exports['default'];
/***/ },
/* 16 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports['default'] = function (instance) {
instance.registerHelper('log', function () /* message, options */{
var args = [undefined],
options = arguments[arguments.length - 1];
for (var i = 0; i < arguments.length - 1; i++) {
args.push(arguments[i]);
}
var level = 1;
if (options.hash.level != null) {
level = options.hash.level;
} else if (options.data && options.data.level != null) {
level = options.data.level;
}
args[0] = level;
instance.log.apply(instance, args);
});
};
module.exports = exports['default'];
/***/ },
/* 17 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports['default'] = function (instance) {
instance.registerHelper('lookup', function (obj, field) {
return obj && obj[field];
});
};
module.exports = exports['default'];
/***/ },
/* 18 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _utils = __webpack_require__(4);
exports['default'] = function (instance) {
instance.registerHelper('with', function (context, options) {
if (_utils.isFunction(context)) {
context = context.call(this);
}
var fn = options.fn;
if (!_utils.isEmpty(context)) {
var data = options.data;
if (options.data && options.ids) {
data = _utils.createFrame(options.data);
data.contextPath = _utils.appendContextPath(options.data.contextPath, options.ids[0]);
}
return fn(context, {
data: data,
blockParams: _utils.blockParams([context], [data && data.contextPath])
});
} else {
return options.inverse(this);
}
});
};
module.exports = exports['default'];
/***/ },
/* 19 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _utils = __webpack_require__(4);
exports['default'] = function (instance) {
instance.registerDecorator('inline', function (fn, props, container, options) {
var ret = fn;
if (!props.partials) {
props.partials = {};
ret = function (context, options) {
// Create a new partials stack frame prior to exec.
var original = container.partials;
container.partials = _utils.extend({}, original, props.partials);
var ret = fn(context, options);
container.partials = original;
return ret;
};
}
props.partials[options.args[0]] = options.fn;
return ret;
});
};
module.exports = exports['default'];
/***/ }
/******/ ])
});
; |
/**
* @license
* lodash (Custom Build) /license | Underscore.js 1.8.3 underscorejs.org/LICENSE
* Build: `lodash core -o ./dist/lodash.core.js`
*/
;(function(){function n(n,t){return n.push.apply(n,t),n}function t(n){return function(t){return null==t?nn:t[n]}}function r(n,t,r,e,u){return u(n,function(n,u,o){r=e?(e=false,n):t(r,n,u,o)}),r}function e(n,t){return j(t,function(t){return n[t]})}function u(n){return n instanceof o?n:new o(n)}function o(n,t){this.__wrapped__=n,this.__actions__=[],this.__chain__=!!t}function i(n,t,r,e){return n===nn||M(n,ln[r])&&!pn.call(e,r)?t:n}function c(n,t,r){if(typeof n!="function")throw new TypeError("Expected a function");
return setTimeout(function(){n.apply(nn,r)},t)}function f(n,t){var r=true;return mn(n,function(n,e,u){return r=!!t(n,e,u)}),r}function a(n,t,r){for(var e=-1,u=n.length;++e<u;){var o=n[e],i=t(o);if(null!=i&&(c===nn?i===i:r(i,c)))var c=i,f=o}return f}function l(n,t){var r=[];return mn(n,function(n,e,u){t(n,e,u)&&r.push(n)}),r}function p(t,r,e,u,o){var i=-1,c=t.length;for(e||(e=R),o||(o=[]);++i<c;){var f=t[i];0<r&&e(f)?1<r?p(f,r-1,e,u,o):n(o,f):u||(o[o.length]=f)}return o}function s(n,t){return n&&On(n,t,qn);
}function h(n,t){return l(t,function(t){return V(n[t])})}function v(n,t){return n>t}function y(n,t,r,e,u){return n===t||(null==n||null==t||!H(n)&&!K(t)?n!==n&&t!==t:b(n,t,y,r,e,u))}function b(n,t,r,e,u,o){var i=Sn(n),c=Sn(t),f="[object Array]",a="[object Array]";i||(f=hn.call(n),f="[object Arguments]"==f?"[object Object]":f),c||(a=hn.call(t),a="[object Arguments]"==a?"[object Object]":a);var l="[object Object]"==f,c="[object Object]"==a,a=f==a;o||(o=[]);var p=En(o,function(t){return t[0]==n}),s=En(o,function(n){
return n[0]==t});if(p&&s)return p[1]==t;if(o.push([n,t]),o.push([t,n]),a&&!l){if(i)r=F(n,t,r,e,u,o);else n:{switch(f){case"[object Boolean]":case"[object Date]":case"[object Number]":r=M(+n,+t);break n;case"[object Error]":r=n.name==t.name&&n.message==t.message;break n;case"[object RegExp]":case"[object String]":r=n==t+"";break n}r=false}return o.pop(),r}return 2&u||(i=l&&pn.call(n,"__wrapped__"),f=c&&pn.call(t,"__wrapped__"),!i&&!f)?!!a&&(r=B(n,t,r,e,u,o),o.pop(),r):(i=i?n.value():n,f=f?t.value():t,
r=r(i,f,e,u,o),o.pop(),r)}function g(n){return typeof n=="function"?n:null==n?Y:(typeof n=="object"?d:t)(n)}function _(n,t){return n<t}function j(n,t){var r=-1,e=U(n)?Array(n.length):[];return mn(n,function(n,u,o){e[++r]=t(n,u,o)}),e}function d(n){var t=_n(n);return function(r){var e=t.length;if(null==r)return!e;for(r=Object(r);e--;){var u=t[e];if(!(u in r&&y(n[u],r[u],nn,3)))return false}return true}}function m(n,t){return n=Object(n),G(t,function(t,r){return r in n&&(t[r]=n[r]),t},{})}function O(n){return xn(I(n,void 0,Y),n+"");
}function x(n,t,r){var e=-1,u=n.length;for(0>t&&(t=-t>u?0:u+t),r=r>u?u:r,0>r&&(r+=u),u=t>r?0:r-t>>>0,t>>>=0,r=Array(u);++e<u;)r[e]=n[e+t];return r}function A(n){return x(n,0,n.length)}function E(n,t){var r;return mn(n,function(n,e,u){return r=t(n,e,u),!r}),!!r}function w(t,r){return G(r,function(t,r){return r.func.apply(r.thisArg,n([t],r.args))},t)}function k(n,t,r,e){var u=!r;r||(r={});for(var o=-1,i=t.length;++o<i;){var c=t[o],f=e?e(r[c],n[c],c,r,n):nn;if(f===nn&&(f=n[c]),u)r[c]=f;else{var a=r,l=a[c];
pn.call(a,c)&&M(l,f)&&(f!==nn||c in a)||(a[c]=f)}}return r}function N(n){return O(function(t,r){var e=-1,u=r.length,o=1<u?r[u-1]:nn,o=3<n.length&&typeof o=="function"?(u--,o):nn;for(t=Object(t);++e<u;){var i=r[e];i&&n(t,i,e,o)}return t})}function S(n){return function(){var t=arguments,r=dn(n.prototype),t=n.apply(r,t);return H(t)?t:r}}function T(n,t,r){function e(){for(var o=-1,i=arguments.length,c=-1,f=r.length,a=Array(f+i),l=this&&this!==on&&this instanceof e?u:n;++c<f;)a[c]=r[c];for(;i--;)a[c++]=arguments[++o];
return l.apply(t,a)}if(typeof n!="function")throw new TypeError("Expected a function");var u=S(n);return e}function F(n,t,r,e,u,o){var i=n.length,c=t.length;if(i!=c&&!(2&u&&c>i))return false;for(var c=-1,f=true,a=1&u?[]:nn;++c<i;){var l=n[c],p=t[c];if(void 0!==nn){f=false;break}if(a){if(!E(t,function(n,t){if(!z(a,t)&&(l===n||r(l,n,e,u,o)))return a.push(t)})){f=false;break}}else if(l!==p&&!r(l,p,e,u,o)){f=false;break}}return f}function B(n,t,r,e,u,o){var i=2&u,c=qn(n),f=c.length,a=qn(t).length;if(f!=a&&!i)return false;
for(var l=f;l--;){var p=c[l];if(!(i?p in t:pn.call(t,p)))return false}for(a=true;++l<f;){var p=c[l],s=n[p],h=t[p];if(void 0!==nn||s!==h&&!r(s,h,e,u,o)){a=false;break}i||(i="constructor"==p)}return a&&!i&&(r=n.constructor,e=t.constructor,r!=e&&"constructor"in n&&"constructor"in t&&!(typeof r=="function"&&r instanceof r&&typeof e=="function"&&e instanceof e)&&(a=false)),a}function R(n){return Sn(n)||P(n)}function D(n){var t=[];if(null!=n)for(var r in Object(n))t.push(r);return t}function I(n,t,r){return t=jn(t===nn?n.length-1:t,0),
function(){for(var e=arguments,u=-1,o=jn(e.length-t,0),i=Array(o);++u<o;)i[u]=e[t+u];for(u=-1,o=Array(t+1);++u<t;)o[u]=e[u];return o[t]=r(i),n.apply(this,o)}}function q(n){return n&&n.length?p(n,1):[]}function $(n){return n&&n.length?n[0]:nn}function z(n,t,r){var e=n?n.length:0;r=typeof r=="number"?0>r?jn(e+r,0):r:0,r=(r||0)-1;for(var u=t===t;++r<e;){var o=n[r];if(u?o===t:o!==o)return r}return-1}function C(n,t){return mn(n,g(t))}function G(n,t,e){return r(n,g(t),e,3>arguments.length,mn)}function J(n,t){
var r;if(typeof t!="function")throw new TypeError("Expected a function");return n=Tn(n),function(){return 0<--n&&(r=t.apply(this,arguments)),1>=n&&(t=nn),r}}function M(n,t){return n===t||n!==n&&t!==t}function P(n){return K(n)&&U(n)&&pn.call(n,"callee")&&(!bn.call(n,"callee")||"[object Arguments]"==hn.call(n))}function U(n){var t;return(t=null!=n)&&(t=n.length,t=typeof t=="number"&&-1<t&&0==t%1&&9007199254740991>=t),t&&!V(n)}function V(n){return n=H(n)?hn.call(n):"","[object Function]"==n||"[object GeneratorFunction]"==n;
}function H(n){var t=typeof n;return null!=n&&("object"==t||"function"==t)}function K(n){return null!=n&&typeof n=="object"}function L(n){return typeof n=="number"||K(n)&&"[object Number]"==hn.call(n)}function Q(n){return typeof n=="string"||!Sn(n)&&K(n)&&"[object String]"==hn.call(n)}function W(n){return typeof n=="string"?n:null==n?"":n+""}function X(n){return n?e(n,qn(n)):[]}function Y(n){return n}function Z(t,r,e){var u=qn(r),o=h(r,u);null!=e||H(r)&&(o.length||!u.length)||(e=r,r=t,t=this,o=h(r,qn(r)));
var i=!(H(e)&&"chain"in e&&!e.chain),c=V(t);return mn(o,function(e){var u=r[e];t[e]=u,c&&(t.prototype[e]=function(){var r=this.__chain__;if(i||r){var e=t(this.__wrapped__);return(e.__actions__=A(this.__actions__)).push({func:u,args:arguments,thisArg:t}),e.__chain__=r,e}return u.apply(t,n([this.value()],arguments))})}),t}var nn,tn=1/0,rn=/[&<>"']/g,en=RegExp(rn.source),un=typeof self=="object"&&self&&self.Object===Object&&self,on=typeof global=="object"&&global&&global.Object===Object&&global||un||Function("return this")(),cn=(un=typeof exports=="object"&&exports&&!exports.nodeType&&exports)&&typeof module=="object"&&module&&!module.nodeType&&module,fn=function(n){
return function(t){return null==n?nn:n[t]}}({"&":"&","<":"<",">":">",'"':""","'":"'"}),an=Array.prototype,ln=Object.prototype,pn=ln.hasOwnProperty,sn=0,hn=ln.toString,vn=on._,yn=Object.create,bn=ln.propertyIsEnumerable,gn=on.isFinite,_n=function(n,t){return function(r){return n(t(r))}}(Object.keys,Object),jn=Math.max,dn=function(){function n(){}return function(t){return H(t)?yn?yn(t):(n.prototype=prototype,t=new n,n.prototype=nn,t):{}}}();o.prototype=dn(u.prototype),o.prototype.constructor=o;
var mn=function(n,t){return function(r,e){if(null==r)return r;if(!U(r))return n(r,e);for(var u=r.length,o=t?u:-1,i=Object(r);(t?o--:++o<u)&&false!==e(i[o],o,i););return r}}(s),On=function(n){return function(t,r,e){var u=-1,o=Object(t);e=e(t);for(var i=e.length;i--;){var c=e[n?i:++u];if(false===r(o[c],c,o))break}return t}}(),xn=Y,An=String,En=function(n){return function(t,r,e){var u=Object(t);if(!U(t)){var o=g(r);t=qn(t),r=function(n){return o(u[n],n,u)}}return r=n(t,r,e),-1<r?u[o?t[r]:r]:nn}}(function(n,t,r){
var e=n?n.length:0;if(!e)return-1;r=null==r?0:Tn(r),0>r&&(r=jn(e+r,0));n:{for(t=g(t),e=n.length,r+=-1;++r<e;)if(t(n[r],r,n)){n=r;break n}n=-1}return n}),wn=O(function(n,t,r){return T(n,t,r)}),kn=O(function(n,t){return c(n,1,t)}),Nn=O(function(n,t,r){return c(n,Fn(t)||0,r)}),Sn=Array.isArray,Tn=Number,Fn=Number,Bn=N(function(n,t){k(t,_n(t),n)}),Rn=N(function(n,t){k(t,D(t),n)}),Dn=N(function(n,t,r,e){k(t,$n(t),n,e)}),In=O(function(n){return n.push(nn,i),Dn.apply(nn,n)}),qn=_n,$n=D,zn=function(n){return xn(I(n,nn,q),n+"");
}(function(n,t){return null==n?{}:m(n,j(t,An))});u.assignIn=Rn,u.before=J,u.bind=wn,u.chain=function(n){return n=u(n),n.__chain__=true,n},u.compact=function(n){return l(n,Boolean)},u.concat=function(){var t=arguments.length;if(!t)return[];for(var r=Array(t-1),e=arguments[0];t--;)r[t-1]=arguments[t];return n(Sn(e)?A(e):[e],p(r,1))},u.create=function(n,t){var r=dn(n);return t?Bn(r,t):r},u.defaults=In,u.defer=kn,u.delay=Nn,u.filter=function(n,t){return l(n,g(t))},u.flatten=q,u.flattenDeep=function(n){
return n&&n.length?p(n,tn):[]},u.iteratee=g,u.keys=qn,u.map=function(n,t){return j(n,g(t))},u.matches=function(n){return d(Bn({},n))},u.mixin=Z,u.negate=function(n){if(typeof n!="function")throw new TypeError("Expected a function");return function(){return!n.apply(this,arguments)}},u.once=function(n){return J(2,n)},u.pick=zn,u.slice=function(n,t,r){var e=n?n.length:0;return r=r===nn?e:+r,e?x(n,null==t?0:+t,r):[]},u.sortBy=function(n,r){var e=0;return r=g(r),j(j(n,function(n,t,u){return{value:n,index:e++,
criteria:r(n,t,u)}}).sort(function(n,t){var r;n:{r=n.criteria;var e=t.criteria;if(r!==e){var u=r!==nn,o=null===r,i=r===r,c=e!==nn,f=null===e,a=e===e;if(!f&&r>e||o&&c&&a||!u&&a||!i){r=1;break n}if(!o&&r<e||f&&u&&i||!c&&i||!a){r=-1;break n}}r=0}return r||n.index-t.index}),t("value"))},u.tap=function(n,t){return t(n),n},u.thru=function(n,t){return t(n)},u.toArray=function(n){return U(n)?n.length?A(n):[]:X(n)},u.values=X,u.extend=Rn,Z(u,u),u.clone=function(n){return H(n)?Sn(n)?A(n):k(n,_n(n)):n},u.escape=function(n){
return(n=W(n))&&en.test(n)?n.replace(rn,fn):n},u.every=function(n,t,r){return t=r?nn:t,f(n,g(t))},u.find=En,u.forEach=C,u.has=function(n,t){return null!=n&&pn.call(n,t)},u.head=$,u.identity=Y,u.indexOf=z,u.isArguments=P,u.isArray=Sn,u.isBoolean=function(n){return true===n||false===n||K(n)&&"[object Boolean]"==hn.call(n)},u.isDate=function(n){return K(n)&&"[object Date]"==hn.call(n)},u.isEmpty=function(n){return U(n)&&(Sn(n)||Q(n)||V(n.splice)||P(n))?!n.length:!_n(n).length},u.isEqual=function(n,t){return y(n,t);
},u.isFinite=function(n){return typeof n=="number"&&gn(n)},u.isFunction=V,u.isNaN=function(n){return L(n)&&n!=+n},u.isNull=function(n){return null===n},u.isNumber=L,u.isObject=H,u.isRegExp=function(n){return H(n)&&"[object RegExp]"==hn.call(n)},u.isString=Q,u.isUndefined=function(n){return n===nn},u.last=function(n){var t=n?n.length:0;return t?n[t-1]:nn},u.max=function(n){return n&&n.length?a(n,Y,v):nn},u.min=function(n){return n&&n.length?a(n,Y,_):nn},u.noConflict=function(){return on._===this&&(on._=vn),
this},u.noop=function(){},u.reduce=G,u.result=function(n,t,r){return t=null==n?nn:n[t],t===nn&&(t=r),V(t)?t.call(n):t},u.size=function(n){return null==n?0:(n=U(n)?n:_n(n),n.length)},u.some=function(n,t,r){return t=r?nn:t,E(n,g(t))},u.uniqueId=function(n){var t=++sn;return W(n)+t},u.each=C,u.first=$,Z(u,function(){var n={};return s(u,function(t,r){pn.call(u.prototype,r)||(n[r]=t)}),n}(),{chain:false}),u.VERSION="4.16.2",mn("pop join replace reverse split push shift sort splice unshift".split(" "),function(n){
var t=(/^(?:replace|split)$/.test(n)?String.prototype:an)[n],r=/^(?:push|sort|unshift)$/.test(n)?"tap":"thru",e=/^(?:pop|join|replace|shift)$/.test(n);u.prototype[n]=function(){var n=arguments;if(e&&!this.__chain__){var u=this.value();return t.apply(Sn(u)?u:[],n)}return this[r](function(r){return t.apply(Sn(r)?r:[],n)})}}),u.prototype.toJSON=u.prototype.valueOf=u.prototype.value=function(){return w(this.__wrapped__,this.__actions__)},typeof define=="function"&&typeof define.amd=="object"&&define.amd?(on._=u,
define(function(){return u})):cn?((cn.exports=u)._=u,un._=u):on._=u}).call(this); |
/*! Qoopido.js library 3.7.1, 2015-07-25 | https://github.com/dlueth/qoopido.js | (c) 2015 Dirk Lueth */
!function(e){window.qoopido.register("polyfill/window/customevent",e)}(function(e,t,n,o,r,u,b){"use strict";if(!r.CustomEvent){var c=u.createEvent?function(e,t,n){var o=u.createEvent("Event"),r=t&&t.bubbles!==b?t.bubbles:!1,c=t&&t.cancelable!==b?t.cancelable:!0;return o.initEvent(e,r,c),o.detail=n,o}:function(e,t,n){var o=u.createEventObject();return o.type=e,o.bubbles=t&&t.bubbles!==b?t.bubbles:!1,o.cancelable=t&&t.cancelable!==b?t.cancelable:!0,o.detail=n,o};r.CustomEvent=Window.prototype.CustomEvent=function(e,t,n){if(!e)throw new Error("Not enough arguments");return c(e,t,n)}}return r.CustomEvent}); |
/**
* @license jCanvas Hearts v13.12.20
* Copyright 2013 Caleb Evans
* Released under the MIT license
*/(function(e){var t="jCanvas",n=!0,r=Math.PI;e[t].extend({name:"drawHeart",type:"heart",props:{size:0},fn:function(i,s){var o=this,u=s.size,a=.75,f=u*a,l=r*a*(1-a),c,h;e[t].transformShape(o,i,s,u,f);c=s.x;h=s.y+u/8;i.beginPath();i.moveTo(c,h+f/2);i.arc(c+u/4,h-f/2,u/4,l,r,n);i.arc(c-u/4,h-f/2,u/4,0,r-l,n);s.closed=n;e[t].detectEvents(o,i,s);e[t].closePath(o,i,s)}})})(jQuery); |
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails react-core
*/
'use strict';
var React;
var ReactTransitionChildMapping;
describe('ReactTransitionChildMapping', function() {
beforeEach(function() {
React = require('React');
ReactTransitionChildMapping = require('ReactTransitionChildMapping');
});
it('should support getChildMapping', function() {
var oneone = <div key="oneone" />;
var onetwo = <div key="onetwo" />;
var one = <div key="one">{oneone}{onetwo}</div>;
var two = <div key="two" />;
var component = <div>{one}{two}</div>;
expect(
ReactTransitionChildMapping.getChildMapping(component.props.children)
).toEqual({
'.$one': one,
'.$two': two
});
});
it('should support mergeChildMappings for adding keys', function() {
var prev = {
one: true,
two: true
};
var next = {
one: true,
two: true,
three: true
};
expect(ReactTransitionChildMapping.mergeChildMappings(prev, next)).toEqual({
one: true,
two: true,
three: true
});
});
it('should support mergeChildMappings for removing keys', function() {
var prev = {
one: true,
two: true,
three: true
};
var next = {
one: true,
two: true
};
expect(ReactTransitionChildMapping.mergeChildMappings(prev, next)).toEqual({
one: true,
two: true,
three: true
});
});
it('should support mergeChildMappings for adding and removing', function() {
var prev = {
one: true,
two: true,
three: true
};
var next = {
one: true,
two: true,
four: true
};
expect(ReactTransitionChildMapping.mergeChildMappings(prev, next)).toEqual({
one: true,
two: true,
three: true,
four: true
});
});
it('should reconcile overlapping insertions and deletions', function() {
var prev = {
one: true,
two: true,
four: true,
five: true
};
var next = {
one: true,
two: true,
three: true,
five: true
};
expect(ReactTransitionChildMapping.mergeChildMappings(prev, next)).toEqual({
one: true,
two: true,
three: true,
four: true,
five: true
});
});
it('should support mergeChildMappings with undefined input', function() {
var prev = {
one: true,
two: true
};
var next = undefined;
expect(ReactTransitionChildMapping.mergeChildMappings(prev, next)).toEqual({
one: true,
two: true
});
prev = undefined;
next = {
three: true,
four: true
};
expect(ReactTransitionChildMapping.mergeChildMappings(prev, next)).toEqual({
three: true,
four: true
});
});
});
|
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var ExternalModuleFactoryPlugin = require("./ExternalModuleFactoryPlugin");
function ExternalsPlugin(type, externals) {
this.type = type;
this.externals = externals;
}
module.exports = ExternalsPlugin;
ExternalsPlugin.prototype.apply = function(compiler) {
compiler.plugin("compile", function(params) {
params.normalModuleFactory.apply(new ExternalModuleFactoryPlugin(this.type, this.externals));
}.bind(this));
};
|
/*
Copyright (c) 2004-2011, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
//>>built
define("dojo/_base/xhr",["./kernel","./sniff","require","../io-query","../dom","../dom-form","./Deferred","./config","./json","./lang","./array","../on","../aspect","../request/watch","../request/xhr","../request/util"],function(_1,_2,_3,_4,_5,_6,_7,_8,_9,_a,_b,on,_c,_d,_e,_f){
_1._xhrObj=_e._create;
var cfg=_1.config;
_1.objectToQuery=_4.objectToQuery;
_1.queryToObject=_4.queryToObject;
_1.fieldToObject=_6.fieldToObject;
_1.formToObject=_6.toObject;
_1.formToQuery=_6.toQuery;
_1.formToJson=_6.toJson;
_1._blockAsync=false;
var _10=_1._contentHandlers=_1.contentHandlers={"text":function(xhr){
return xhr.responseText;
},"json":function(xhr){
return _9.fromJson(xhr.responseText||null);
},"json-comment-filtered":function(xhr){
if(!_8.useCommentedJson){
console.warn("Consider using the standard mimetype:application/json."+" json-commenting can introduce security issues. To"+" decrease the chances of hijacking, use the standard the 'json' handler and"+" prefix your json with: {}&&\n"+"Use djConfig.useCommentedJson=true to turn off this message.");
}
var _11=xhr.responseText;
var _12=_11.indexOf("/*");
var _13=_11.lastIndexOf("*/");
if(_12==-1||_13==-1){
throw new Error("JSON was not comment filtered");
}
return _9.fromJson(_11.substring(_12+2,_13));
},"javascript":function(xhr){
return _1.eval(xhr.responseText);
},"xml":function(xhr){
var _14=xhr.responseXML;
if(_14&&_2("dom-qsa2.1")&&!_14.querySelectorAll&&_2("dom-parser")){
_14=new DOMParser().parseFromString(xhr.responseText,"application/xml");
}
if(_2("ie")){
if((!_14||!_14.documentElement)){
var ms=function(n){
return "MSXML"+n+".DOMDocument";
};
var dp=["Microsoft.XMLDOM",ms(6),ms(4),ms(3),ms(2)];
_b.some(dp,function(p){
try{
var dom=new ActiveXObject(p);
dom.async=false;
dom.loadXML(xhr.responseText);
_14=dom;
}
catch(e){
return false;
}
return true;
});
}
}
return _14;
},"json-comment-optional":function(xhr){
if(xhr.responseText&&/^[^{\[]*\/\*/.test(xhr.responseText)){
return _10["json-comment-filtered"](xhr);
}else{
return _10["json"](xhr);
}
}};
_1._ioSetArgs=function(_15,_16,_17,_18){
var _19={args:_15,url:_15.url};
var _1a=null;
if(_15.form){
var _1b=_5.byId(_15.form);
var _1c=_1b.getAttributeNode("action");
_19.url=_19.url||(_1c?_1c.value:(_1.doc?_1.doc.URL:null));
_1a=_6.toObject(_1b);
}
var _1d=[{}];
if(_1a){
_1d.push(_1a);
}
if(_15.content){
_1d.push(_15.content);
}
if(_15.preventCache){
_1d.push({"dojo.preventCache":new Date().valueOf()});
}
_19.query=_4.objectToQuery(_a.mixin.apply(null,_1d));
_19.handleAs=_15.handleAs||"text";
var d=new _7(function(dfd){
dfd.canceled=true;
_16&&_16(dfd);
var err=dfd.ioArgs.error;
if(!err){
err=new Error("request cancelled");
err.dojoType="cancel";
dfd.ioArgs.error=err;
}
return err;
});
d.addCallback(_17);
var ld=_15.load;
if(ld&&_a.isFunction(ld)){
d.addCallback(function(_1e){
return ld.call(_15,_1e,_19);
});
}
var err=_15.error;
if(err&&_a.isFunction(err)){
d.addErrback(function(_1f){
return err.call(_15,_1f,_19);
});
}
var _20=_15.handle;
if(_20&&_a.isFunction(_20)){
d.addBoth(function(_21){
return _20.call(_15,_21,_19);
});
}
d.addErrback(function(_22){
return _18(_22,d);
});
if(cfg.ioPublish&&_1.publish&&_19.args.ioPublish!==false){
d.addCallbacks(function(res){
_1.publish("/dojo/io/load",[d,res]);
return res;
},function(res){
_1.publish("/dojo/io/error",[d,res]);
return res;
});
d.addBoth(function(res){
_1.publish("/dojo/io/done",[d,res]);
return res;
});
}
d.ioArgs=_19;
return d;
};
var _23=function(dfd){
var ret=_10[dfd.ioArgs.handleAs](dfd.ioArgs.xhr);
return ret===undefined?null:ret;
};
var _24=function(_25,dfd){
if(!dfd.ioArgs.args.failOk){
console.error(_25);
}
return _25;
};
var _26=function(dfd){
if(_27<=0){
_27=0;
if(cfg.ioPublish&&_1.publish&&(!dfd||dfd&&dfd.ioArgs.args.ioPublish!==false)){
_1.publish("/dojo/io/stop");
}
}
};
var _27=0;
_c.after(_d,"_onAction",function(){
_27-=1;
});
_c.after(_d,"_onInFlight",_26);
_1._ioCancelAll=_d.cancelAll;
_1._ioNotifyStart=function(dfd){
if(cfg.ioPublish&&_1.publish&&dfd.ioArgs.args.ioPublish!==false){
if(!_27){
_1.publish("/dojo/io/start");
}
_27+=1;
_1.publish("/dojo/io/send",[dfd]);
}
};
_1._ioWatch=function(dfd,_28,_29,_2a){
var _2b=dfd.ioArgs.options=dfd.ioArgs.args;
_a.mixin(dfd,{response:dfd.ioArgs,isValid:function(_2c){
return _28(dfd);
},isReady:function(_2d){
return _29(dfd);
},handleResponse:function(_2e){
return _2a(dfd);
}});
_d(dfd);
_26(dfd);
};
var _2f="application/x-www-form-urlencoded";
_1._ioAddQueryToUrl=function(_30){
if(_30.query.length){
_30.url+=(_30.url.indexOf("?")==-1?"?":"&")+_30.query;
_30.query=null;
}
};
_1.xhr=function(_31,_32,_33){
var _34;
var dfd=_1._ioSetArgs(_32,function(dfd){
_34&&_34.cancel();
},_23,_24);
var _35=dfd.ioArgs;
if("postData" in _32){
_35.query=_32.postData;
}else{
if("putData" in _32){
_35.query=_32.putData;
}else{
if("rawBody" in _32){
_35.query=_32.rawBody;
}else{
if((arguments.length>2&&!_33)||"POST|PUT".indexOf(_31.toUpperCase())===-1){
_1._ioAddQueryToUrl(_35);
}
}
}
}
var _36={method:_31,handleAs:"text",timeout:_32.timeout,withCredentials:_32.withCredentials,ioArgs:_35};
if(typeof _32.headers!=="undefined"){
_36.headers=_32.headers;
}
if(typeof _32.contentType!=="undefined"){
if(!_36.headers){
_36.headers={};
}
_36.headers["Content-Type"]=_32.contentType;
}
if(typeof _35.query!=="undefined"){
_36.data=_35.query;
}
if(typeof _32.sync!=="undefined"){
_36.sync=_32.sync;
}
_1._ioNotifyStart(dfd);
try{
_34=_e(_35.url,_36,true);
}
catch(e){
dfd.cancel();
return dfd;
}
dfd.ioArgs.xhr=_34.response.xhr;
_34.then(function(){
dfd.resolve(dfd);
}).otherwise(function(_37){
_35.error=_37;
if(_37.response){
_37.status=_37.response.status;
_37.responseText=_37.response.text;
_37.xhr=_37.response.xhr;
}
dfd.reject(_37);
});
return dfd;
};
_1.xhrGet=function(_38){
return _1.xhr("GET",_38);
};
_1.rawXhrPost=_1.xhrPost=function(_39){
return _1.xhr("POST",_39,true);
};
_1.rawXhrPut=_1.xhrPut=function(_3a){
return _1.xhr("PUT",_3a,true);
};
_1.xhrDelete=function(_3b){
return _1.xhr("DELETE",_3b);
};
_1._isDocumentOk=function(x){
return _f.checkStatus(x.status);
};
_1._getText=function(url){
var _3c;
_1.xhrGet({url:url,sync:true,load:function(_3d){
_3c=_3d;
}});
return _3c;
};
_a.mixin(_1.xhr,{_xhrObj:_1._xhrObj,fieldToObject:_6.fieldToObject,formToObject:_6.toObject,objectToQuery:_4.objectToQuery,formToQuery:_6.toQuery,formToJson:_6.toJson,queryToObject:_4.queryToObject,contentHandlers:_10,_ioSetArgs:_1._ioSetArgs,_ioCancelAll:_1._ioCancelAll,_ioNotifyStart:_1._ioNotifyStart,_ioWatch:_1._ioWatch,_ioAddQueryToUrl:_1._ioAddQueryToUrl,_isDocumentOk:_1._isDocumentOk,_getText:_1._getText,get:_1.xhrGet,post:_1.xhrPost,put:_1.xhrPut,del:_1.xhrDelete});
return _1.xhr;
});
|
const
TEMPLATE_REGEX = /<msg>([^<]+)<\/msg>/g,
SINGLE_QUOTE_REGEX = /translate\('([^']+)'\)/g,
DOUBLE_QUOTE_REGEX = /translate\("([^"]+)"\)/g;
class FS_Transformer_Translator extends FS_Transformer {
fetchTranslations(messages, callback) {
var hashmap = { };
if (messages.length === 0) {
return void callback(null, hashmap);
}
if (this.isDefaultLanguage()) {
messages.forEach(function each(message) {
hashmap[message] = message;
});
return void callback(null, hashmap);
}
var hashes = [ ];
messages.forEach(function each(message) {
var hash = Utility_KeyGenerator.hash(message);
hashes.push(hash);
hashmap[hash] = message;
});
var query = 'SELECT * FROM translations WHERE language = ? AND md5_hash IN ("';
query += hashes.join('", "') + '")';
var language = this.getLanguage();
SQL.query(query, [language], function handler(error, translations) {
if (error) {
return void callback(error);
}
var result = { };
translations.forEach(function each(translation) {
result[hashmap[translation.md5_hash]] = translation.value;
});
return void callback(null, result);
});
}
translateTemplate(content, callback) {
var
translation_map = { },
messages = [ ];
content = content.replace(TEMPLATE_REGEX, function replacer(match, text) {
var hash = Utility_KeyGenerator.hash(text);
translation_map[text] = hash;
messages.push(text);
return hash;
});
this.fetchTranslations(messages, function handler(error, translations) {
if (error) {
return void callback(error);
}
var
key,
hash;
for (key in translation_map) {
hash = translation_map[key];
content = content.replace(hash, translations[key] || key);
}
return void callback(null, content);
});
}
translateMap(map, language, callback) {
var
messages = [ ],
key,
value;
for (key in map) {
value = map[key];
if (typeof value !== 'string') {
continue;
}
messages.push(value);
}
this.fetchTranslations(messages, language, function handler(error, translations) {
if (error) {
return void callback(error);
}
var
key,
result = { },
message;
for (key in map) {
message = map[key];
result[key] = translations[message] || message;
}
callback(null, result);
});
}
trim(text) {
return text.replace(/\s+/g, ' ');
}
hashAndStoreTranslatableMessage(message) {
var hash = Utility_KeyGenerator.hash(message);
this.getTranslationMap()[message] = hash;
this.getMessagesToTranslate().push(message);
return hash;
}
replaceSingleQuotes(match, text) {
text = this.trim(text);
if (this.isDefaultLanguage()) {
return "'" + text + "'";
}
var hash = this.hashAndStoreTranslatableMessage(text);
return "'" + hash + "'";
}
replaceDoubleQuotes(match, text) {
text = this.trim(text);
if (this.isDefaultLanguage()) {
return '"' + text + '"';
}
var hash = this.hashAndStoreTranslatableMessage(text);
return '"' + hash + '"';
}
getTranslationMap() {
if (!this.translation_map) {
this.translation_map = [ ];
}
return this.translation_map;
}
getMessagesToTranslate() {
if (!this.messages_to_translate) {
this.messages_to_translate = [ ];
}
return this.messages_to_translate;
}
transform(content, callback) {
content = content.replace(
SINGLE_QUOTE_REGEX,
this.replaceSingleQuotes.bind(this)
);
content = content.replace(
DOUBLE_QUOTE_REGEX,
this.replaceDoubleQuotes.bind(this)
);
if (this.isDefaultLanguage()) {
return void callback(null, content);
}
function handler(error, translations) {
if (error) {
return void callback(error);
}
var translation_map = this.getTranslationMap();
ObjectHelper.each(translation_map, function each(key, hash) {
content = content.replace(hash, translations[key] || key);
});
return void callback(null, content);
}
this.fetchTranslations(
this.getMessagesToTranslate(),
handler.bind(this)
);
}
}
ObjectHelper.extend(FS_Transformer_Translator.prototype, {
translation_map: null,
messages_to_translate: null
});
module.exports = FS_Transformer_Translator;
|
import mod277 from './mod277';
var value=mod277+1;
export default value;
|
describe('virtualization', function() {
before(function() {
document.styleSheets[0].insertRule('frypan { display: block; width: 300px; height: 200px; overflow: auto }', 1);
})
after(function() {
document.styleSheets[0].deleteRule(1)
})
beforeEach(function() {
addFruits(100)
})
it('should not virtualize when the frypan element does not scroll', function() {
document.styleSheets[0].deleteRule(1)
testSetup('data: data', { data: fruits })
getComputedStyle(testEl.querySelector('thead')).position.should.equal('static')
testEl.should.not.have.class('frypan-virtualized')
testEl.querySelector('tbody:not(.frypan-top-spacer):not(.frypan-bottom-spacer)').offsetHeight.should.be.above(1000)
document.styleSheets[0].insertRule('frypan { display: block; width: 300px; height: 200px; overflow: auto }', 1);
})
it('should float the header', function() {
testSetup('data: data', { data: fruits })
var style = getComputedStyle(testEl.querySelector('thead'))
style.position.should.equal('absolute')
style.left.should.equal('0px')
style.top.should.equal('0px')
testEl.should.have.class('frypan-virtualized')
})
it('should adjust the header when the user scrolls horizontally', function() {
clock.restore()
clock = null
fruits.forEach(function(fruit) {
fruit.blurb = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.'
})
document.styleSheets[0].insertRule('tbody td, thead th { white-space: nowrap; overflow: hidden; }', 3);
testSetup('data: data', { data: fruits })
var
scrollArea = testEl.querySelector('.frypan-scroll-area'),
thead = testEl.querySelector('thead')
scrollArea.querySelector('table').offsetWidth.should.be.above(300)
scrollArea.scrollLeft = 25
return pollUntilPassing(function() {
thead.offsetLeft.should.be.above(-26).and.below(-24)
}).then(function() {
document.styleSheets[0].deleteRule(3)
})
})
it('should have an initial offset of 0 and top and bottom spacers calculated correctly', function() {
testSetup('data: data', { data: fruits })
var thead = testEl.querySelector('thead')
testEl.querySelector('.frypan-top-spacer').offsetHeight.should.be.above(19).and.below(22)
testEl.querySelector('.frypan-bottom-spacer').offsetHeight.should.be.above(1839).and.below(1842)
})
it('should update the spacers and offset when the user scrolls', function() {
clock.restore()
clock = null
testSetup('data: data', { data: fruits })
var
scrollArea = testEl.querySelector('.frypan-scroll-area'),
topSpacer = testEl.querySelector('.frypan-top-spacer'),
bottomSpacer = testEl.querySelector('.frypan-bottom-spacer')
scrollArea.scrollTop = 171
return pollUntilPassing(function() {
topSpacer.offsetHeight.should.equal(randomOf(180, 181))
bottomSpacer.offsetHeight.should.equal(randomOf(1680, 1681))
}).then(function() {
scrollArea.scrollTop = 320
}).then(function() {
return pollUntilPassing(function() {
[320, 340, 341].some(function(x) { return topSpacer.offsetHeight == x }).should.be.true;
[1520, 1540, 1561].some(function(x) { return bottomSpacer.offsetHeight == x }).should.be.true
})
})
})
it('should add a frypan-odd class to odd index rows', function() {
clock.restore()
clock = null
testSetup('data: data', { data: fruits })
var tbody = testEl.querySelector('tbody:not(.frypan-top-spacer):not(.frypan-bottom-spacer)')
tbody.querySelectorAll('tr.frypan-odd').length.should.equal(5)
tbody.querySelector('tr:first-child').should.not.have.class('frypan-odd')
tbody.querySelector('tr:nth-child(2)').should.have.class('frypan-odd')
// need slice(0,3) for a phantomjs bug
textNodesFor('tr.frypan-odd:nth-child(2) td').slice(0,3).should.deep.equal(['banana', 'true', 'yellow'])
testEl.querySelector('.frypan-scroll-area').scrollTop = 35
return pollUntilPassing(function() {
tbody.querySelector('tr:first-child').should.have.class('frypan-odd')
tbody.querySelector('tr:nth-child(2)').should.not.have.class('frypan-odd')
textNodesFor('tr.frypan-odd:first-child td').should.deep.equal(['banana', 'true', 'yellow'])
})
})
it('should update the bottom spacer when new data comes in', function() {
fruits = ko.observableArray(fruits)
testSetup('data: data', { data: fruits })
var bottomSpacer = testEl.querySelector('.frypan-bottom-spacer')
bottomSpacer.offsetHeight.should.equal(1840)
addFruits(1)
clock.tick(100)
bottomSpacer.offsetHeight.should.equal(1860)
})
function cssWidths(selector) {
return Array.prototype.map.call(testEl.querySelectorAll(selector), function(el) {
var width = parseInt(el.style.width)
width.should.be.above(30)
return width
})
}
it('should update the thead and colgroup widths when dynamic columns change', function() {
fruits = ko.observableArray(fruits)
testSetup('data: data', { data: fruits })
var thWidths = cssWidths('thead th')
thWidths.length.should.equal(3)
cssWidths('colgroup col').should.deep.equal(thWidths)
fruits([{ moon: '--Europa--', planet: '--Jupiter--' }])
var immediateWidths = cssWidths('thead th')
immediateWidths.length.should.equal(2)
immediateWidths[0].should.be.above(35)
immediateWidths[1].should.be.above(40)
cssWidths('colgroup col').should.deep.equal(immediateWidths)
clock.tick(100)
testEl.querySelectorAll('tbody tr').length.should.equal(1)
var afterDataWidths = cssWidths('thead th')
afterDataWidths.length.should.equal(2)
afterDataWidths[0].should.be.above(immediateWidths[0])
afterDataWidths[1].should.be.above(immediateWidths[1])
})
if (window.MutationObserver && window.MutationObserver.toString() === 'function MutationObserver() { [native code] }') {
it('should release widths to let the grid naturally resize when not using resziable columns', function(done) {
clock.restore()
clock = null
testSetup('data: data', { data: fruits })
var widthChanges = 0, tableChanged, doneCalled,
observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.target.tagName === 'TH' && mutation.attributeName === 'style') widthChanges++
if (mutation.target.tagName === 'TABLE' && /px/.test(mutation.target.style.width)) tableChanged = true
if (tableChanged && widthChanges > 4 && !doneCalled) {
doneCalled = true
done()
}
})
})
observer.observe(testEl.querySelector('thead'), {
subtree: true,
attributes: true,
})
observer.observe(testEl.querySelector('table'), { attributes: true })
var evt = document.createEvent('Events')
evt.initEvent('resize', true, true)
window.dispatchEvent(evt)
setTimeout(function() {
observer.disconnect()
}, 3)
})
it('should not naturally resize the grid when using resizable columns', function(done) {
clock.restore()
clock = null
testSetup('data: data, resizableColumns: true', { data: fruits })
var widthChanges = 0
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.target.tagName === 'TH' && mutation.attributeName === 'style') {
clearTimeout(complete)
done(new Error('a <th> width was changed when it should not have'))
}
})
})
observer.observe(testEl.querySelector('thead'), {
subtree: true,
attributes: true,
})
var evt = document.createEvent('Events')
evt.initEvent('resize', true, true)
window.dispatchEvent(evt)
setTimeout(function() {
observer.disconnect()
}, 3)
var complete = setTimeout(function() {
done()
}, 20)
})
}
})
|
"use strict";
var fs = require('fs');
var gulp = require('gulp');
var gulputil = require('gulp-util');
var uglify = require('gulp-uglify');
var rename = require("gulp-rename");
var replace = require("gulp-replace");
var BUILDDIR = './build';
var pkg = JSON.parse(fs.readFileSync('./package.json'));
gulp.task('initialize', function(callback) {
fs.exists(BUILDDIR, function(found) {
if (!found) {
fs.mkdir(BUILDDIR, function(err) {
if (!err) gulputil.log('Build directory created...');
else gulputil.log('Build directory creation error : '+err+'...');
if (typeof(callback) == 'function') callback();
});
}
else {
if (typeof(callback) == 'function') callback();
}
});
});
gulp.task('minify', function(callback) {
return gulp.src('./src/index.js')
.pipe(replace('$_VERSION', pkg['version']))
.pipe(uglify())
.on('error', function (err) { gulputil.log(gutil.colors.red('[Error]'), err.toString()); })
.pipe(rename({basename : 'microgear'}))
.pipe(gulp.dest('./build'));
});
gulp.task('build', ['initialize','minify'], function(callback) {
}); |
#!/usr/bin/env node
const fs = require('fs');
let p_build = process.argv[2];
let s_contents = fs.readFileSync(p_build, 'utf8');
let s_replace = s_contents.replace(/((?:^|\n))[ \t]*(\/\/ [^\n]+)\n([ \t]*)/g,
(s_line, s_pre, s_comment, s_indent) => `${s_pre}${s_indent}${s_comment}\n${s_indent}`);
fs.writeFileSync(p_build, s_replace);
|
// adopted from: deep-assign <https://github.com/sindresorhus/deep-assign>
// Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com) (MIT)
var isObject = require('../lang/isObject')
var hasOwnProperty = Object.prototype.hasOwnProperty
var propEnum = Object.prototype.propertyIsEnumerable
function toObject (val) {
if (val == null) throw new TypeError('Sources cannot be null or undefined.')
return Object(val)
}
function base (to, from) {
if (to === from) return to
from = Object(from)
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
var val = from[key]
if (isArray(val)) to[key] = val.slice()
else if (isObject(val)) to[key] = base(to[key] || {}, val)
else if (val !== undefined) to[key] = val
}
}
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(from)
for (var i = 0; i < symbols.length; i++) {
if (propEnum.call(from, symbols[i])) to[symbols[i]] = from[symbols[i]]
}
}
return to
}
function deepAssign (target) {
target = toObject(target)
var s = 0
while (++s < arguments.length) {
base(target, arguments[s])
}
return target
}
module.exports = deepAssign
|
'use strict';
const Riak = require('basho-riak-client');
const _ = require('lodash');
class Client {
/**
* Creates a new client with config,
* and adds delegated methods
* @param config
*/
constructor(config) {
this.config = _.defaults({}, config.cluster, {
// need to create new copy of config
// riak decides to replace nodes with node objects
nodes: Riak.Node.buildNodes(config.nodes, config.nodeOptions)
});
/**
* The Riak client
* @type {Riak.Client}
*/
this.client = new Riak.Client(new Riak.Cluster(this.config), (err) => {
if (err) {
throw new Error(err);
}
});
// Delegate methods
delegate(this, 'deleteIndex');
delegate(this, 'deleteValue');
delegate(this, 'execute');
delegate(this, 'fetchBucketProps');
delegate(this, 'fetchBucketTypeProps');
delegate(this, 'fetchCounter');
delegate(this, 'fetchIndex');
delegate(this, 'fetchMap');
delegate(this, 'fetchPreflist');
delegate(this, 'fetchSchema');
delegate(this, 'fetchSet');
delegate(this, 'fetchValue');
delegate(this, 'ListBuckets');
delegate(this, 'listKeys');
delegate(this, 'mapReduce');
delegate(this, 'ping');
delegate(this, 'resetBucketProps');
delegate(this, 'search');
delegate(this, 'secondaryIndexQuery');
delegate(this, 'storeBucketProps');
delegate(this, 'storeBucketTypeProps');
delegate(this, 'storeIndex');
delegate(this, 'storeSchema');
delegate(this, 'storeValue');
delegate(this, 'tsDelete');
delegate(this, 'tsDescribe');
delegate(this, 'tsGet');
delegate(this, 'tsListKeys');
delegate(this, 'tsQuery');
delegate(this, 'tsStore');
delegate(this, 'updateCounter');
delegate(this, 'updateMap');
delegate(this, 'updateSet');
}
/**
* Stop the client
*/
stop() {
this._isConnected = false;
this.client.stop();
}
}
module.exports = Client;
/**
* Delegate the function to the client, but
* add a connection check first
*
* @param {Client} client - the sand-riak client
* @param {string} fn - function name
*/
function delegate(client, fn) {
// Add this function to the current client
// and wrap with a connection check
client[fn] = function(...args) {
let self = this;
let p = null;
if (sand.profiler && sand.profiler.enabled) {
// Build the profiler request
let req = `riak ${fn} `;
if (args[0].bucketType) {
req += `types/${args[0].bucketType} `;
}
if (args[0].bucket) {
req += `bucket/${args[0].bucket} `;
}
if (args[0].indexName) {
req += `search/${args[0].indexName} `;
}
if (args[0].q) {
req += `query/${args[0].q.replace(/(\w+):\w+/ig, '$1:*')}`
}
p = sand.profiler.profile(req.trim());
}
return new Promise(function(resolve, reject) {
function returnResult(err, response, data) {
p && p.stop();
if (err) {
err = new Error(err);
err.data = data;
err.req = `${fn}: ${args[0]}`;
sand.riak.error(`${err.message} ${fn}:`, ...args);
return reject(err);
}
resolve(response);
}
client.client[fn](...args, returnResult);
}).catch(sand.error);
};
}
/**
* We check if the client is connected
* and throw error if not
*/
function checkIsConnected() {
if (!this._isConnected) {
throw Error('Could not connect to riak server');
}
} |
/*
* Game Helpers
*
* A collection of useful math and object helpers
*/
window.game = window.game || {};
var __helpers = {
// Convert from polar coordinates to Cartesian coordinates using length and radian
polarToCartesian: function(vectorLength, vectorDirection) {
return {
x: vectorLength * Math.cos(vectorDirection),
y: vectorLength * Math.sin(vectorDirection)
};
},
// Convert radians to degrees (1 radian = 57.3 degrees => PI * radian = 180 degrees)
radToDeg: function(radians) {
return radians * (180 / Math.PI);
},
// Convert degrees to radians
degToRad: function(degrees) {
return degrees * Math.PI / 180;
},
// Generate a random number between a fixedrange
random: function(min, max, round) {
return round ? (Math.floor(Math.random() * (max + 1)) + min) : (Math.random() * max) + min;
},
// Clone an object recursively
cloneObject: function(obj) {
var copy;
if (obj === null || typeof obj !== "object") {
return obj;
}
if (obj instanceof Date) {
copy = new Date();
copy.setTime(obj.getTime());
return copy;
}
if (obj instanceof Array) {
copy = [];
for (var i = 0, len = obj.length; i < len; i++) {
copy[i] = window.game.helpers.cloneObject(obj[i]);
}
return copy;
}
if (obj instanceof Object) {
copy = {};
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) {
copy[attr] = window.game.helpers.cloneObject(obj[attr]);
}
}
return copy;
}
}
};
window.game.helpers = __helpers; |
/**
* @license AngularJS v1.3.15
* (c) 2010-2014 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, document, undefined) {'use strict';
/**
* @description
*
* This object provides a utility for producing rich Error messages within
* Angular. It can be called as follows:
*
* var exampleMinErr = minErr('example');
* throw exampleMinErr('one', 'This {0} is {1}', foo, bar);
*
* The above creates an instance of minErr in the example namespace. The
* resulting error will have a namespaced error code of example.one. The
* resulting error will replace {0} with the value of foo, and {1} with the
* value of bar. The object is not restricted in the number of arguments it can
* take.
*
* If fewer arguments are specified than necessary for interpolation, the extra
* interpolation markers will be preserved in the final string.
*
* Since data will be parsed statically during a build step, some restrictions
* are applied with respect to how minErr instances are created and called.
* Instances should have names of the form namespaceMinErr for a minErr created
* using minErr('namespace') . Error codes, namespaces and template strings
* should all be static strings, not variables or general expressions.
*
* @param {string} module The namespace to use for the new minErr instance.
* @param {function} ErrorConstructor Custom error constructor to be instantiated when returning
* error from returned function, for cases when a particular type of error is useful.
* @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance
*/
function minErr(module, ErrorConstructor) {
ErrorConstructor = ErrorConstructor || Error;
return function() {
var code = arguments[0],
prefix = '[' + (module ? module + ':' : '') + code + '] ',
template = arguments[1],
templateArgs = arguments,
message, i;
message = prefix + template.replace(/\{\d+\}/g, function(match) {
var index = +match.slice(1, -1), arg;
if (index + 2 < templateArgs.length) {
return toDebugString(templateArgs[index + 2]);
}
return match;
});
message = message + '\nhttp://errors.angularjs.org/1.3.15/' +
(module ? module + '/' : '') + code;
for (i = 2; i < arguments.length; i++) {
message = message + (i == 2 ? '?' : '&') + 'p' + (i - 2) + '=' +
encodeURIComponent(toDebugString(arguments[i]));
}
return new ErrorConstructor(message);
};
}
/* We need to tell jshint what variables are being exported */
/* global angular: true,
msie: true,
jqLite: true,
jQuery: true,
slice: true,
splice: true,
push: true,
toString: true,
ngMinErr: true,
angularModule: true,
uid: true,
REGEX_STRING_REGEXP: true,
VALIDITY_STATE_PROPERTY: true,
lowercase: true,
uppercase: true,
manualLowercase: true,
manualUppercase: true,
nodeName_: true,
isArrayLike: true,
forEach: true,
sortedKeys: true,
forEachSorted: true,
reverseParams: true,
nextUid: true,
setHashKey: true,
extend: true,
int: true,
inherit: true,
noop: true,
identity: true,
valueFn: true,
isUndefined: true,
isDefined: true,
isObject: true,
isString: true,
isNumber: true,
isDate: true,
isArray: true,
isFunction: true,
isRegExp: true,
isWindow: true,
isScope: true,
isFile: true,
isFormData: true,
isBlob: true,
isBoolean: true,
isPromiseLike: true,
trim: true,
escapeForRegexp: true,
isElement: true,
makeMap: true,
includes: true,
arrayRemove: true,
copy: true,
shallowCopy: true,
equals: true,
csp: true,
concat: true,
sliceArgs: true,
bind: true,
toJsonReplacer: true,
toJson: true,
fromJson: true,
startingTag: true,
tryDecodeURIComponent: true,
parseKeyValue: true,
toKeyValue: true,
encodeUriSegment: true,
encodeUriQuery: true,
angularInit: true,
bootstrap: true,
getTestability: true,
snake_case: true,
bindJQuery: true,
assertArg: true,
assertArgFn: true,
assertNotHasOwnProperty: true,
getter: true,
getBlockNodes: true,
hasOwnProperty: true,
createMap: true,
NODE_TYPE_ELEMENT: true,
NODE_TYPE_TEXT: true,
NODE_TYPE_COMMENT: true,
NODE_TYPE_DOCUMENT: true,
NODE_TYPE_DOCUMENT_FRAGMENT: true,
*/
////////////////////////////////////
/**
* @ngdoc module
* @name ng
* @module ng
* @description
*
* # ng (core module)
* The ng module is loaded by default when an AngularJS application is started. The module itself
* contains the essential components for an AngularJS application to function. The table below
* lists a high level breakdown of each of the services/factories, filters, directives and testing
* components available within this core module.
*
* <div doc-module-components="ng"></div>
*/
var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/;
// The name of a form control's ValidityState property.
// This is used so that it's possible for internal tests to create mock ValidityStates.
var VALIDITY_STATE_PROPERTY = 'validity';
/**
* @ngdoc function
* @name angular.lowercase
* @module ng
* @kind function
*
* @description Converts the specified string to lowercase.
* @param {string} string String to be converted to lowercase.
* @returns {string} Lowercased string.
*/
var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
var hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* @ngdoc function
* @name angular.uppercase
* @module ng
* @kind function
*
* @description Converts the specified string to uppercase.
* @param {string} string String to be converted to uppercase.
* @returns {string} Uppercased string.
*/
var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
var manualLowercase = function(s) {
/* jshint bitwise: false */
return isString(s)
? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
: s;
};
var manualUppercase = function(s) {
/* jshint bitwise: false */
return isString(s)
? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
: s;
};
// String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
// locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
// with correct but slower alternatives.
if ('i' !== 'I'.toLowerCase()) {
lowercase = manualLowercase;
uppercase = manualUppercase;
}
var
msie, // holds major version number for IE, or NaN if UA is not IE.
jqLite, // delay binding since jQuery could be loaded after us.
jQuery, // delay binding
slice = [].slice,
splice = [].splice,
push = [].push,
toString = Object.prototype.toString,
ngMinErr = minErr('ng'),
/** @name angular */
angular = window.angular || (window.angular = {}),
angularModule,
uid = 0;
/**
* documentMode is an IE-only property
* http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
*/
msie = document.documentMode;
/**
* @private
* @param {*} obj
* @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
* String ...)
*/
function isArrayLike(obj) {
if (obj == null || isWindow(obj)) {
return false;
}
var length = obj.length;
if (obj.nodeType === NODE_TYPE_ELEMENT && length) {
return true;
}
return isString(obj) || isArray(obj) || length === 0 ||
typeof length === 'number' && length > 0 && (length - 1) in obj;
}
/**
* @ngdoc function
* @name angular.forEach
* @module ng
* @kind function
*
* @description
* Invokes the `iterator` function once for each item in `obj` collection, which can be either an
* object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
* is the value of an object property or an array element, `key` is the object property key or
* array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
*
* It is worth noting that `.forEach` does not iterate over inherited properties because it filters
* using the `hasOwnProperty` method.
*
* Unlike ES262's
* [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
* Providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
* return the value provided.
*
```js
var values = {name: 'misko', gender: 'male'};
var log = [];
angular.forEach(values, function(value, key) {
this.push(key + ': ' + value);
}, log);
expect(log).toEqual(['name: misko', 'gender: male']);
```
*
* @param {Object|Array} obj Object to iterate over.
* @param {Function} iterator Iterator function.
* @param {Object=} context Object to become context (`this`) for the iterator function.
* @returns {Object|Array} Reference to `obj`.
*/
function forEach(obj, iterator, context) {
var key, length;
if (obj) {
if (isFunction(obj)) {
for (key in obj) {
// Need to check if hasOwnProperty exists,
// as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
iterator.call(context, obj[key], key, obj);
}
}
} else if (isArray(obj) || isArrayLike(obj)) {
var isPrimitive = typeof obj !== 'object';
for (key = 0, length = obj.length; key < length; key++) {
if (isPrimitive || key in obj) {
iterator.call(context, obj[key], key, obj);
}
}
} else if (obj.forEach && obj.forEach !== forEach) {
obj.forEach(iterator, context, obj);
} else {
for (key in obj) {
if (obj.hasOwnProperty(key)) {
iterator.call(context, obj[key], key, obj);
}
}
}
}
return obj;
}
function sortedKeys(obj) {
return Object.keys(obj).sort();
}
function forEachSorted(obj, iterator, context) {
var keys = sortedKeys(obj);
for (var i = 0; i < keys.length; i++) {
iterator.call(context, obj[keys[i]], keys[i]);
}
return keys;
}
/**
* when using forEach the params are value, key, but it is often useful to have key, value.
* @param {function(string, *)} iteratorFn
* @returns {function(*, string)}
*/
function reverseParams(iteratorFn) {
return function(value, key) { iteratorFn(key, value); };
}
/**
* A consistent way of creating unique IDs in angular.
*
* Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
* we hit number precision issues in JavaScript.
*
* Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
*
* @returns {number} an unique alpha-numeric string
*/
function nextUid() {
return ++uid;
}
/**
* Set or clear the hashkey for an object.
* @param obj object
* @param h the hashkey (!truthy to delete the hashkey)
*/
function setHashKey(obj, h) {
if (h) {
obj.$$hashKey = h;
} else {
delete obj.$$hashKey;
}
}
/**
* @ngdoc function
* @name angular.extend
* @module ng
* @kind function
*
* @description
* Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
* to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
* by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
* Note: Keep in mind that `angular.extend` does not support recursive merge (deep copy).
*
* @param {Object} dst Destination object.
* @param {...Object} src Source object(s).
* @returns {Object} Reference to `dst`.
*/
function extend(dst) {
var h = dst.$$hashKey;
for (var i = 1, ii = arguments.length; i < ii; i++) {
var obj = arguments[i];
if (obj) {
var keys = Object.keys(obj);
for (var j = 0, jj = keys.length; j < jj; j++) {
var key = keys[j];
dst[key] = obj[key];
}
}
}
setHashKey(dst, h);
return dst;
}
function int(str) {
return parseInt(str, 10);
}
function inherit(parent, extra) {
return extend(Object.create(parent), extra);
}
/**
* @ngdoc function
* @name angular.noop
* @module ng
* @kind function
*
* @description
* A function that performs no operations. This function can be useful when writing code in the
* functional style.
```js
function foo(callback) {
var result = calculateResult();
(callback || angular.noop)(result);
}
```
*/
function noop() {}
noop.$inject = [];
/**
* @ngdoc function
* @name angular.identity
* @module ng
* @kind function
*
* @description
* A function that returns its first argument. This function is useful when writing code in the
* functional style.
*
```js
function transformer(transformationFn, value) {
return (transformationFn || angular.identity)(value);
};
```
* @param {*} value to be returned.
* @returns {*} the value passed in.
*/
function identity($) {return $;}
identity.$inject = [];
function valueFn(value) {return function() {return value;};}
/**
* @ngdoc function
* @name angular.isUndefined
* @module ng
* @kind function
*
* @description
* Determines if a reference is undefined.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is undefined.
*/
function isUndefined(value) {return typeof value === 'undefined';}
/**
* @ngdoc function
* @name angular.isDefined
* @module ng
* @kind function
*
* @description
* Determines if a reference is defined.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is defined.
*/
function isDefined(value) {return typeof value !== 'undefined';}
/**
* @ngdoc function
* @name angular.isObject
* @module ng
* @kind function
*
* @description
* Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
* considered to be objects. Note that JavaScript arrays are objects.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is an `Object` but not `null`.
*/
function isObject(value) {
// http://jsperf.com/isobject4
return value !== null && typeof value === 'object';
}
/**
* @ngdoc function
* @name angular.isString
* @module ng
* @kind function
*
* @description
* Determines if a reference is a `String`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `String`.
*/
function isString(value) {return typeof value === 'string';}
/**
* @ngdoc function
* @name angular.isNumber
* @module ng
* @kind function
*
* @description
* Determines if a reference is a `Number`.
*
* This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
*
* If you wish to exclude these then you can use the native
* [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
* method.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Number`.
*/
function isNumber(value) {return typeof value === 'number';}
/**
* @ngdoc function
* @name angular.isDate
* @module ng
* @kind function
*
* @description
* Determines if a value is a date.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Date`.
*/
function isDate(value) {
return toString.call(value) === '[object Date]';
}
/**
* @ngdoc function
* @name angular.isArray
* @module ng
* @kind function
*
* @description
* Determines if a reference is an `Array`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is an `Array`.
*/
var isArray = Array.isArray;
/**
* @ngdoc function
* @name angular.isFunction
* @module ng
* @kind function
*
* @description
* Determines if a reference is a `Function`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Function`.
*/
function isFunction(value) {return typeof value === 'function';}
/**
* Determines if a value is a regular expression object.
*
* @private
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `RegExp`.
*/
function isRegExp(value) {
return toString.call(value) === '[object RegExp]';
}
/**
* Checks if `obj` is a window object.
*
* @private
* @param {*} obj Object to check
* @returns {boolean} True if `obj` is a window obj.
*/
function isWindow(obj) {
return obj && obj.window === obj;
}
function isScope(obj) {
return obj && obj.$evalAsync && obj.$watch;
}
function isFile(obj) {
return toString.call(obj) === '[object File]';
}
function isFormData(obj) {
return toString.call(obj) === '[object FormData]';
}
function isBlob(obj) {
return toString.call(obj) === '[object Blob]';
}
function isBoolean(value) {
return typeof value === 'boolean';
}
function isPromiseLike(obj) {
return obj && isFunction(obj.then);
}
var trim = function(value) {
return isString(value) ? value.trim() : value;
};
// Copied from:
// http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
// Prereq: s is a string.
var escapeForRegexp = function(s) {
return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
replace(/\x08/g, '\\x08');
};
/**
* @ngdoc function
* @name angular.isElement
* @module ng
* @kind function
*
* @description
* Determines if a reference is a DOM element (or wrapped jQuery element).
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
*/
function isElement(node) {
return !!(node &&
(node.nodeName // we are a direct element
|| (node.prop && node.attr && node.find))); // we have an on and find method part of jQuery API
}
/**
* @param str 'key1,key2,...'
* @returns {object} in the form of {key1:true, key2:true, ...}
*/
function makeMap(str) {
var obj = {}, items = str.split(","), i;
for (i = 0; i < items.length; i++)
obj[items[i]] = true;
return obj;
}
function nodeName_(element) {
return lowercase(element.nodeName || (element[0] && element[0].nodeName));
}
function includes(array, obj) {
return Array.prototype.indexOf.call(array, obj) != -1;
}
function arrayRemove(array, value) {
var index = array.indexOf(value);
if (index >= 0)
array.splice(index, 1);
return value;
}
/**
* @ngdoc function
* @name angular.copy
* @module ng
* @kind function
*
* @description
* Creates a deep copy of `source`, which should be an object or an array.
*
* * If no destination is supplied, a copy of the object or array is created.
* * If a destination is provided, all of its elements (for arrays) or properties (for objects)
* are deleted and then all elements/properties from the source are copied to it.
* * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
* * If `source` is identical to 'destination' an exception will be thrown.
*
* @param {*} source The source that will be used to make a copy.
* Can be any type, including primitives, `null`, and `undefined`.
* @param {(Object|Array)=} destination Destination into which the source is copied. If
* provided, must be of the same type as `source`.
* @returns {*} The copy or updated `destination`, if `destination` was specified.
*
* @example
<example module="copyExample">
<file name="index.html">
<div ng-controller="ExampleController">
<form novalidate class="simple-form">
Name: <input type="text" ng-model="user.name" /><br />
E-mail: <input type="email" ng-model="user.email" /><br />
Gender: <input type="radio" ng-model="user.gender" value="male" />male
<input type="radio" ng-model="user.gender" value="female" />female<br />
<button ng-click="reset()">RESET</button>
<button ng-click="update(user)">SAVE</button>
</form>
<pre>form = {{user | json}}</pre>
<pre>master = {{master | json}}</pre>
</div>
<script>
angular.module('copyExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.master= {};
$scope.update = function(user) {
// Example with 1 argument
$scope.master= angular.copy(user);
};
$scope.reset = function() {
// Example with 2 arguments
angular.copy($scope.master, $scope.user);
};
$scope.reset();
}]);
</script>
</file>
</example>
*/
function copy(source, destination, stackSource, stackDest) {
if (isWindow(source) || isScope(source)) {
throw ngMinErr('cpws',
"Can't copy! Making copies of Window or Scope instances is not supported.");
}
if (!destination) {
destination = source;
if (source) {
if (isArray(source)) {
destination = copy(source, [], stackSource, stackDest);
} else if (isDate(source)) {
destination = new Date(source.getTime());
} else if (isRegExp(source)) {
destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
destination.lastIndex = source.lastIndex;
} else if (isObject(source)) {
var emptyObject = Object.create(Object.getPrototypeOf(source));
destination = copy(source, emptyObject, stackSource, stackDest);
}
}
} else {
if (source === destination) throw ngMinErr('cpi',
"Can't copy! Source and destination are identical.");
stackSource = stackSource || [];
stackDest = stackDest || [];
if (isObject(source)) {
var index = stackSource.indexOf(source);
if (index !== -1) return stackDest[index];
stackSource.push(source);
stackDest.push(destination);
}
var result;
if (isArray(source)) {
destination.length = 0;
for (var i = 0; i < source.length; i++) {
result = copy(source[i], null, stackSource, stackDest);
if (isObject(source[i])) {
stackSource.push(source[i]);
stackDest.push(result);
}
destination.push(result);
}
} else {
var h = destination.$$hashKey;
if (isArray(destination)) {
destination.length = 0;
} else {
forEach(destination, function(value, key) {
delete destination[key];
});
}
for (var key in source) {
if (source.hasOwnProperty(key)) {
result = copy(source[key], null, stackSource, stackDest);
if (isObject(source[key])) {
stackSource.push(source[key]);
stackDest.push(result);
}
destination[key] = result;
}
}
setHashKey(destination,h);
}
}
return destination;
}
/**
* Creates a shallow copy of an object, an array or a primitive.
*
* Assumes that there are no proto properties for objects.
*/
function shallowCopy(src, dst) {
if (isArray(src)) {
dst = dst || [];
for (var i = 0, ii = src.length; i < ii; i++) {
dst[i] = src[i];
}
} else if (isObject(src)) {
dst = dst || {};
for (var key in src) {
if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
dst[key] = src[key];
}
}
}
return dst || src;
}
/**
* @ngdoc function
* @name angular.equals
* @module ng
* @kind function
*
* @description
* Determines if two objects or two values are equivalent. Supports value types, regular
* expressions, arrays and objects.
*
* Two objects or values are considered equivalent if at least one of the following is true:
*
* * Both objects or values pass `===` comparison.
* * Both objects or values are of the same type and all of their properties are equal by
* comparing them with `angular.equals`.
* * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
* * Both values represent the same regular expression (In JavaScript,
* /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
* representation matches).
*
* During a property comparison, properties of `function` type and properties with names
* that begin with `$` are ignored.
*
* Scope and DOMWindow objects are being compared only by identify (`===`).
*
* @param {*} o1 Object or value to compare.
* @param {*} o2 Object or value to compare.
* @returns {boolean} True if arguments are equal.
*/
function equals(o1, o2) {
if (o1 === o2) return true;
if (o1 === null || o2 === null) return false;
if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
if (t1 == t2) {
if (t1 == 'object') {
if (isArray(o1)) {
if (!isArray(o2)) return false;
if ((length = o1.length) == o2.length) {
for (key = 0; key < length; key++) {
if (!equals(o1[key], o2[key])) return false;
}
return true;
}
} else if (isDate(o1)) {
if (!isDate(o2)) return false;
return equals(o1.getTime(), o2.getTime());
} else if (isRegExp(o1)) {
return isRegExp(o2) ? o1.toString() == o2.toString() : false;
} else {
if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
keySet = {};
for (key in o1) {
if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
if (!equals(o1[key], o2[key])) return false;
keySet[key] = true;
}
for (key in o2) {
if (!keySet.hasOwnProperty(key) &&
key.charAt(0) !== '$' &&
o2[key] !== undefined &&
!isFunction(o2[key])) return false;
}
return true;
}
}
}
return false;
}
var csp = function() {
if (isDefined(csp.isActive_)) return csp.isActive_;
var active = !!(document.querySelector('[ng-csp]') ||
document.querySelector('[data-ng-csp]'));
if (!active) {
try {
/* jshint -W031, -W054 */
new Function('');
/* jshint +W031, +W054 */
} catch (e) {
active = true;
}
}
return (csp.isActive_ = active);
};
function concat(array1, array2, index) {
return array1.concat(slice.call(array2, index));
}
function sliceArgs(args, startIndex) {
return slice.call(args, startIndex || 0);
}
/* jshint -W101 */
/**
* @ngdoc function
* @name angular.bind
* @module ng
* @kind function
*
* @description
* Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
* `fn`). You can supply optional `args` that are prebound to the function. This feature is also
* known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
* distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
*
* @param {Object} self Context which `fn` should be evaluated in.
* @param {function()} fn Function to be bound.
* @param {...*} args Optional arguments to be prebound to the `fn` function call.
* @returns {function()} Function that wraps the `fn` with all the specified bindings.
*/
/* jshint +W101 */
function bind(self, fn) {
var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
if (isFunction(fn) && !(fn instanceof RegExp)) {
return curryArgs.length
? function() {
return arguments.length
? fn.apply(self, concat(curryArgs, arguments, 0))
: fn.apply(self, curryArgs);
}
: function() {
return arguments.length
? fn.apply(self, arguments)
: fn.call(self);
};
} else {
// in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
return fn;
}
}
function toJsonReplacer(key, value) {
var val = value;
if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
val = undefined;
} else if (isWindow(value)) {
val = '$WINDOW';
} else if (value && document === value) {
val = '$DOCUMENT';
} else if (isScope(value)) {
val = '$SCOPE';
}
return val;
}
/**
* @ngdoc function
* @name angular.toJson
* @module ng
* @kind function
*
* @description
* Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
* stripped since angular uses this notation internally.
*
* @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
* @param {boolean|number=} pretty If set to true, the JSON output will contain newlines and whitespace.
* If set to an integer, the JSON output will contain that many spaces per indentation (the default is 2).
* @returns {string|undefined} JSON-ified string representing `obj`.
*/
function toJson(obj, pretty) {
if (typeof obj === 'undefined') return undefined;
if (!isNumber(pretty)) {
pretty = pretty ? 2 : null;
}
return JSON.stringify(obj, toJsonReplacer, pretty);
}
/**
* @ngdoc function
* @name angular.fromJson
* @module ng
* @kind function
*
* @description
* Deserializes a JSON string.
*
* @param {string} json JSON string to deserialize.
* @returns {Object|Array|string|number} Deserialized JSON string.
*/
function fromJson(json) {
return isString(json)
? JSON.parse(json)
: json;
}
/**
* @returns {string} Returns the string representation of the element.
*/
function startingTag(element) {
element = jqLite(element).clone();
try {
// turns out IE does not let you set .html() on elements which
// are not allowed to have children. So we just ignore it.
element.empty();
} catch (e) {}
var elemHtml = jqLite('<div>').append(element).html();
try {
return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
elemHtml.
match(/^(<[^>]+>)/)[1].
replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
} catch (e) {
return lowercase(elemHtml);
}
}
/////////////////////////////////////////////////
/**
* Tries to decode the URI component without throwing an exception.
*
* @private
* @param str value potential URI component to check.
* @returns {boolean} True if `value` can be decoded
* with the decodeURIComponent function.
*/
function tryDecodeURIComponent(value) {
try {
return decodeURIComponent(value);
} catch (e) {
// Ignore any invalid uri component
}
}
/**
* Parses an escaped url query string into key-value pairs.
* @returns {Object.<string,boolean|Array>}
*/
function parseKeyValue(/**string*/keyValue) {
var obj = {}, key_value, key;
forEach((keyValue || "").split('&'), function(keyValue) {
if (keyValue) {
key_value = keyValue.replace(/\+/g,'%20').split('=');
key = tryDecodeURIComponent(key_value[0]);
if (isDefined(key)) {
var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true;
if (!hasOwnProperty.call(obj, key)) {
obj[key] = val;
} else if (isArray(obj[key])) {
obj[key].push(val);
} else {
obj[key] = [obj[key],val];
}
}
}
});
return obj;
}
function toKeyValue(obj) {
var parts = [];
forEach(obj, function(value, key) {
if (isArray(value)) {
forEach(value, function(arrayValue) {
parts.push(encodeUriQuery(key, true) +
(arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
});
} else {
parts.push(encodeUriQuery(key, true) +
(value === true ? '' : '=' + encodeUriQuery(value, true)));
}
});
return parts.length ? parts.join('&') : '';
}
/**
* We need our custom method because encodeURIComponent is too aggressive and doesn't follow
* http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
* segments:
* segment = *pchar
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* pct-encoded = "%" HEXDIG HEXDIG
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriSegment(val) {
return encodeUriQuery(val, true).
replace(/%26/gi, '&').
replace(/%3D/gi, '=').
replace(/%2B/gi, '+');
}
/**
* This method is intended for encoding *key* or *value* parts of query component. We need a custom
* method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
* encoded per http://tools.ietf.org/html/rfc3986:
* query = *( pchar / "/" / "?" )
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* pct-encoded = "%" HEXDIG HEXDIG
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriQuery(val, pctEncodeSpaces) {
return encodeURIComponent(val).
replace(/%40/gi, '@').
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace(/%3B/gi, ';').
replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
}
var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
function getNgAttribute(element, ngAttr) {
var attr, i, ii = ngAttrPrefixes.length;
element = jqLite(element);
for (i = 0; i < ii; ++i) {
attr = ngAttrPrefixes[i] + ngAttr;
if (isString(attr = element.attr(attr))) {
return attr;
}
}
return null;
}
/**
* @ngdoc directive
* @name ngApp
* @module ng
*
* @element ANY
* @param {angular.Module} ngApp an optional application
* {@link angular.module module} name to load.
* @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
* created in "strict-di" mode. This means that the application will fail to invoke functions which
* do not use explicit function annotation (and are thus unsuitable for minification), as described
* in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
* tracking down the root of these bugs.
*
* @description
*
* Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
* designates the **root element** of the application and is typically placed near the root element
* of the page - e.g. on the `<body>` or `<html>` tags.
*
* Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
* found in the document will be used to define the root element to auto-bootstrap as an
* application. To run multiple applications in an HTML document you must manually bootstrap them using
* {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other.
*
* You can specify an **AngularJS module** to be used as the root module for the application. This
* module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
* should contain the application code needed or have dependencies on other modules that will
* contain the code. See {@link angular.module} for more information.
*
* In the example below if the `ngApp` directive were not placed on the `html` element then the
* document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
* would not be resolved to `3`.
*
* `ngApp` is the easiest, and most common way to bootstrap an application.
*
<example module="ngAppDemo">
<file name="index.html">
<div ng-controller="ngAppDemoController">
I can add: {{a}} + {{b}} = {{ a+b }}
</div>
</file>
<file name="script.js">
angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
$scope.a = 1;
$scope.b = 2;
});
</file>
</example>
*
* Using `ngStrictDi`, you would see something like this:
*
<example ng-app-included="true">
<file name="index.html">
<div ng-app="ngAppStrictDemo" ng-strict-di>
<div ng-controller="GoodController1">
I can add: {{a}} + {{b}} = {{ a+b }}
<p>This renders because the controller does not fail to
instantiate, by using explicit annotation style (see
script.js for details)
</p>
</div>
<div ng-controller="GoodController2">
Name: <input ng-model="name"><br />
Hello, {{name}}!
<p>This renders because the controller does not fail to
instantiate, by using explicit annotation style
(see script.js for details)
</p>
</div>
<div ng-controller="BadController">
I can add: {{a}} + {{b}} = {{ a+b }}
<p>The controller could not be instantiated, due to relying
on automatic function annotations (which are disabled in
strict mode). As such, the content of this section is not
interpolated, and there should be an error in your web console.
</p>
</div>
</div>
</file>
<file name="script.js">
angular.module('ngAppStrictDemo', [])
// BadController will fail to instantiate, due to relying on automatic function annotation,
// rather than an explicit annotation
.controller('BadController', function($scope) {
$scope.a = 1;
$scope.b = 2;
})
// Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
// due to using explicit annotations using the array style and $inject property, respectively.
.controller('GoodController1', ['$scope', function($scope) {
$scope.a = 1;
$scope.b = 2;
}])
.controller('GoodController2', GoodController2);
function GoodController2($scope) {
$scope.name = "World";
}
GoodController2.$inject = ['$scope'];
</file>
<file name="style.css">
div[ng-controller] {
margin-bottom: 1em;
-webkit-border-radius: 4px;
border-radius: 4px;
border: 1px solid;
padding: .5em;
}
div[ng-controller^=Good] {
border-color: #d6e9c6;
background-color: #dff0d8;
color: #3c763d;
}
div[ng-controller^=Bad] {
border-color: #ebccd1;
background-color: #f2dede;
color: #a94442;
margin-bottom: 0;
}
</file>
</example>
*/
function angularInit(element, bootstrap) {
var appElement,
module,
config = {};
// The element `element` has priority over any other element
forEach(ngAttrPrefixes, function(prefix) {
var name = prefix + 'app';
if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
appElement = element;
module = element.getAttribute(name);
}
});
forEach(ngAttrPrefixes, function(prefix) {
var name = prefix + 'app';
var candidate;
if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
appElement = candidate;
module = candidate.getAttribute(name);
}
});
if (appElement) {
config.strictDi = getNgAttribute(appElement, "strict-di") !== null;
bootstrap(appElement, module ? [module] : [], config);
}
}
/**
* @ngdoc function
* @name angular.bootstrap
* @module ng
* @description
* Use this function to manually start up angular application.
*
* See: {@link guide/bootstrap Bootstrap}
*
* Note that Protractor based end-to-end tests cannot use this function to bootstrap manually.
* They must use {@link ng.directive:ngApp ngApp}.
*
* Angular will detect if it has been loaded into the browser more than once and only allow the
* first loaded script to be bootstrapped and will report a warning to the browser console for
* each of the subsequent scripts. This prevents strange results in applications, where otherwise
* multiple instances of Angular try to work on the DOM.
*
* ```html
* <!doctype html>
* <html>
* <body>
* <div ng-controller="WelcomeController">
* {{greeting}}
* </div>
*
* <script src="angular.js"></script>
* <script>
* var app = angular.module('demo', [])
* .controller('WelcomeController', function($scope) {
* $scope.greeting = 'Welcome!';
* });
* angular.bootstrap(document, ['demo']);
* </script>
* </body>
* </html>
* ```
*
* @param {DOMElement} element DOM element which is the root of angular application.
* @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
* Each item in the array should be the name of a predefined module or a (DI annotated)
* function that will be invoked by the injector as a `config` block.
* See: {@link angular.module modules}
* @param {Object=} config an object for defining configuration options for the application. The
* following keys are supported:
*
* * `strictDi` - disable automatic function annotation for the application. This is meant to
* assist in finding bugs which break minified code. Defaults to `false`.
*
* @returns {auto.$injector} Returns the newly created injector for this app.
*/
function bootstrap(element, modules, config) {
if (!isObject(config)) config = {};
var defaultConfig = {
strictDi: false
};
config = extend(defaultConfig, config);
var doBootstrap = function() {
element = jqLite(element);
if (element.injector()) {
var tag = (element[0] === document) ? 'document' : startingTag(element);
//Encode angle brackets to prevent input from being sanitized to empty string #8683
throw ngMinErr(
'btstrpd',
"App Already Bootstrapped with this Element '{0}'",
tag.replace(/</,'<').replace(/>/,'>'));
}
modules = modules || [];
modules.unshift(['$provide', function($provide) {
$provide.value('$rootElement', element);
}]);
if (config.debugInfoEnabled) {
// Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
modules.push(['$compileProvider', function($compileProvider) {
$compileProvider.debugInfoEnabled(true);
}]);
}
modules.unshift('ng');
var injector = createInjector(modules, config.strictDi);
injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
function bootstrapApply(scope, element, compile, injector) {
scope.$apply(function() {
element.data('$injector', injector);
compile(element)(scope);
});
}]
);
return injector;
};
var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
config.debugInfoEnabled = true;
window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
}
if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
return doBootstrap();
}
window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
angular.resumeBootstrap = function(extraModules) {
forEach(extraModules, function(module) {
modules.push(module);
});
return doBootstrap();
};
if (isFunction(angular.resumeDeferredBootstrap)) {
angular.resumeDeferredBootstrap();
}
}
/**
* @ngdoc function
* @name angular.reloadWithDebugInfo
* @module ng
* @description
* Use this function to reload the current application with debug information turned on.
* This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
*
* See {@link ng.$compileProvider#debugInfoEnabled} for more.
*/
function reloadWithDebugInfo() {
window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
window.location.reload();
}
/**
* @name angular.getTestability
* @module ng
* @description
* Get the testability service for the instance of Angular on the given
* element.
* @param {DOMElement} element DOM element which is the root of angular application.
*/
function getTestability(rootElement) {
var injector = angular.element(rootElement).injector();
if (!injector) {
throw ngMinErr('test',
'no injector found for element argument to getTestability');
}
return injector.get('$$testability');
}
var SNAKE_CASE_REGEXP = /[A-Z]/g;
function snake_case(name, separator) {
separator = separator || '_';
return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
return (pos ? separator : '') + letter.toLowerCase();
});
}
var bindJQueryFired = false;
var skipDestroyOnNextJQueryCleanData;
function bindJQuery() {
var originalCleanData;
if (bindJQueryFired) {
return;
}
// bind to jQuery if present;
jQuery = window.jQuery;
// Use jQuery if it exists with proper functionality, otherwise default to us.
// Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
// Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
// versions. It will not work for sure with jQuery <1.7, though.
if (jQuery && jQuery.fn.on) {
jqLite = jQuery;
extend(jQuery.fn, {
scope: JQLitePrototype.scope,
isolateScope: JQLitePrototype.isolateScope,
controller: JQLitePrototype.controller,
injector: JQLitePrototype.injector,
inheritedData: JQLitePrototype.inheritedData
});
// All nodes removed from the DOM via various jQuery APIs like .remove()
// are passed through jQuery.cleanData. Monkey-patch this method to fire
// the $destroy event on all removed nodes.
originalCleanData = jQuery.cleanData;
jQuery.cleanData = function(elems) {
var events;
if (!skipDestroyOnNextJQueryCleanData) {
for (var i = 0, elem; (elem = elems[i]) != null; i++) {
events = jQuery._data(elem, "events");
if (events && events.$destroy) {
jQuery(elem).triggerHandler('$destroy');
}
}
} else {
skipDestroyOnNextJQueryCleanData = false;
}
originalCleanData(elems);
};
} else {
jqLite = JQLite;
}
angular.element = jqLite;
// Prevent double-proxying.
bindJQueryFired = true;
}
/**
* throw error if the argument is falsy.
*/
function assertArg(arg, name, reason) {
if (!arg) {
throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
}
return arg;
}
function assertArgFn(arg, name, acceptArrayAnnotation) {
if (acceptArrayAnnotation && isArray(arg)) {
arg = arg[arg.length - 1];
}
assertArg(isFunction(arg), name, 'not a function, got ' +
(arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
return arg;
}
/**
* throw error if the name given is hasOwnProperty
* @param {String} name the name to test
* @param {String} context the context in which the name is used, such as module or directive
*/
function assertNotHasOwnProperty(name, context) {
if (name === 'hasOwnProperty') {
throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
}
}
/**
* Return the value accessible from the object by path. Any undefined traversals are ignored
* @param {Object} obj starting object
* @param {String} path path to traverse
* @param {boolean} [bindFnToScope=true]
* @returns {Object} value as accessible by path
*/
//TODO(misko): this function needs to be removed
function getter(obj, path, bindFnToScope) {
if (!path) return obj;
var keys = path.split('.');
var key;
var lastInstance = obj;
var len = keys.length;
for (var i = 0; i < len; i++) {
key = keys[i];
if (obj) {
obj = (lastInstance = obj)[key];
}
}
if (!bindFnToScope && isFunction(obj)) {
return bind(lastInstance, obj);
}
return obj;
}
/**
* Return the DOM siblings between the first and last node in the given array.
* @param {Array} array like object
* @returns {jqLite} jqLite collection containing the nodes
*/
function getBlockNodes(nodes) {
// TODO(perf): just check if all items in `nodes` are siblings and if they are return the original
// collection, otherwise update the original collection.
var node = nodes[0];
var endNode = nodes[nodes.length - 1];
var blockNodes = [node];
do {
node = node.nextSibling;
if (!node) break;
blockNodes.push(node);
} while (node !== endNode);
return jqLite(blockNodes);
}
/**
* Creates a new object without a prototype. This object is useful for lookup without having to
* guard against prototypically inherited properties via hasOwnProperty.
*
* Related micro-benchmarks:
* - http://jsperf.com/object-create2
* - http://jsperf.com/proto-map-lookup/2
* - http://jsperf.com/for-in-vs-object-keys2
*
* @returns {Object}
*/
function createMap() {
return Object.create(null);
}
var NODE_TYPE_ELEMENT = 1;
var NODE_TYPE_TEXT = 3;
var NODE_TYPE_COMMENT = 8;
var NODE_TYPE_DOCUMENT = 9;
var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
/**
* @ngdoc type
* @name angular.Module
* @module ng
* @description
*
* Interface for configuring angular {@link angular.module modules}.
*/
function setupModuleLoader(window) {
var $injectorMinErr = minErr('$injector');
var ngMinErr = minErr('ng');
function ensure(obj, name, factory) {
return obj[name] || (obj[name] = factory());
}
var angular = ensure(window, 'angular', Object);
// We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
angular.$$minErr = angular.$$minErr || minErr;
return ensure(angular, 'module', function() {
/** @type {Object.<string, angular.Module>} */
var modules = {};
/**
* @ngdoc function
* @name angular.module
* @module ng
* @description
*
* The `angular.module` is a global place for creating, registering and retrieving Angular
* modules.
* All modules (angular core or 3rd party) that should be available to an application must be
* registered using this mechanism.
*
* When passed two or more arguments, a new module is created. If passed only one argument, an
* existing module (the name passed as the first argument to `module`) is retrieved.
*
*
* # Module
*
* A module is a collection of services, directives, controllers, filters, and configuration information.
* `angular.module` is used to configure the {@link auto.$injector $injector}.
*
* ```js
* // Create a new module
* var myModule = angular.module('myModule', []);
*
* // register a new service
* myModule.value('appName', 'MyCoolApp');
*
* // configure existing services inside initialization blocks.
* myModule.config(['$locationProvider', function($locationProvider) {
* // Configure existing providers
* $locationProvider.hashPrefix('!');
* }]);
* ```
*
* Then you can create an injector and load your modules like this:
*
* ```js
* var injector = angular.injector(['ng', 'myModule'])
* ```
*
* However it's more likely that you'll just use
* {@link ng.directive:ngApp ngApp} or
* {@link angular.bootstrap} to simplify this process for you.
*
* @param {!string} name The name of the module to create or retrieve.
* @param {!Array.<string>=} requires If specified then new module is being created. If
* unspecified then the module is being retrieved for further configuration.
* @param {Function=} configFn Optional configuration function for the module. Same as
* {@link angular.Module#config Module#config()}.
* @returns {module} new module with the {@link angular.Module} api.
*/
return function module(name, requires, configFn) {
var assertNotHasOwnProperty = function(name, context) {
if (name === 'hasOwnProperty') {
throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
}
};
assertNotHasOwnProperty(name, 'module');
if (requires && modules.hasOwnProperty(name)) {
modules[name] = null;
}
return ensure(modules, name, function() {
if (!requires) {
throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
"the module name or forgot to load it. If registering a module ensure that you " +
"specify the dependencies as the second argument.", name);
}
/** @type {!Array.<Array.<*>>} */
var invokeQueue = [];
/** @type {!Array.<Function>} */
var configBlocks = [];
/** @type {!Array.<Function>} */
var runBlocks = [];
var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
/** @type {angular.Module} */
var moduleInstance = {
// Private state
_invokeQueue: invokeQueue,
_configBlocks: configBlocks,
_runBlocks: runBlocks,
/**
* @ngdoc property
* @name angular.Module#requires
* @module ng
*
* @description
* Holds the list of modules which the injector will load before the current module is
* loaded.
*/
requires: requires,
/**
* @ngdoc property
* @name angular.Module#name
* @module ng
*
* @description
* Name of the module.
*/
name: name,
/**
* @ngdoc method
* @name angular.Module#provider
* @module ng
* @param {string} name service name
* @param {Function} providerType Construction function for creating new instance of the
* service.
* @description
* See {@link auto.$provide#provider $provide.provider()}.
*/
provider: invokeLater('$provide', 'provider'),
/**
* @ngdoc method
* @name angular.Module#factory
* @module ng
* @param {string} name service name
* @param {Function} providerFunction Function for creating new instance of the service.
* @description
* See {@link auto.$provide#factory $provide.factory()}.
*/
factory: invokeLater('$provide', 'factory'),
/**
* @ngdoc method
* @name angular.Module#service
* @module ng
* @param {string} name service name
* @param {Function} constructor A constructor function that will be instantiated.
* @description
* See {@link auto.$provide#service $provide.service()}.
*/
service: invokeLater('$provide', 'service'),
/**
* @ngdoc method
* @name angular.Module#value
* @module ng
* @param {string} name service name
* @param {*} object Service instance object.
* @description
* See {@link auto.$provide#value $provide.value()}.
*/
value: invokeLater('$provide', 'value'),
/**
* @ngdoc method
* @name angular.Module#constant
* @module ng
* @param {string} name constant name
* @param {*} object Constant value.
* @description
* Because the constant are fixed, they get applied before other provide methods.
* See {@link auto.$provide#constant $provide.constant()}.
*/
constant: invokeLater('$provide', 'constant', 'unshift'),
/**
* @ngdoc method
* @name angular.Module#animation
* @module ng
* @param {string} name animation name
* @param {Function} animationFactory Factory function for creating new instance of an
* animation.
* @description
*
* **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
*
*
* Defines an animation hook that can be later used with
* {@link ngAnimate.$animate $animate} service and directives that use this service.
*
* ```js
* module.animation('.animation-name', function($inject1, $inject2) {
* return {
* eventName : function(element, done) {
* //code to run the animation
* //once complete, then run done()
* return function cancellationFunction(element) {
* //code to cancel the animation
* }
* }
* }
* })
* ```
*
* See {@link ng.$animateProvider#register $animateProvider.register()} and
* {@link ngAnimate ngAnimate module} for more information.
*/
animation: invokeLater('$animateProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#filter
* @module ng
* @param {string} name Filter name.
* @param {Function} filterFactory Factory function for creating new instance of filter.
* @description
* See {@link ng.$filterProvider#register $filterProvider.register()}.
*/
filter: invokeLater('$filterProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#controller
* @module ng
* @param {string|Object} name Controller name, or an object map of controllers where the
* keys are the names and the values are the constructors.
* @param {Function} constructor Controller constructor function.
* @description
* See {@link ng.$controllerProvider#register $controllerProvider.register()}.
*/
controller: invokeLater('$controllerProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#directive
* @module ng
* @param {string|Object} name Directive name, or an object map of directives where the
* keys are the names and the values are the factories.
* @param {Function} directiveFactory Factory function for creating new instance of
* directives.
* @description
* See {@link ng.$compileProvider#directive $compileProvider.directive()}.
*/
directive: invokeLater('$compileProvider', 'directive'),
/**
* @ngdoc method
* @name angular.Module#config
* @module ng
* @param {Function} configFn Execute this function on module load. Useful for service
* configuration.
* @description
* Use this method to register work which needs to be performed on module loading.
* For more about how to configure services, see
* {@link providers#provider-recipe Provider Recipe}.
*/
config: config,
/**
* @ngdoc method
* @name angular.Module#run
* @module ng
* @param {Function} initializationFn Execute this function after injector creation.
* Useful for application initialization.
* @description
* Use this method to register work which should be performed when the injector is done
* loading all modules.
*/
run: function(block) {
runBlocks.push(block);
return this;
}
};
if (configFn) {
config(configFn);
}
return moduleInstance;
/**
* @param {string} provider
* @param {string} method
* @param {String=} insertMethod
* @returns {angular.Module}
*/
function invokeLater(provider, method, insertMethod, queue) {
if (!queue) queue = invokeQueue;
return function() {
queue[insertMethod || 'push']([provider, method, arguments]);
return moduleInstance;
};
}
});
};
});
}
/* global: toDebugString: true */
function serializeObject(obj) {
var seen = [];
return JSON.stringify(obj, function(key, val) {
val = toJsonReplacer(key, val);
if (isObject(val)) {
if (seen.indexOf(val) >= 0) return '<<already seen>>';
seen.push(val);
}
return val;
});
}
function toDebugString(obj) {
if (typeof obj === 'function') {
return obj.toString().replace(/ \{[\s\S]*$/, '');
} else if (typeof obj === 'undefined') {
return 'undefined';
} else if (typeof obj !== 'string') {
return serializeObject(obj);
}
return obj;
}
/* global angularModule: true,
version: true,
$LocaleProvider,
$CompileProvider,
htmlAnchorDirective,
inputDirective,
inputDirective,
formDirective,
scriptDirective,
selectDirective,
styleDirective,
optionDirective,
ngBindDirective,
ngBindHtmlDirective,
ngBindTemplateDirective,
ngClassDirective,
ngClassEvenDirective,
ngClassOddDirective,
ngCspDirective,
ngCloakDirective,
ngControllerDirective,
ngFormDirective,
ngHideDirective,
ngIfDirective,
ngIncludeDirective,
ngIncludeFillContentDirective,
ngInitDirective,
ngNonBindableDirective,
ngPluralizeDirective,
ngRepeatDirective,
ngShowDirective,
ngStyleDirective,
ngSwitchDirective,
ngSwitchWhenDirective,
ngSwitchDefaultDirective,
ngOptionsDirective,
ngTranscludeDirective,
ngModelDirective,
ngListDirective,
ngChangeDirective,
patternDirective,
patternDirective,
requiredDirective,
requiredDirective,
minlengthDirective,
minlengthDirective,
maxlengthDirective,
maxlengthDirective,
ngValueDirective,
ngModelOptionsDirective,
ngAttributeAliasDirectives,
ngEventDirectives,
$AnchorScrollProvider,
$AnimateProvider,
$BrowserProvider,
$CacheFactoryProvider,
$ControllerProvider,
$DocumentProvider,
$ExceptionHandlerProvider,
$FilterProvider,
$InterpolateProvider,
$IntervalProvider,
$HttpProvider,
$HttpBackendProvider,
$LocationProvider,
$LogProvider,
$ParseProvider,
$RootScopeProvider,
$QProvider,
$$QProvider,
$$SanitizeUriProvider,
$SceProvider,
$SceDelegateProvider,
$SnifferProvider,
$TemplateCacheProvider,
$TemplateRequestProvider,
$$TestabilityProvider,
$TimeoutProvider,
$$RAFProvider,
$$AsyncCallbackProvider,
$WindowProvider,
$$jqLiteProvider
*/
/**
* @ngdoc object
* @name angular.version
* @module ng
* @description
* An object that contains information about the current AngularJS version. This object has the
* following properties:
*
* - `full` – `{string}` – Full version string, such as "0.9.18".
* - `major` – `{number}` – Major version number, such as "0".
* - `minor` – `{number}` – Minor version number, such as "9".
* - `dot` – `{number}` – Dot version number, such as "18".
* - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
*/
var version = {
full: '1.3.15', // all of these placeholder strings will be replaced by grunt's
major: 1, // package task
minor: 3,
dot: 15,
codeName: 'locality-filtration'
};
function publishExternalAPI(angular) {
extend(angular, {
'bootstrap': bootstrap,
'copy': copy,
'extend': extend,
'equals': equals,
'element': jqLite,
'forEach': forEach,
'injector': createInjector,
'noop': noop,
'bind': bind,
'toJson': toJson,
'fromJson': fromJson,
'identity': identity,
'isUndefined': isUndefined,
'isDefined': isDefined,
'isString': isString,
'isFunction': isFunction,
'isObject': isObject,
'isNumber': isNumber,
'isElement': isElement,
'isArray': isArray,
'version': version,
'isDate': isDate,
'lowercase': lowercase,
'uppercase': uppercase,
'callbacks': {counter: 0},
'getTestability': getTestability,
'$$minErr': minErr,
'$$csp': csp,
'reloadWithDebugInfo': reloadWithDebugInfo
});
angularModule = setupModuleLoader(window);
try {
angularModule('ngLocale');
} catch (e) {
angularModule('ngLocale', []).provider('$locale', $LocaleProvider);
}
angularModule('ng', ['ngLocale'], ['$provide',
function ngModule($provide) {
// $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
$provide.provider({
$$sanitizeUri: $$SanitizeUriProvider
});
$provide.provider('$compile', $CompileProvider).
directive({
a: htmlAnchorDirective,
input: inputDirective,
textarea: inputDirective,
form: formDirective,
script: scriptDirective,
select: selectDirective,
style: styleDirective,
option: optionDirective,
ngBind: ngBindDirective,
ngBindHtml: ngBindHtmlDirective,
ngBindTemplate: ngBindTemplateDirective,
ngClass: ngClassDirective,
ngClassEven: ngClassEvenDirective,
ngClassOdd: ngClassOddDirective,
ngCloak: ngCloakDirective,
ngController: ngControllerDirective,
ngForm: ngFormDirective,
ngHide: ngHideDirective,
ngIf: ngIfDirective,
ngInclude: ngIncludeDirective,
ngInit: ngInitDirective,
ngNonBindable: ngNonBindableDirective,
ngPluralize: ngPluralizeDirective,
ngRepeat: ngRepeatDirective,
ngShow: ngShowDirective,
ngStyle: ngStyleDirective,
ngSwitch: ngSwitchDirective,
ngSwitchWhen: ngSwitchWhenDirective,
ngSwitchDefault: ngSwitchDefaultDirective,
ngOptions: ngOptionsDirective,
ngTransclude: ngTranscludeDirective,
ngModel: ngModelDirective,
ngList: ngListDirective,
ngChange: ngChangeDirective,
pattern: patternDirective,
ngPattern: patternDirective,
required: requiredDirective,
ngRequired: requiredDirective,
minlength: minlengthDirective,
ngMinlength: minlengthDirective,
maxlength: maxlengthDirective,
ngMaxlength: maxlengthDirective,
ngValue: ngValueDirective,
ngModelOptions: ngModelOptionsDirective
}).
directive({
ngInclude: ngIncludeFillContentDirective
}).
directive(ngAttributeAliasDirectives).
directive(ngEventDirectives);
$provide.provider({
$anchorScroll: $AnchorScrollProvider,
$animate: $AnimateProvider,
$browser: $BrowserProvider,
$cacheFactory: $CacheFactoryProvider,
$controller: $ControllerProvider,
$document: $DocumentProvider,
$exceptionHandler: $ExceptionHandlerProvider,
$filter: $FilterProvider,
$interpolate: $InterpolateProvider,
$interval: $IntervalProvider,
$http: $HttpProvider,
$httpBackend: $HttpBackendProvider,
$location: $LocationProvider,
$log: $LogProvider,
$parse: $ParseProvider,
$rootScope: $RootScopeProvider,
$q: $QProvider,
$$q: $$QProvider,
$sce: $SceProvider,
$sceDelegate: $SceDelegateProvider,
$sniffer: $SnifferProvider,
$templateCache: $TemplateCacheProvider,
$templateRequest: $TemplateRequestProvider,
$$testability: $$TestabilityProvider,
$timeout: $TimeoutProvider,
$window: $WindowProvider,
$$rAF: $$RAFProvider,
$$asyncCallback: $$AsyncCallbackProvider,
$$jqLite: $$jqLiteProvider
});
}
]);
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Any commits to this file should be reviewed with security in mind. *
* Changes to this file can potentially create security vulnerabilities. *
* An approval from 2 Core members with history of modifying *
* this file is required. *
* *
* Does the change somehow allow for arbitrary javascript to be executed? *
* Or allows for someone to change the prototype of built-in objects? *
* Or gives undesired access to variables likes document or window? *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* global JQLitePrototype: true,
addEventListenerFn: true,
removeEventListenerFn: true,
BOOLEAN_ATTR: true,
ALIASED_ATTR: true,
*/
//////////////////////////////////
//JQLite
//////////////////////////////////
/**
* @ngdoc function
* @name angular.element
* @module ng
* @kind function
*
* @description
* Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
*
* If jQuery is available, `angular.element` is an alias for the
* [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
* delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite."
*
* <div class="alert alert-success">jqLite is a tiny, API-compatible subset of jQuery that allows
* Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most
* commonly needed functionality with the goal of having a very small footprint.</div>
*
* To use jQuery, simply load it before `DOMContentLoaded` event fired.
*
* <div class="alert">**Note:** all element references in Angular are always wrapped with jQuery or
* jqLite; they are never raw DOM references.</div>
*
* ## Angular's jqLite
* jqLite provides only the following jQuery methods:
*
* - [`addClass()`](http://api.jquery.com/addClass/)
* - [`after()`](http://api.jquery.com/after/)
* - [`append()`](http://api.jquery.com/append/)
* - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
* - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData
* - [`children()`](http://api.jquery.com/children/) - Does not support selectors
* - [`clone()`](http://api.jquery.com/clone/)
* - [`contents()`](http://api.jquery.com/contents/)
* - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`
* - [`data()`](http://api.jquery.com/data/)
* - [`detach()`](http://api.jquery.com/detach/)
* - [`empty()`](http://api.jquery.com/empty/)
* - [`eq()`](http://api.jquery.com/eq/)
* - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
* - [`hasClass()`](http://api.jquery.com/hasClass/)
* - [`html()`](http://api.jquery.com/html/)
* - [`next()`](http://api.jquery.com/next/) - Does not support selectors
* - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
* - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors
* - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
* - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
* - [`prepend()`](http://api.jquery.com/prepend/)
* - [`prop()`](http://api.jquery.com/prop/)
* - [`ready()`](http://api.jquery.com/ready/)
* - [`remove()`](http://api.jquery.com/remove/)
* - [`removeAttr()`](http://api.jquery.com/removeAttr/)
* - [`removeClass()`](http://api.jquery.com/removeClass/)
* - [`removeData()`](http://api.jquery.com/removeData/)
* - [`replaceWith()`](http://api.jquery.com/replaceWith/)
* - [`text()`](http://api.jquery.com/text/)
* - [`toggleClass()`](http://api.jquery.com/toggleClass/)
* - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
* - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces
* - [`val()`](http://api.jquery.com/val/)
* - [`wrap()`](http://api.jquery.com/wrap/)
*
* ## jQuery/jqLite Extras
* Angular also provides the following additional methods and events to both jQuery and jqLite:
*
* ### Events
* - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
* on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
* element before it is removed.
*
* ### Methods
* - `controller(name)` - retrieves the controller of the current element or its parent. By default
* retrieves controller associated with the `ngController` directive. If `name` is provided as
* camelCase directive name, then the controller for this directive will be retrieved (e.g.
* `'ngModel'`).
* - `injector()` - retrieves the injector of the current element or its parent.
* - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
* element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
* be enabled.
* - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
* current element. This getter should be used only on elements that contain a directive which starts a new isolate
* scope. Calling `scope()` on this element always returns the original non-isolate scope.
* Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
* - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
* parent element is reached.
*
* @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
* @returns {Object} jQuery object.
*/
JQLite.expando = 'ng339';
var jqCache = JQLite.cache = {},
jqId = 1,
addEventListenerFn = function(element, type, fn) {
element.addEventListener(type, fn, false);
},
removeEventListenerFn = function(element, type, fn) {
element.removeEventListener(type, fn, false);
};
/*
* !!! This is an undocumented "private" function !!!
*/
JQLite._data = function(node) {
//jQuery always returns an object on cache miss
return this.cache[node[this.expando]] || {};
};
function jqNextId() { return ++jqId; }
var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
var MOZ_HACK_REGEXP = /^moz([A-Z])/;
var MOUSE_EVENT_MAP= { mouseleave: "mouseout", mouseenter: "mouseover"};
var jqLiteMinErr = minErr('jqLite');
/**
* Converts snake_case to camelCase.
* Also there is special case for Moz prefix starting with upper case letter.
* @param name Name to normalize
*/
function camelCase(name) {
return name.
replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
return offset ? letter.toUpperCase() : letter;
}).
replace(MOZ_HACK_REGEXP, 'Moz$1');
}
var SINGLE_TAG_REGEXP = /^<(\w+)\s*\/?>(?:<\/\1>|)$/;
var HTML_REGEXP = /<|&#?\w+;/;
var TAG_NAME_REGEXP = /<([\w:]+)/;
var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi;
var wrapMap = {
'option': [1, '<select multiple="multiple">', '</select>'],
'thead': [1, '<table>', '</table>'],
'col': [2, '<table><colgroup>', '</colgroup></table>'],
'tr': [2, '<table><tbody>', '</tbody></table>'],
'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
'_default': [0, "", ""]
};
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
function jqLiteIsTextNode(html) {
return !HTML_REGEXP.test(html);
}
function jqLiteAcceptsData(node) {
// The window object can accept data but has no nodeType
// Otherwise we are only interested in elements (1) and documents (9)
var nodeType = node.nodeType;
return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
}
function jqLiteBuildFragment(html, context) {
var tmp, tag, wrap,
fragment = context.createDocumentFragment(),
nodes = [], i;
if (jqLiteIsTextNode(html)) {
// Convert non-html into a text node
nodes.push(context.createTextNode(html));
} else {
// Convert html into DOM nodes
tmp = tmp || fragment.appendChild(context.createElement("div"));
tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase();
wrap = wrapMap[tag] || wrapMap._default;
tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2];
// Descend through wrappers to the right content
i = wrap[0];
while (i--) {
tmp = tmp.lastChild;
}
nodes = concat(nodes, tmp.childNodes);
tmp = fragment.firstChild;
tmp.textContent = "";
}
// Remove wrapper from fragment
fragment.textContent = "";
fragment.innerHTML = ""; // Clear inner HTML
forEach(nodes, function(node) {
fragment.appendChild(node);
});
return fragment;
}
function jqLiteParseHTML(html, context) {
context = context || document;
var parsed;
if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
return [context.createElement(parsed[1])];
}
if ((parsed = jqLiteBuildFragment(html, context))) {
return parsed.childNodes;
}
return [];
}
/////////////////////////////////////////////
function JQLite(element) {
if (element instanceof JQLite) {
return element;
}
var argIsString;
if (isString(element)) {
element = trim(element);
argIsString = true;
}
if (!(this instanceof JQLite)) {
if (argIsString && element.charAt(0) != '<') {
throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
}
return new JQLite(element);
}
if (argIsString) {
jqLiteAddNodes(this, jqLiteParseHTML(element));
} else {
jqLiteAddNodes(this, element);
}
}
function jqLiteClone(element) {
return element.cloneNode(true);
}
function jqLiteDealoc(element, onlyDescendants) {
if (!onlyDescendants) jqLiteRemoveData(element);
if (element.querySelectorAll) {
var descendants = element.querySelectorAll('*');
for (var i = 0, l = descendants.length; i < l; i++) {
jqLiteRemoveData(descendants[i]);
}
}
}
function jqLiteOff(element, type, fn, unsupported) {
if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
var expandoStore = jqLiteExpandoStore(element);
var events = expandoStore && expandoStore.events;
var handle = expandoStore && expandoStore.handle;
if (!handle) return; //no listeners registered
if (!type) {
for (type in events) {
if (type !== '$destroy') {
removeEventListenerFn(element, type, handle);
}
delete events[type];
}
} else {
forEach(type.split(' '), function(type) {
if (isDefined(fn)) {
var listenerFns = events[type];
arrayRemove(listenerFns || [], fn);
if (listenerFns && listenerFns.length > 0) {
return;
}
}
removeEventListenerFn(element, type, handle);
delete events[type];
});
}
}
function jqLiteRemoveData(element, name) {
var expandoId = element.ng339;
var expandoStore = expandoId && jqCache[expandoId];
if (expandoStore) {
if (name) {
delete expandoStore.data[name];
return;
}
if (expandoStore.handle) {
if (expandoStore.events.$destroy) {
expandoStore.handle({}, '$destroy');
}
jqLiteOff(element);
}
delete jqCache[expandoId];
element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
}
}
function jqLiteExpandoStore(element, createIfNecessary) {
var expandoId = element.ng339,
expandoStore = expandoId && jqCache[expandoId];
if (createIfNecessary && !expandoStore) {
element.ng339 = expandoId = jqNextId();
expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
}
return expandoStore;
}
function jqLiteData(element, key, value) {
if (jqLiteAcceptsData(element)) {
var isSimpleSetter = isDefined(value);
var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
var massGetter = !key;
var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
var data = expandoStore && expandoStore.data;
if (isSimpleSetter) { // data('key', value)
data[key] = value;
} else {
if (massGetter) { // data()
return data;
} else {
if (isSimpleGetter) { // data('key')
// don't force creation of expandoStore if it doesn't exist yet
return data && data[key];
} else { // mass-setter: data({key1: val1, key2: val2})
extend(data, key);
}
}
}
}
}
function jqLiteHasClass(element, selector) {
if (!element.getAttribute) return false;
return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
indexOf(" " + selector + " ") > -1);
}
function jqLiteRemoveClass(element, cssClasses) {
if (cssClasses && element.setAttribute) {
forEach(cssClasses.split(' '), function(cssClass) {
element.setAttribute('class', trim(
(" " + (element.getAttribute('class') || '') + " ")
.replace(/[\n\t]/g, " ")
.replace(" " + trim(cssClass) + " ", " "))
);
});
}
}
function jqLiteAddClass(element, cssClasses) {
if (cssClasses && element.setAttribute) {
var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
.replace(/[\n\t]/g, " ");
forEach(cssClasses.split(' '), function(cssClass) {
cssClass = trim(cssClass);
if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
existingClasses += cssClass + ' ';
}
});
element.setAttribute('class', trim(existingClasses));
}
}
function jqLiteAddNodes(root, elements) {
// THIS CODE IS VERY HOT. Don't make changes without benchmarking.
if (elements) {
// if a Node (the most common case)
if (elements.nodeType) {
root[root.length++] = elements;
} else {
var length = elements.length;
// if an Array or NodeList and not a Window
if (typeof length === 'number' && elements.window !== elements) {
if (length) {
for (var i = 0; i < length; i++) {
root[root.length++] = elements[i];
}
}
} else {
root[root.length++] = elements;
}
}
}
}
function jqLiteController(element, name) {
return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
}
function jqLiteInheritedData(element, name, value) {
// if element is the document object work with the html element instead
// this makes $(document).scope() possible
if (element.nodeType == NODE_TYPE_DOCUMENT) {
element = element.documentElement;
}
var names = isArray(name) ? name : [name];
while (element) {
for (var i = 0, ii = names.length; i < ii; i++) {
if ((value = jqLite.data(element, names[i])) !== undefined) return value;
}
// If dealing with a document fragment node with a host element, and no parent, use the host
// element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
// to lookup parent controllers.
element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
}
}
function jqLiteEmpty(element) {
jqLiteDealoc(element, true);
while (element.firstChild) {
element.removeChild(element.firstChild);
}
}
function jqLiteRemove(element, keepData) {
if (!keepData) jqLiteDealoc(element);
var parent = element.parentNode;
if (parent) parent.removeChild(element);
}
function jqLiteDocumentLoaded(action, win) {
win = win || window;
if (win.document.readyState === 'complete') {
// Force the action to be run async for consistent behaviour
// from the action's point of view
// i.e. it will definitely not be in a $apply
win.setTimeout(action);
} else {
// No need to unbind this handler as load is only ever called once
jqLite(win).on('load', action);
}
}
//////////////////////////////////////////
// Functions which are declared directly.
//////////////////////////////////////////
var JQLitePrototype = JQLite.prototype = {
ready: function(fn) {
var fired = false;
function trigger() {
if (fired) return;
fired = true;
fn();
}
// check if document is already loaded
if (document.readyState === 'complete') {
setTimeout(trigger);
} else {
this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
// we can not use jqLite since we are not done loading and jQuery could be loaded later.
// jshint -W064
JQLite(window).on('load', trigger); // fallback to window.onload for others
// jshint +W064
}
},
toString: function() {
var value = [];
forEach(this, function(e) { value.push('' + e);});
return '[' + value.join(', ') + ']';
},
eq: function(index) {
return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
},
length: 0,
push: push,
sort: [].sort,
splice: [].splice
};
//////////////////////////////////////////
// Functions iterating getter/setters.
// these functions return self on setter and
// value on get.
//////////////////////////////////////////
var BOOLEAN_ATTR = {};
forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
BOOLEAN_ATTR[lowercase(value)] = value;
});
var BOOLEAN_ELEMENTS = {};
forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
BOOLEAN_ELEMENTS[value] = true;
});
var ALIASED_ATTR = {
'ngMinlength': 'minlength',
'ngMaxlength': 'maxlength',
'ngMin': 'min',
'ngMax': 'max',
'ngPattern': 'pattern'
};
function getBooleanAttrName(element, name) {
// check dom last since we will most likely fail on name
var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
// booleanAttr is here twice to minimize DOM access
return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
}
function getAliasedAttrName(element, name) {
var nodeName = element.nodeName;
return (nodeName === 'INPUT' || nodeName === 'TEXTAREA') && ALIASED_ATTR[name];
}
forEach({
data: jqLiteData,
removeData: jqLiteRemoveData
}, function(fn, name) {
JQLite[name] = fn;
});
forEach({
data: jqLiteData,
inheritedData: jqLiteInheritedData,
scope: function(element) {
// Can't use jqLiteData here directly so we stay compatible with jQuery!
return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
},
isolateScope: function(element) {
// Can't use jqLiteData here directly so we stay compatible with jQuery!
return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
},
controller: jqLiteController,
injector: function(element) {
return jqLiteInheritedData(element, '$injector');
},
removeAttr: function(element, name) {
element.removeAttribute(name);
},
hasClass: jqLiteHasClass,
css: function(element, name, value) {
name = camelCase(name);
if (isDefined(value)) {
element.style[name] = value;
} else {
return element.style[name];
}
},
attr: function(element, name, value) {
var lowercasedName = lowercase(name);
if (BOOLEAN_ATTR[lowercasedName]) {
if (isDefined(value)) {
if (!!value) {
element[name] = true;
element.setAttribute(name, lowercasedName);
} else {
element[name] = false;
element.removeAttribute(lowercasedName);
}
} else {
return (element[name] ||
(element.attributes.getNamedItem(name) || noop).specified)
? lowercasedName
: undefined;
}
} else if (isDefined(value)) {
element.setAttribute(name, value);
} else if (element.getAttribute) {
// the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
// some elements (e.g. Document) don't have get attribute, so return undefined
var ret = element.getAttribute(name, 2);
// normalize non-existing attributes to undefined (as jQuery)
return ret === null ? undefined : ret;
}
},
prop: function(element, name, value) {
if (isDefined(value)) {
element[name] = value;
} else {
return element[name];
}
},
text: (function() {
getText.$dv = '';
return getText;
function getText(element, value) {
if (isUndefined(value)) {
var nodeType = element.nodeType;
return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
}
element.textContent = value;
}
})(),
val: function(element, value) {
if (isUndefined(value)) {
if (element.multiple && nodeName_(element) === 'select') {
var result = [];
forEach(element.options, function(option) {
if (option.selected) {
result.push(option.value || option.text);
}
});
return result.length === 0 ? null : result;
}
return element.value;
}
element.value = value;
},
html: function(element, value) {
if (isUndefined(value)) {
return element.innerHTML;
}
jqLiteDealoc(element, true);
element.innerHTML = value;
},
empty: jqLiteEmpty
}, function(fn, name) {
/**
* Properties: writes return selection, reads return first value
*/
JQLite.prototype[name] = function(arg1, arg2) {
var i, key;
var nodeCount = this.length;
// jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
// in a way that survives minification.
// jqLiteEmpty takes no arguments but is a setter.
if (fn !== jqLiteEmpty &&
(((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) {
if (isObject(arg1)) {
// we are a write, but the object properties are the key/values
for (i = 0; i < nodeCount; i++) {
if (fn === jqLiteData) {
// data() takes the whole object in jQuery
fn(this[i], arg1);
} else {
for (key in arg1) {
fn(this[i], key, arg1[key]);
}
}
}
// return self for chaining
return this;
} else {
// we are a read, so read the first child.
// TODO: do we still need this?
var value = fn.$dv;
// Only if we have $dv do we iterate over all, otherwise it is just the first element.
var jj = (value === undefined) ? Math.min(nodeCount, 1) : nodeCount;
for (var j = 0; j < jj; j++) {
var nodeValue = fn(this[j], arg1, arg2);
value = value ? value + nodeValue : nodeValue;
}
return value;
}
} else {
// we are a write, so apply to all children
for (i = 0; i < nodeCount; i++) {
fn(this[i], arg1, arg2);
}
// return self for chaining
return this;
}
};
});
function createEventHandler(element, events) {
var eventHandler = function(event, type) {
// jQuery specific api
event.isDefaultPrevented = function() {
return event.defaultPrevented;
};
var eventFns = events[type || event.type];
var eventFnsLength = eventFns ? eventFns.length : 0;
if (!eventFnsLength) return;
if (isUndefined(event.immediatePropagationStopped)) {
var originalStopImmediatePropagation = event.stopImmediatePropagation;
event.stopImmediatePropagation = function() {
event.immediatePropagationStopped = true;
if (event.stopPropagation) {
event.stopPropagation();
}
if (originalStopImmediatePropagation) {
originalStopImmediatePropagation.call(event);
}
};
}
event.isImmediatePropagationStopped = function() {
return event.immediatePropagationStopped === true;
};
// Copy event handlers in case event handlers array is modified during execution.
if ((eventFnsLength > 1)) {
eventFns = shallowCopy(eventFns);
}
for (var i = 0; i < eventFnsLength; i++) {
if (!event.isImmediatePropagationStopped()) {
eventFns[i].call(element, event);
}
}
};
// TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
// events on `element`
eventHandler.elem = element;
return eventHandler;
}
//////////////////////////////////////////
// Functions iterating traversal.
// These functions chain results into a single
// selector.
//////////////////////////////////////////
forEach({
removeData: jqLiteRemoveData,
on: function jqLiteOn(element, type, fn, unsupported) {
if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
// Do not add event handlers to non-elements because they will not be cleaned up.
if (!jqLiteAcceptsData(element)) {
return;
}
var expandoStore = jqLiteExpandoStore(element, true);
var events = expandoStore.events;
var handle = expandoStore.handle;
if (!handle) {
handle = expandoStore.handle = createEventHandler(element, events);
}
// http://jsperf.com/string-indexof-vs-split
var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
var i = types.length;
while (i--) {
type = types[i];
var eventFns = events[type];
if (!eventFns) {
events[type] = [];
if (type === 'mouseenter' || type === 'mouseleave') {
// Refer to jQuery's implementation of mouseenter & mouseleave
// Read about mouseenter and mouseleave:
// http://www.quirksmode.org/js/events_mouse.html#link8
jqLiteOn(element, MOUSE_EVENT_MAP[type], function(event) {
var target = this, related = event.relatedTarget;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if (!related || (related !== target && !target.contains(related))) {
handle(event, type);
}
});
} else {
if (type !== '$destroy') {
addEventListenerFn(element, type, handle);
}
}
eventFns = events[type];
}
eventFns.push(fn);
}
},
off: jqLiteOff,
one: function(element, type, fn) {
element = jqLite(element);
//add the listener twice so that when it is called
//you can remove the original function and still be
//able to call element.off(ev, fn) normally
element.on(type, function onFn() {
element.off(type, fn);
element.off(type, onFn);
});
element.on(type, fn);
},
replaceWith: function(element, replaceNode) {
var index, parent = element.parentNode;
jqLiteDealoc(element);
forEach(new JQLite(replaceNode), function(node) {
if (index) {
parent.insertBefore(node, index.nextSibling);
} else {
parent.replaceChild(node, element);
}
index = node;
});
},
children: function(element) {
var children = [];
forEach(element.childNodes, function(element) {
if (element.nodeType === NODE_TYPE_ELEMENT)
children.push(element);
});
return children;
},
contents: function(element) {
return element.contentDocument || element.childNodes || [];
},
append: function(element, node) {
var nodeType = element.nodeType;
if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
node = new JQLite(node);
for (var i = 0, ii = node.length; i < ii; i++) {
var child = node[i];
element.appendChild(child);
}
},
prepend: function(element, node) {
if (element.nodeType === NODE_TYPE_ELEMENT) {
var index = element.firstChild;
forEach(new JQLite(node), function(child) {
element.insertBefore(child, index);
});
}
},
wrap: function(element, wrapNode) {
wrapNode = jqLite(wrapNode).eq(0).clone()[0];
var parent = element.parentNode;
if (parent) {
parent.replaceChild(wrapNode, element);
}
wrapNode.appendChild(element);
},
remove: jqLiteRemove,
detach: function(element) {
jqLiteRemove(element, true);
},
after: function(element, newElement) {
var index = element, parent = element.parentNode;
newElement = new JQLite(newElement);
for (var i = 0, ii = newElement.length; i < ii; i++) {
var node = newElement[i];
parent.insertBefore(node, index.nextSibling);
index = node;
}
},
addClass: jqLiteAddClass,
removeClass: jqLiteRemoveClass,
toggleClass: function(element, selector, condition) {
if (selector) {
forEach(selector.split(' '), function(className) {
var classCondition = condition;
if (isUndefined(classCondition)) {
classCondition = !jqLiteHasClass(element, className);
}
(classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
});
}
},
parent: function(element) {
var parent = element.parentNode;
return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
},
next: function(element) {
return element.nextElementSibling;
},
find: function(element, selector) {
if (element.getElementsByTagName) {
return element.getElementsByTagName(selector);
} else {
return [];
}
},
clone: jqLiteClone,
triggerHandler: function(element, event, extraParameters) {
var dummyEvent, eventFnsCopy, handlerArgs;
var eventName = event.type || event;
var expandoStore = jqLiteExpandoStore(element);
var events = expandoStore && expandoStore.events;
var eventFns = events && events[eventName];
if (eventFns) {
// Create a dummy event to pass to the handlers
dummyEvent = {
preventDefault: function() { this.defaultPrevented = true; },
isDefaultPrevented: function() { return this.defaultPrevented === true; },
stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
stopPropagation: noop,
type: eventName,
target: element
};
// If a custom event was provided then extend our dummy event with it
if (event.type) {
dummyEvent = extend(dummyEvent, event);
}
// Copy event handlers in case event handlers array is modified during execution.
eventFnsCopy = shallowCopy(eventFns);
handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
forEach(eventFnsCopy, function(fn) {
if (!dummyEvent.isImmediatePropagationStopped()) {
fn.apply(element, handlerArgs);
}
});
}
}
}, function(fn, name) {
/**
* chaining functions
*/
JQLite.prototype[name] = function(arg1, arg2, arg3) {
var value;
for (var i = 0, ii = this.length; i < ii; i++) {
if (isUndefined(value)) {
value = fn(this[i], arg1, arg2, arg3);
if (isDefined(value)) {
// any function which returns a value needs to be wrapped
value = jqLite(value);
}
} else {
jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
}
}
return isDefined(value) ? value : this;
};
// bind legacy bind/unbind to on/off
JQLite.prototype.bind = JQLite.prototype.on;
JQLite.prototype.unbind = JQLite.prototype.off;
});
// Provider for private $$jqLite service
function $$jqLiteProvider() {
this.$get = function $$jqLite() {
return extend(JQLite, {
hasClass: function(node, classes) {
if (node.attr) node = node[0];
return jqLiteHasClass(node, classes);
},
addClass: function(node, classes) {
if (node.attr) node = node[0];
return jqLiteAddClass(node, classes);
},
removeClass: function(node, classes) {
if (node.attr) node = node[0];
return jqLiteRemoveClass(node, classes);
}
});
};
}
/**
* Computes a hash of an 'obj'.
* Hash of a:
* string is string
* number is number as string
* object is either result of calling $$hashKey function on the object or uniquely generated id,
* that is also assigned to the $$hashKey property of the object.
*
* @param obj
* @returns {string} hash string such that the same input will have the same hash string.
* The resulting string key is in 'type:hashKey' format.
*/
function hashKey(obj, nextUidFn) {
var key = obj && obj.$$hashKey;
if (key) {
if (typeof key === 'function') {
key = obj.$$hashKey();
}
return key;
}
var objType = typeof obj;
if (objType == 'function' || (objType == 'object' && obj !== null)) {
key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
} else {
key = objType + ':' + obj;
}
return key;
}
/**
* HashMap which can use objects as keys
*/
function HashMap(array, isolatedUid) {
if (isolatedUid) {
var uid = 0;
this.nextUid = function() {
return ++uid;
};
}
forEach(array, this.put, this);
}
HashMap.prototype = {
/**
* Store key value pair
* @param key key to store can be any type
* @param value value to store can be any type
*/
put: function(key, value) {
this[hashKey(key, this.nextUid)] = value;
},
/**
* @param key
* @returns {Object} the value for the key
*/
get: function(key) {
return this[hashKey(key, this.nextUid)];
},
/**
* Remove the key/value pair
* @param key
*/
remove: function(key) {
var value = this[key = hashKey(key, this.nextUid)];
delete this[key];
return value;
}
};
/**
* @ngdoc function
* @module ng
* @name angular.injector
* @kind function
*
* @description
* Creates an injector object that can be used for retrieving services as well as for
* dependency injection (see {@link guide/di dependency injection}).
*
* @param {Array.<string|Function>} modules A list of module functions or their aliases. See
* {@link angular.module}. The `ng` module must be explicitly added.
* @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
* disallows argument name annotation inference.
* @returns {injector} Injector object. See {@link auto.$injector $injector}.
*
* @example
* Typical usage
* ```js
* // create an injector
* var $injector = angular.injector(['ng']);
*
* // use the injector to kick off your application
* // use the type inference to auto inject arguments, or use implicit injection
* $injector.invoke(function($rootScope, $compile, $document) {
* $compile($document)($rootScope);
* $rootScope.$digest();
* });
* ```
*
* Sometimes you want to get access to the injector of a currently running Angular app
* from outside Angular. Perhaps, you want to inject and compile some markup after the
* application has been bootstrapped. You can do this using the extra `injector()` added
* to JQuery/jqLite elements. See {@link angular.element}.
*
* *This is fairly rare but could be the case if a third party library is injecting the
* markup.*
*
* In the following example a new block of HTML containing a `ng-controller`
* directive is added to the end of the document body by JQuery. We then compile and link
* it into the current AngularJS scope.
*
* ```js
* var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
* $(document.body).append($div);
*
* angular.element(document).injector().invoke(function($compile) {
* var scope = angular.element($div).scope();
* $compile($div)(scope);
* });
* ```
*/
/**
* @ngdoc module
* @name auto
* @description
*
* Implicit module which gets automatically added to each {@link auto.$injector $injector}.
*/
var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
var FN_ARG_SPLIT = /,/;
var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var $injectorMinErr = minErr('$injector');
function anonFn(fn) {
// For anonymous functions, showing at the very least the function signature can help in
// debugging.
var fnText = fn.toString().replace(STRIP_COMMENTS, ''),
args = fnText.match(FN_ARGS);
if (args) {
return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
}
return 'fn';
}
function annotate(fn, strictDi, name) {
var $inject,
fnText,
argDecl,
last;
if (typeof fn === 'function') {
if (!($inject = fn.$inject)) {
$inject = [];
if (fn.length) {
if (strictDi) {
if (!isString(name) || !name) {
name = fn.name || anonFn(fn);
}
throw $injectorMinErr('strictdi',
'{0} is not using explicit annotation and cannot be invoked in strict mode', name);
}
fnText = fn.toString().replace(STRIP_COMMENTS, '');
argDecl = fnText.match(FN_ARGS);
forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
arg.replace(FN_ARG, function(all, underscore, name) {
$inject.push(name);
});
});
}
fn.$inject = $inject;
}
} else if (isArray(fn)) {
last = fn.length - 1;
assertArgFn(fn[last], 'fn');
$inject = fn.slice(0, last);
} else {
assertArgFn(fn, 'fn', true);
}
return $inject;
}
///////////////////////////////////////
/**
* @ngdoc service
* @name $injector
*
* @description
*
* `$injector` is used to retrieve object instances as defined by
* {@link auto.$provide provider}, instantiate types, invoke methods,
* and load modules.
*
* The following always holds true:
*
* ```js
* var $injector = angular.injector();
* expect($injector.get('$injector')).toBe($injector);
* expect($injector.invoke(function($injector) {
* return $injector;
* })).toBe($injector);
* ```
*
* # Injection Function Annotation
*
* JavaScript does not have annotations, and annotations are needed for dependency injection. The
* following are all valid ways of annotating function with injection arguments and are equivalent.
*
* ```js
* // inferred (only works if code not minified/obfuscated)
* $injector.invoke(function(serviceA){});
*
* // annotated
* function explicit(serviceA) {};
* explicit.$inject = ['serviceA'];
* $injector.invoke(explicit);
*
* // inline
* $injector.invoke(['serviceA', function(serviceA){}]);
* ```
*
* ## Inference
*
* In JavaScript calling `toString()` on a function returns the function definition. The definition
* can then be parsed and the function arguments can be extracted. This method of discovering
* annotations is disallowed when the injector is in strict mode.
* *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
* argument names.
*
* ## `$inject` Annotation
* By adding an `$inject` property onto a function the injection parameters can be specified.
*
* ## Inline
* As an array of injection names, where the last item in the array is the function to call.
*/
/**
* @ngdoc method
* @name $injector#get
*
* @description
* Return an instance of the service.
*
* @param {string} name The name of the instance to retrieve.
* @param {string} caller An optional string to provide the origin of the function call for error messages.
* @return {*} The instance.
*/
/**
* @ngdoc method
* @name $injector#invoke
*
* @description
* Invoke the method and supply the method arguments from the `$injector`.
*
* @param {!Function} fn The function to invoke. Function parameters are injected according to the
* {@link guide/di $inject Annotation} rules.
* @param {Object=} self The `this` for the invoked method.
* @param {Object=} locals Optional object. If preset then any argument names are read from this
* object first, before the `$injector` is consulted.
* @returns {*} the value returned by the invoked `fn` function.
*/
/**
* @ngdoc method
* @name $injector#has
*
* @description
* Allows the user to query if the particular service exists.
*
* @param {string} name Name of the service to query.
* @returns {boolean} `true` if injector has given service.
*/
/**
* @ngdoc method
* @name $injector#instantiate
* @description
* Create a new instance of JS type. The method takes a constructor function, invokes the new
* operator, and supplies all of the arguments to the constructor function as specified by the
* constructor annotation.
*
* @param {Function} Type Annotated constructor function.
* @param {Object=} locals Optional object. If preset then any argument names are read from this
* object first, before the `$injector` is consulted.
* @returns {Object} new instance of `Type`.
*/
/**
* @ngdoc method
* @name $injector#annotate
*
* @description
* Returns an array of service names which the function is requesting for injection. This API is
* used by the injector to determine which services need to be injected into the function when the
* function is invoked. There are three ways in which the function can be annotated with the needed
* dependencies.
*
* # Argument names
*
* The simplest form is to extract the dependencies from the arguments of the function. This is done
* by converting the function into a string using `toString()` method and extracting the argument
* names.
* ```js
* // Given
* function MyController($scope, $route) {
* // ...
* }
*
* // Then
* expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
* ```
*
* You can disallow this method by using strict injection mode.
*
* This method does not work with code minification / obfuscation. For this reason the following
* annotation strategies are supported.
*
* # The `$inject` property
*
* If a function has an `$inject` property and its value is an array of strings, then the strings
* represent names of services to be injected into the function.
* ```js
* // Given
* var MyController = function(obfuscatedScope, obfuscatedRoute) {
* // ...
* }
* // Define function dependencies
* MyController['$inject'] = ['$scope', '$route'];
*
* // Then
* expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
* ```
*
* # The array notation
*
* It is often desirable to inline Injected functions and that's when setting the `$inject` property
* is very inconvenient. In these situations using the array notation to specify the dependencies in
* a way that survives minification is a better choice:
*
* ```js
* // We wish to write this (not minification / obfuscation safe)
* injector.invoke(function($compile, $rootScope) {
* // ...
* });
*
* // We are forced to write break inlining
* var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
* // ...
* };
* tmpFn.$inject = ['$compile', '$rootScope'];
* injector.invoke(tmpFn);
*
* // To better support inline function the inline annotation is supported
* injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
* // ...
* }]);
*
* // Therefore
* expect(injector.annotate(
* ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
* ).toEqual(['$compile', '$rootScope']);
* ```
*
* @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
* be retrieved as described above.
*
* @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
*
* @returns {Array.<string>} The names of the services which the function requires.
*/
/**
* @ngdoc service
* @name $provide
*
* @description
*
* The {@link auto.$provide $provide} service has a number of methods for registering components
* with the {@link auto.$injector $injector}. Many of these functions are also exposed on
* {@link angular.Module}.
*
* An Angular **service** is a singleton object created by a **service factory**. These **service
* factories** are functions which, in turn, are created by a **service provider**.
* The **service providers** are constructor functions. When instantiated they must contain a
* property called `$get`, which holds the **service factory** function.
*
* When you request a service, the {@link auto.$injector $injector} is responsible for finding the
* correct **service provider**, instantiating it and then calling its `$get` **service factory**
* function to get the instance of the **service**.
*
* Often services have no configuration options and there is no need to add methods to the service
* provider. The provider will be no more than a constructor function with a `$get` property. For
* these cases the {@link auto.$provide $provide} service has additional helper methods to register
* services without specifying a provider.
*
* * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the
* {@link auto.$injector $injector}
* * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by
* providers and services.
* * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by
* services, not providers.
* * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`,
* that will be wrapped in a **service provider** object, whose `$get` property will contain the
* given factory function.
* * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class`
* that will be wrapped in a **service provider** object, whose `$get` property will instantiate
* a new object using the given constructor function.
*
* See the individual methods for more information and examples.
*/
/**
* @ngdoc method
* @name $provide#provider
* @description
*
* Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
* are constructor functions, whose instances are responsible for "providing" a factory for a
* service.
*
* Service provider names start with the name of the service they provide followed by `Provider`.
* For example, the {@link ng.$log $log} service has a provider called
* {@link ng.$logProvider $logProvider}.
*
* Service provider objects can have additional methods which allow configuration of the provider
* and its service. Importantly, you can configure what kind of service is created by the `$get`
* method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
* method {@link ng.$logProvider#debugEnabled debugEnabled}
* which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
* console or not.
*
* @param {string} name The name of the instance. NOTE: the provider will be available under `name +
'Provider'` key.
* @param {(Object|function())} provider If the provider is:
*
* - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
* {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
* - `Constructor`: a new instance of the provider will be created using
* {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
*
* @returns {Object} registered provider instance
* @example
*
* The following example shows how to create a simple event tracking service and register it using
* {@link auto.$provide#provider $provide.provider()}.
*
* ```js
* // Define the eventTracker provider
* function EventTrackerProvider() {
* var trackingUrl = '/track';
*
* // A provider method for configuring where the tracked events should been saved
* this.setTrackingUrl = function(url) {
* trackingUrl = url;
* };
*
* // The service factory function
* this.$get = ['$http', function($http) {
* var trackedEvents = {};
* return {
* // Call this to track an event
* event: function(event) {
* var count = trackedEvents[event] || 0;
* count += 1;
* trackedEvents[event] = count;
* return count;
* },
* // Call this to save the tracked events to the trackingUrl
* save: function() {
* $http.post(trackingUrl, trackedEvents);
* }
* };
* }];
* }
*
* describe('eventTracker', function() {
* var postSpy;
*
* beforeEach(module(function($provide) {
* // Register the eventTracker provider
* $provide.provider('eventTracker', EventTrackerProvider);
* }));
*
* beforeEach(module(function(eventTrackerProvider) {
* // Configure eventTracker provider
* eventTrackerProvider.setTrackingUrl('/custom-track');
* }));
*
* it('tracks events', inject(function(eventTracker) {
* expect(eventTracker.event('login')).toEqual(1);
* expect(eventTracker.event('login')).toEqual(2);
* }));
*
* it('saves to the tracking url', inject(function(eventTracker, $http) {
* postSpy = spyOn($http, 'post');
* eventTracker.event('login');
* eventTracker.save();
* expect(postSpy).toHaveBeenCalled();
* expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
* expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
* expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
* }));
* });
* ```
*/
/**
* @ngdoc method
* @name $provide#factory
* @description
*
* Register a **service factory**, which will be called to return the service instance.
* This is short for registering a service where its provider consists of only a `$get` property,
* which is the given service factory function.
* You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
* configure your service in a provider.
*
* @param {string} name The name of the instance.
* @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand
* for `$provide.provider(name, {$get: $getFn})`.
* @returns {Object} registered provider instance
*
* @example
* Here is an example of registering a service
* ```js
* $provide.factory('ping', ['$http', function($http) {
* return function ping() {
* return $http.send('/ping');
* };
* }]);
* ```
* You would then inject and use this service like this:
* ```js
* someModule.controller('Ctrl', ['ping', function(ping) {
* ping();
* }]);
* ```
*/
/**
* @ngdoc method
* @name $provide#service
* @description
*
* Register a **service constructor**, which will be invoked with `new` to create the service
* instance.
* This is short for registering a service where its provider's `$get` property is the service
* constructor function that will be used to instantiate the service instance.
*
* You should use {@link auto.$provide#service $provide.service(class)} if you define your service
* as a type/class.
*
* @param {string} name The name of the instance.
* @param {Function} constructor A class (constructor function) that will be instantiated.
* @returns {Object} registered provider instance
*
* @example
* Here is an example of registering a service using
* {@link auto.$provide#service $provide.service(class)}.
* ```js
* var Ping = function($http) {
* this.$http = $http;
* };
*
* Ping.$inject = ['$http'];
*
* Ping.prototype.send = function() {
* return this.$http.get('/ping');
* };
* $provide.service('ping', Ping);
* ```
* You would then inject and use this service like this:
* ```js
* someModule.controller('Ctrl', ['ping', function(ping) {
* ping.send();
* }]);
* ```
*/
/**
* @ngdoc method
* @name $provide#value
* @description
*
* Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
* number, an array, an object or a function. This is short for registering a service where its
* provider's `$get` property is a factory function that takes no arguments and returns the **value
* service**.
*
* Value services are similar to constant services, except that they cannot be injected into a
* module configuration function (see {@link angular.Module#config}) but they can be overridden by
* an Angular
* {@link auto.$provide#decorator decorator}.
*
* @param {string} name The name of the instance.
* @param {*} value The value.
* @returns {Object} registered provider instance
*
* @example
* Here are some examples of creating value services.
* ```js
* $provide.value('ADMIN_USER', 'admin');
*
* $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
*
* $provide.value('halfOf', function(value) {
* return value / 2;
* });
* ```
*/
/**
* @ngdoc method
* @name $provide#constant
* @description
*
* Register a **constant service**, such as a string, a number, an array, an object or a function,
* with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be
* injected into a module configuration function (see {@link angular.Module#config}) and it cannot
* be overridden by an Angular {@link auto.$provide#decorator decorator}.
*
* @param {string} name The name of the constant.
* @param {*} value The constant value.
* @returns {Object} registered instance
*
* @example
* Here a some examples of creating constants:
* ```js
* $provide.constant('SHARD_HEIGHT', 306);
*
* $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
*
* $provide.constant('double', function(value) {
* return value * 2;
* });
* ```
*/
/**
* @ngdoc method
* @name $provide#decorator
* @description
*
* Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator
* intercepts the creation of a service, allowing it to override or modify the behaviour of the
* service. The object returned by the decorator may be the original service, or a new service
* object which replaces or wraps and delegates to the original service.
*
* @param {string} name The name of the service to decorate.
* @param {function()} decorator This function will be invoked when the service needs to be
* instantiated and should return the decorated service instance. The function is called using
* the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
* Local injection arguments:
*
* * `$delegate` - The original service instance, which can be monkey patched, configured,
* decorated or delegated to.
*
* @example
* Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
* calls to {@link ng.$log#error $log.warn()}.
* ```js
* $provide.decorator('$log', ['$delegate', function($delegate) {
* $delegate.warn = $delegate.error;
* return $delegate;
* }]);
* ```
*/
function createInjector(modulesToLoad, strictDi) {
strictDi = (strictDi === true);
var INSTANTIATING = {},
providerSuffix = 'Provider',
path = [],
loadedModules = new HashMap([], true),
providerCache = {
$provide: {
provider: supportObject(provider),
factory: supportObject(factory),
service: supportObject(service),
value: supportObject(value),
constant: supportObject(constant),
decorator: decorator
}
},
providerInjector = (providerCache.$injector =
createInternalInjector(providerCache, function(serviceName, caller) {
if (angular.isString(caller)) {
path.push(caller);
}
throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
})),
instanceCache = {},
instanceInjector = (instanceCache.$injector =
createInternalInjector(instanceCache, function(serviceName, caller) {
var provider = providerInjector.get(serviceName + providerSuffix, caller);
return instanceInjector.invoke(provider.$get, provider, undefined, serviceName);
}));
forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); });
return instanceInjector;
////////////////////////////////////
// $provider
////////////////////////////////////
function supportObject(delegate) {
return function(key, value) {
if (isObject(key)) {
forEach(key, reverseParams(delegate));
} else {
return delegate(key, value);
}
};
}
function provider(name, provider_) {
assertNotHasOwnProperty(name, 'service');
if (isFunction(provider_) || isArray(provider_)) {
provider_ = providerInjector.instantiate(provider_);
}
if (!provider_.$get) {
throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
}
return providerCache[name + providerSuffix] = provider_;
}
function enforceReturnValue(name, factory) {
return function enforcedReturnValue() {
var result = instanceInjector.invoke(factory, this);
if (isUndefined(result)) {
throw $injectorMinErr('undef', "Provider '{0}' must return a value from $get factory method.", name);
}
return result;
};
}
function factory(name, factoryFn, enforce) {
return provider(name, {
$get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
});
}
function service(name, constructor) {
return factory(name, ['$injector', function($injector) {
return $injector.instantiate(constructor);
}]);
}
function value(name, val) { return factory(name, valueFn(val), false); }
function constant(name, value) {
assertNotHasOwnProperty(name, 'constant');
providerCache[name] = value;
instanceCache[name] = value;
}
function decorator(serviceName, decorFn) {
var origProvider = providerInjector.get(serviceName + providerSuffix),
orig$get = origProvider.$get;
origProvider.$get = function() {
var origInstance = instanceInjector.invoke(orig$get, origProvider);
return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
};
}
////////////////////////////////////
// Module Loading
////////////////////////////////////
function loadModules(modulesToLoad) {
var runBlocks = [], moduleFn;
forEach(modulesToLoad, function(module) {
if (loadedModules.get(module)) return;
loadedModules.put(module, true);
function runInvokeQueue(queue) {
var i, ii;
for (i = 0, ii = queue.length; i < ii; i++) {
var invokeArgs = queue[i],
provider = providerInjector.get(invokeArgs[0]);
provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
}
}
try {
if (isString(module)) {
moduleFn = angularModule(module);
runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
runInvokeQueue(moduleFn._invokeQueue);
runInvokeQueue(moduleFn._configBlocks);
} else if (isFunction(module)) {
runBlocks.push(providerInjector.invoke(module));
} else if (isArray(module)) {
runBlocks.push(providerInjector.invoke(module));
} else {
assertArgFn(module, 'module');
}
} catch (e) {
if (isArray(module)) {
module = module[module.length - 1];
}
if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
// Safari & FF's stack traces don't contain error.message content
// unlike those of Chrome and IE
// So if stack doesn't contain message, we create a new string that contains both.
// Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
/* jshint -W022 */
e = e.message + '\n' + e.stack;
}
throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}",
module, e.stack || e.message || e);
}
});
return runBlocks;
}
////////////////////////////////////
// internal Injector
////////////////////////////////////
function createInternalInjector(cache, factory) {
function getService(serviceName, caller) {
if (cache.hasOwnProperty(serviceName)) {
if (cache[serviceName] === INSTANTIATING) {
throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
serviceName + ' <- ' + path.join(' <- '));
}
return cache[serviceName];
} else {
try {
path.unshift(serviceName);
cache[serviceName] = INSTANTIATING;
return cache[serviceName] = factory(serviceName, caller);
} catch (err) {
if (cache[serviceName] === INSTANTIATING) {
delete cache[serviceName];
}
throw err;
} finally {
path.shift();
}
}
}
function invoke(fn, self, locals, serviceName) {
if (typeof locals === 'string') {
serviceName = locals;
locals = null;
}
var args = [],
$inject = createInjector.$$annotate(fn, strictDi, serviceName),
length, i,
key;
for (i = 0, length = $inject.length; i < length; i++) {
key = $inject[i];
if (typeof key !== 'string') {
throw $injectorMinErr('itkn',
'Incorrect injection token! Expected service name as string, got {0}', key);
}
args.push(
locals && locals.hasOwnProperty(key)
? locals[key]
: getService(key, serviceName)
);
}
if (isArray(fn)) {
fn = fn[length];
}
// http://jsperf.com/angularjs-invoke-apply-vs-switch
// #5388
return fn.apply(self, args);
}
function instantiate(Type, locals, serviceName) {
// Check if Type is annotated and use just the given function at n-1 as parameter
// e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
// Object creation: http://jsperf.com/create-constructor/2
var instance = Object.create((isArray(Type) ? Type[Type.length - 1] : Type).prototype || null);
var returnedValue = invoke(Type, instance, locals, serviceName);
return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;
}
return {
invoke: invoke,
instantiate: instantiate,
get: getService,
annotate: createInjector.$$annotate,
has: function(name) {
return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
}
};
}
}
createInjector.$$annotate = annotate;
/**
* @ngdoc provider
* @name $anchorScrollProvider
*
* @description
* Use `$anchorScrollProvider` to disable automatic scrolling whenever
* {@link ng.$location#hash $location.hash()} changes.
*/
function $AnchorScrollProvider() {
var autoScrollingEnabled = true;
/**
* @ngdoc method
* @name $anchorScrollProvider#disableAutoScrolling
*
* @description
* By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
* {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
* Use this method to disable automatic scrolling.
*
* If automatic scrolling is disabled, one must explicitly call
* {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
* current hash.
*/
this.disableAutoScrolling = function() {
autoScrollingEnabled = false;
};
/**
* @ngdoc service
* @name $anchorScroll
* @kind function
* @requires $window
* @requires $location
* @requires $rootScope
*
* @description
* When called, it checks the current value of {@link ng.$location#hash $location.hash()} and
* scrolls to the related element, according to the rules specified in the
* [Html5 spec](http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document).
*
* It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
* match any anchor whenever it changes. This can be disabled by calling
* {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
*
* Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
* vertical scroll-offset (either fixed or dynamic).
*
* @property {(number|function|jqLite)} yOffset
* If set, specifies a vertical scroll-offset. This is often useful when there are fixed
* positioned elements at the top of the page, such as navbars, headers etc.
*
* `yOffset` can be specified in various ways:
* - **number**: A fixed number of pixels to be used as offset.<br /><br />
* - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
* a number representing the offset (in pixels).<br /><br />
* - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
* the top of the page to the element's bottom will be used as offset.<br />
* **Note**: The element will be taken into account only as long as its `position` is set to
* `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
* their height and/or positioning according to the viewport's size.
*
* <br />
* <div class="alert alert-warning">
* In order for `yOffset` to work properly, scrolling should take place on the document's root and
* not some child element.
* </div>
*
* @example
<example module="anchorScrollExample">
<file name="index.html">
<div id="scrollArea" ng-controller="ScrollController">
<a ng-click="gotoBottom()">Go to bottom</a>
<a id="bottom"></a> You're at the bottom!
</div>
</file>
<file name="script.js">
angular.module('anchorScrollExample', [])
.controller('ScrollController', ['$scope', '$location', '$anchorScroll',
function ($scope, $location, $anchorScroll) {
$scope.gotoBottom = function() {
// set the location.hash to the id of
// the element you wish to scroll to.
$location.hash('bottom');
// call $anchorScroll()
$anchorScroll();
};
}]);
</file>
<file name="style.css">
#scrollArea {
height: 280px;
overflow: auto;
}
#bottom {
display: block;
margin-top: 2000px;
}
</file>
</example>
*
* <hr />
* The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
* See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
*
* @example
<example module="anchorScrollOffsetExample">
<file name="index.html">
<div class="fixed-header" ng-controller="headerCtrl">
<a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
Go to anchor {{x}}
</a>
</div>
<div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
Anchor {{x}} of 5
</div>
</file>
<file name="script.js">
angular.module('anchorScrollOffsetExample', [])
.run(['$anchorScroll', function($anchorScroll) {
$anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
}])
.controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
function ($anchorScroll, $location, $scope) {
$scope.gotoAnchor = function(x) {
var newHash = 'anchor' + x;
if ($location.hash() !== newHash) {
// set the $location.hash to `newHash` and
// $anchorScroll will automatically scroll to it
$location.hash('anchor' + x);
} else {
// call $anchorScroll() explicitly,
// since $location.hash hasn't changed
$anchorScroll();
}
};
}
]);
</file>
<file name="style.css">
body {
padding-top: 50px;
}
.anchor {
border: 2px dashed DarkOrchid;
padding: 10px 10px 200px 10px;
}
.fixed-header {
background-color: rgba(0, 0, 0, 0.2);
height: 50px;
position: fixed;
top: 0; left: 0; right: 0;
}
.fixed-header > a {
display: inline-block;
margin: 5px 15px;
}
</file>
</example>
*/
this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
var document = $window.document;
// Helper function to get first anchor from a NodeList
// (using `Array#some()` instead of `angular#forEach()` since it's more performant
// and working in all supported browsers.)
function getFirstAnchor(list) {
var result = null;
Array.prototype.some.call(list, function(element) {
if (nodeName_(element) === 'a') {
result = element;
return true;
}
});
return result;
}
function getYOffset() {
var offset = scroll.yOffset;
if (isFunction(offset)) {
offset = offset();
} else if (isElement(offset)) {
var elem = offset[0];
var style = $window.getComputedStyle(elem);
if (style.position !== 'fixed') {
offset = 0;
} else {
offset = elem.getBoundingClientRect().bottom;
}
} else if (!isNumber(offset)) {
offset = 0;
}
return offset;
}
function scrollTo(elem) {
if (elem) {
elem.scrollIntoView();
var offset = getYOffset();
if (offset) {
// `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
// This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
// top of the viewport.
//
// IF the number of pixels from the top of `elem` to the end of the page's content is less
// than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
// way down the page.
//
// This is often the case for elements near the bottom of the page.
//
// In such cases we do not need to scroll the whole `offset` up, just the difference between
// the top of the element and the offset, which is enough to align the top of `elem` at the
// desired position.
var elemTop = elem.getBoundingClientRect().top;
$window.scrollBy(0, elemTop - offset);
}
} else {
$window.scrollTo(0, 0);
}
}
function scroll() {
var hash = $location.hash(), elm;
// empty hash, scroll to the top of the page
if (!hash) scrollTo(null);
// element with given id
else if ((elm = document.getElementById(hash))) scrollTo(elm);
// first anchor with given name :-D
else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
// no element and hash == 'top', scroll to the top of the page
else if (hash === 'top') scrollTo(null);
}
// does not scroll when user clicks on anchor link that is currently on
// (no url change, no $location.hash() change), browser native does scroll
if (autoScrollingEnabled) {
$rootScope.$watch(function autoScrollWatch() {return $location.hash();},
function autoScrollWatchAction(newVal, oldVal) {
// skip the initial scroll if $location.hash is empty
if (newVal === oldVal && newVal === '') return;
jqLiteDocumentLoaded(function() {
$rootScope.$evalAsync(scroll);
});
});
}
return scroll;
}];
}
var $animateMinErr = minErr('$animate');
/**
* @ngdoc provider
* @name $animateProvider
*
* @description
* Default implementation of $animate that doesn't perform any animations, instead just
* synchronously performs DOM
* updates and calls done() callbacks.
*
* In order to enable animations the ngAnimate module has to be loaded.
*
* To see the functional implementation check out src/ngAnimate/animate.js
*/
var $AnimateProvider = ['$provide', function($provide) {
this.$$selectors = {};
/**
* @ngdoc method
* @name $animateProvider#register
*
* @description
* Registers a new injectable animation factory function. The factory function produces the
* animation object which contains callback functions for each event that is expected to be
* animated.
*
* * `eventFn`: `function(Element, doneFunction)` The element to animate, the `doneFunction`
* must be called once the element animation is complete. If a function is returned then the
* animation service will use this function to cancel the animation whenever a cancel event is
* triggered.
*
*
* ```js
* return {
* eventFn : function(element, done) {
* //code to run the animation
* //once complete, then run done()
* return function cancellationFunction() {
* //code to cancel the animation
* }
* }
* }
* ```
*
* @param {string} name The name of the animation.
* @param {Function} factory The factory function that will be executed to return the animation
* object.
*/
this.register = function(name, factory) {
var key = name + '-animation';
if (name && name.charAt(0) != '.') throw $animateMinErr('notcsel',
"Expecting class selector starting with '.' got '{0}'.", name);
this.$$selectors[name.substr(1)] = key;
$provide.factory(key, factory);
};
/**
* @ngdoc method
* @name $animateProvider#classNameFilter
*
* @description
* Sets and/or returns the CSS class regular expression that is checked when performing
* an animation. Upon bootstrap the classNameFilter value is not set at all and will
* therefore enable $animate to attempt to perform an animation on any element.
* When setting the classNameFilter value, animations will only be performed on elements
* that successfully match the filter expression. This in turn can boost performance
* for low-powered devices as well as applications containing a lot of structural operations.
* @param {RegExp=} expression The className expression which will be checked against all animations
* @return {RegExp} The current CSS className expression value. If null then there is no expression value
*/
this.classNameFilter = function(expression) {
if (arguments.length === 1) {
this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
}
return this.$$classNameFilter;
};
this.$get = ['$$q', '$$asyncCallback', '$rootScope', function($$q, $$asyncCallback, $rootScope) {
var currentDefer;
function runAnimationPostDigest(fn) {
var cancelFn, defer = $$q.defer();
defer.promise.$$cancelFn = function ngAnimateMaybeCancel() {
cancelFn && cancelFn();
};
$rootScope.$$postDigest(function ngAnimatePostDigest() {
cancelFn = fn(function ngAnimateNotifyComplete() {
defer.resolve();
});
});
return defer.promise;
}
function resolveElementClasses(element, classes) {
var toAdd = [], toRemove = [];
var hasClasses = createMap();
forEach((element.attr('class') || '').split(/\s+/), function(className) {
hasClasses[className] = true;
});
forEach(classes, function(status, className) {
var hasClass = hasClasses[className];
// If the most recent class manipulation (via $animate) was to remove the class, and the
// element currently has the class, the class is scheduled for removal. Otherwise, if
// the most recent class manipulation (via $animate) was to add the class, and the
// element does not currently have the class, the class is scheduled to be added.
if (status === false && hasClass) {
toRemove.push(className);
} else if (status === true && !hasClass) {
toAdd.push(className);
}
});
return (toAdd.length + toRemove.length) > 0 &&
[toAdd.length ? toAdd : null, toRemove.length ? toRemove : null];
}
function cachedClassManipulation(cache, classes, op) {
for (var i=0, ii = classes.length; i < ii; ++i) {
var className = classes[i];
cache[className] = op;
}
}
function asyncPromise() {
// only serve one instance of a promise in order to save CPU cycles
if (!currentDefer) {
currentDefer = $$q.defer();
$$asyncCallback(function() {
currentDefer.resolve();
currentDefer = null;
});
}
return currentDefer.promise;
}
function applyStyles(element, options) {
if (angular.isObject(options)) {
var styles = extend(options.from || {}, options.to || {});
element.css(styles);
}
}
/**
*
* @ngdoc service
* @name $animate
* @description The $animate service provides rudimentary DOM manipulation functions to
* insert, remove and move elements within the DOM, as well as adding and removing classes.
* This service is the core service used by the ngAnimate $animator service which provides
* high-level animation hooks for CSS and JavaScript.
*
* $animate is available in the AngularJS core, however, the ngAnimate module must be included
* to enable full out animation support. Otherwise, $animate will only perform simple DOM
* manipulation operations.
*
* To learn more about enabling animation support, click here to visit the {@link ngAnimate
* ngAnimate module page} as well as the {@link ngAnimate.$animate ngAnimate $animate service
* page}.
*/
return {
animate: function(element, from, to) {
applyStyles(element, { from: from, to: to });
return asyncPromise();
},
/**
*
* @ngdoc method
* @name $animate#enter
* @kind function
* @description Inserts the element into the DOM either after the `after` element or
* as the first child within the `parent` element. When the function is called a promise
* is returned that will be resolved at a later time.
* @param {DOMElement} element the element which will be inserted into the DOM
* @param {DOMElement} parent the parent element which will append the element as
* a child (if the after element is not present)
* @param {DOMElement} after the sibling element which will append the element
* after itself
* @param {object=} options an optional collection of styles that will be applied to the element.
* @return {Promise} the animation callback promise
*/
enter: function(element, parent, after, options) {
applyStyles(element, options);
after ? after.after(element)
: parent.prepend(element);
return asyncPromise();
},
/**
*
* @ngdoc method
* @name $animate#leave
* @kind function
* @description Removes the element from the DOM. When the function is called a promise
* is returned that will be resolved at a later time.
* @param {DOMElement} element the element which will be removed from the DOM
* @param {object=} options an optional collection of options that will be applied to the element.
* @return {Promise} the animation callback promise
*/
leave: function(element, options) {
applyStyles(element, options);
element.remove();
return asyncPromise();
},
/**
*
* @ngdoc method
* @name $animate#move
* @kind function
* @description Moves the position of the provided element within the DOM to be placed
* either after the `after` element or inside of the `parent` element. When the function
* is called a promise is returned that will be resolved at a later time.
*
* @param {DOMElement} element the element which will be moved around within the
* DOM
* @param {DOMElement} parent the parent element where the element will be
* inserted into (if the after element is not present)
* @param {DOMElement} after the sibling element where the element will be
* positioned next to
* @param {object=} options an optional collection of options that will be applied to the element.
* @return {Promise} the animation callback promise
*/
move: function(element, parent, after, options) {
// Do not remove element before insert. Removing will cause data associated with the
// element to be dropped. Insert will implicitly do the remove.
return this.enter(element, parent, after, options);
},
/**
*
* @ngdoc method
* @name $animate#addClass
* @kind function
* @description Adds the provided className CSS class value to the provided element.
* When the function is called a promise is returned that will be resolved at a later time.
* @param {DOMElement} element the element which will have the className value
* added to it
* @param {string} className the CSS class which will be added to the element
* @param {object=} options an optional collection of options that will be applied to the element.
* @return {Promise} the animation callback promise
*/
addClass: function(element, className, options) {
return this.setClass(element, className, [], options);
},
$$addClassImmediately: function(element, className, options) {
element = jqLite(element);
className = !isString(className)
? (isArray(className) ? className.join(' ') : '')
: className;
forEach(element, function(element) {
jqLiteAddClass(element, className);
});
applyStyles(element, options);
return asyncPromise();
},
/**
*
* @ngdoc method
* @name $animate#removeClass
* @kind function
* @description Removes the provided className CSS class value from the provided element.
* When the function is called a promise is returned that will be resolved at a later time.
* @param {DOMElement} element the element which will have the className value
* removed from it
* @param {string} className the CSS class which will be removed from the element
* @param {object=} options an optional collection of options that will be applied to the element.
* @return {Promise} the animation callback promise
*/
removeClass: function(element, className, options) {
return this.setClass(element, [], className, options);
},
$$removeClassImmediately: function(element, className, options) {
element = jqLite(element);
className = !isString(className)
? (isArray(className) ? className.join(' ') : '')
: className;
forEach(element, function(element) {
jqLiteRemoveClass(element, className);
});
applyStyles(element, options);
return asyncPromise();
},
/**
*
* @ngdoc method
* @name $animate#setClass
* @kind function
* @description Adds and/or removes the given CSS classes to and from the element.
* When the function is called a promise is returned that will be resolved at a later time.
* @param {DOMElement} element the element which will have its CSS classes changed
* removed from it
* @param {string} add the CSS classes which will be added to the element
* @param {string} remove the CSS class which will be removed from the element
* @param {object=} options an optional collection of options that will be applied to the element.
* @return {Promise} the animation callback promise
*/
setClass: function(element, add, remove, options) {
var self = this;
var STORAGE_KEY = '$$animateClasses';
var createdCache = false;
element = jqLite(element);
var cache = element.data(STORAGE_KEY);
if (!cache) {
cache = {
classes: {},
options: options
};
createdCache = true;
} else if (options && cache.options) {
cache.options = angular.extend(cache.options || {}, options);
}
var classes = cache.classes;
add = isArray(add) ? add : add.split(' ');
remove = isArray(remove) ? remove : remove.split(' ');
cachedClassManipulation(classes, add, true);
cachedClassManipulation(classes, remove, false);
if (createdCache) {
cache.promise = runAnimationPostDigest(function(done) {
var cache = element.data(STORAGE_KEY);
element.removeData(STORAGE_KEY);
// in the event that the element is removed before postDigest
// is run then the cache will be undefined and there will be
// no need anymore to add or remove and of the element classes
if (cache) {
var classes = resolveElementClasses(element, cache.classes);
if (classes) {
self.$$setClassImmediately(element, classes[0], classes[1], cache.options);
}
}
done();
});
element.data(STORAGE_KEY, cache);
}
return cache.promise;
},
$$setClassImmediately: function(element, add, remove, options) {
add && this.$$addClassImmediately(element, add);
remove && this.$$removeClassImmediately(element, remove);
applyStyles(element, options);
return asyncPromise();
},
enabled: noop,
cancel: noop
};
}];
}];
function $$AsyncCallbackProvider() {
this.$get = ['$$rAF', '$timeout', function($$rAF, $timeout) {
return $$rAF.supported
? function(fn) { return $$rAF(fn); }
: function(fn) {
return $timeout(fn, 0, false);
};
}];
}
/* global stripHash: true */
/**
* ! This is a private undocumented service !
*
* @name $browser
* @requires $log
* @description
* This object has two goals:
*
* - hide all the global state in the browser caused by the window object
* - abstract away all the browser specific features and inconsistencies
*
* For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
* service, which can be used for convenient testing of the application without the interaction with
* the real browser apis.
*/
/**
* @param {object} window The global window object.
* @param {object} document jQuery wrapped document.
* @param {object} $log window.console or an object with the same interface.
* @param {object} $sniffer $sniffer service
*/
function Browser(window, document, $log, $sniffer) {
var self = this,
rawDocument = document[0],
location = window.location,
history = window.history,
setTimeout = window.setTimeout,
clearTimeout = window.clearTimeout,
pendingDeferIds = {};
self.isMock = false;
var outstandingRequestCount = 0;
var outstandingRequestCallbacks = [];
// TODO(vojta): remove this temporary api
self.$$completeOutstandingRequest = completeOutstandingRequest;
self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
/**
* Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
* counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
*/
function completeOutstandingRequest(fn) {
try {
fn.apply(null, sliceArgs(arguments, 1));
} finally {
outstandingRequestCount--;
if (outstandingRequestCount === 0) {
while (outstandingRequestCallbacks.length) {
try {
outstandingRequestCallbacks.pop()();
} catch (e) {
$log.error(e);
}
}
}
}
}
function getHash(url) {
var index = url.indexOf('#');
return index === -1 ? '' : url.substr(index + 1);
}
/**
* @private
* Note: this method is used only by scenario runner
* TODO(vojta): prefix this method with $$ ?
* @param {function()} callback Function that will be called when no outstanding request
*/
self.notifyWhenNoOutstandingRequests = function(callback) {
// force browser to execute all pollFns - this is needed so that cookies and other pollers fire
// at some deterministic time in respect to the test runner's actions. Leaving things up to the
// regular poller would result in flaky tests.
forEach(pollFns, function(pollFn) { pollFn(); });
if (outstandingRequestCount === 0) {
callback();
} else {
outstandingRequestCallbacks.push(callback);
}
};
//////////////////////////////////////////////////////////////
// Poll Watcher API
//////////////////////////////////////////////////////////////
var pollFns = [],
pollTimeout;
/**
* @name $browser#addPollFn
*
* @param {function()} fn Poll function to add
*
* @description
* Adds a function to the list of functions that poller periodically executes,
* and starts polling if not started yet.
*
* @returns {function()} the added function
*/
self.addPollFn = function(fn) {
if (isUndefined(pollTimeout)) startPoller(100, setTimeout);
pollFns.push(fn);
return fn;
};
/**
* @param {number} interval How often should browser call poll functions (ms)
* @param {function()} setTimeout Reference to a real or fake `setTimeout` function.
*
* @description
* Configures the poller to run in the specified intervals, using the specified
* setTimeout fn and kicks it off.
*/
function startPoller(interval, setTimeout) {
(function check() {
forEach(pollFns, function(pollFn) { pollFn(); });
pollTimeout = setTimeout(check, interval);
})();
}
//////////////////////////////////////////////////////////////
// URL API
//////////////////////////////////////////////////////////////
var cachedState, lastHistoryState,
lastBrowserUrl = location.href,
baseElement = document.find('base'),
reloadLocation = null;
cacheState();
lastHistoryState = cachedState;
/**
* @name $browser#url
*
* @description
* GETTER:
* Without any argument, this method just returns current value of location.href.
*
* SETTER:
* With at least one argument, this method sets url to new value.
* If html5 history api supported, pushState/replaceState is used, otherwise
* location.href/location.replace is used.
* Returns its own instance to allow chaining
*
* NOTE: this api is intended for use only by the $location service. Please use the
* {@link ng.$location $location service} to change url.
*
* @param {string} url New url (when used as setter)
* @param {boolean=} replace Should new url replace current history record?
* @param {object=} state object to use with pushState/replaceState
*/
self.url = function(url, replace, state) {
// In modern browsers `history.state` is `null` by default; treating it separately
// from `undefined` would cause `$browser.url('/foo')` to change `history.state`
// to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
if (isUndefined(state)) {
state = null;
}
// Android Browser BFCache causes location, history reference to become stale.
if (location !== window.location) location = window.location;
if (history !== window.history) history = window.history;
// setter
if (url) {
var sameState = lastHistoryState === state;
// Don't change anything if previous and current URLs and states match. This also prevents
// IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
// See https://github.com/angular/angular.js/commit/ffb2701
if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
return self;
}
var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
lastBrowserUrl = url;
lastHistoryState = state;
// Don't use history API if only the hash changed
// due to a bug in IE10/IE11 which leads
// to not firing a `hashchange` nor `popstate` event
// in some cases (see #9143).
if ($sniffer.history && (!sameBase || !sameState)) {
history[replace ? 'replaceState' : 'pushState'](state, '', url);
cacheState();
// Do the assignment again so that those two variables are referentially identical.
lastHistoryState = cachedState;
} else {
if (!sameBase) {
reloadLocation = url;
}
if (replace) {
location.replace(url);
} else if (!sameBase) {
location.href = url;
} else {
location.hash = getHash(url);
}
}
return self;
// getter
} else {
// - reloadLocation is needed as browsers don't allow to read out
// the new location.href if a reload happened.
// - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
return reloadLocation || location.href.replace(/%27/g,"'");
}
};
/**
* @name $browser#state
*
* @description
* This method is a getter.
*
* Return history.state or null if history.state is undefined.
*
* @returns {object} state
*/
self.state = function() {
return cachedState;
};
var urlChangeListeners = [],
urlChangeInit = false;
function cacheStateAndFireUrlChange() {
cacheState();
fireUrlChange();
}
function getCurrentState() {
try {
return history.state;
} catch (e) {
// MSIE can reportedly throw when there is no state (UNCONFIRMED).
}
}
// This variable should be used *only* inside the cacheState function.
var lastCachedState = null;
function cacheState() {
// This should be the only place in $browser where `history.state` is read.
cachedState = getCurrentState();
cachedState = isUndefined(cachedState) ? null : cachedState;
// Prevent callbacks fo fire twice if both hashchange & popstate were fired.
if (equals(cachedState, lastCachedState)) {
cachedState = lastCachedState;
}
lastCachedState = cachedState;
}
function fireUrlChange() {
if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {
return;
}
lastBrowserUrl = self.url();
lastHistoryState = cachedState;
forEach(urlChangeListeners, function(listener) {
listener(self.url(), cachedState);
});
}
/**
* @name $browser#onUrlChange
*
* @description
* Register callback function that will be called, when url changes.
*
* It's only called when the url is changed from outside of angular:
* - user types different url into address bar
* - user clicks on history (forward/back) button
* - user clicks on a link
*
* It's not called when url is changed by $browser.url() method
*
* The listener gets called with new url as parameter.
*
* NOTE: this api is intended for use only by the $location service. Please use the
* {@link ng.$location $location service} to monitor url changes in angular apps.
*
* @param {function(string)} listener Listener function to be called when url changes.
* @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
*/
self.onUrlChange = function(callback) {
// TODO(vojta): refactor to use node's syntax for events
if (!urlChangeInit) {
// We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
// don't fire popstate when user change the address bar and don't fire hashchange when url
// changed by push/replaceState
// html5 history api - popstate event
if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
// hashchange event
jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
urlChangeInit = true;
}
urlChangeListeners.push(callback);
return callback;
};
/**
* Checks whether the url has changed outside of Angular.
* Needs to be exported to be able to check for changes that have been done in sync,
* as hashchange/popstate events fire in async.
*/
self.$$checkUrlChange = fireUrlChange;
//////////////////////////////////////////////////////////////
// Misc API
//////////////////////////////////////////////////////////////
/**
* @name $browser#baseHref
*
* @description
* Returns current <base href>
* (always relative - without domain)
*
* @returns {string} The current base href
*/
self.baseHref = function() {
var href = baseElement.attr('href');
return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
};
//////////////////////////////////////////////////////////////
// Cookies API
//////////////////////////////////////////////////////////////
var lastCookies = {};
var lastCookieString = '';
var cookiePath = self.baseHref();
function safeDecodeURIComponent(str) {
try {
return decodeURIComponent(str);
} catch (e) {
return str;
}
}
/**
* @name $browser#cookies
*
* @param {string=} name Cookie name
* @param {string=} value Cookie value
*
* @description
* The cookies method provides a 'private' low level access to browser cookies.
* It is not meant to be used directly, use the $cookie service instead.
*
* The return values vary depending on the arguments that the method was called with as follows:
*
* - cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify
* it
* - cookies(name, value) -> set name to value, if value is undefined delete the cookie
* - cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that
* way)
*
* @returns {Object} Hash of all cookies (if called without any parameter)
*/
self.cookies = function(name, value) {
var cookieLength, cookieArray, cookie, i, index;
if (name) {
if (value === undefined) {
rawDocument.cookie = encodeURIComponent(name) + "=;path=" + cookiePath +
";expires=Thu, 01 Jan 1970 00:00:00 GMT";
} else {
if (isString(value)) {
cookieLength = (rawDocument.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value) +
';path=' + cookiePath).length + 1;
// per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum:
// - 300 cookies
// - 20 cookies per unique domain
// - 4096 bytes per cookie
if (cookieLength > 4096) {
$log.warn("Cookie '" + name +
"' possibly not set or overflowed because it was too large (" +
cookieLength + " > 4096 bytes)!");
}
}
}
} else {
if (rawDocument.cookie !== lastCookieString) {
lastCookieString = rawDocument.cookie;
cookieArray = lastCookieString.split("; ");
lastCookies = {};
for (i = 0; i < cookieArray.length; i++) {
cookie = cookieArray[i];
index = cookie.indexOf('=');
if (index > 0) { //ignore nameless cookies
name = safeDecodeURIComponent(cookie.substring(0, index));
// the first value that is seen for a cookie is the most
// specific one. values for the same cookie name that
// follow are for less specific paths.
if (lastCookies[name] === undefined) {
lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
}
}
}
}
return lastCookies;
}
};
/**
* @name $browser#defer
* @param {function()} fn A function, who's execution should be deferred.
* @param {number=} [delay=0] of milliseconds to defer the function execution.
* @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
*
* @description
* Executes a fn asynchronously via `setTimeout(fn, delay)`.
*
* Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
* `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
* via `$browser.defer.flush()`.
*
*/
self.defer = function(fn, delay) {
var timeoutId;
outstandingRequestCount++;
timeoutId = setTimeout(function() {
delete pendingDeferIds[timeoutId];
completeOutstandingRequest(fn);
}, delay || 0);
pendingDeferIds[timeoutId] = true;
return timeoutId;
};
/**
* @name $browser#defer.cancel
*
* @description
* Cancels a deferred task identified with `deferId`.
*
* @param {*} deferId Token returned by the `$browser.defer` function.
* @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
* canceled.
*/
self.defer.cancel = function(deferId) {
if (pendingDeferIds[deferId]) {
delete pendingDeferIds[deferId];
clearTimeout(deferId);
completeOutstandingRequest(noop);
return true;
}
return false;
};
}
function $BrowserProvider() {
this.$get = ['$window', '$log', '$sniffer', '$document',
function($window, $log, $sniffer, $document) {
return new Browser($window, $document, $log, $sniffer);
}];
}
/**
* @ngdoc service
* @name $cacheFactory
*
* @description
* Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
* them.
*
* ```js
*
* var cache = $cacheFactory('cacheId');
* expect($cacheFactory.get('cacheId')).toBe(cache);
* expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
*
* cache.put("key", "value");
* cache.put("another key", "another value");
*
* // We've specified no options on creation
* expect(cache.info()).toEqual({id: 'cacheId', size: 2});
*
* ```
*
*
* @param {string} cacheId Name or id of the newly created cache.
* @param {object=} options Options object that specifies the cache behavior. Properties:
*
* - `{number=}` `capacity` — turns the cache into LRU cache.
*
* @returns {object} Newly created cache object with the following set of methods:
*
* - `{object}` `info()` — Returns id, size, and options of cache.
* - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
* it.
* - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
* - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
* - `{void}` `removeAll()` — Removes all cached values.
* - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
*
* @example
<example module="cacheExampleApp">
<file name="index.html">
<div ng-controller="CacheController">
<input ng-model="newCacheKey" placeholder="Key">
<input ng-model="newCacheValue" placeholder="Value">
<button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
<p ng-if="keys.length">Cached Values</p>
<div ng-repeat="key in keys">
<span ng-bind="key"></span>
<span>: </span>
<b ng-bind="cache.get(key)"></b>
</div>
<p>Cache Info</p>
<div ng-repeat="(key, value) in cache.info()">
<span ng-bind="key"></span>
<span>: </span>
<b ng-bind="value"></b>
</div>
</div>
</file>
<file name="script.js">
angular.module('cacheExampleApp', []).
controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
$scope.keys = [];
$scope.cache = $cacheFactory('cacheId');
$scope.put = function(key, value) {
if ($scope.cache.get(key) === undefined) {
$scope.keys.push(key);
}
$scope.cache.put(key, value === undefined ? null : value);
};
}]);
</file>
<file name="style.css">
p {
margin: 10px 0 3px;
}
</file>
</example>
*/
function $CacheFactoryProvider() {
this.$get = function() {
var caches = {};
function cacheFactory(cacheId, options) {
if (cacheId in caches) {
throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
}
var size = 0,
stats = extend({}, options, {id: cacheId}),
data = {},
capacity = (options && options.capacity) || Number.MAX_VALUE,
lruHash = {},
freshEnd = null,
staleEnd = null;
/**
* @ngdoc type
* @name $cacheFactory.Cache
*
* @description
* A cache object used to store and retrieve data, primarily used by
* {@link $http $http} and the {@link ng.directive:script script} directive to cache
* templates and other data.
*
* ```js
* angular.module('superCache')
* .factory('superCache', ['$cacheFactory', function($cacheFactory) {
* return $cacheFactory('super-cache');
* }]);
* ```
*
* Example test:
*
* ```js
* it('should behave like a cache', inject(function(superCache) {
* superCache.put('key', 'value');
* superCache.put('another key', 'another value');
*
* expect(superCache.info()).toEqual({
* id: 'super-cache',
* size: 2
* });
*
* superCache.remove('another key');
* expect(superCache.get('another key')).toBeUndefined();
*
* superCache.removeAll();
* expect(superCache.info()).toEqual({
* id: 'super-cache',
* size: 0
* });
* }));
* ```
*/
return caches[cacheId] = {
/**
* @ngdoc method
* @name $cacheFactory.Cache#put
* @kind function
*
* @description
* Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
* retrieved later, and incrementing the size of the cache if the key was not already
* present in the cache. If behaving like an LRU cache, it will also remove stale
* entries from the set.
*
* It will not insert undefined values into the cache.
*
* @param {string} key the key under which the cached data is stored.
* @param {*} value the value to store alongside the key. If it is undefined, the key
* will not be stored.
* @returns {*} the value stored.
*/
put: function(key, value) {
if (capacity < Number.MAX_VALUE) {
var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
refresh(lruEntry);
}
if (isUndefined(value)) return;
if (!(key in data)) size++;
data[key] = value;
if (size > capacity) {
this.remove(staleEnd.key);
}
return value;
},
/**
* @ngdoc method
* @name $cacheFactory.Cache#get
* @kind function
*
* @description
* Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
*
* @param {string} key the key of the data to be retrieved
* @returns {*} the value stored.
*/
get: function(key) {
if (capacity < Number.MAX_VALUE) {
var lruEntry = lruHash[key];
if (!lruEntry) return;
refresh(lruEntry);
}
return data[key];
},
/**
* @ngdoc method
* @name $cacheFactory.Cache#remove
* @kind function
*
* @description
* Removes an entry from the {@link $cacheFactory.Cache Cache} object.
*
* @param {string} key the key of the entry to be removed
*/
remove: function(key) {
if (capacity < Number.MAX_VALUE) {
var lruEntry = lruHash[key];
if (!lruEntry) return;
if (lruEntry == freshEnd) freshEnd = lruEntry.p;
if (lruEntry == staleEnd) staleEnd = lruEntry.n;
link(lruEntry.n,lruEntry.p);
delete lruHash[key];
}
delete data[key];
size--;
},
/**
* @ngdoc method
* @name $cacheFactory.Cache#removeAll
* @kind function
*
* @description
* Clears the cache object of any entries.
*/
removeAll: function() {
data = {};
size = 0;
lruHash = {};
freshEnd = staleEnd = null;
},
/**
* @ngdoc method
* @name $cacheFactory.Cache#destroy
* @kind function
*
* @description
* Destroys the {@link $cacheFactory.Cache Cache} object entirely,
* removing it from the {@link $cacheFactory $cacheFactory} set.
*/
destroy: function() {
data = null;
stats = null;
lruHash = null;
delete caches[cacheId];
},
/**
* @ngdoc method
* @name $cacheFactory.Cache#info
* @kind function
*
* @description
* Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
*
* @returns {object} an object with the following properties:
* <ul>
* <li>**id**: the id of the cache instance</li>
* <li>**size**: the number of entries kept in the cache instance</li>
* <li>**...**: any additional properties from the options object when creating the
* cache.</li>
* </ul>
*/
info: function() {
return extend({}, stats, {size: size});
}
};
/**
* makes the `entry` the freshEnd of the LRU linked list
*/
function refresh(entry) {
if (entry != freshEnd) {
if (!staleEnd) {
staleEnd = entry;
} else if (staleEnd == entry) {
staleEnd = entry.n;
}
link(entry.n, entry.p);
link(entry, freshEnd);
freshEnd = entry;
freshEnd.n = null;
}
}
/**
* bidirectionally links two entries of the LRU linked list
*/
function link(nextEntry, prevEntry) {
if (nextEntry != prevEntry) {
if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
}
}
}
/**
* @ngdoc method
* @name $cacheFactory#info
*
* @description
* Get information about all the caches that have been created
*
* @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
*/
cacheFactory.info = function() {
var info = {};
forEach(caches, function(cache, cacheId) {
info[cacheId] = cache.info();
});
return info;
};
/**
* @ngdoc method
* @name $cacheFactory#get
*
* @description
* Get access to a cache object by the `cacheId` used when it was created.
*
* @param {string} cacheId Name or id of a cache to access.
* @returns {object} Cache object identified by the cacheId or undefined if no such cache.
*/
cacheFactory.get = function(cacheId) {
return caches[cacheId];
};
return cacheFactory;
};
}
/**
* @ngdoc service
* @name $templateCache
*
* @description
* The first time a template is used, it is loaded in the template cache for quick retrieval. You
* can load templates directly into the cache in a `script` tag, or by consuming the
* `$templateCache` service directly.
*
* Adding via the `script` tag:
*
* ```html
* <script type="text/ng-template" id="templateId.html">
* <p>This is the content of the template</p>
* </script>
* ```
*
* **Note:** the `script` tag containing the template does not need to be included in the `head` of
* the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,
* element with ng-app attribute), otherwise the template will be ignored.
*
* Adding via the `$templateCache` service:
*
* ```js
* var myApp = angular.module('myApp', []);
* myApp.run(function($templateCache) {
* $templateCache.put('templateId.html', 'This is the content of the template');
* });
* ```
*
* To retrieve the template later, simply use it in your HTML:
* ```html
* <div ng-include=" 'templateId.html' "></div>
* ```
*
* or get it via Javascript:
* ```js
* $templateCache.get('templateId.html')
* ```
*
* See {@link ng.$cacheFactory $cacheFactory}.
*
*/
function $TemplateCacheProvider() {
this.$get = ['$cacheFactory', function($cacheFactory) {
return $cacheFactory('templates');
}];
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Any commits to this file should be reviewed with security in mind. *
* Changes to this file can potentially create security vulnerabilities. *
* An approval from 2 Core members with history of modifying *
* this file is required. *
* *
* Does the change somehow allow for arbitrary javascript to be executed? *
* Or allows for someone to change the prototype of built-in objects? *
* Or gives undesired access to variables likes document or window? *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
*
* DOM-related variables:
*
* - "node" - DOM Node
* - "element" - DOM Element or Node
* - "$node" or "$element" - jqLite-wrapped node or element
*
*
* Compiler related stuff:
*
* - "linkFn" - linking fn of a single directive
* - "nodeLinkFn" - function that aggregates all linking fns for a particular node
* - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
* - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
*/
/**
* @ngdoc service
* @name $compile
* @kind function
*
* @description
* Compiles an HTML string or DOM into a template and produces a template function, which
* can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
*
* The compilation is a process of walking the DOM tree and matching DOM elements to
* {@link ng.$compileProvider#directive directives}.
*
* <div class="alert alert-warning">
* **Note:** This document is an in-depth reference of all directive options.
* For a gentle introduction to directives with examples of common use cases,
* see the {@link guide/directive directive guide}.
* </div>
*
* ## Comprehensive Directive API
*
* There are many different options for a directive.
*
* The difference resides in the return value of the factory function.
* You can either return a "Directive Definition Object" (see below) that defines the directive properties,
* or just the `postLink` function (all other properties will have the default values).
*
* <div class="alert alert-success">
* **Best Practice:** It's recommended to use the "directive definition object" form.
* </div>
*
* Here's an example directive declared with a Directive Definition Object:
*
* ```js
* var myModule = angular.module(...);
*
* myModule.directive('directiveName', function factory(injectables) {
* var directiveDefinitionObject = {
* priority: 0,
* template: '<div></div>', // or // function(tElement, tAttrs) { ... },
* // or
* // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
* transclude: false,
* restrict: 'A',
* templateNamespace: 'html',
* scope: false,
* controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
* controllerAs: 'stringAlias',
* require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
* compile: function compile(tElement, tAttrs, transclude) {
* return {
* pre: function preLink(scope, iElement, iAttrs, controller) { ... },
* post: function postLink(scope, iElement, iAttrs, controller) { ... }
* }
* // or
* // return function postLink( ... ) { ... }
* },
* // or
* // link: {
* // pre: function preLink(scope, iElement, iAttrs, controller) { ... },
* // post: function postLink(scope, iElement, iAttrs, controller) { ... }
* // }
* // or
* // link: function postLink( ... ) { ... }
* };
* return directiveDefinitionObject;
* });
* ```
*
* <div class="alert alert-warning">
* **Note:** Any unspecified options will use the default value. You can see the default values below.
* </div>
*
* Therefore the above can be simplified as:
*
* ```js
* var myModule = angular.module(...);
*
* myModule.directive('directiveName', function factory(injectables) {
* var directiveDefinitionObject = {
* link: function postLink(scope, iElement, iAttrs) { ... }
* };
* return directiveDefinitionObject;
* // or
* // return function postLink(scope, iElement, iAttrs) { ... }
* });
* ```
*
*
*
* ### Directive Definition Object
*
* The directive definition object provides instructions to the {@link ng.$compile
* compiler}. The attributes are:
*
* #### `multiElement`
* When this property is set to true, the HTML compiler will collect DOM nodes between
* nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
* together as the directive elements. It is recommended that this feature be used on directives
* which are not strictly behavioural (such as {@link ngClick}), and which
* do not manipulate or replace child nodes (such as {@link ngInclude}).
*
* #### `priority`
* When there are multiple directives defined on a single DOM element, sometimes it
* is necessary to specify the order in which the directives are applied. The `priority` is used
* to sort the directives before their `compile` functions get called. Priority is defined as a
* number. Directives with greater numerical `priority` are compiled first. Pre-link functions
* are also run in priority order, but post-link functions are run in reverse order. The order
* of directives with the same priority is undefined. The default priority is `0`.
*
* #### `terminal`
* If set to true then the current `priority` will be the last set of directives
* which will execute (any directives at the current priority will still execute
* as the order of execution on same `priority` is undefined). Note that expressions
* and other directives used in the directive's template will also be excluded from execution.
*
* #### `scope`
* **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the
* same element request a new scope, only one new scope is created. The new scope rule does not
* apply for the root of the template since the root of the template always gets a new scope.
*
* **If set to `{}` (object hash),** then a new "isolate" scope is created. The 'isolate' scope differs from
* normal scope in that it does not prototypically inherit from the parent scope. This is useful
* when creating reusable components, which should not accidentally read or modify data in the
* parent scope.
*
* The 'isolate' scope takes an object hash which defines a set of local scope properties
* derived from the parent scope. These local properties are useful for aliasing values for
* templates. Locals definition is a hash of local scope property to its source:
*
* * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
* always a string since DOM attributes are strings. If no `attr` name is specified then the
* attribute name is assumed to be the same as the local name.
* Given `<widget my-attr="hello {{name}}">` and widget definition
* of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect
* the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the
* `localName` property on the widget scope. The `name` is read from the parent scope (not
* component scope).
*
* * `=` or `=attr` - set up bi-directional binding between a local scope property and the
* parent scope property of name defined via the value of the `attr` attribute. If no `attr`
* name is specified then the attribute name is assumed to be the same as the local name.
* Given `<widget my-attr="parentModel">` and widget definition of
* `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the
* value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
* in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent
* scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You
* can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional. If
* you want to shallow watch for changes (i.e. $watchCollection instead of $watch) you can use
* `=*` or `=*attr` (`=*?` or `=*?attr` if the property is optional).
*
* * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.
* If no `attr` name is specified then the attribute name is assumed to be the same as the
* local name. Given `<widget my-attr="count = count + value">` and widget definition of
* `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to
* a function wrapper for the `count = count + value` expression. Often it's desirable to
* pass data from the isolated scope via an expression to the parent scope, this can be
* done by passing a map of local variable names and values into the expression wrapper fn.
* For example, if the expression is `increment(amount)` then we can specify the amount value
* by calling the `localFn` as `localFn({amount: 22})`.
*
*
* #### `bindToController`
* When an isolate scope is used for a component (see above), and `controllerAs` is used, `bindToController: true` will
* allow a component to have its properties bound to the controller, rather than to scope. When the controller
* is instantiated, the initial values of the isolate scope bindings are already available.
*
* #### `controller`
* Controller constructor function. The controller is instantiated before the
* pre-linking phase and it is shared with other directives (see
* `require` attribute). This allows the directives to communicate with each other and augment
* each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
*
* * `$scope` - Current scope associated with the element
* * `$element` - Current element
* * `$attrs` - Current attributes object for the element
* * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
* `function([scope], cloneLinkingFn, futureParentElement)`.
* * `scope`: optional argument to override the scope.
* * `cloneLinkingFn`: optional argument to create clones of the original transcluded content.
* * `futureParentElement`:
* * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
* * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
* * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
* and when the `cloneLinkinFn` is passed,
* as those elements need to created and cloned in a special way when they are defined outside their
* usual containers (e.g. like `<svg>`).
* * See also the `directive.templateNamespace` property.
*
*
* #### `require`
* Require another directive and inject its controller as the fourth argument to the linking function. The
* `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the
* injected argument will be an array in corresponding order. If no such directive can be
* found, or if the directive does not have a controller, then an error is raised (unless no link function
* is specified, in which case error checking is skipped). The name can be prefixed with:
*
* * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
* * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
* * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
* * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
* * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
* `null` to the `link` fn if not found.
* * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
* `null` to the `link` fn if not found.
*
*
* #### `controllerAs`
* Controller alias at the directive scope. An alias for the controller so it
* can be referenced at the directive template. The directive needs to define a scope for this
* configuration to be used. Useful in the case when directive is used as component.
*
*
* #### `restrict`
* String of subset of `EACM` which restricts the directive to a specific directive
* declaration style. If omitted, the defaults (elements and attributes) are used.
*
* * `E` - Element name (default): `<my-directive></my-directive>`
* * `A` - Attribute (default): `<div my-directive="exp"></div>`
* * `C` - Class: `<div class="my-directive: exp;"></div>`
* * `M` - Comment: `<!-- directive: my-directive exp -->`
*
*
* #### `templateNamespace`
* String representing the document type used by the markup in the template.
* AngularJS needs this information as those elements need to be created and cloned
* in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
*
* * `html` - All root nodes in the template are HTML. Root nodes may also be
* top-level elements such as `<svg>` or `<math>`.
* * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
* * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
*
* If no `templateNamespace` is specified, then the namespace is considered to be `html`.
*
* #### `template`
* HTML markup that may:
* * Replace the contents of the directive's element (default).
* * Replace the directive's element itself (if `replace` is true - DEPRECATED).
* * Wrap the contents of the directive's element (if `transclude` is true).
*
* Value may be:
*
* * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
* * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
* function api below) and returns a string value.
*
*
* #### `templateUrl`
* This is similar to `template` but the template is loaded from the specified URL, asynchronously.
*
* Because template loading is asynchronous the compiler will suspend compilation of directives on that element
* for later when the template has been resolved. In the meantime it will continue to compile and link
* sibling and parent elements as though this element had not contained any directives.
*
* The compiler does not suspend the entire compilation to wait for templates to be loaded because this
* would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
* case when only one deeply nested directive has `templateUrl`.
*
* Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
*
* You can specify `templateUrl` as a string representing the URL or as a function which takes two
* arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
* a string value representing the url. In either case, the template URL is passed through {@link
* $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
*
*
* #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)
* specify what the template should replace. Defaults to `false`.
*
* * `true` - the template will replace the directive's element.
* * `false` - the template will replace the contents of the directive's element.
*
* The replacement process migrates all of the attributes / classes from the old element to the new
* one. See the {@link guide/directive#template-expanding-directive
* Directives Guide} for an example.
*
* There are very few scenarios where element replacement is required for the application function,
* the main one being reusable custom components that are used within SVG contexts
* (because SVG doesn't work with custom elements in the DOM tree).
*
* #### `transclude`
* Extract the contents of the element where the directive appears and make it available to the directive.
* The contents are compiled and provided to the directive as a **transclusion function**. See the
* {@link $compile#transclusion Transclusion} section below.
*
* There are two kinds of transclusion depending upon whether you want to transclude just the contents of the
* directive's element or the entire element:
*
* * `true` - transclude the content (i.e. the child nodes) of the directive's element.
* * `'element'` - transclude the whole of the directive's element including any directives on this
* element that defined at a lower priority than this directive. When used, the `template`
* property is ignored.
*
*
* #### `compile`
*
* ```js
* function compile(tElement, tAttrs, transclude) { ... }
* ```
*
* The compile function deals with transforming the template DOM. Since most directives do not do
* template transformation, it is not used often. The compile function takes the following arguments:
*
* * `tElement` - template element - The element where the directive has been declared. It is
* safe to do template transformation on the element and child elements only.
*
* * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
* between all directive compile functions.
*
* * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
*
* <div class="alert alert-warning">
* **Note:** The template instance and the link instance may be different objects if the template has
* been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
* apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
* should be done in a linking function rather than in a compile function.
* </div>
* <div class="alert alert-warning">
* **Note:** The compile function cannot handle directives that recursively use themselves in their
* own templates or compile functions. Compiling these directives results in an infinite loop and a
* stack overflow errors.
*
* This can be avoided by manually using $compile in the postLink function to imperatively compile
* a directive's template instead of relying on automatic template compilation via `template` or
* `templateUrl` declaration or manual compilation inside the compile function.
* </div>
*
* <div class="alert alert-error">
* **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
* e.g. does not know about the right outer scope. Please use the transclude function that is passed
* to the link function instead.
* </div>
* A compile function can have a return value which can be either a function or an object.
*
* * returning a (post-link) function - is equivalent to registering the linking function via the
* `link` property of the config object when the compile function is empty.
*
* * returning an object with function(s) registered via `pre` and `post` properties - allows you to
* control when a linking function should be called during the linking phase. See info about
* pre-linking and post-linking functions below.
*
*
* #### `link`
* This property is used only if the `compile` property is not defined.
*
* ```js
* function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
* ```
*
* The link function is responsible for registering DOM listeners as well as updating the DOM. It is
* executed after the template has been cloned. This is where most of the directive logic will be
* put.
*
* * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
* directive for registering {@link ng.$rootScope.Scope#$watch watches}.
*
* * `iElement` - instance element - The element where the directive is to be used. It is safe to
* manipulate the children of the element only in `postLink` function since the children have
* already been linked.
*
* * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
* between all directive linking functions.
*
* * `controller` - a controller instance - A controller instance if at least one directive on the
* element defines a controller. The controller is shared among all the directives, which allows
* the directives to use the controllers as a communication channel.
*
* * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
* This is the same as the `$transclude`
* parameter of directive controllers, see there for details.
* `function([scope], cloneLinkingFn, futureParentElement)`.
*
* #### Pre-linking function
*
* Executed before the child elements are linked. Not safe to do DOM transformation since the
* compiler linking function will fail to locate the correct elements for linking.
*
* #### Post-linking function
*
* Executed after the child elements are linked.
*
* Note that child elements that contain `templateUrl` directives will not have been compiled
* and linked since they are waiting for their template to load asynchronously and their own
* compilation and linking has been suspended until that occurs.
*
* It is safe to do DOM transformation in the post-linking function on elements that are not waiting
* for their async templates to be resolved.
*
*
* ### Transclusion
*
* Transclusion is the process of extracting a collection of DOM element from one part of the DOM and
* copying them to another part of the DOM, while maintaining their connection to the original AngularJS
* scope from where they were taken.
*
* Transclusion is used (often with {@link ngTransclude}) to insert the
* original contents of a directive's element into a specified place in the template of the directive.
* The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
* content has access to the properties on the scope from which it was taken, even if the directive
* has isolated scope.
* See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
*
* This makes it possible for the widget to have private state for its template, while the transcluded
* content has access to its originating scope.
*
* <div class="alert alert-warning">
* **Note:** When testing an element transclude directive you must not place the directive at the root of the
* DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
* Testing Transclusion Directives}.
* </div>
*
* #### Transclusion Functions
*
* When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
* function** to the directive's `link` function and `controller`. This transclusion function is a special
* **linking function** that will return the compiled contents linked to a new transclusion scope.
*
* <div class="alert alert-info">
* If you are just using {@link ngTransclude} then you don't need to worry about this function, since
* ngTransclude will deal with it for us.
* </div>
*
* If you want to manually control the insertion and removal of the transcluded content in your directive
* then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
* object that contains the compiled DOM, which is linked to the correct transclusion scope.
*
* When you call a transclusion function you can pass in a **clone attach function**. This function accepts
* two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
* content and the `scope` is the newly created transclusion scope, to which the clone is bound.
*
* <div class="alert alert-info">
* **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a translude function
* since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
* </div>
*
* It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
* attach function**:
*
* ```js
* var transcludedContent, transclusionScope;
*
* $transclude(function(clone, scope) {
* element.append(clone);
* transcludedContent = clone;
* transclusionScope = scope;
* });
* ```
*
* Later, if you want to remove the transcluded content from your DOM then you should also destroy the
* associated transclusion scope:
*
* ```js
* transcludedContent.remove();
* transclusionScope.$destroy();
* ```
*
* <div class="alert alert-info">
* **Best Practice**: if you intend to add and remove transcluded content manually in your directive
* (by calling the transclude function to get the DOM and and calling `element.remove()` to remove it),
* then you are also responsible for calling `$destroy` on the transclusion scope.
* </div>
*
* The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
* automatically destroy their transluded clones as necessary so you do not need to worry about this if
* you are simply using {@link ngTransclude} to inject the transclusion into your directive.
*
*
* #### Transclusion Scopes
*
* When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
* scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
* when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
* was taken.
*
* For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
* like this:
*
* ```html
* <div ng-app>
* <div isolate>
* <div transclusion>
* </div>
* </div>
* </div>
* ```
*
* The `$parent` scope hierarchy will look like this:
*
* ```
* - $rootScope
* - isolate
* - transclusion
* ```
*
* but the scopes will inherit prototypically from different scopes to their `$parent`.
*
* ```
* - $rootScope
* - transclusion
* - isolate
* ```
*
*
* ### Attributes
*
* The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
* `link()` or `compile()` functions. It has a variety of uses.
*
* accessing *Normalized attribute names:*
* Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.
* the attributes object allows for normalized access to
* the attributes.
*
* * *Directive inter-communication:* All directives share the same instance of the attributes
* object which allows the directives to use the attributes object as inter directive
* communication.
*
* * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
* allowing other directives to read the interpolated value.
*
* * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
* that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
* the only way to easily get the actual value because during the linking phase the interpolation
* hasn't been evaluated yet and so the value is at this time set to `undefined`.
*
* ```js
* function linkingFn(scope, elm, attrs, ctrl) {
* // get the attribute value
* console.log(attrs.ngModel);
*
* // change the attribute
* attrs.$set('ngModel', 'new value');
*
* // observe changes to interpolated attribute
* attrs.$observe('ngModel', function(value) {
* console.log('ngModel has changed value to ' + value);
* });
* }
* ```
*
* ## Example
*
* <div class="alert alert-warning">
* **Note**: Typically directives are registered with `module.directive`. The example below is
* to illustrate how `$compile` works.
* </div>
*
<example module="compileExample">
<file name="index.html">
<script>
angular.module('compileExample', [], function($compileProvider) {
// configure new 'compile' directive by passing a directive
// factory function. The factory function injects the '$compile'
$compileProvider.directive('compile', function($compile) {
// directive factory creates a link function
return function(scope, element, attrs) {
scope.$watch(
function(scope) {
// watch the 'compile' expression for changes
return scope.$eval(attrs.compile);
},
function(value) {
// when the 'compile' expression changes
// assign it into the current DOM
element.html(value);
// compile the new DOM and link it to the current
// scope.
// NOTE: we only compile .childNodes so that
// we don't get into infinite loop compiling ourselves
$compile(element.contents())(scope);
}
);
};
});
})
.controller('GreeterController', ['$scope', function($scope) {
$scope.name = 'Angular';
$scope.html = 'Hello {{name}}';
}]);
</script>
<div ng-controller="GreeterController">
<input ng-model="name"> <br>
<textarea ng-model="html"></textarea> <br>
<div compile="html"></div>
</div>
</file>
<file name="protractor.js" type="protractor">
it('should auto compile', function() {
var textarea = $('textarea');
var output = $('div[compile]');
// The initial state reads 'Hello Angular'.
expect(output.getText()).toBe('Hello Angular');
textarea.clear();
textarea.sendKeys('{{name}}!');
expect(output.getText()).toBe('Angular!');
});
</file>
</example>
*
*
* @param {string|DOMElement} element Element or HTML string to compile into a template function.
* @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
*
* <div class="alert alert-error">
* **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
* e.g. will not use the right outer scope. Please pass the transclude function as a
* `parentBoundTranscludeFn` to the link function instead.
* </div>
*
* @param {number} maxPriority only apply directives lower than given priority (Only effects the
* root element(s), not their children)
* @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
* (a DOM element/tree) to a scope. Where:
*
* * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
* * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
* `template` and call the `cloneAttachFn` function allowing the caller to attach the
* cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
* called as: <br> `cloneAttachFn(clonedElement, scope)` where:
*
* * `clonedElement` - is a clone of the original `element` passed into the compiler.
* * `scope` - is the current scope with which the linking function is working with.
*
* * `options` - An optional object hash with linking options. If `options` is provided, then the following
* keys may be used to control linking behavior:
*
* * `parentBoundTranscludeFn` - the transclude function made available to
* directives; if given, it will be passed through to the link functions of
* directives found in `element` during compilation.
* * `transcludeControllers` - an object hash with keys that map controller names
* to controller instances; if given, it will make the controllers
* available to directives.
* * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
* the cloned elements; only needed for transcludes that are allowed to contain non html
* elements (e.g. SVG elements). See also the directive.controller property.
*
* Calling the linking function returns the element of the template. It is either the original
* element passed in, or the clone of the element if the `cloneAttachFn` is provided.
*
* After linking the view is not updated until after a call to $digest which typically is done by
* Angular automatically.
*
* If you need access to the bound view, there are two ways to do it:
*
* - If you are not asking the linking function to clone the template, create the DOM element(s)
* before you send them to the compiler and keep this reference around.
* ```js
* var element = $compile('<p>{{total}}</p>')(scope);
* ```
*
* - if on the other hand, you need the element to be cloned, the view reference from the original
* example would not point to the clone, but rather to the original template that was cloned. In
* this case, you can access the clone via the cloneAttachFn:
* ```js
* var templateElement = angular.element('<p>{{total}}</p>'),
* scope = ....;
*
* var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
* //attach the clone to DOM document at the right place
* });
*
* //now we have reference to the cloned DOM via `clonedElement`
* ```
*
*
* For information on how the compiler works, see the
* {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
*/
var $compileMinErr = minErr('$compile');
/**
* @ngdoc provider
* @name $compileProvider
*
* @description
*/
$CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
function $CompileProvider($provide, $$sanitizeUriProvider) {
var hasDirectives = {},
Suffix = 'Directive',
COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\w\-]+)\s+(.*)$/,
CLASS_DIRECTIVE_REGEXP = /(([\w\-]+)(?:\:([^;]+))?;?)/,
ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
// Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
// The assumption is that future DOM event attribute names will begin with
// 'on' and be composed of only English letters.
var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
function parseIsolateBindings(scope, directiveName) {
var LOCAL_REGEXP = /^\s*([@&]|=(\*?))(\??)\s*(\w*)\s*$/;
var bindings = {};
forEach(scope, function(definition, scopeName) {
var match = definition.match(LOCAL_REGEXP);
if (!match) {
throw $compileMinErr('iscp',
"Invalid isolate scope definition for directive '{0}'." +
" Definition: {... {1}: '{2}' ...}",
directiveName, scopeName, definition);
}
bindings[scopeName] = {
mode: match[1][0],
collection: match[2] === '*',
optional: match[3] === '?',
attrName: match[4] || scopeName
};
});
return bindings;
}
/**
* @ngdoc method
* @name $compileProvider#directive
* @kind function
*
* @description
* Register a new directive with the compiler.
*
* @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
* will match as <code>ng-bind</code>), or an object map of directives where the keys are the
* names and the values are the factories.
* @param {Function|Array} directiveFactory An injectable directive factory function. See
* {@link guide/directive} for more info.
* @returns {ng.$compileProvider} Self for chaining.
*/
this.directive = function registerDirective(name, directiveFactory) {
assertNotHasOwnProperty(name, 'directive');
if (isString(name)) {
assertArg(directiveFactory, 'directiveFactory');
if (!hasDirectives.hasOwnProperty(name)) {
hasDirectives[name] = [];
$provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
function($injector, $exceptionHandler) {
var directives = [];
forEach(hasDirectives[name], function(directiveFactory, index) {
try {
var directive = $injector.invoke(directiveFactory);
if (isFunction(directive)) {
directive = { compile: valueFn(directive) };
} else if (!directive.compile && directive.link) {
directive.compile = valueFn(directive.link);
}
directive.priority = directive.priority || 0;
directive.index = index;
directive.name = directive.name || name;
directive.require = directive.require || (directive.controller && directive.name);
directive.restrict = directive.restrict || 'EA';
if (isObject(directive.scope)) {
directive.$$isolateBindings = parseIsolateBindings(directive.scope, directive.name);
}
directives.push(directive);
} catch (e) {
$exceptionHandler(e);
}
});
return directives;
}]);
}
hasDirectives[name].push(directiveFactory);
} else {
forEach(name, reverseParams(registerDirective));
}
return this;
};
/**
* @ngdoc method
* @name $compileProvider#aHrefSanitizationWhitelist
* @kind function
*
* @description
* Retrieves or overrides the default regular expression that is used for whitelisting of safe
* urls during a[href] sanitization.
*
* The sanitization is a security measure aimed at preventing XSS attacks via html links.
*
* Any url about to be assigned to a[href] via data-binding is first normalized and turned into
* an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
* regular expression. If a match is found, the original url is written into the dom. Otherwise,
* the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
*
* @param {RegExp=} regexp New regexp to whitelist urls with.
* @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
* chaining otherwise.
*/
this.aHrefSanitizationWhitelist = function(regexp) {
if (isDefined(regexp)) {
$$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
return this;
} else {
return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
}
};
/**
* @ngdoc method
* @name $compileProvider#imgSrcSanitizationWhitelist
* @kind function
*
* @description
* Retrieves or overrides the default regular expression that is used for whitelisting of safe
* urls during img[src] sanitization.
*
* The sanitization is a security measure aimed at prevent XSS attacks via html links.
*
* Any url about to be assigned to img[src] via data-binding is first normalized and turned into
* an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
* regular expression. If a match is found, the original url is written into the dom. Otherwise,
* the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
*
* @param {RegExp=} regexp New regexp to whitelist urls with.
* @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
* chaining otherwise.
*/
this.imgSrcSanitizationWhitelist = function(regexp) {
if (isDefined(regexp)) {
$$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
return this;
} else {
return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
}
};
/**
* @ngdoc method
* @name $compileProvider#debugInfoEnabled
*
* @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
* current debugInfoEnabled state
* @returns {*} current value if used as getter or itself (chaining) if used as setter
*
* @kind function
*
* @description
* Call this method to enable/disable various debug runtime information in the compiler such as adding
* binding information and a reference to the current scope on to DOM elements.
* If enabled, the compiler will add the following to DOM elements that have been bound to the scope
* * `ng-binding` CSS class
* * `$binding` data property containing an array of the binding expressions
*
* You may want to disable this in production for a significant performance boost. See
* {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
*
* The default value is true.
*/
var debugInfoEnabled = true;
this.debugInfoEnabled = function(enabled) {
if (isDefined(enabled)) {
debugInfoEnabled = enabled;
return this;
}
return debugInfoEnabled;
};
this.$get = [
'$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
'$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri',
function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,
$controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) {
var Attributes = function(element, attributesToCopy) {
if (attributesToCopy) {
var keys = Object.keys(attributesToCopy);
var i, l, key;
for (i = 0, l = keys.length; i < l; i++) {
key = keys[i];
this[key] = attributesToCopy[key];
}
} else {
this.$attr = {};
}
this.$$element = element;
};
Attributes.prototype = {
/**
* @ngdoc method
* @name $compile.directive.Attributes#$normalize
* @kind function
*
* @description
* Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
* `data-`) to its normalized, camelCase form.
*
* Also there is special case for Moz prefix starting with upper case letter.
*
* For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
*
* @param {string} name Name to normalize
*/
$normalize: directiveNormalize,
/**
* @ngdoc method
* @name $compile.directive.Attributes#$addClass
* @kind function
*
* @description
* Adds the CSS class value specified by the classVal parameter to the element. If animations
* are enabled then an animation will be triggered for the class addition.
*
* @param {string} classVal The className value that will be added to the element
*/
$addClass: function(classVal) {
if (classVal && classVal.length > 0) {
$animate.addClass(this.$$element, classVal);
}
},
/**
* @ngdoc method
* @name $compile.directive.Attributes#$removeClass
* @kind function
*
* @description
* Removes the CSS class value specified by the classVal parameter from the element. If
* animations are enabled then an animation will be triggered for the class removal.
*
* @param {string} classVal The className value that will be removed from the element
*/
$removeClass: function(classVal) {
if (classVal && classVal.length > 0) {
$animate.removeClass(this.$$element, classVal);
}
},
/**
* @ngdoc method
* @name $compile.directive.Attributes#$updateClass
* @kind function
*
* @description
* Adds and removes the appropriate CSS class values to the element based on the difference
* between the new and old CSS class values (specified as newClasses and oldClasses).
*
* @param {string} newClasses The current CSS className value
* @param {string} oldClasses The former CSS className value
*/
$updateClass: function(newClasses, oldClasses) {
var toAdd = tokenDifference(newClasses, oldClasses);
if (toAdd && toAdd.length) {
$animate.addClass(this.$$element, toAdd);
}
var toRemove = tokenDifference(oldClasses, newClasses);
if (toRemove && toRemove.length) {
$animate.removeClass(this.$$element, toRemove);
}
},
/**
* Set a normalized attribute on the element in a way such that all directives
* can share the attribute. This function properly handles boolean attributes.
* @param {string} key Normalized key. (ie ngAttribute)
* @param {string|boolean} value The value to set. If `null` attribute will be deleted.
* @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
* Defaults to true.
* @param {string=} attrName Optional none normalized name. Defaults to key.
*/
$set: function(key, value, writeAttr, attrName) {
// TODO: decide whether or not to throw an error if "class"
//is set through this function since it may cause $updateClass to
//become unstable.
var node = this.$$element[0],
booleanKey = getBooleanAttrName(node, key),
aliasedKey = getAliasedAttrName(node, key),
observer = key,
nodeName;
if (booleanKey) {
this.$$element.prop(key, value);
attrName = booleanKey;
} else if (aliasedKey) {
this[aliasedKey] = value;
observer = aliasedKey;
}
this[key] = value;
// translate normalized key to actual key
if (attrName) {
this.$attr[key] = attrName;
} else {
attrName = this.$attr[key];
if (!attrName) {
this.$attr[key] = attrName = snake_case(key, '-');
}
}
nodeName = nodeName_(this.$$element);
if ((nodeName === 'a' && key === 'href') ||
(nodeName === 'img' && key === 'src')) {
// sanitize a[href] and img[src] values
this[key] = value = $$sanitizeUri(value, key === 'src');
} else if (nodeName === 'img' && key === 'srcset') {
// sanitize img[srcset] values
var result = "";
// first check if there are spaces because it's not the same pattern
var trimmedSrcset = trim(value);
// ( 999x ,| 999w ,| ,|, )
var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
// split srcset into tuple of uri and descriptor except for the last item
var rawUris = trimmedSrcset.split(pattern);
// for each tuples
var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
for (var i = 0; i < nbrUrisWith2parts; i++) {
var innerIdx = i * 2;
// sanitize the uri
result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
// add the descriptor
result += (" " + trim(rawUris[innerIdx + 1]));
}
// split the last item into uri and descriptor
var lastTuple = trim(rawUris[i * 2]).split(/\s/);
// sanitize the last uri
result += $$sanitizeUri(trim(lastTuple[0]), true);
// and add the last descriptor if any
if (lastTuple.length === 2) {
result += (" " + trim(lastTuple[1]));
}
this[key] = value = result;
}
if (writeAttr !== false) {
if (value === null || value === undefined) {
this.$$element.removeAttr(attrName);
} else {
this.$$element.attr(attrName, value);
}
}
// fire observers
var $$observers = this.$$observers;
$$observers && forEach($$observers[observer], function(fn) {
try {
fn(value);
} catch (e) {
$exceptionHandler(e);
}
});
},
/**
* @ngdoc method
* @name $compile.directive.Attributes#$observe
* @kind function
*
* @description
* Observes an interpolated attribute.
*
* The observer function will be invoked once during the next `$digest` following
* compilation. The observer is then invoked whenever the interpolated value
* changes.
*
* @param {string} key Normalized key. (ie ngAttribute) .
* @param {function(interpolatedValue)} fn Function that will be called whenever
the interpolated value of the attribute changes.
* See the {@link guide/directive#text-and-attribute-bindings Directives} guide for more info.
* @returns {function()} Returns a deregistration function for this observer.
*/
$observe: function(key, fn) {
var attrs = this,
$$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
listeners = ($$observers[key] || ($$observers[key] = []));
listeners.push(fn);
$rootScope.$evalAsync(function() {
if (!listeners.$$inter && attrs.hasOwnProperty(key)) {
// no one registered attribute interpolation function, so lets call it manually
fn(attrs[key]);
}
});
return function() {
arrayRemove(listeners, fn);
};
}
};
function safeAddClass($element, className) {
try {
$element.addClass(className);
} catch (e) {
// ignore, since it means that we are trying to set class on
// SVG element, where class name is read-only.
}
}
var startSymbol = $interpolate.startSymbol(),
endSymbol = $interpolate.endSymbol(),
denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
? identity
: function denormalizeTemplate(template) {
return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
},
NG_ATTR_BINDING = /^ngAttr[A-Z]/;
compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
var bindings = $element.data('$binding') || [];
if (isArray(binding)) {
bindings = bindings.concat(binding);
} else {
bindings.push(binding);
}
$element.data('$binding', bindings);
} : noop;
compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
safeAddClass($element, 'ng-binding');
} : noop;
compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
$element.data(dataName, scope);
} : noop;
compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
} : noop;
return compile;
//================================
function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
previousCompileContext) {
if (!($compileNodes instanceof jqLite)) {
// jquery always rewraps, whereas we need to preserve the original selector so that we can
// modify it.
$compileNodes = jqLite($compileNodes);
}
// We can not compile top level text elements since text nodes can be merged and we will
// not be able to attach scope data to them, so we will wrap them in <span>
forEach($compileNodes, function(node, index) {
if (node.nodeType == NODE_TYPE_TEXT && node.nodeValue.match(/\S+/) /* non-empty */ ) {
$compileNodes[index] = jqLite(node).wrap('<span></span>').parent()[0];
}
});
var compositeLinkFn =
compileNodes($compileNodes, transcludeFn, $compileNodes,
maxPriority, ignoreDirective, previousCompileContext);
compile.$$addScopeClass($compileNodes);
var namespace = null;
return function publicLinkFn(scope, cloneConnectFn, options) {
assertArg(scope, 'scope');
options = options || {};
var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
transcludeControllers = options.transcludeControllers,
futureParentElement = options.futureParentElement;
// When `parentBoundTranscludeFn` is passed, it is a
// `controllersBoundTransclude` function (it was previously passed
// as `transclude` to directive.link) so we must unwrap it to get
// its `boundTranscludeFn`
if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
}
if (!namespace) {
namespace = detectNamespaceForChildElements(futureParentElement);
}
var $linkNode;
if (namespace !== 'html') {
// When using a directive with replace:true and templateUrl the $compileNodes
// (or a child element inside of them)
// might change, so we need to recreate the namespace adapted compileNodes
// for call to the link function.
// Note: This will already clone the nodes...
$linkNode = jqLite(
wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
);
} else if (cloneConnectFn) {
// important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
// and sometimes changes the structure of the DOM.
$linkNode = JQLitePrototype.clone.call($compileNodes);
} else {
$linkNode = $compileNodes;
}
if (transcludeControllers) {
for (var controllerName in transcludeControllers) {
$linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
}
}
compile.$$addScopeInfo($linkNode, scope);
if (cloneConnectFn) cloneConnectFn($linkNode, scope);
if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
return $linkNode;
};
}
function detectNamespaceForChildElements(parentElement) {
// TODO: Make this detect MathML as well...
var node = parentElement && parentElement[0];
if (!node) {
return 'html';
} else {
return nodeName_(node) !== 'foreignobject' && node.toString().match(/SVG/) ? 'svg' : 'html';
}
}
/**
* Compile function matches each node in nodeList against the directives. Once all directives
* for a particular node are collected their compile functions are executed. The compile
* functions return values - the linking functions - are combined into a composite linking
* function, which is the a linking function for the node.
*
* @param {NodeList} nodeList an array of nodes or NodeList to compile
* @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
* scope argument is auto-generated to the new child of the transcluded parent scope.
* @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
* the rootElement must be set the jqLite collection of the compile root. This is
* needed so that the jqLite collection items can be replaced with widgets.
* @param {number=} maxPriority Max directive priority.
* @returns {Function} A composite linking function of all of the matched directives or null.
*/
function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
previousCompileContext) {
var linkFns = [],
attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
for (var i = 0; i < nodeList.length; i++) {
attrs = new Attributes();
// we must always refer to nodeList[i] since the nodes can be replaced underneath us.
directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
ignoreDirective);
nodeLinkFn = (directives.length)
? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
null, [], [], previousCompileContext)
: null;
if (nodeLinkFn && nodeLinkFn.scope) {
compile.$$addScopeClass(attrs.$$element);
}
childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
!(childNodes = nodeList[i].childNodes) ||
!childNodes.length)
? null
: compileNodes(childNodes,
nodeLinkFn ? (
(nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
&& nodeLinkFn.transclude) : transcludeFn);
if (nodeLinkFn || childLinkFn) {
linkFns.push(i, nodeLinkFn, childLinkFn);
linkFnFound = true;
nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
}
//use the previous context only for the first element in the virtual group
previousCompileContext = null;
}
// return a linking function if we have found anything, null otherwise
return linkFnFound ? compositeLinkFn : null;
function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
var stableNodeList;
if (nodeLinkFnFound) {
// copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
// offsets don't get screwed up
var nodeListLength = nodeList.length;
stableNodeList = new Array(nodeListLength);
// create a sparse array by only copying the elements which have a linkFn
for (i = 0; i < linkFns.length; i+=3) {
idx = linkFns[i];
stableNodeList[idx] = nodeList[idx];
}
} else {
stableNodeList = nodeList;
}
for (i = 0, ii = linkFns.length; i < ii;) {
node = stableNodeList[linkFns[i++]];
nodeLinkFn = linkFns[i++];
childLinkFn = linkFns[i++];
if (nodeLinkFn) {
if (nodeLinkFn.scope) {
childScope = scope.$new();
compile.$$addScopeInfo(jqLite(node), childScope);
} else {
childScope = scope;
}
if (nodeLinkFn.transcludeOnThisElement) {
childBoundTranscludeFn = createBoundTranscludeFn(
scope, nodeLinkFn.transclude, parentBoundTranscludeFn,
nodeLinkFn.elementTranscludeOnThisElement);
} else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
childBoundTranscludeFn = parentBoundTranscludeFn;
} else if (!parentBoundTranscludeFn && transcludeFn) {
childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
} else {
childBoundTranscludeFn = null;
}
nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);
} else if (childLinkFn) {
childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
}
}
}
}
function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn, elementTransclusion) {
var boundTranscludeFn = function(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
if (!transcludedScope) {
transcludedScope = scope.$new(false, containingScope);
transcludedScope.$$transcluded = true;
}
return transcludeFn(transcludedScope, cloneFn, {
parentBoundTranscludeFn: previousBoundTranscludeFn,
transcludeControllers: controllers,
futureParentElement: futureParentElement
});
};
return boundTranscludeFn;
}
/**
* Looks for directives on the given node and adds them to the directive collection which is
* sorted.
*
* @param node Node to search.
* @param directives An array to which the directives are added to. This array is sorted before
* the function returns.
* @param attrs The shared attrs object which is used to populate the normalized attributes.
* @param {number=} maxPriority Max directive priority.
*/
function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
var nodeType = node.nodeType,
attrsMap = attrs.$attr,
match,
className;
switch (nodeType) {
case NODE_TYPE_ELEMENT: /* Element */
// use the node name: <directive>
addDirective(directives,
directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective);
// iterate over the attributes
for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
var attrStartName = false;
var attrEndName = false;
attr = nAttrs[j];
name = attr.name;
value = trim(attr.value);
// support ngAttr attribute binding
ngAttrName = directiveNormalize(name);
if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {
name = name.replace(PREFIX_REGEXP, '')
.substr(8).replace(/_(.)/g, function(match, letter) {
return letter.toUpperCase();
});
}
var directiveNName = ngAttrName.replace(/(Start|End)$/, '');
if (directiveIsMultiElement(directiveNName)) {
if (ngAttrName === directiveNName + 'Start') {
attrStartName = name;
attrEndName = name.substr(0, name.length - 5) + 'end';
name = name.substr(0, name.length - 6);
}
}
nName = directiveNormalize(name.toLowerCase());
attrsMap[nName] = name;
if (isNgAttr || !attrs.hasOwnProperty(nName)) {
attrs[nName] = value;
if (getBooleanAttrName(node, nName)) {
attrs[nName] = true; // presence means true
}
}
addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
attrEndName);
}
// use class as directive
className = node.className;
if (isObject(className)) {
// Maybe SVGAnimatedString
className = className.animVal;
}
if (isString(className) && className !== '') {
while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
nName = directiveNormalize(match[2]);
if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
attrs[nName] = trim(match[3]);
}
className = className.substr(match.index + match[0].length);
}
}
break;
case NODE_TYPE_TEXT: /* Text Node */
addTextInterpolateDirective(directives, node.nodeValue);
break;
case NODE_TYPE_COMMENT: /* Comment */
try {
match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
if (match) {
nName = directiveNormalize(match[1]);
if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
attrs[nName] = trim(match[2]);
}
}
} catch (e) {
// turns out that under some circumstances IE9 throws errors when one attempts to read
// comment's node value.
// Just ignore it and continue. (Can't seem to reproduce in test case.)
}
break;
}
directives.sort(byPriority);
return directives;
}
/**
* Given a node with an directive-start it collects all of the siblings until it finds
* directive-end.
* @param node
* @param attrStart
* @param attrEnd
* @returns {*}
*/
function groupScan(node, attrStart, attrEnd) {
var nodes = [];
var depth = 0;
if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
do {
if (!node) {
throw $compileMinErr('uterdir',
"Unterminated attribute, found '{0}' but no matching '{1}' found.",
attrStart, attrEnd);
}
if (node.nodeType == NODE_TYPE_ELEMENT) {
if (node.hasAttribute(attrStart)) depth++;
if (node.hasAttribute(attrEnd)) depth--;
}
nodes.push(node);
node = node.nextSibling;
} while (depth > 0);
} else {
nodes.push(node);
}
return jqLite(nodes);
}
/**
* Wrapper for linking function which converts normal linking function into a grouped
* linking function.
* @param linkFn
* @param attrStart
* @param attrEnd
* @returns {Function}
*/
function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
return function(scope, element, attrs, controllers, transcludeFn) {
element = groupScan(element[0], attrStart, attrEnd);
return linkFn(scope, element, attrs, controllers, transcludeFn);
};
}
/**
* Once the directives have been collected, their compile functions are executed. This method
* is responsible for inlining directive templates as well as terminating the application
* of the directives if the terminal directive has been reached.
*
* @param {Array} directives Array of collected directives to execute their compile function.
* this needs to be pre-sorted by priority order.
* @param {Node} compileNode The raw DOM node to apply the compile functions to
* @param {Object} templateAttrs The shared attribute function
* @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
* scope argument is auto-generated to the new
* child of the transcluded parent scope.
* @param {JQLite} jqCollection If we are working on the root of the compile tree then this
* argument has the root jqLite array so that we can replace nodes
* on it.
* @param {Object=} originalReplaceDirective An optional directive that will be ignored when
* compiling the transclusion.
* @param {Array.<Function>} preLinkFns
* @param {Array.<Function>} postLinkFns
* @param {Object} previousCompileContext Context used for previous compilation of the current
* node
* @returns {Function} linkFn
*/
function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
previousCompileContext) {
previousCompileContext = previousCompileContext || {};
var terminalPriority = -Number.MAX_VALUE,
newScopeDirective,
controllerDirectives = previousCompileContext.controllerDirectives,
controllers,
newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
templateDirective = previousCompileContext.templateDirective,
nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
hasTranscludeDirective = false,
hasTemplate = false,
hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
$compileNode = templateAttrs.$$element = jqLite(compileNode),
directive,
directiveName,
$template,
replaceDirective = originalReplaceDirective,
childTranscludeFn = transcludeFn,
linkFn,
directiveValue;
// executes all directives on the current element
for (var i = 0, ii = directives.length; i < ii; i++) {
directive = directives[i];
var attrStart = directive.$$start;
var attrEnd = directive.$$end;
// collect multiblock sections
if (attrStart) {
$compileNode = groupScan(compileNode, attrStart, attrEnd);
}
$template = undefined;
if (terminalPriority > directive.priority) {
break; // prevent further processing of directives
}
if (directiveValue = directive.scope) {
// skip the check for directives with async templates, we'll check the derived sync
// directive when the template arrives
if (!directive.templateUrl) {
if (isObject(directiveValue)) {
// This directive is trying to add an isolated scope.
// Check that there is no scope of any kind already
assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
directive, $compileNode);
newIsolateScopeDirective = directive;
} else {
// This directive is trying to add a child scope.
// Check that there is no isolated scope already
assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
$compileNode);
}
}
newScopeDirective = newScopeDirective || directive;
}
directiveName = directive.name;
if (!directive.templateUrl && directive.controller) {
directiveValue = directive.controller;
controllerDirectives = controllerDirectives || {};
assertNoDuplicate("'" + directiveName + "' controller",
controllerDirectives[directiveName], directive, $compileNode);
controllerDirectives[directiveName] = directive;
}
if (directiveValue = directive.transclude) {
hasTranscludeDirective = true;
// Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
// This option should only be used by directives that know how to safely handle element transclusion,
// where the transcluded nodes are added or replaced after linking.
if (!directive.$$tlb) {
assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
nonTlbTranscludeDirective = directive;
}
if (directiveValue == 'element') {
hasElementTranscludeDirective = true;
terminalPriority = directive.priority;
$template = $compileNode;
$compileNode = templateAttrs.$$element =
jqLite(document.createComment(' ' + directiveName + ': ' +
templateAttrs[directiveName] + ' '));
compileNode = $compileNode[0];
replaceWith(jqCollection, sliceArgs($template), compileNode);
childTranscludeFn = compile($template, transcludeFn, terminalPriority,
replaceDirective && replaceDirective.name, {
// Don't pass in:
// - controllerDirectives - otherwise we'll create duplicates controllers
// - newIsolateScopeDirective or templateDirective - combining templates with
// element transclusion doesn't make sense.
//
// We need only nonTlbTranscludeDirective so that we prevent putting transclusion
// on the same element more than once.
nonTlbTranscludeDirective: nonTlbTranscludeDirective
});
} else {
$template = jqLite(jqLiteClone(compileNode)).contents();
$compileNode.empty(); // clear contents
childTranscludeFn = compile($template, transcludeFn);
}
}
if (directive.template) {
hasTemplate = true;
assertNoDuplicate('template', templateDirective, directive, $compileNode);
templateDirective = directive;
directiveValue = (isFunction(directive.template))
? directive.template($compileNode, templateAttrs)
: directive.template;
directiveValue = denormalizeTemplate(directiveValue);
if (directive.replace) {
replaceDirective = directive;
if (jqLiteIsTextNode(directiveValue)) {
$template = [];
} else {
$template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
}
compileNode = $template[0];
if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
throw $compileMinErr('tplrt',
"Template for directive '{0}' must have exactly one root element. {1}",
directiveName, '');
}
replaceWith(jqCollection, $compileNode, compileNode);
var newTemplateAttrs = {$attr: {}};
// combine directives from the original node and from the template:
// - take the array of directives for this element
// - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
// - collect directives from the template and sort them by priority
// - combine directives as: processed + template + unprocessed
var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
if (newIsolateScopeDirective) {
markDirectivesAsIsolate(templateDirectives);
}
directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
ii = directives.length;
} else {
$compileNode.html(directiveValue);
}
}
if (directive.templateUrl) {
hasTemplate = true;
assertNoDuplicate('template', templateDirective, directive, $compileNode);
templateDirective = directive;
if (directive.replace) {
replaceDirective = directive;
}
nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
controllerDirectives: controllerDirectives,
newIsolateScopeDirective: newIsolateScopeDirective,
templateDirective: templateDirective,
nonTlbTranscludeDirective: nonTlbTranscludeDirective
});
ii = directives.length;
} else if (directive.compile) {
try {
linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
if (isFunction(linkFn)) {
addLinkFns(null, linkFn, attrStart, attrEnd);
} else if (linkFn) {
addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
}
} catch (e) {
$exceptionHandler(e, startingTag($compileNode));
}
}
if (directive.terminal) {
nodeLinkFn.terminal = true;
terminalPriority = Math.max(terminalPriority, directive.priority);
}
}
nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
nodeLinkFn.elementTranscludeOnThisElement = hasElementTranscludeDirective;
nodeLinkFn.templateOnThisElement = hasTemplate;
nodeLinkFn.transclude = childTranscludeFn;
previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
// might be normal or delayed nodeLinkFn depending on if templateUrl is present
return nodeLinkFn;
////////////////////
function addLinkFns(pre, post, attrStart, attrEnd) {
if (pre) {
if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
pre.require = directive.require;
pre.directiveName = directiveName;
if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
pre = cloneAndAnnotateFn(pre, {isolateScope: true});
}
preLinkFns.push(pre);
}
if (post) {
if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
post.require = directive.require;
post.directiveName = directiveName;
if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
post = cloneAndAnnotateFn(post, {isolateScope: true});
}
postLinkFns.push(post);
}
}
function getControllers(directiveName, require, $element, elementControllers) {
var value, retrievalMethod = 'data', optional = false;
var $searchElement = $element;
var match;
if (isString(require)) {
match = require.match(REQUIRE_PREFIX_REGEXP);
require = require.substring(match[0].length);
if (match[3]) {
if (match[1]) match[3] = null;
else match[1] = match[3];
}
if (match[1] === '^') {
retrievalMethod = 'inheritedData';
} else if (match[1] === '^^') {
retrievalMethod = 'inheritedData';
$searchElement = $element.parent();
}
if (match[2] === '?') {
optional = true;
}
value = null;
if (elementControllers && retrievalMethod === 'data') {
if (value = elementControllers[require]) {
value = value.instance;
}
}
value = value || $searchElement[retrievalMethod]('$' + require + 'Controller');
if (!value && !optional) {
throw $compileMinErr('ctreq',
"Controller '{0}', required by directive '{1}', can't be found!",
require, directiveName);
}
return value || null;
} else if (isArray(require)) {
value = [];
forEach(require, function(require) {
value.push(getControllers(directiveName, require, $element, elementControllers));
});
}
return value;
}
function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
var i, ii, linkFn, controller, isolateScope, elementControllers, transcludeFn, $element,
attrs;
if (compileNode === linkNode) {
attrs = templateAttrs;
$element = templateAttrs.$$element;
} else {
$element = jqLite(linkNode);
attrs = new Attributes($element, templateAttrs);
}
if (newIsolateScopeDirective) {
isolateScope = scope.$new(true);
}
if (boundTranscludeFn) {
// track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
// is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
transcludeFn = controllersBoundTransclude;
transcludeFn.$$boundTransclude = boundTranscludeFn;
}
if (controllerDirectives) {
// TODO: merge `controllers` and `elementControllers` into single object.
controllers = {};
elementControllers = {};
forEach(controllerDirectives, function(directive) {
var locals = {
$scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
$element: $element,
$attrs: attrs,
$transclude: transcludeFn
}, controllerInstance;
controller = directive.controller;
if (controller == '@') {
controller = attrs[directive.name];
}
controllerInstance = $controller(controller, locals, true, directive.controllerAs);
// For directives with element transclusion the element is a comment,
// but jQuery .data doesn't support attaching data to comment nodes as it's hard to
// clean up (http://bugs.jquery.com/ticket/8335).
// Instead, we save the controllers for the element in a local hash and attach to .data
// later, once we have the actual element.
elementControllers[directive.name] = controllerInstance;
if (!hasElementTranscludeDirective) {
$element.data('$' + directive.name + 'Controller', controllerInstance.instance);
}
controllers[directive.name] = controllerInstance;
});
}
if (newIsolateScopeDirective) {
compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
templateDirective === newIsolateScopeDirective.$$originalDirective)));
compile.$$addScopeClass($element, true);
var isolateScopeController = controllers && controllers[newIsolateScopeDirective.name];
var isolateBindingContext = isolateScope;
if (isolateScopeController && isolateScopeController.identifier &&
newIsolateScopeDirective.bindToController === true) {
isolateBindingContext = isolateScopeController.instance;
}
forEach(isolateScope.$$isolateBindings = newIsolateScopeDirective.$$isolateBindings, function(definition, scopeName) {
var attrName = definition.attrName,
optional = definition.optional,
mode = definition.mode, // @, =, or &
lastValue,
parentGet, parentSet, compare;
switch (mode) {
case '@':
attrs.$observe(attrName, function(value) {
isolateBindingContext[scopeName] = value;
});
attrs.$$observers[attrName].$$scope = scope;
if (attrs[attrName]) {
// If the attribute has been provided then we trigger an interpolation to ensure
// the value is there for use in the link fn
isolateBindingContext[scopeName] = $interpolate(attrs[attrName])(scope);
}
break;
case '=':
if (optional && !attrs[attrName]) {
return;
}
parentGet = $parse(attrs[attrName]);
if (parentGet.literal) {
compare = equals;
} else {
compare = function(a, b) { return a === b || (a !== a && b !== b); };
}
parentSet = parentGet.assign || function() {
// reset the change, or we will throw this exception on every $digest
lastValue = isolateBindingContext[scopeName] = parentGet(scope);
throw $compileMinErr('nonassign',
"Expression '{0}' used with directive '{1}' is non-assignable!",
attrs[attrName], newIsolateScopeDirective.name);
};
lastValue = isolateBindingContext[scopeName] = parentGet(scope);
var parentValueWatch = function parentValueWatch(parentValue) {
if (!compare(parentValue, isolateBindingContext[scopeName])) {
// we are out of sync and need to copy
if (!compare(parentValue, lastValue)) {
// parent changed and it has precedence
isolateBindingContext[scopeName] = parentValue;
} else {
// if the parent can be assigned then do so
parentSet(scope, parentValue = isolateBindingContext[scopeName]);
}
}
return lastValue = parentValue;
};
parentValueWatch.$stateful = true;
var unwatch;
if (definition.collection) {
unwatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
} else {
unwatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
}
isolateScope.$on('$destroy', unwatch);
break;
case '&':
parentGet = $parse(attrs[attrName]);
isolateBindingContext[scopeName] = function(locals) {
return parentGet(scope, locals);
};
break;
}
});
}
if (controllers) {
forEach(controllers, function(controller) {
controller();
});
controllers = null;
}
// PRELINKING
for (i = 0, ii = preLinkFns.length; i < ii; i++) {
linkFn = preLinkFns[i];
invokeLinkFn(linkFn,
linkFn.isolateScope ? isolateScope : scope,
$element,
attrs,
linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
transcludeFn
);
}
// RECURSION
// We only pass the isolate scope, if the isolate directive has a template,
// otherwise the child elements do not belong to the isolate directive.
var scopeToChild = scope;
if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
scopeToChild = isolateScope;
}
childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
// POSTLINKING
for (i = postLinkFns.length - 1; i >= 0; i--) {
linkFn = postLinkFns[i];
invokeLinkFn(linkFn,
linkFn.isolateScope ? isolateScope : scope,
$element,
attrs,
linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
transcludeFn
);
}
// This is the function that is injected as `$transclude`.
// Note: all arguments are optional!
function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement) {
var transcludeControllers;
// No scope passed in:
if (!isScope(scope)) {
futureParentElement = cloneAttachFn;
cloneAttachFn = scope;
scope = undefined;
}
if (hasElementTranscludeDirective) {
transcludeControllers = elementControllers;
}
if (!futureParentElement) {
futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
}
return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
}
}
}
function markDirectivesAsIsolate(directives) {
// mark all directives as needing isolate scope.
for (var j = 0, jj = directives.length; j < jj; j++) {
directives[j] = inherit(directives[j], {$$isolateScope: true});
}
}
/**
* looks up the directive and decorates it with exception handling and proper parameters. We
* call this the boundDirective.
*
* @param {string} name name of the directive to look up.
* @param {string} location The directive must be found in specific format.
* String containing any of theses characters:
*
* * `E`: element name
* * `A': attribute
* * `C`: class
* * `M`: comment
* @returns {boolean} true if directive was added.
*/
function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
endAttrName) {
if (name === ignoreDirective) return null;
var match = null;
if (hasDirectives.hasOwnProperty(name)) {
for (var directive, directives = $injector.get(name + Suffix),
i = 0, ii = directives.length; i < ii; i++) {
try {
directive = directives[i];
if ((maxPriority === undefined || maxPriority > directive.priority) &&
directive.restrict.indexOf(location) != -1) {
if (startAttrName) {
directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
}
tDirectives.push(directive);
match = directive;
}
} catch (e) { $exceptionHandler(e); }
}
}
return match;
}
/**
* looks up the directive and returns true if it is a multi-element directive,
* and therefore requires DOM nodes between -start and -end markers to be grouped
* together.
*
* @param {string} name name of the directive to look up.
* @returns true if directive was registered as multi-element.
*/
function directiveIsMultiElement(name) {
if (hasDirectives.hasOwnProperty(name)) {
for (var directive, directives = $injector.get(name + Suffix),
i = 0, ii = directives.length; i < ii; i++) {
directive = directives[i];
if (directive.multiElement) {
return true;
}
}
}
return false;
}
/**
* When the element is replaced with HTML template then the new attributes
* on the template need to be merged with the existing attributes in the DOM.
* The desired effect is to have both of the attributes present.
*
* @param {object} dst destination attributes (original DOM)
* @param {object} src source attributes (from the directive template)
*/
function mergeTemplateAttributes(dst, src) {
var srcAttr = src.$attr,
dstAttr = dst.$attr,
$element = dst.$$element;
// reapply the old attributes to the new element
forEach(dst, function(value, key) {
if (key.charAt(0) != '$') {
if (src[key] && src[key] !== value) {
value += (key === 'style' ? ';' : ' ') + src[key];
}
dst.$set(key, value, true, srcAttr[key]);
}
});
// copy the new attributes on the old attrs object
forEach(src, function(value, key) {
if (key == 'class') {
safeAddClass($element, value);
dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
} else if (key == 'style') {
$element.attr('style', $element.attr('style') + ';' + value);
dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;
// `dst` will never contain hasOwnProperty as DOM parser won't let it.
// You will get an "InvalidCharacterError: DOM Exception 5" error if you
// have an attribute like "has-own-property" or "data-has-own-property", etc.
} else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
dst[key] = value;
dstAttr[key] = srcAttr[key];
}
});
}
function compileTemplateUrl(directives, $compileNode, tAttrs,
$rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
var linkQueue = [],
afterTemplateNodeLinkFn,
afterTemplateChildLinkFn,
beforeTemplateCompileNode = $compileNode[0],
origAsyncDirective = directives.shift(),
derivedSyncDirective = inherit(origAsyncDirective, {
templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
}),
templateUrl = (isFunction(origAsyncDirective.templateUrl))
? origAsyncDirective.templateUrl($compileNode, tAttrs)
: origAsyncDirective.templateUrl,
templateNamespace = origAsyncDirective.templateNamespace;
$compileNode.empty();
$templateRequest($sce.getTrustedResourceUrl(templateUrl))
.then(function(content) {
var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
content = denormalizeTemplate(content);
if (origAsyncDirective.replace) {
if (jqLiteIsTextNode(content)) {
$template = [];
} else {
$template = removeComments(wrapTemplate(templateNamespace, trim(content)));
}
compileNode = $template[0];
if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
throw $compileMinErr('tplrt',
"Template for directive '{0}' must have exactly one root element. {1}",
origAsyncDirective.name, templateUrl);
}
tempTemplateAttrs = {$attr: {}};
replaceWith($rootElement, $compileNode, compileNode);
var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
if (isObject(origAsyncDirective.scope)) {
markDirectivesAsIsolate(templateDirectives);
}
directives = templateDirectives.concat(directives);
mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
} else {
compileNode = beforeTemplateCompileNode;
$compileNode.html(content);
}
directives.unshift(derivedSyncDirective);
afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
previousCompileContext);
forEach($rootElement, function(node, i) {
if (node == compileNode) {
$rootElement[i] = $compileNode[0];
}
});
afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
while (linkQueue.length) {
var scope = linkQueue.shift(),
beforeTemplateLinkNode = linkQueue.shift(),
linkRootElement = linkQueue.shift(),
boundTranscludeFn = linkQueue.shift(),
linkNode = $compileNode[0];
if (scope.$$destroyed) continue;
if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
var oldClasses = beforeTemplateLinkNode.className;
if (!(previousCompileContext.hasElementTranscludeDirective &&
origAsyncDirective.replace)) {
// it was cloned therefore we have to clone as well.
linkNode = jqLiteClone(compileNode);
}
replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
// Copy in CSS classes from original node
safeAddClass(jqLite(linkNode), oldClasses);
}
if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
} else {
childBoundTranscludeFn = boundTranscludeFn;
}
afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
childBoundTranscludeFn);
}
linkQueue = null;
});
return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
var childBoundTranscludeFn = boundTranscludeFn;
if (scope.$$destroyed) return;
if (linkQueue) {
linkQueue.push(scope,
node,
rootElement,
childBoundTranscludeFn);
} else {
if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
}
afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);
}
};
}
/**
* Sorting function for bound directives.
*/
function byPriority(a, b) {
var diff = b.priority - a.priority;
if (diff !== 0) return diff;
if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
return a.index - b.index;
}
function assertNoDuplicate(what, previousDirective, directive, element) {
if (previousDirective) {
throw $compileMinErr('multidir', 'Multiple directives [{0}, {1}] asking for {2} on: {3}',
previousDirective.name, directive.name, what, startingTag(element));
}
}
function addTextInterpolateDirective(directives, text) {
var interpolateFn = $interpolate(text, true);
if (interpolateFn) {
directives.push({
priority: 0,
compile: function textInterpolateCompileFn(templateNode) {
var templateNodeParent = templateNode.parent(),
hasCompileParent = !!templateNodeParent.length;
// When transcluding a template that has bindings in the root
// we don't have a parent and thus need to add the class during linking fn.
if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
return function textInterpolateLinkFn(scope, node) {
var parent = node.parent();
if (!hasCompileParent) compile.$$addBindingClass(parent);
compile.$$addBindingInfo(parent, interpolateFn.expressions);
scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
node[0].nodeValue = value;
});
};
}
});
}
}
function wrapTemplate(type, template) {
type = lowercase(type || 'html');
switch (type) {
case 'svg':
case 'math':
var wrapper = document.createElement('div');
wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
return wrapper.childNodes[0].childNodes;
default:
return template;
}
}
function getTrustedContext(node, attrNormalizedName) {
if (attrNormalizedName == "srcdoc") {
return $sce.HTML;
}
var tag = nodeName_(node);
// maction[xlink:href] can source SVG. It's not limited to <maction>.
if (attrNormalizedName == "xlinkHref" ||
(tag == "form" && attrNormalizedName == "action") ||
(tag != "img" && (attrNormalizedName == "src" ||
attrNormalizedName == "ngSrc"))) {
return $sce.RESOURCE_URL;
}
}
function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) {
var trustedContext = getTrustedContext(node, name);
allOrNothing = ALL_OR_NOTHING_ATTRS[name] || allOrNothing;
var interpolateFn = $interpolate(value, true, trustedContext, allOrNothing);
// no interpolation found -> ignore
if (!interpolateFn) return;
if (name === "multiple" && nodeName_(node) === "select") {
throw $compileMinErr("selmulti",
"Binding to the 'multiple' attribute is not supported. Element: {0}",
startingTag(node));
}
directives.push({
priority: 100,
compile: function() {
return {
pre: function attrInterpolatePreLinkFn(scope, element, attr) {
var $$observers = (attr.$$observers || (attr.$$observers = {}));
if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
throw $compileMinErr('nodomevents',
"Interpolations for HTML DOM event attributes are disallowed. Please use the " +
"ng- versions (such as ng-click instead of onclick) instead.");
}
// If the attribute has changed since last $interpolate()ed
var newValue = attr[name];
if (newValue !== value) {
// we need to interpolate again since the attribute value has been updated
// (e.g. by another directive's compile function)
// ensure unset/empty values make interpolateFn falsy
interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);
value = newValue;
}
// if attribute was updated so that there is no interpolation going on we don't want to
// register any observers
if (!interpolateFn) return;
// initialize attr object so that it's ready in case we need the value for isolate
// scope initialization, otherwise the value would not be available from isolate
// directive's linking fn during linking phase
attr[name] = interpolateFn(scope);
($$observers[name] || ($$observers[name] = [])).$$inter = true;
(attr.$$observers && attr.$$observers[name].$$scope || scope).
$watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
//special case for class attribute addition + removal
//so that class changes can tap into the animation
//hooks provided by the $animate service. Be sure to
//skip animations when the first digest occurs (when
//both the new and the old values are the same) since
//the CSS classes are the non-interpolated values
if (name === 'class' && newValue != oldValue) {
attr.$updateClass(newValue, oldValue);
} else {
attr.$set(name, newValue);
}
});
}
};
}
});
}
/**
* This is a special jqLite.replaceWith, which can replace items which
* have no parents, provided that the containing jqLite collection is provided.
*
* @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
* in the root of the tree.
* @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
* the shell, but replace its DOM node reference.
* @param {Node} newNode The new DOM node.
*/
function replaceWith($rootElement, elementsToRemove, newNode) {
var firstElementToRemove = elementsToRemove[0],
removeCount = elementsToRemove.length,
parent = firstElementToRemove.parentNode,
i, ii;
if ($rootElement) {
for (i = 0, ii = $rootElement.length; i < ii; i++) {
if ($rootElement[i] == firstElementToRemove) {
$rootElement[i++] = newNode;
for (var j = i, j2 = j + removeCount - 1,
jj = $rootElement.length;
j < jj; j++, j2++) {
if (j2 < jj) {
$rootElement[j] = $rootElement[j2];
} else {
delete $rootElement[j];
}
}
$rootElement.length -= removeCount - 1;
// If the replaced element is also the jQuery .context then replace it
// .context is a deprecated jQuery api, so we should set it only when jQuery set it
// http://api.jquery.com/context/
if ($rootElement.context === firstElementToRemove) {
$rootElement.context = newNode;
}
break;
}
}
}
if (parent) {
parent.replaceChild(newNode, firstElementToRemove);
}
// TODO(perf): what's this document fragment for? is it needed? can we at least reuse it?
var fragment = document.createDocumentFragment();
fragment.appendChild(firstElementToRemove);
// Copy over user data (that includes Angular's $scope etc.). Don't copy private
// data here because there's no public interface in jQuery to do that and copying over
// event listeners (which is the main use of private data) wouldn't work anyway.
jqLite(newNode).data(jqLite(firstElementToRemove).data());
// Remove data of the replaced element. We cannot just call .remove()
// on the element it since that would deallocate scope that is needed
// for the new node. Instead, remove the data "manually".
if (!jQuery) {
delete jqLite.cache[firstElementToRemove[jqLite.expando]];
} else {
// jQuery 2.x doesn't expose the data storage. Use jQuery.cleanData to clean up after
// the replaced element. The cleanData version monkey-patched by Angular would cause
// the scope to be trashed and we do need the very same scope to work with the new
// element. However, we cannot just cache the non-patched version and use it here as
// that would break if another library patches the method after Angular does (one
// example is jQuery UI). Instead, set a flag indicating scope destroying should be
// skipped this one time.
skipDestroyOnNextJQueryCleanData = true;
jQuery.cleanData([firstElementToRemove]);
}
for (var k = 1, kk = elementsToRemove.length; k < kk; k++) {
var element = elementsToRemove[k];
jqLite(element).remove(); // must do this way to clean up expando
fragment.appendChild(element);
delete elementsToRemove[k];
}
elementsToRemove[0] = newNode;
elementsToRemove.length = 1;
}
function cloneAndAnnotateFn(fn, annotation) {
return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
}
function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
try {
linkFn(scope, $element, attrs, controllers, transcludeFn);
} catch (e) {
$exceptionHandler(e, startingTag($element));
}
}
}];
}
var PREFIX_REGEXP = /^((?:x|data)[\:\-_])/i;
/**
* Converts all accepted directives format into proper directive name.
* @param name Name to normalize
*/
function directiveNormalize(name) {
return camelCase(name.replace(PREFIX_REGEXP, ''));
}
/**
* @ngdoc type
* @name $compile.directive.Attributes
*
* @description
* A shared object between directive compile / linking functions which contains normalized DOM
* element attributes. The values reflect current binding state `{{ }}`. The normalization is
* needed since all of these are treated as equivalent in Angular:
*
* ```
* <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
* ```
*/
/**
* @ngdoc property
* @name $compile.directive.Attributes#$attr
*
* @description
* A map of DOM element attribute names to the normalized name. This is
* needed to do reverse lookup from normalized name back to actual name.
*/
/**
* @ngdoc method
* @name $compile.directive.Attributes#$set
* @kind function
*
* @description
* Set DOM element attribute value.
*
*
* @param {string} name Normalized element attribute name of the property to modify. The name is
* reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
* property to the original name.
* @param {string} value Value to set the attribute to. The value can be an interpolated string.
*/
/**
* Closure compiler type information
*/
function nodesetLinkingFn(
/* angular.Scope */ scope,
/* NodeList */ nodeList,
/* Element */ rootElement,
/* function(Function) */ boundTranscludeFn
) {}
function directiveLinkingFn(
/* nodesetLinkingFn */ nodesetLinkingFn,
/* angular.Scope */ scope,
/* Node */ node,
/* Element */ rootElement,
/* function(Function) */ boundTranscludeFn
) {}
function tokenDifference(str1, str2) {
var values = '',
tokens1 = str1.split(/\s+/),
tokens2 = str2.split(/\s+/);
outer:
for (var i = 0; i < tokens1.length; i++) {
var token = tokens1[i];
for (var j = 0; j < tokens2.length; j++) {
if (token == tokens2[j]) continue outer;
}
values += (values.length > 0 ? ' ' : '') + token;
}
return values;
}
function removeComments(jqNodes) {
jqNodes = jqLite(jqNodes);
var i = jqNodes.length;
if (i <= 1) {
return jqNodes;
}
while (i--) {
var node = jqNodes[i];
if (node.nodeType === NODE_TYPE_COMMENT) {
splice.call(jqNodes, i, 1);
}
}
return jqNodes;
}
var $controllerMinErr = minErr('$controller');
/**
* @ngdoc provider
* @name $controllerProvider
* @description
* The {@link ng.$controller $controller service} is used by Angular to create new
* controllers.
*
* This provider allows controller registration via the
* {@link ng.$controllerProvider#register register} method.
*/
function $ControllerProvider() {
var controllers = {},
globals = false,
CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/;
/**
* @ngdoc method
* @name $controllerProvider#register
* @param {string|Object} name Controller name, or an object map of controllers where the keys are
* the names and the values are the constructors.
* @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
* annotations in the array notation).
*/
this.register = function(name, constructor) {
assertNotHasOwnProperty(name, 'controller');
if (isObject(name)) {
extend(controllers, name);
} else {
controllers[name] = constructor;
}
};
/**
* @ngdoc method
* @name $controllerProvider#allowGlobals
* @description If called, allows `$controller` to find controller constructors on `window`
*/
this.allowGlobals = function() {
globals = true;
};
this.$get = ['$injector', '$window', function($injector, $window) {
/**
* @ngdoc service
* @name $controller
* @requires $injector
*
* @param {Function|string} constructor If called with a function then it's considered to be the
* controller constructor function. Otherwise it's considered to be a string which is used
* to retrieve the controller constructor using the following steps:
*
* * check if a controller with given name is registered via `$controllerProvider`
* * check if evaluating the string on the current scope returns a constructor
* * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
* `window` object (not recommended)
*
* The string can use the `controller as property` syntax, where the controller instance is published
* as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
* to work correctly.
*
* @param {Object} locals Injection locals for Controller.
* @return {Object} Instance of given controller.
*
* @description
* `$controller` service is responsible for instantiating controllers.
*
* It's just a simple call to {@link auto.$injector $injector}, but extracted into
* a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
*/
return function(expression, locals, later, ident) {
// PRIVATE API:
// param `later` --- indicates that the controller's constructor is invoked at a later time.
// If true, $controller will allocate the object with the correct
// prototype chain, but will not invoke the controller until a returned
// callback is invoked.
// param `ident` --- An optional label which overrides the label parsed from the controller
// expression, if any.
var instance, match, constructor, identifier;
later = later === true;
if (ident && isString(ident)) {
identifier = ident;
}
if (isString(expression)) {
match = expression.match(CNTRL_REG);
if (!match) {
throw $controllerMinErr('ctrlfmt',
"Badly formed controller string '{0}'. " +
"Must match `__name__ as __id__` or `__name__`.", expression);
}
constructor = match[1],
identifier = identifier || match[3];
expression = controllers.hasOwnProperty(constructor)
? controllers[constructor]
: getter(locals.$scope, constructor, true) ||
(globals ? getter($window, constructor, true) : undefined);
assertArgFn(expression, constructor, true);
}
if (later) {
// Instantiate controller later:
// This machinery is used to create an instance of the object before calling the
// controller's constructor itself.
//
// This allows properties to be added to the controller before the constructor is
// invoked. Primarily, this is used for isolate scope bindings in $compile.
//
// This feature is not intended for use by applications, and is thus not documented
// publicly.
// Object creation: http://jsperf.com/create-constructor/2
var controllerPrototype = (isArray(expression) ?
expression[expression.length - 1] : expression).prototype;
instance = Object.create(controllerPrototype || null);
if (identifier) {
addIdentifier(locals, identifier, instance, constructor || expression.name);
}
return extend(function() {
$injector.invoke(expression, instance, locals, constructor);
return instance;
}, {
instance: instance,
identifier: identifier
});
}
instance = $injector.instantiate(expression, locals, constructor);
if (identifier) {
addIdentifier(locals, identifier, instance, constructor || expression.name);
}
return instance;
};
function addIdentifier(locals, identifier, instance, name) {
if (!(locals && isObject(locals.$scope))) {
throw minErr('$controller')('noscp',
"Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
name, identifier);
}
locals.$scope[identifier] = instance;
}
}];
}
/**
* @ngdoc service
* @name $document
* @requires $window
*
* @description
* A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
*
* @example
<example module="documentExample">
<file name="index.html">
<div ng-controller="ExampleController">
<p>$document title: <b ng-bind="title"></b></p>
<p>window.document title: <b ng-bind="windowTitle"></b></p>
</div>
</file>
<file name="script.js">
angular.module('documentExample', [])
.controller('ExampleController', ['$scope', '$document', function($scope, $document) {
$scope.title = $document[0].title;
$scope.windowTitle = angular.element(window.document)[0].title;
}]);
</file>
</example>
*/
function $DocumentProvider() {
this.$get = ['$window', function(window) {
return jqLite(window.document);
}];
}
/**
* @ngdoc service
* @name $exceptionHandler
* @requires ng.$log
*
* @description
* Any uncaught exception in angular expressions is delegated to this service.
* The default implementation simply delegates to `$log.error` which logs it into
* the browser console.
*
* In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
* {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
*
* ## Example:
*
* ```js
* angular.module('exceptionOverride', []).factory('$exceptionHandler', function() {
* return function(exception, cause) {
* exception.message += ' (caused by "' + cause + '")';
* throw exception;
* };
* });
* ```
*
* This example will override the normal action of `$exceptionHandler`, to make angular
* exceptions fail hard when they happen, instead of just logging to the console.
*
* <hr />
* Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
* methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
* (unless executed during a digest).
*
* If you wish, you can manually delegate exceptions, e.g.
* `try { ... } catch(e) { $exceptionHandler(e); }`
*
* @param {Error} exception Exception associated with the error.
* @param {string=} cause optional information about the context in which
* the error was thrown.
*
*/
function $ExceptionHandlerProvider() {
this.$get = ['$log', function($log) {
return function(exception, cause) {
$log.error.apply($log, arguments);
};
}];
}
var APPLICATION_JSON = 'application/json';
var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
var JSON_START = /^\[|^\{(?!\{)/;
var JSON_ENDS = {
'[': /]$/,
'{': /}$/
};
var JSON_PROTECTION_PREFIX = /^\)\]\}',?\n/;
function defaultHttpResponseTransform(data, headers) {
if (isString(data)) {
// Strip json vulnerability protection prefix and trim whitespace
var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
if (tempData) {
var contentType = headers('Content-Type');
if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
data = fromJson(tempData);
}
}
}
return data;
}
function isJsonLike(str) {
var jsonStart = str.match(JSON_START);
return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
}
/**
* Parse headers into key value object
*
* @param {string} headers Raw headers as a string
* @returns {Object} Parsed headers as key value object
*/
function parseHeaders(headers) {
var parsed = createMap(), key, val, i;
if (!headers) return parsed;
forEach(headers.split('\n'), function(line) {
i = line.indexOf(':');
key = lowercase(trim(line.substr(0, i)));
val = trim(line.substr(i + 1));
if (key) {
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
}
});
return parsed;
}
/**
* Returns a function that provides access to parsed headers.
*
* Headers are lazy parsed when first requested.
* @see parseHeaders
*
* @param {(string|Object)} headers Headers to provide access to.
* @returns {function(string=)} Returns a getter function which if called with:
*
* - if called with single an argument returns a single header value or null
* - if called with no arguments returns an object containing all headers.
*/
function headersGetter(headers) {
var headersObj = isObject(headers) ? headers : undefined;
return function(name) {
if (!headersObj) headersObj = parseHeaders(headers);
if (name) {
var value = headersObj[lowercase(name)];
if (value === void 0) {
value = null;
}
return value;
}
return headersObj;
};
}
/**
* Chain all given functions
*
* This function is used for both request and response transforming
*
* @param {*} data Data to transform.
* @param {function(string=)} headers HTTP headers getter fn.
* @param {number} status HTTP status code of the response.
* @param {(Function|Array.<Function>)} fns Function or an array of functions.
* @returns {*} Transformed data.
*/
function transformData(data, headers, status, fns) {
if (isFunction(fns))
return fns(data, headers, status);
forEach(fns, function(fn) {
data = fn(data, headers, status);
});
return data;
}
function isSuccess(status) {
return 200 <= status && status < 300;
}
/**
* @ngdoc provider
* @name $httpProvider
* @description
* Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
* */
function $HttpProvider() {
/**
* @ngdoc property
* @name $httpProvider#defaults
* @description
*
* Object containing default values for all {@link ng.$http $http} requests.
*
* - **`defaults.cache`** - {Object} - an object built with {@link ng.$cacheFactory `$cacheFactory`}
* that will provide the cache for all requests who set their `cache` property to `true`.
* If you set the `default.cache = false` then only requests that specify their own custom
* cache object will be cached. See {@link $http#caching $http Caching} for more information.
*
* - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
* Defaults value is `'XSRF-TOKEN'`.
*
* - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
* XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
*
* - **`defaults.headers`** - {Object} - Default headers for all $http requests.
* Refer to {@link ng.$http#setting-http-headers $http} for documentation on
* setting default headers.
* - **`defaults.headers.common`**
* - **`defaults.headers.post`**
* - **`defaults.headers.put`**
* - **`defaults.headers.patch`**
*
**/
var defaults = this.defaults = {
// transform incoming response data
transformResponse: [defaultHttpResponseTransform],
// transform outgoing request data
transformRequest: [function(d) {
return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
}],
// default headers
headers: {
common: {
'Accept': 'application/json, text/plain, */*'
},
post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
},
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN'
};
var useApplyAsync = false;
/**
* @ngdoc method
* @name $httpProvider#useApplyAsync
* @description
*
* Configure $http service to combine processing of multiple http responses received at around
* the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
* significant performance improvement for bigger applications that make many HTTP requests
* concurrently (common during application bootstrap).
*
* Defaults to false. If no value is specifed, returns the current configured value.
*
* @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
* "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
* to load and share the same digest cycle.
*
* @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
* otherwise, returns the current configured value.
**/
this.useApplyAsync = function(value) {
if (isDefined(value)) {
useApplyAsync = !!value;
return this;
}
return useApplyAsync;
};
/**
* @ngdoc property
* @name $httpProvider#interceptors
* @description
*
* Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
* pre-processing of request or postprocessing of responses.
*
* These service factories are ordered by request, i.e. they are applied in the same order as the
* array, on request, but reverse order, on response.
*
* {@link ng.$http#interceptors Interceptors detailed info}
**/
var interceptorFactories = this.interceptors = [];
this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector',
function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) {
var defaultCache = $cacheFactory('$http');
/**
* Interceptors stored in reverse order. Inner interceptors before outer interceptors.
* The reversal is needed so that we can build up the interception chain around the
* server request.
*/
var reversedInterceptors = [];
forEach(interceptorFactories, function(interceptorFactory) {
reversedInterceptors.unshift(isString(interceptorFactory)
? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
});
/**
* @ngdoc service
* @kind function
* @name $http
* @requires ng.$httpBackend
* @requires $cacheFactory
* @requires $rootScope
* @requires $q
* @requires $injector
*
* @description
* The `$http` service is a core Angular service that facilitates communication with the remote
* HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
* object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
*
* For unit testing applications that use `$http` service, see
* {@link ngMock.$httpBackend $httpBackend mock}.
*
* For a higher level of abstraction, please check out the {@link ngResource.$resource
* $resource} service.
*
* The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
* the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
* it is important to familiarize yourself with these APIs and the guarantees they provide.
*
*
* ## General usage
* The `$http` service is a function which takes a single argument — a configuration object —
* that is used to generate an HTTP request and returns a {@link ng.$q promise}
* with two $http specific methods: `success` and `error`.
*
* ```js
* // Simple GET request example :
* $http.get('/someUrl').
* success(function(data, status, headers, config) {
* // this callback will be called asynchronously
* // when the response is available
* }).
* error(function(data, status, headers, config) {
* // called asynchronously if an error occurs
* // or server returns response with an error status.
* });
* ```
*
* ```js
* // Simple POST request example (passing data) :
* $http.post('/someUrl', {msg:'hello word!'}).
* success(function(data, status, headers, config) {
* // this callback will be called asynchronously
* // when the response is available
* }).
* error(function(data, status, headers, config) {
* // called asynchronously if an error occurs
* // or server returns response with an error status.
* });
* ```
*
*
* Since the returned value of calling the $http function is a `promise`, you can also use
* the `then` method to register callbacks, and these callbacks will receive a single argument –
* an object representing the response. See the API signature and type info below for more
* details.
*
* A response status code between 200 and 299 is considered a success status and
* will result in the success callback being called. Note that if the response is a redirect,
* XMLHttpRequest will transparently follow it, meaning that the error callback will not be
* called for such responses.
*
* ## Writing Unit Tests that use $http
* When unit testing (using {@link ngMock ngMock}), it is necessary to call
* {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
* request using trained responses.
*
* ```
* $httpBackend.expectGET(...);
* $http.get(...);
* $httpBackend.flush();
* ```
*
* ## Shortcut methods
*
* Shortcut methods are also available. All shortcut methods require passing in the URL, and
* request data must be passed in for POST/PUT requests.
*
* ```js
* $http.get('/someUrl').success(successCallback);
* $http.post('/someUrl', data).success(successCallback);
* ```
*
* Complete list of shortcut methods:
*
* - {@link ng.$http#get $http.get}
* - {@link ng.$http#head $http.head}
* - {@link ng.$http#post $http.post}
* - {@link ng.$http#put $http.put}
* - {@link ng.$http#delete $http.delete}
* - {@link ng.$http#jsonp $http.jsonp}
* - {@link ng.$http#patch $http.patch}
*
*
* ## Setting HTTP Headers
*
* The $http service will automatically add certain HTTP headers to all requests. These defaults
* can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
* object, which currently contains this default configuration:
*
* - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
* - `Accept: application/json, text/plain, * / *`
* - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
* - `Content-Type: application/json`
* - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
* - `Content-Type: application/json`
*
* To add or overwrite these defaults, simply add or remove a property from these configuration
* objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
* with the lowercased HTTP method name as the key, e.g.
* `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }.
*
* The defaults can also be set at runtime via the `$http.defaults` object in the same
* fashion. For example:
*
* ```
* module.run(function($http) {
* $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'
* });
* ```
*
* In addition, you can supply a `headers` property in the config object passed when
* calling `$http(config)`, which overrides the defaults without changing them globally.
*
* To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
* Use the `headers` property, setting the desired header to `undefined`. For example:
*
* ```js
* var req = {
* method: 'POST',
* url: 'http://example.com',
* headers: {
* 'Content-Type': undefined
* },
* data: { test: 'test' },
* }
*
* $http(req).success(function(){...}).error(function(){...});
* ```
*
* ## Transforming Requests and Responses
*
* Both requests and responses can be transformed using transformation functions: `transformRequest`
* and `transformResponse`. These properties can be a single function that returns
* the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,
* which allows you to `push` or `unshift` a new transformation function into the transformation chain.
*
* ### Default Transformations
*
* The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
* `defaults.transformResponse` properties. If a request does not provide its own transformations
* then these will be applied.
*
* You can augment or replace the default transformations by modifying these properties by adding to or
* replacing the array.
*
* Angular provides the following default transformations:
*
* Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):
*
* - If the `data` property of the request configuration object contains an object, serialize it
* into JSON format.
*
* Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):
*
* - If XSRF prefix is detected, strip it (see Security Considerations section below).
* - If JSON response is detected, deserialize it using a JSON parser.
*
*
* ### Overriding the Default Transformations Per Request
*
* If you wish override the request/response transformations only for a single request then provide
* `transformRequest` and/or `transformResponse` properties on the configuration object passed
* into `$http`.
*
* Note that if you provide these properties on the config object the default transformations will be
* overwritten. If you wish to augment the default transformations then you must include them in your
* local transformation array.
*
* The following code demonstrates adding a new response transformation to be run after the default response
* transformations have been run.
*
* ```js
* function appendTransform(defaults, transform) {
*
* // We can't guarantee that the default transformation is an array
* defaults = angular.isArray(defaults) ? defaults : [defaults];
*
* // Append the new transformation to the defaults
* return defaults.concat(transform);
* }
*
* $http({
* url: '...',
* method: 'GET',
* transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
* return doTransform(value);
* })
* });
* ```
*
*
* ## Caching
*
* To enable caching, set the request configuration `cache` property to `true` (to use default
* cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).
* When the cache is enabled, `$http` stores the response from the server in the specified
* cache. The next time the same request is made, the response is served from the cache without
* sending a request to the server.
*
* Note that even if the response is served from cache, delivery of the data is asynchronous in
* the same way that real requests are.
*
* If there are multiple GET requests for the same URL that should be cached using the same
* cache, but the cache is not populated yet, only one request to the server will be made and
* the remaining requests will be fulfilled using the response from the first request.
*
* You can change the default cache to a new object (built with
* {@link ng.$cacheFactory `$cacheFactory`}) by updating the
* {@link ng.$http#defaults `$http.defaults.cache`} property. All requests who set
* their `cache` property to `true` will now use this cache object.
*
* If you set the default cache to `false` then only requests that specify their own custom
* cache object will be cached.
*
* ## Interceptors
*
* Before you start creating interceptors, be sure to understand the
* {@link ng.$q $q and deferred/promise APIs}.
*
* For purposes of global error handling, authentication, or any kind of synchronous or
* asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
* able to intercept requests before they are handed to the server and
* responses before they are handed over to the application code that
* initiated these requests. The interceptors leverage the {@link ng.$q
* promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
*
* The interceptors are service factories that are registered with the `$httpProvider` by
* adding them to the `$httpProvider.interceptors` array. The factory is called and
* injected with dependencies (if specified) and returns the interceptor.
*
* There are two kinds of interceptors (and two kinds of rejection interceptors):
*
* * `request`: interceptors get called with a http `config` object. The function is free to
* modify the `config` object or create a new one. The function needs to return the `config`
* object directly, or a promise containing the `config` or a new `config` object.
* * `requestError`: interceptor gets called when a previous interceptor threw an error or
* resolved with a rejection.
* * `response`: interceptors get called with http `response` object. The function is free to
* modify the `response` object or create a new one. The function needs to return the `response`
* object directly, or as a promise containing the `response` or a new `response` object.
* * `responseError`: interceptor gets called when a previous interceptor threw an error or
* resolved with a rejection.
*
*
* ```js
* // register the interceptor as a service
* $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
* return {
* // optional method
* 'request': function(config) {
* // do something on success
* return config;
* },
*
* // optional method
* 'requestError': function(rejection) {
* // do something on error
* if (canRecover(rejection)) {
* return responseOrNewPromise
* }
* return $q.reject(rejection);
* },
*
*
*
* // optional method
* 'response': function(response) {
* // do something on success
* return response;
* },
*
* // optional method
* 'responseError': function(rejection) {
* // do something on error
* if (canRecover(rejection)) {
* return responseOrNewPromise
* }
* return $q.reject(rejection);
* }
* };
* });
*
* $httpProvider.interceptors.push('myHttpInterceptor');
*
*
* // alternatively, register the interceptor via an anonymous factory
* $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
* return {
* 'request': function(config) {
* // same as above
* },
*
* 'response': function(response) {
* // same as above
* }
* };
* });
* ```
*
* ## Security Considerations
*
* When designing web applications, consider security threats from:
*
* - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
* - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
*
* Both server and the client must cooperate in order to eliminate these threats. Angular comes
* pre-configured with strategies that address these issues, but for this to work backend server
* cooperation is required.
*
* ### JSON Vulnerability Protection
*
* A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
* allows third party website to turn your JSON resource URL into
* [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
* counter this your server can prefix all JSON requests with following string `")]}',\n"`.
* Angular will automatically strip the prefix before processing it as JSON.
*
* For example if your server needs to return:
* ```js
* ['one','two']
* ```
*
* which is vulnerable to attack, your server can return:
* ```js
* )]}',
* ['one','two']
* ```
*
* Angular will strip the prefix, before processing the JSON.
*
*
* ### Cross Site Request Forgery (XSRF) Protection
*
* [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which
* an unauthorized site can gain your user's private data. Angular provides a mechanism
* to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
* (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only
* JavaScript that runs on your domain could read the cookie, your server can be assured that
* the XHR came from JavaScript running on your domain. The header will not be set for
* cross-domain requests.
*
* To take advantage of this, your server needs to set a token in a JavaScript readable session
* cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
* server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
* that only JavaScript running on your domain could have sent the request. The token must be
* unique for each user and must be verifiable by the server (to prevent the JavaScript from
* making up its own tokens). We recommend that the token is a digest of your site's
* authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography))
* for added security.
*
* The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
* properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
* or the per-request config object.
*
*
* @param {object} config Object describing the request to be made and how it should be
* processed. The object has following properties:
*
* - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
* - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
* - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned
* to `?key1=value1&key2=value2` after the url. If the value is not a string, it will be
* JSONified.
* - **data** – `{string|Object}` – Data to be sent as the request message data.
* - **headers** – `{Object}` – Map of strings or functions which return strings representing
* HTTP headers to send to the server. If the return value of a function is null, the
* header will not be sent.
* - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
* - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
* - **transformRequest** –
* `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
* transform function or an array of such functions. The transform function takes the http
* request body and headers and returns its transformed (typically serialized) version.
* See {@link ng.$http#overriding-the-default-transformations-per-request
* Overriding the Default Transformations}
* - **transformResponse** –
* `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
* transform function or an array of such functions. The transform function takes the http
* response body, headers and status and returns its transformed (typically deserialized) version.
* See {@link ng.$http#overriding-the-default-transformations-per-request
* Overriding the Default Transformations}
* - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
* GET request, otherwise if a cache instance built with
* {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
* caching.
* - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
* that should abort the request when resolved.
* - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
* XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
* for more information.
* - **responseType** - `{string}` - see
* [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType).
*
* @returns {HttpPromise} Returns a {@link ng.$q promise} object with the
* standard `then` method and two http specific methods: `success` and `error`. The `then`
* method takes two arguments a success and an error callback which will be called with a
* response object. The `success` and `error` methods take a single argument - a function that
* will be called when the request succeeds or fails respectively. The arguments passed into
* these functions are destructured representation of the response object passed into the
* `then` method. The response object has these properties:
*
* - **data** – `{string|Object}` – The response body transformed with the transform
* functions.
* - **status** – `{number}` – HTTP status code of the response.
* - **headers** – `{function([headerName])}` – Header getter function.
* - **config** – `{Object}` – The configuration object that was used to generate the request.
* - **statusText** – `{string}` – HTTP status text of the response.
*
* @property {Array.<Object>} pendingRequests Array of config objects for currently pending
* requests. This is primarily meant to be used for debugging purposes.
*
*
* @example
<example module="httpExample">
<file name="index.html">
<div ng-controller="FetchController">
<select ng-model="method">
<option>GET</option>
<option>JSONP</option>
</select>
<input type="text" ng-model="url" size="80"/>
<button id="fetchbtn" ng-click="fetch()">fetch</button><br>
<button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
<button id="samplejsonpbtn"
ng-click="updateModel('JSONP',
'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
Sample JSONP
</button>
<button id="invalidjsonpbtn"
ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
Invalid JSONP
</button>
<pre>http status code: {{status}}</pre>
<pre>http response data: {{data}}</pre>
</div>
</file>
<file name="script.js">
angular.module('httpExample', [])
.controller('FetchController', ['$scope', '$http', '$templateCache',
function($scope, $http, $templateCache) {
$scope.method = 'GET';
$scope.url = 'http-hello.html';
$scope.fetch = function() {
$scope.code = null;
$scope.response = null;
$http({method: $scope.method, url: $scope.url, cache: $templateCache}).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
}).
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
$scope.updateModel = function(method, url) {
$scope.method = method;
$scope.url = url;
};
}]);
</file>
<file name="http-hello.html">
Hello, $http!
</file>
<file name="protractor.js" type="protractor">
var status = element(by.binding('status'));
var data = element(by.binding('data'));
var fetchBtn = element(by.id('fetchbtn'));
var sampleGetBtn = element(by.id('samplegetbtn'));
var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
it('should make an xhr GET request', function() {
sampleGetBtn.click();
fetchBtn.click();
expect(status.getText()).toMatch('200');
expect(data.getText()).toMatch(/Hello, \$http!/);
});
// Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
// it('should make a JSONP request to angularjs.org', function() {
// sampleJsonpBtn.click();
// fetchBtn.click();
// expect(status.getText()).toMatch('200');
// expect(data.getText()).toMatch(/Super Hero!/);
// });
it('should make JSONP request to invalid URL and invoke the error handler',
function() {
invalidJsonpBtn.click();
fetchBtn.click();
expect(status.getText()).toMatch('0');
expect(data.getText()).toMatch('Request failed');
});
</file>
</example>
*/
function $http(requestConfig) {
if (!angular.isObject(requestConfig)) {
throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);
}
var config = extend({
method: 'get',
transformRequest: defaults.transformRequest,
transformResponse: defaults.transformResponse
}, requestConfig);
config.headers = mergeHeaders(requestConfig);
config.method = uppercase(config.method);
var serverRequest = function(config) {
var headers = config.headers;
var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
// strip content-type if data is undefined
if (isUndefined(reqData)) {
forEach(headers, function(value, header) {
if (lowercase(header) === 'content-type') {
delete headers[header];
}
});
}
if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
config.withCredentials = defaults.withCredentials;
}
// send request
return sendReq(config, reqData).then(transformResponse, transformResponse);
};
var chain = [serverRequest, undefined];
var promise = $q.when(config);
// apply interceptors
forEach(reversedInterceptors, function(interceptor) {
if (interceptor.request || interceptor.requestError) {
chain.unshift(interceptor.request, interceptor.requestError);
}
if (interceptor.response || interceptor.responseError) {
chain.push(interceptor.response, interceptor.responseError);
}
});
while (chain.length) {
var thenFn = chain.shift();
var rejectFn = chain.shift();
promise = promise.then(thenFn, rejectFn);
}
promise.success = function(fn) {
promise.then(function(response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
promise.error = function(fn) {
promise.then(null, function(response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
return promise;
function transformResponse(response) {
// make a copy since the response must be cacheable
var resp = extend({}, response);
if (!response.data) {
resp.data = response.data;
} else {
resp.data = transformData(response.data, response.headers, response.status, config.transformResponse);
}
return (isSuccess(response.status))
? resp
: $q.reject(resp);
}
function executeHeaderFns(headers) {
var headerContent, processedHeaders = {};
forEach(headers, function(headerFn, header) {
if (isFunction(headerFn)) {
headerContent = headerFn();
if (headerContent != null) {
processedHeaders[header] = headerContent;
}
} else {
processedHeaders[header] = headerFn;
}
});
return processedHeaders;
}
function mergeHeaders(config) {
var defHeaders = defaults.headers,
reqHeaders = extend({}, config.headers),
defHeaderName, lowercaseDefHeaderName, reqHeaderName;
defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
// using for-in instead of forEach to avoid unecessary iteration after header has been found
defaultHeadersIteration:
for (defHeaderName in defHeaders) {
lowercaseDefHeaderName = lowercase(defHeaderName);
for (reqHeaderName in reqHeaders) {
if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
continue defaultHeadersIteration;
}
}
reqHeaders[defHeaderName] = defHeaders[defHeaderName];
}
// execute if header value is a function for merged headers
return executeHeaderFns(reqHeaders);
}
}
$http.pendingRequests = [];
/**
* @ngdoc method
* @name $http#get
*
* @description
* Shortcut method to perform `GET` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name $http#delete
*
* @description
* Shortcut method to perform `DELETE` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name $http#head
*
* @description
* Shortcut method to perform `HEAD` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name $http#jsonp
*
* @description
* Shortcut method to perform `JSONP` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request.
* The name of the callback should be the string `JSON_CALLBACK`.
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
createShortMethods('get', 'delete', 'head', 'jsonp');
/**
* @ngdoc method
* @name $http#post
*
* @description
* Shortcut method to perform `POST` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {*} data Request content
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name $http#put
*
* @description
* Shortcut method to perform `PUT` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {*} data Request content
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name $http#patch
*
* @description
* Shortcut method to perform `PATCH` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {*} data Request content
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
createShortMethodsWithData('post', 'put', 'patch');
/**
* @ngdoc property
* @name $http#defaults
*
* @description
* Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
* default headers, withCredentials as well as request and response transformations.
*
* See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
*/
$http.defaults = defaults;
return $http;
function createShortMethods(names) {
forEach(arguments, function(name) {
$http[name] = function(url, config) {
return $http(extend(config || {}, {
method: name,
url: url
}));
};
});
}
function createShortMethodsWithData(name) {
forEach(arguments, function(name) {
$http[name] = function(url, data, config) {
return $http(extend(config || {}, {
method: name,
url: url,
data: data
}));
};
});
}
/**
* Makes the request.
*
* !!! ACCESSES CLOSURE VARS:
* $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
*/
function sendReq(config, reqData) {
var deferred = $q.defer(),
promise = deferred.promise,
cache,
cachedResp,
reqHeaders = config.headers,
url = buildUrl(config.url, config.params);
$http.pendingRequests.push(config);
promise.then(removePendingReq, removePendingReq);
if ((config.cache || defaults.cache) && config.cache !== false &&
(config.method === 'GET' || config.method === 'JSONP')) {
cache = isObject(config.cache) ? config.cache
: isObject(defaults.cache) ? defaults.cache
: defaultCache;
}
if (cache) {
cachedResp = cache.get(url);
if (isDefined(cachedResp)) {
if (isPromiseLike(cachedResp)) {
// cached request has already been sent, but there is no response yet
cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
} else {
// serving from cache
if (isArray(cachedResp)) {
resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
} else {
resolvePromise(cachedResp, 200, {}, 'OK');
}
}
} else {
// put the promise for the non-transformed response into cache as a placeholder
cache.put(url, promise);
}
}
// if we won't have the response in cache, set the xsrf headers and
// send the request to the backend
if (isUndefined(cachedResp)) {
var xsrfValue = urlIsSameOrigin(config.url)
? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName]
: undefined;
if (xsrfValue) {
reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
}
$httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
config.withCredentials, config.responseType);
}
return promise;
/**
* Callback registered to $httpBackend():
* - caches the response if desired
* - resolves the raw $http promise
* - calls $apply
*/
function done(status, response, headersString, statusText) {
if (cache) {
if (isSuccess(status)) {
cache.put(url, [status, response, parseHeaders(headersString), statusText]);
} else {
// remove promise from the cache
cache.remove(url);
}
}
function resolveHttpPromise() {
resolvePromise(response, status, headersString, statusText);
}
if (useApplyAsync) {
$rootScope.$applyAsync(resolveHttpPromise);
} else {
resolveHttpPromise();
if (!$rootScope.$$phase) $rootScope.$apply();
}
}
/**
* Resolves the raw $http promise.
*/
function resolvePromise(response, status, headers, statusText) {
// normalize internal statuses to 0
status = Math.max(status, 0);
(isSuccess(status) ? deferred.resolve : deferred.reject)({
data: response,
status: status,
headers: headersGetter(headers),
config: config,
statusText: statusText
});
}
function resolvePromiseWithResult(result) {
resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);
}
function removePendingReq() {
var idx = $http.pendingRequests.indexOf(config);
if (idx !== -1) $http.pendingRequests.splice(idx, 1);
}
}
function buildUrl(url, params) {
if (!params) return url;
var parts = [];
forEachSorted(params, function(value, key) {
if (value === null || isUndefined(value)) return;
if (!isArray(value)) value = [value];
forEach(value, function(v) {
if (isObject(v)) {
if (isDate(v)) {
v = v.toISOString();
} else {
v = toJson(v);
}
}
parts.push(encodeUriQuery(key) + '=' +
encodeUriQuery(v));
});
});
if (parts.length > 0) {
url += ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&');
}
return url;
}
}];
}
function createXhr() {
return new window.XMLHttpRequest();
}
/**
* @ngdoc service
* @name $httpBackend
* @requires $window
* @requires $document
*
* @description
* HTTP backend used by the {@link ng.$http service} that delegates to
* XMLHttpRequest object or JSONP and deals with browser incompatibilities.
*
* You should never need to use this service directly, instead use the higher-level abstractions:
* {@link ng.$http $http} or {@link ngResource.$resource $resource}.
*
* During testing this implementation is swapped with {@link ngMock.$httpBackend mock
* $httpBackend} which can be trained with responses.
*/
function $HttpBackendProvider() {
this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) {
return createHttpBackend($browser, createXhr, $browser.defer, $window.angular.callbacks, $document[0]);
}];
}
function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
// TODO(vojta): fix the signature
return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
$browser.$$incOutstandingRequestCount();
url = url || $browser.url();
if (lowercase(method) == 'jsonp') {
var callbackId = '_' + (callbacks.counter++).toString(36);
callbacks[callbackId] = function(data) {
callbacks[callbackId].data = data;
callbacks[callbackId].called = true;
};
var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
callbackId, function(status, text) {
completeRequest(callback, status, callbacks[callbackId].data, "", text);
callbacks[callbackId] = noop;
});
} else {
var xhr = createXhr();
xhr.open(method, url, true);
forEach(headers, function(value, key) {
if (isDefined(value)) {
xhr.setRequestHeader(key, value);
}
});
xhr.onload = function requestLoaded() {
var statusText = xhr.statusText || '';
// responseText is the old-school way of retrieving response (supported by IE8 & 9)
// response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
var response = ('response' in xhr) ? xhr.response : xhr.responseText;
// normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
var status = xhr.status === 1223 ? 204 : xhr.status;
// fix status code when it is 0 (0 status is undocumented).
// Occurs when accessing file resources or on Android 4.1 stock browser
// while retrieving files from application cache.
if (status === 0) {
status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;
}
completeRequest(callback,
status,
response,
xhr.getAllResponseHeaders(),
statusText);
};
var requestError = function() {
// The response is always empty
// See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
completeRequest(callback, -1, null, null, '');
};
xhr.onerror = requestError;
xhr.onabort = requestError;
if (withCredentials) {
xhr.withCredentials = true;
}
if (responseType) {
try {
xhr.responseType = responseType;
} catch (e) {
// WebKit added support for the json responseType value on 09/03/2013
// https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
// known to throw when setting the value "json" as the response type. Other older
// browsers implementing the responseType
//
// The json response type can be ignored if not supported, because JSON payloads are
// parsed on the client-side regardless.
if (responseType !== 'json') {
throw e;
}
}
}
xhr.send(post || null);
}
if (timeout > 0) {
var timeoutId = $browserDefer(timeoutRequest, timeout);
} else if (isPromiseLike(timeout)) {
timeout.then(timeoutRequest);
}
function timeoutRequest() {
jsonpDone && jsonpDone();
xhr && xhr.abort();
}
function completeRequest(callback, status, response, headersString, statusText) {
// cancel timeout and subsequent timeout promise resolution
if (timeoutId !== undefined) {
$browserDefer.cancel(timeoutId);
}
jsonpDone = xhr = null;
callback(status, response, headersString, statusText);
$browser.$$completeOutstandingRequest(noop);
}
};
function jsonpReq(url, callbackId, done) {
// we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.:
// - fetches local scripts via XHR and evals them
// - adds and immediately removes script elements from the document
var script = rawDocument.createElement('script'), callback = null;
script.type = "text/javascript";
script.src = url;
script.async = true;
callback = function(event) {
removeEventListenerFn(script, "load", callback);
removeEventListenerFn(script, "error", callback);
rawDocument.body.removeChild(script);
script = null;
var status = -1;
var text = "unknown";
if (event) {
if (event.type === "load" && !callbacks[callbackId].called) {
event = { type: "error" };
}
text = event.type;
status = event.type === "error" ? 404 : 200;
}
if (done) {
done(status, text);
}
};
addEventListenerFn(script, "load", callback);
addEventListenerFn(script, "error", callback);
rawDocument.body.appendChild(script);
return callback;
}
}
var $interpolateMinErr = minErr('$interpolate');
/**
* @ngdoc provider
* @name $interpolateProvider
*
* @description
*
* Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
*
* @example
<example module="customInterpolationApp">
<file name="index.html">
<script>
var customInterpolationApp = angular.module('customInterpolationApp', []);
customInterpolationApp.config(function($interpolateProvider) {
$interpolateProvider.startSymbol('//');
$interpolateProvider.endSymbol('//');
});
customInterpolationApp.controller('DemoController', function() {
this.label = "This binding is brought you by // interpolation symbols.";
});
</script>
<div ng-app="App" ng-controller="DemoController as demo">
//demo.label//
</div>
</file>
<file name="protractor.js" type="protractor">
it('should interpolate binding with custom symbols', function() {
expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
});
</file>
</example>
*/
function $InterpolateProvider() {
var startSymbol = '{{';
var endSymbol = '}}';
/**
* @ngdoc method
* @name $interpolateProvider#startSymbol
* @description
* Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
*
* @param {string=} value new value to set the starting symbol to.
* @returns {string|self} Returns the symbol when used as getter and self if used as setter.
*/
this.startSymbol = function(value) {
if (value) {
startSymbol = value;
return this;
} else {
return startSymbol;
}
};
/**
* @ngdoc method
* @name $interpolateProvider#endSymbol
* @description
* Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
*
* @param {string=} value new value to set the ending symbol to.
* @returns {string|self} Returns the symbol when used as getter and self if used as setter.
*/
this.endSymbol = function(value) {
if (value) {
endSymbol = value;
return this;
} else {
return endSymbol;
}
};
this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
var startSymbolLength = startSymbol.length,
endSymbolLength = endSymbol.length,
escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
function escape(ch) {
return '\\\\\\' + ch;
}
/**
* @ngdoc service
* @name $interpolate
* @kind function
*
* @requires $parse
* @requires $sce
*
* @description
*
* Compiles a string with markup into an interpolation function. This service is used by the
* HTML {@link ng.$compile $compile} service for data binding. See
* {@link ng.$interpolateProvider $interpolateProvider} for configuring the
* interpolation markup.
*
*
* ```js
* var $interpolate = ...; // injected
* var exp = $interpolate('Hello {{name | uppercase}}!');
* expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!');
* ```
*
* `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
* `true`, the interpolation function will return `undefined` unless all embedded expressions
* guide to a value other than `undefined`.
*
* ```js
* var $interpolate = ...; // injected
* var context = {greeting: 'Hello', name: undefined };
*
* // default "forgiving" mode
* var exp = $interpolate('{{greeting}} {{name}}!');
* expect(exp(context)).toEqual('Hello !');
*
* // "allOrNothing" mode
* exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
* expect(exp(context)).toBeUndefined();
* context.name = 'Angular';
* expect(exp(context)).toEqual('Hello Angular!');
* ```
*
* `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
*
* ####Escaped Interpolation
* $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
* can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
* It will be rendered as a regular start/end marker, and will not be interpreted as an expression
* or binding.
*
* This enables web-servers to prevent script injection attacks and defacing attacks, to some
* degree, while also enabling code examples to work without relying on the
* {@link ng.directive:ngNonBindable ngNonBindable} directive.
*
* **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
* replacing angle brackets (<, >) with &lt; and &gt; respectively, and replacing all
* interpolation start/end markers with their escaped counterparts.**
*
* Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
* output when the $interpolate service processes the text. So, for HTML elements interpolated
* by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
* set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
* this is typically useful only when user-data is used in rendering a template from the server, or
* when otherwise untrusted data is used by a directive.
*
* <example>
* <file name="index.html">
* <div ng-init="username='A user'">
* <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
* </p>
* <p><strong>{{username}}</strong> attempts to inject code which will deface the
* application, but fails to accomplish their task, because the server has correctly
* escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
* characters.</p>
* <p>Instead, the result of the attempted script injection is visible, and can be removed
* from the database by an administrator.</p>
* </div>
* </file>
* </example>
*
* @param {string} text The text with markup to interpolate.
* @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
* embedded expression in order to return an interpolation function. Strings with no
* embedded expression will return null for the interpolation function.
* @param {string=} trustedContext when provided, the returned function passes the interpolated
* result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
* trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
* provides Strict Contextual Escaping for details.
* @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
* unless all embedded expressions guide to a value other than `undefined`.
* @returns {function(context)} an interpolation function which is used to compute the
* interpolated string. The function has these parameters:
*
* - `context`: guide context for all expressions embedded in the interpolated text
*/
function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
allOrNothing = !!allOrNothing;
var startIndex,
endIndex,
index = 0,
expressions = [],
parseFns = [],
textLength = text.length,
exp,
concat = [],
expressionPositions = [];
while (index < textLength) {
if (((startIndex = text.indexOf(startSymbol, index)) != -1) &&
((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1)) {
if (index !== startIndex) {
concat.push(unescapeText(text.substring(index, startIndex)));
}
exp = text.substring(startIndex + startSymbolLength, endIndex);
expressions.push(exp);
parseFns.push($parse(exp, parseStringifyInterceptor));
index = endIndex + endSymbolLength;
expressionPositions.push(concat.length);
concat.push('');
} else {
// we did not find an interpolation, so we have to add the remainder to the separators array
if (index !== textLength) {
concat.push(unescapeText(text.substring(index)));
}
break;
}
}
// Concatenating expressions makes it hard to reason about whether some combination of
// concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
// single expression be used for iframe[src], object[src], etc., we ensure that the value
// that's used is assigned or constructed by some JS code somewhere that is more testable or
// make it obvious that you bound the value to some user controlled value. This helps reduce
// the load when auditing for XSS issues.
if (trustedContext && concat.length > 1) {
throw $interpolateMinErr('noconcat',
"Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
"interpolations that concatenate multiple expressions when a trusted value is " +
"required. See http://docs.angularjs.org/api/ng.$sce", text);
}
if (!mustHaveExpression || expressions.length) {
var compute = function(values) {
for (var i = 0, ii = expressions.length; i < ii; i++) {
if (allOrNothing && isUndefined(values[i])) return;
concat[expressionPositions[i]] = values[i];
}
return concat.join('');
};
var getValue = function(value) {
return trustedContext ?
$sce.getTrusted(trustedContext, value) :
$sce.valueOf(value);
};
var stringify = function(value) {
if (value == null) { // null || undefined
return '';
}
switch (typeof value) {
case 'string':
break;
case 'number':
value = '' + value;
break;
default:
value = toJson(value);
}
return value;
};
return extend(function interpolationFn(context) {
var i = 0;
var ii = expressions.length;
var values = new Array(ii);
try {
for (; i < ii; i++) {
values[i] = parseFns[i](context);
}
return compute(values);
} catch (err) {
var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text,
err.toString());
$exceptionHandler(newErr);
}
}, {
// all of these properties are undocumented for now
exp: text, //just for compatibility with regular watchers created via $watch
expressions: expressions,
$$watchDelegate: function(scope, listener, objectEquality) {
var lastValue;
return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) {
var currValue = compute(values);
if (isFunction(listener)) {
listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
}
lastValue = currValue;
}, objectEquality);
}
});
}
function unescapeText(text) {
return text.replace(escapedStartRegexp, startSymbol).
replace(escapedEndRegexp, endSymbol);
}
function parseStringifyInterceptor(value) {
try {
value = getValue(value);
return allOrNothing && !isDefined(value) ? value : stringify(value);
} catch (err) {
var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text,
err.toString());
$exceptionHandler(newErr);
}
}
}
/**
* @ngdoc method
* @name $interpolate#startSymbol
* @description
* Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
*
* Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
* the symbol.
*
* @returns {string} start symbol.
*/
$interpolate.startSymbol = function() {
return startSymbol;
};
/**
* @ngdoc method
* @name $interpolate#endSymbol
* @description
* Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
*
* Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
* the symbol.
*
* @returns {string} end symbol.
*/
$interpolate.endSymbol = function() {
return endSymbol;
};
return $interpolate;
}];
}
function $IntervalProvider() {
this.$get = ['$rootScope', '$window', '$q', '$$q',
function($rootScope, $window, $q, $$q) {
var intervals = {};
/**
* @ngdoc service
* @name $interval
*
* @description
* Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
* milliseconds.
*
* The return value of registering an interval function is a promise. This promise will be
* notified upon each tick of the interval, and will be resolved after `count` iterations, or
* run indefinitely if `count` is not defined. The value of the notification will be the
* number of iterations that have run.
* To cancel an interval, call `$interval.cancel(promise)`.
*
* In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
* move forward by `millis` milliseconds and trigger any functions scheduled to run in that
* time.
*
* <div class="alert alert-warning">
* **Note**: Intervals created by this service must be explicitly destroyed when you are finished
* with them. In particular they are not automatically destroyed when a controller's scope or a
* directive's element are destroyed.
* You should take this into consideration and make sure to always cancel the interval at the
* appropriate moment. See the example below for more details on how and when to do this.
* </div>
*
* @param {function()} fn A function that should be called repeatedly.
* @param {number} delay Number of milliseconds between each function call.
* @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
* indefinitely.
* @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
* will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
* @returns {promise} A promise which will be notified on each iteration.
*
* @example
* <example module="intervalExample">
* <file name="index.html">
* <script>
* angular.module('intervalExample', [])
* .controller('ExampleController', ['$scope', '$interval',
* function($scope, $interval) {
* $scope.format = 'M/d/yy h:mm:ss a';
* $scope.blood_1 = 100;
* $scope.blood_2 = 120;
*
* var stop;
* $scope.fight = function() {
* // Don't start a new fight if we are already fighting
* if ( angular.isDefined(stop) ) return;
*
* stop = $interval(function() {
* if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
* $scope.blood_1 = $scope.blood_1 - 3;
* $scope.blood_2 = $scope.blood_2 - 4;
* } else {
* $scope.stopFight();
* }
* }, 100);
* };
*
* $scope.stopFight = function() {
* if (angular.isDefined(stop)) {
* $interval.cancel(stop);
* stop = undefined;
* }
* };
*
* $scope.resetFight = function() {
* $scope.blood_1 = 100;
* $scope.blood_2 = 120;
* };
*
* $scope.$on('$destroy', function() {
* // Make sure that the interval is destroyed too
* $scope.stopFight();
* });
* }])
* // Register the 'myCurrentTime' directive factory method.
* // We inject $interval and dateFilter service since the factory method is DI.
* .directive('myCurrentTime', ['$interval', 'dateFilter',
* function($interval, dateFilter) {
* // return the directive link function. (compile function not needed)
* return function(scope, element, attrs) {
* var format, // date format
* stopTime; // so that we can cancel the time updates
*
* // used to update the UI
* function updateTime() {
* element.text(dateFilter(new Date(), format));
* }
*
* // watch the expression, and update the UI on change.
* scope.$watch(attrs.myCurrentTime, function(value) {
* format = value;
* updateTime();
* });
*
* stopTime = $interval(updateTime, 1000);
*
* // listen on DOM destroy (removal) event, and cancel the next UI update
* // to prevent updating time after the DOM element was removed.
* element.on('$destroy', function() {
* $interval.cancel(stopTime);
* });
* }
* }]);
* </script>
*
* <div>
* <div ng-controller="ExampleController">
* Date format: <input ng-model="format"> <hr/>
* Current time is: <span my-current-time="format"></span>
* <hr/>
* Blood 1 : <font color='red'>{{blood_1}}</font>
* Blood 2 : <font color='red'>{{blood_2}}</font>
* <button type="button" data-ng-click="fight()">Fight</button>
* <button type="button" data-ng-click="stopFight()">StopFight</button>
* <button type="button" data-ng-click="resetFight()">resetFight</button>
* </div>
* </div>
*
* </file>
* </example>
*/
function interval(fn, delay, count, invokeApply) {
var setInterval = $window.setInterval,
clearInterval = $window.clearInterval,
iteration = 0,
skipApply = (isDefined(invokeApply) && !invokeApply),
deferred = (skipApply ? $$q : $q).defer(),
promise = deferred.promise;
count = isDefined(count) ? count : 0;
promise.then(null, null, fn);
promise.$$intervalId = setInterval(function tick() {
deferred.notify(iteration++);
if (count > 0 && iteration >= count) {
deferred.resolve(iteration);
clearInterval(promise.$$intervalId);
delete intervals[promise.$$intervalId];
}
if (!skipApply) $rootScope.$apply();
}, delay);
intervals[promise.$$intervalId] = deferred;
return promise;
}
/**
* @ngdoc method
* @name $interval#cancel
*
* @description
* Cancels a task associated with the `promise`.
*
* @param {promise} promise returned by the `$interval` function.
* @returns {boolean} Returns `true` if the task was successfully canceled.
*/
interval.cancel = function(promise) {
if (promise && promise.$$intervalId in intervals) {
intervals[promise.$$intervalId].reject('canceled');
$window.clearInterval(promise.$$intervalId);
delete intervals[promise.$$intervalId];
return true;
}
return false;
};
return interval;
}];
}
/**
* @ngdoc service
* @name $locale
*
* @description
* $locale service provides localization rules for various Angular components. As of right now the
* only public api is:
*
* * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
*/
function $LocaleProvider() {
this.$get = function() {
return {
id: 'en-us',
NUMBER_FORMATS: {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PATTERNS: [
{ // Decimal Pattern
minInt: 1,
minFrac: 0,
maxFrac: 3,
posPre: '',
posSuf: '',
negPre: '-',
negSuf: '',
gSize: 3,
lgSize: 3
},{ //Currency Pattern
minInt: 1,
minFrac: 2,
maxFrac: 2,
posPre: '\u00A4',
posSuf: '',
negPre: '(\u00A4',
negSuf: ')',
gSize: 3,
lgSize: 3
}
],
CURRENCY_SYM: '$'
},
DATETIME_FORMATS: {
MONTH:
'January,February,March,April,May,June,July,August,September,October,November,December'
.split(','),
SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','),
DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','),
SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','),
AMPMS: ['AM','PM'],
medium: 'MMM d, y h:mm:ss a',
'short': 'M/d/yy h:mm a',
fullDate: 'EEEE, MMMM d, y',
longDate: 'MMMM d, y',
mediumDate: 'MMM d, y',
shortDate: 'M/d/yy',
mediumTime: 'h:mm:ss a',
shortTime: 'h:mm a',
ERANAMES: [
"Before Christ",
"Anno Domini"
],
ERAS: [
"BC",
"AD"
]
},
pluralCat: function(num) {
if (num === 1) {
return 'one';
}
return 'other';
}
};
};
}
var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
var $locationMinErr = minErr('$location');
/**
* Encode path using encodeUriSegment, ignoring forward slashes
*
* @param {string} path Path to encode
* @returns {string}
*/
function encodePath(path) {
var segments = path.split('/'),
i = segments.length;
while (i--) {
segments[i] = encodeUriSegment(segments[i]);
}
return segments.join('/');
}
function parseAbsoluteUrl(absoluteUrl, locationObj) {
var parsedUrl = urlResolve(absoluteUrl);
locationObj.$$protocol = parsedUrl.protocol;
locationObj.$$host = parsedUrl.hostname;
locationObj.$$port = int(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
}
function parseAppUrl(relativeUrl, locationObj) {
var prefixed = (relativeUrl.charAt(0) !== '/');
if (prefixed) {
relativeUrl = '/' + relativeUrl;
}
var match = urlResolve(relativeUrl);
locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
match.pathname.substring(1) : match.pathname);
locationObj.$$search = parseKeyValue(match.search);
locationObj.$$hash = decodeURIComponent(match.hash);
// make sure path starts with '/';
if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
locationObj.$$path = '/' + locationObj.$$path;
}
}
/**
*
* @param {string} begin
* @param {string} whole
* @returns {string} returns text from whole after begin or undefined if it does not begin with
* expected string.
*/
function beginsWith(begin, whole) {
if (whole.indexOf(begin) === 0) {
return whole.substr(begin.length);
}
}
function stripHash(url) {
var index = url.indexOf('#');
return index == -1 ? url : url.substr(0, index);
}
function trimEmptyHash(url) {
return url.replace(/(#.+)|#$/, '$1');
}
function stripFile(url) {
return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
}
/* return the server only (scheme://host:port) */
function serverBase(url) {
return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
}
/**
* LocationHtml5Url represents an url
* This object is exposed as $location service when HTML5 mode is enabled and supported
*
* @constructor
* @param {string} appBase application base URL
* @param {string} basePrefix url path prefix
*/
function LocationHtml5Url(appBase, basePrefix) {
this.$$html5 = true;
basePrefix = basePrefix || '';
var appBaseNoFile = stripFile(appBase);
parseAbsoluteUrl(appBase, this);
/**
* Parse given html5 (regular) url string into properties
* @param {string} url HTML5 url
* @private
*/
this.$$parse = function(url) {
var pathUrl = beginsWith(appBaseNoFile, url);
if (!isString(pathUrl)) {
throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
appBaseNoFile);
}
parseAppUrl(pathUrl, this);
if (!this.$$path) {
this.$$path = '/';
}
this.$$compose();
};
/**
* Compose url and update `absUrl` property
* @private
*/
this.$$compose = function() {
var search = toKeyValue(this.$$search),
hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
};
this.$$parseLinkUrl = function(url, relHref) {
if (relHref && relHref[0] === '#') {
// special case for links to hash fragments:
// keep the old url and only replace the hash fragment
this.hash(relHref.slice(1));
return true;
}
var appUrl, prevAppUrl;
var rewrittenUrl;
if ((appUrl = beginsWith(appBase, url)) !== undefined) {
prevAppUrl = appUrl;
if ((appUrl = beginsWith(basePrefix, appUrl)) !== undefined) {
rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
} else {
rewrittenUrl = appBase + prevAppUrl;
}
} else if ((appUrl = beginsWith(appBaseNoFile, url)) !== undefined) {
rewrittenUrl = appBaseNoFile + appUrl;
} else if (appBaseNoFile == url + '/') {
rewrittenUrl = appBaseNoFile;
}
if (rewrittenUrl) {
this.$$parse(rewrittenUrl);
}
return !!rewrittenUrl;
};
}
/**
* LocationHashbangUrl represents url
* This object is exposed as $location service when developer doesn't opt into html5 mode.
* It also serves as the base class for html5 mode fallback on legacy browsers.
*
* @constructor
* @param {string} appBase application base URL
* @param {string} hashPrefix hashbang prefix
*/
function LocationHashbangUrl(appBase, hashPrefix) {
var appBaseNoFile = stripFile(appBase);
parseAbsoluteUrl(appBase, this);
/**
* Parse given hashbang url into properties
* @param {string} url Hashbang url
* @private
*/
this.$$parse = function(url) {
var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
var withoutHashUrl;
if (withoutBaseUrl.charAt(0) === '#') {
// The rest of the url starts with a hash so we have
// got either a hashbang path or a plain hash fragment
withoutHashUrl = beginsWith(hashPrefix, withoutBaseUrl);
if (isUndefined(withoutHashUrl)) {
// There was no hashbang prefix so we just have a hash fragment
withoutHashUrl = withoutBaseUrl;
}
} else {
// There was no hashbang path nor hash fragment:
// If we are in HTML5 mode we use what is left as the path;
// Otherwise we ignore what is left
withoutHashUrl = this.$$html5 ? withoutBaseUrl : '';
}
parseAppUrl(withoutHashUrl, this);
this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
this.$$compose();
/*
* In Windows, on an anchor node on documents loaded from
* the filesystem, the browser will return a pathname
* prefixed with the drive name ('/C:/path') when a
* pathname without a drive is set:
* * a.setAttribute('href', '/foo')
* * a.pathname === '/C:/foo' //true
*
* Inside of Angular, we're always using pathnames that
* do not include drive names for routing.
*/
function removeWindowsDriveName(path, url, base) {
/*
Matches paths for file protocol on windows,
such as /C:/foo/bar, and captures only /foo/bar.
*/
var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
var firstPathSegmentMatch;
//Get the relative path from the input URL.
if (url.indexOf(base) === 0) {
url = url.replace(base, '');
}
// The input URL intentionally contains a first path segment that ends with a colon.
if (windowsFilePathExp.exec(url)) {
return path;
}
firstPathSegmentMatch = windowsFilePathExp.exec(path);
return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
}
};
/**
* Compose hashbang url and update `absUrl` property
* @private
*/
this.$$compose = function() {
var search = toKeyValue(this.$$search),
hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
};
this.$$parseLinkUrl = function(url, relHref) {
if (stripHash(appBase) == stripHash(url)) {
this.$$parse(url);
return true;
}
return false;
};
}
/**
* LocationHashbangUrl represents url
* This object is exposed as $location service when html5 history api is enabled but the browser
* does not support it.
*
* @constructor
* @param {string} appBase application base URL
* @param {string} hashPrefix hashbang prefix
*/
function LocationHashbangInHtml5Url(appBase, hashPrefix) {
this.$$html5 = true;
LocationHashbangUrl.apply(this, arguments);
var appBaseNoFile = stripFile(appBase);
this.$$parseLinkUrl = function(url, relHref) {
if (relHref && relHref[0] === '#') {
// special case for links to hash fragments:
// keep the old url and only replace the hash fragment
this.hash(relHref.slice(1));
return true;
}
var rewrittenUrl;
var appUrl;
if (appBase == stripHash(url)) {
rewrittenUrl = url;
} else if ((appUrl = beginsWith(appBaseNoFile, url))) {
rewrittenUrl = appBase + hashPrefix + appUrl;
} else if (appBaseNoFile === url + '/') {
rewrittenUrl = appBaseNoFile;
}
if (rewrittenUrl) {
this.$$parse(rewrittenUrl);
}
return !!rewrittenUrl;
};
this.$$compose = function() {
var search = toKeyValue(this.$$search),
hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
// include hashPrefix in $$absUrl when $$url is empty so IE8 & 9 do not reload page because of removal of '#'
this.$$absUrl = appBase + hashPrefix + this.$$url;
};
}
var locationPrototype = {
/**
* Are we in html5 mode?
* @private
*/
$$html5: false,
/**
* Has any change been replacing?
* @private
*/
$$replace: false,
/**
* @ngdoc method
* @name $location#absUrl
*
* @description
* This method is getter only.
*
* Return full url representation with all segments encoded according to rules specified in
* [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
*
*
* ```js
* // given url http://example.com/#/some/path?foo=bar&baz=xoxo
* var absUrl = $location.absUrl();
* // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
* ```
*
* @return {string} full url
*/
absUrl: locationGetter('$$absUrl'),
/**
* @ngdoc method
* @name $location#url
*
* @description
* This method is getter / setter.
*
* Return url (e.g. `/path?a=b#hash`) when called without any parameter.
*
* Change path, search and hash, when called with parameter and return `$location`.
*
*
* ```js
* // given url http://example.com/#/some/path?foo=bar&baz=xoxo
* var url = $location.url();
* // => "/some/path?foo=bar&baz=xoxo"
* ```
*
* @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
* @return {string} url
*/
url: function(url) {
if (isUndefined(url))
return this.$$url;
var match = PATH_MATCH.exec(url);
if (match[1] || url === '') this.path(decodeURIComponent(match[1]));
if (match[2] || match[1] || url === '') this.search(match[3] || '');
this.hash(match[5] || '');
return this;
},
/**
* @ngdoc method
* @name $location#protocol
*
* @description
* This method is getter only.
*
* Return protocol of current url.
*
*
* ```js
* // given url http://example.com/#/some/path?foo=bar&baz=xoxo
* var protocol = $location.protocol();
* // => "http"
* ```
*
* @return {string} protocol of current url
*/
protocol: locationGetter('$$protocol'),
/**
* @ngdoc method
* @name $location#host
*
* @description
* This method is getter only.
*
* Return host of current url.
*
*
* ```js
* // given url http://example.com/#/some/path?foo=bar&baz=xoxo
* var host = $location.host();
* // => "example.com"
* ```
*
* @return {string} host of current url.
*/
host: locationGetter('$$host'),
/**
* @ngdoc method
* @name $location#port
*
* @description
* This method is getter only.
*
* Return port of current url.
*
*
* ```js
* // given url http://example.com/#/some/path?foo=bar&baz=xoxo
* var port = $location.port();
* // => 80
* ```
*
* @return {Number} port
*/
port: locationGetter('$$port'),
/**
* @ngdoc method
* @name $location#path
*
* @description
* This method is getter / setter.
*
* Return path of current url when called without any parameter.
*
* Change path when called with parameter and return `$location`.
*
* Note: Path should always begin with forward slash (/), this method will add the forward slash
* if it is missing.
*
*
* ```js
* // given url http://example.com/#/some/path?foo=bar&baz=xoxo
* var path = $location.path();
* // => "/some/path"
* ```
*
* @param {(string|number)=} path New path
* @return {string} path
*/
path: locationGetterSetter('$$path', function(path) {
path = path !== null ? path.toString() : '';
return path.charAt(0) == '/' ? path : '/' + path;
}),
/**
* @ngdoc method
* @name $location#search
*
* @description
* This method is getter / setter.
*
* Return search part (as object) of current url when called without any parameter.
*
* Change search part when called with parameter and return `$location`.
*
*
* ```js
* // given url http://example.com/#/some/path?foo=bar&baz=xoxo
* var searchObject = $location.search();
* // => {foo: 'bar', baz: 'xoxo'}
*
* // set foo to 'yipee'
* $location.search('foo', 'yipee');
* // $location.search() => {foo: 'yipee', baz: 'xoxo'}
* ```
*
* @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
* hash object.
*
* When called with a single argument the method acts as a setter, setting the `search` component
* of `$location` to the specified value.
*
* If the argument is a hash object containing an array of values, these values will be encoded
* as duplicate search parameters in the url.
*
* @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
* will override only a single search property.
*
* If `paramValue` is an array, it will override the property of the `search` component of
* `$location` specified via the first argument.
*
* If `paramValue` is `null`, the property specified via the first argument will be deleted.
*
* If `paramValue` is `true`, the property specified via the first argument will be added with no
* value nor trailing equal sign.
*
* @return {Object} If called with no arguments returns the parsed `search` object. If called with
* one or more arguments returns `$location` object itself.
*/
search: function(search, paramValue) {
switch (arguments.length) {
case 0:
return this.$$search;
case 1:
if (isString(search) || isNumber(search)) {
search = search.toString();
this.$$search = parseKeyValue(search);
} else if (isObject(search)) {
search = copy(search, {});
// remove object undefined or null properties
forEach(search, function(value, key) {
if (value == null) delete search[key];
});
this.$$search = search;
} else {
throw $locationMinErr('isrcharg',
'The first argument of the `$location#search()` call must be a string or an object.');
}
break;
default:
if (isUndefined(paramValue) || paramValue === null) {
delete this.$$search[search];
} else {
this.$$search[search] = paramValue;
}
}
this.$$compose();
return this;
},
/**
* @ngdoc method
* @name $location#hash
*
* @description
* This method is getter / setter.
*
* Return hash fragment when called without any parameter.
*
* Change hash fragment when called with parameter and return `$location`.
*
*
* ```js
* // given url http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
* var hash = $location.hash();
* // => "hashValue"
* ```
*
* @param {(string|number)=} hash New hash fragment
* @return {string} hash
*/
hash: locationGetterSetter('$$hash', function(hash) {
return hash !== null ? hash.toString() : '';
}),
/**
* @ngdoc method
* @name $location#replace
*
* @description
* If called, all changes to $location during current `$digest` will be replacing current history
* record, instead of adding new one.
*/
replace: function() {
this.$$replace = true;
return this;
}
};
forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
Location.prototype = Object.create(locationPrototype);
/**
* @ngdoc method
* @name $location#state
*
* @description
* This method is getter / setter.
*
* Return the history state object when called without any parameter.
*
* Change the history state object when called with one parameter and return `$location`.
* The state object is later passed to `pushState` or `replaceState`.
*
* NOTE: This method is supported only in HTML5 mode and only in browsers supporting
* the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
* older browsers (like IE9 or Android < 4.0), don't use this method.
*
* @param {object=} state State object for pushState or replaceState
* @return {object} state
*/
Location.prototype.state = function(state) {
if (!arguments.length)
return this.$$state;
if (Location !== LocationHtml5Url || !this.$$html5) {
throw $locationMinErr('nostate', 'History API state support is available only ' +
'in HTML5 mode and only in browsers supporting HTML5 History API');
}
// The user might modify `stateObject` after invoking `$location.state(stateObject)`
// but we're changing the $$state reference to $browser.state() during the $digest
// so the modification window is narrow.
this.$$state = isUndefined(state) ? null : state;
return this;
};
});
function locationGetter(property) {
return function() {
return this[property];
};
}
function locationGetterSetter(property, preprocess) {
return function(value) {
if (isUndefined(value))
return this[property];
this[property] = preprocess(value);
this.$$compose();
return this;
};
}
/**
* @ngdoc service
* @name $location
*
* @requires $rootElement
*
* @description
* The $location service parses the URL in the browser address bar (based on the
* [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
* available to your application. Changes to the URL in the address bar are reflected into
* $location service and changes to $location are reflected into the browser address bar.
*
* **The $location service:**
*
* - Exposes the current URL in the browser address bar, so you can
* - Watch and observe the URL.
* - Change the URL.
* - Synchronizes the URL with the browser when the user
* - Changes the address bar.
* - Clicks the back or forward button (or clicks a History link).
* - Clicks on a link.
* - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
*
* For more information see {@link guide/$location Developer Guide: Using $location}
*/
/**
* @ngdoc provider
* @name $locationProvider
* @description
* Use the `$locationProvider` to configure how the application deep linking paths are stored.
*/
function $LocationProvider() {
var hashPrefix = '',
html5Mode = {
enabled: false,
requireBase: true,
rewriteLinks: true
};
/**
* @ngdoc method
* @name $locationProvider#hashPrefix
* @description
* @param {string=} prefix Prefix for hash part (containing path and search)
* @returns {*} current value if used as getter or itself (chaining) if used as setter
*/
this.hashPrefix = function(prefix) {
if (isDefined(prefix)) {
hashPrefix = prefix;
return this;
} else {
return hashPrefix;
}
};
/**
* @ngdoc method
* @name $locationProvider#html5Mode
* @description
* @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
* If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
* properties:
* - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
* change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
* support `pushState`.
* - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
* whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
* true, and a base tag is not present, an error will be thrown when `$location` is injected.
* See the {@link guide/$location $location guide for more information}
* - **rewriteLinks** - `{boolean}` - (default: `true`) When html5Mode is enabled,
* enables/disables url rewriting for relative links.
*
* @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
*/
this.html5Mode = function(mode) {
if (isBoolean(mode)) {
html5Mode.enabled = mode;
return this;
} else if (isObject(mode)) {
if (isBoolean(mode.enabled)) {
html5Mode.enabled = mode.enabled;
}
if (isBoolean(mode.requireBase)) {
html5Mode.requireBase = mode.requireBase;
}
if (isBoolean(mode.rewriteLinks)) {
html5Mode.rewriteLinks = mode.rewriteLinks;
}
return this;
} else {
return html5Mode;
}
};
/**
* @ngdoc event
* @name $location#$locationChangeStart
* @eventType broadcast on root scope
* @description
* Broadcasted before a URL will change.
*
* This change can be prevented by calling
* `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
* details about event object. Upon successful change
* {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
*
* The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
* the browser supports the HTML5 History API.
*
* @param {Object} angularEvent Synthetic event object.
* @param {string} newUrl New URL
* @param {string=} oldUrl URL that was before it was changed.
* @param {string=} newState New history state object
* @param {string=} oldState History state object that was before it was changed.
*/
/**
* @ngdoc event
* @name $location#$locationChangeSuccess
* @eventType broadcast on root scope
* @description
* Broadcasted after a URL was changed.
*
* The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
* the browser supports the HTML5 History API.
*
* @param {Object} angularEvent Synthetic event object.
* @param {string} newUrl New URL
* @param {string=} oldUrl URL that was before it was changed.
* @param {string=} newState New history state object
* @param {string=} oldState History state object that was before it was changed.
*/
this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',
function($rootScope, $browser, $sniffer, $rootElement, $window) {
var $location,
LocationMode,
baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
initialUrl = $browser.url(),
appBase;
if (html5Mode.enabled) {
if (!baseHref && html5Mode.requireBase) {
throw $locationMinErr('nobase',
"$location in HTML5 mode requires a <base> tag to be present!");
}
appBase = serverBase(initialUrl) + (baseHref || '/');
LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
} else {
appBase = stripHash(initialUrl);
LocationMode = LocationHashbangUrl;
}
$location = new LocationMode(appBase, '#' + hashPrefix);
$location.$$parseLinkUrl(initialUrl, initialUrl);
$location.$$state = $browser.state();
var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
function setBrowserUrlWithFallback(url, replace, state) {
var oldUrl = $location.url();
var oldState = $location.$$state;
try {
$browser.url(url, replace, state);
// Make sure $location.state() returns referentially identical (not just deeply equal)
// state object; this makes possible quick checking if the state changed in the digest
// loop. Checking deep equality would be too expensive.
$location.$$state = $browser.state();
} catch (e) {
// Restore old values if pushState fails
$location.url(oldUrl);
$location.$$state = oldState;
throw e;
}
}
$rootElement.on('click', function(event) {
// TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
// currently we open nice url link and redirect then
if (!html5Mode.rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which == 2 || event.button == 2) return;
var elm = jqLite(event.target);
// traverse the DOM up to find first A tag
while (nodeName_(elm[0]) !== 'a') {
// ignore rewriting if no A tag (reached root element, or no parent - removed from document)
if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
}
var absHref = elm.prop('href');
// get the actual href attribute - see
// http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
var relHref = elm.attr('href') || elm.attr('xlink:href');
if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
// SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
// an animation.
absHref = urlResolve(absHref.animVal).href;
}
// Ignore when url is started with javascript: or mailto:
if (IGNORE_URI_REGEXP.test(absHref)) return;
if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
if ($location.$$parseLinkUrl(absHref, relHref)) {
// We do a preventDefault for all urls that are part of the angular application,
// in html5mode and also without, so that we are able to abort navigation without
// getting double entries in the location history.
event.preventDefault();
// update location manually
if ($location.absUrl() != $browser.url()) {
$rootScope.$apply();
// hack to work around FF6 bug 684208 when scenario runner clicks on links
$window.angular['ff-684208-preventDefault'] = true;
}
}
}
});
// rewrite hashbang url <> html5 url
if (trimEmptyHash($location.absUrl()) != trimEmptyHash(initialUrl)) {
$browser.url($location.absUrl(), true);
}
var initializing = true;
// update $location when $browser url changes
$browser.onUrlChange(function(newUrl, newState) {
$rootScope.$evalAsync(function() {
var oldUrl = $location.absUrl();
var oldState = $location.$$state;
var defaultPrevented;
$location.$$parse(newUrl);
$location.$$state = newState;
defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
newState, oldState).defaultPrevented;
// if the location was changed by a `$locationChangeStart` handler then stop
// processing this location change
if ($location.absUrl() !== newUrl) return;
if (defaultPrevented) {
$location.$$parse(oldUrl);
$location.$$state = oldState;
setBrowserUrlWithFallback(oldUrl, false, oldState);
} else {
initializing = false;
afterLocationChange(oldUrl, oldState);
}
});
if (!$rootScope.$$phase) $rootScope.$digest();
});
// update browser
$rootScope.$watch(function $locationWatch() {
var oldUrl = trimEmptyHash($browser.url());
var newUrl = trimEmptyHash($location.absUrl());
var oldState = $browser.state();
var currentReplace = $location.$$replace;
var urlOrStateChanged = oldUrl !== newUrl ||
($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
if (initializing || urlOrStateChanged) {
initializing = false;
$rootScope.$evalAsync(function() {
var newUrl = $location.absUrl();
var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
$location.$$state, oldState).defaultPrevented;
// if the location was changed by a `$locationChangeStart` handler then stop
// processing this location change
if ($location.absUrl() !== newUrl) return;
if (defaultPrevented) {
$location.$$parse(oldUrl);
$location.$$state = oldState;
} else {
if (urlOrStateChanged) {
setBrowserUrlWithFallback(newUrl, currentReplace,
oldState === $location.$$state ? null : $location.$$state);
}
afterLocationChange(oldUrl, oldState);
}
});
}
$location.$$replace = false;
// we don't need to return anything because $evalAsync will make the digest loop dirty when
// there is a change
});
return $location;
function afterLocationChange(oldUrl, oldState) {
$rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
$location.$$state, oldState);
}
}];
}
/**
* @ngdoc service
* @name $log
* @requires $window
*
* @description
* Simple service for logging. Default implementation safely writes the message
* into the browser's console (if present).
*
* The main purpose of this service is to simplify debugging and troubleshooting.
*
* The default is to log `debug` messages. You can use
* {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
*
* @example
<example module="logExample">
<file name="script.js">
angular.module('logExample', [])
.controller('LogController', ['$scope', '$log', function($scope, $log) {
$scope.$log = $log;
$scope.message = 'Hello World!';
}]);
</file>
<file name="index.html">
<div ng-controller="LogController">
<p>Reload this page with open console, enter text and hit the log button...</p>
Message:
<input type="text" ng-model="message"/>
<button ng-click="$log.log(message)">log</button>
<button ng-click="$log.warn(message)">warn</button>
<button ng-click="$log.info(message)">info</button>
<button ng-click="$log.error(message)">error</button>
<button ng-click="$log.debug(message)">debug</button>
</div>
</file>
</example>
*/
/**
* @ngdoc provider
* @name $logProvider
* @description
* Use the `$logProvider` to configure how the application logs messages
*/
function $LogProvider() {
var debug = true,
self = this;
/**
* @ngdoc method
* @name $logProvider#debugEnabled
* @description
* @param {boolean=} flag enable or disable debug level messages
* @returns {*} current value if used as getter or itself (chaining) if used as setter
*/
this.debugEnabled = function(flag) {
if (isDefined(flag)) {
debug = flag;
return this;
} else {
return debug;
}
};
this.$get = ['$window', function($window) {
return {
/**
* @ngdoc method
* @name $log#log
*
* @description
* Write a log message
*/
log: consoleLog('log'),
/**
* @ngdoc method
* @name $log#info
*
* @description
* Write an information message
*/
info: consoleLog('info'),
/**
* @ngdoc method
* @name $log#warn
*
* @description
* Write a warning message
*/
warn: consoleLog('warn'),
/**
* @ngdoc method
* @name $log#error
*
* @description
* Write an error message
*/
error: consoleLog('error'),
/**
* @ngdoc method
* @name $log#debug
*
* @description
* Write a debug message
*/
debug: (function() {
var fn = consoleLog('debug');
return function() {
if (debug) {
fn.apply(self, arguments);
}
};
}())
};
function formatError(arg) {
if (arg instanceof Error) {
if (arg.stack) {
arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
? 'Error: ' + arg.message + '\n' + arg.stack
: arg.stack;
} else if (arg.sourceURL) {
arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
}
}
return arg;
}
function consoleLog(type) {
var console = $window.console || {},
logFn = console[type] || console.log || noop,
hasApply = false;
// Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
// The reason behind this is that console.log has type "object" in IE8...
try {
hasApply = !!logFn.apply;
} catch (e) {}
if (hasApply) {
return function() {
var args = [];
forEach(arguments, function(arg) {
args.push(formatError(arg));
});
return logFn.apply(console, args);
};
}
// we are IE which either doesn't have window.console => this is noop and we do nothing,
// or we are IE where console.log doesn't have apply so we log at least first 2 args
return function(arg1, arg2) {
logFn(arg1, arg2 == null ? '' : arg2);
};
}
}];
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Any commits to this file should be reviewed with security in mind. *
* Changes to this file can potentially create security vulnerabilities. *
* An approval from 2 Core members with history of modifying *
* this file is required. *
* *
* Does the change somehow allow for arbitrary javascript to be executed? *
* Or allows for someone to change the prototype of built-in objects? *
* Or gives undesired access to variables likes document or window? *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
var $parseMinErr = minErr('$parse');
// Sandboxing Angular Expressions
// ------------------------------
// Angular expressions are generally considered safe because these expressions only have direct
// access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by
// obtaining a reference to native JS functions such as the Function constructor.
//
// As an example, consider the following Angular expression:
//
// {}.toString.constructor('alert("evil JS code")')
//
// This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
// against the expression language, but not to prevent exploits that were enabled by exposing
// sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good
// practice and therefore we are not even trying to protect against interaction with an object
// explicitly exposed in this way.
//
// In general, it is not possible to access a Window object from an angular expression unless a
// window or some DOM object that has a reference to window is published onto a Scope.
// Similarly we prevent invocations of function known to be dangerous, as well as assignments to
// native objects.
//
// See https://docs.angularjs.org/guide/security
function ensureSafeMemberName(name, fullExpression) {
if (name === "__defineGetter__" || name === "__defineSetter__"
|| name === "__lookupGetter__" || name === "__lookupSetter__"
|| name === "__proto__") {
throw $parseMinErr('isecfld',
'Attempting to access a disallowed field in Angular expressions! '
+ 'Expression: {0}', fullExpression);
}
return name;
}
function ensureSafeObject(obj, fullExpression) {
// nifty check if obj is Function that is fast and works across iframes and other contexts
if (obj) {
if (obj.constructor === obj) {
throw $parseMinErr('isecfn',
'Referencing Function in Angular expressions is disallowed! Expression: {0}',
fullExpression);
} else if (// isWindow(obj)
obj.window === obj) {
throw $parseMinErr('isecwindow',
'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
fullExpression);
} else if (// isElement(obj)
obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
throw $parseMinErr('isecdom',
'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
fullExpression);
} else if (// block Object so that we can't get hold of dangerous Object.* methods
obj === Object) {
throw $parseMinErr('isecobj',
'Referencing Object in Angular expressions is disallowed! Expression: {0}',
fullExpression);
}
}
return obj;
}
var CALL = Function.prototype.call;
var APPLY = Function.prototype.apply;
var BIND = Function.prototype.bind;
function ensureSafeFunction(obj, fullExpression) {
if (obj) {
if (obj.constructor === obj) {
throw $parseMinErr('isecfn',
'Referencing Function in Angular expressions is disallowed! Expression: {0}',
fullExpression);
} else if (obj === CALL || obj === APPLY || obj === BIND) {
throw $parseMinErr('isecff',
'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',
fullExpression);
}
}
}
//Keyword constants
var CONSTANTS = createMap();
forEach({
'null': function() { return null; },
'true': function() { return true; },
'false': function() { return false; },
'undefined': function() {}
}, function(constantGetter, name) {
constantGetter.constant = constantGetter.literal = constantGetter.sharedGetter = true;
CONSTANTS[name] = constantGetter;
});
//Not quite a constant, but can be lex/parsed the same
CONSTANTS['this'] = function(self) { return self; };
CONSTANTS['this'].sharedGetter = true;
//Operators - will be wrapped by binaryFn/unaryFn/assignment/filter
var OPERATORS = extend(createMap(), {
'+':function(self, locals, a, b) {
a=a(self, locals); b=b(self, locals);
if (isDefined(a)) {
if (isDefined(b)) {
return a + b;
}
return a;
}
return isDefined(b) ? b : undefined;},
'-':function(self, locals, a, b) {
a=a(self, locals); b=b(self, locals);
return (isDefined(a) ? a : 0) - (isDefined(b) ? b : 0);
},
'*':function(self, locals, a, b) {return a(self, locals) * b(self, locals);},
'/':function(self, locals, a, b) {return a(self, locals) / b(self, locals);},
'%':function(self, locals, a, b) {return a(self, locals) % b(self, locals);},
'===':function(self, locals, a, b) {return a(self, locals) === b(self, locals);},
'!==':function(self, locals, a, b) {return a(self, locals) !== b(self, locals);},
'==':function(self, locals, a, b) {return a(self, locals) == b(self, locals);},
'!=':function(self, locals, a, b) {return a(self, locals) != b(self, locals);},
'<':function(self, locals, a, b) {return a(self, locals) < b(self, locals);},
'>':function(self, locals, a, b) {return a(self, locals) > b(self, locals);},
'<=':function(self, locals, a, b) {return a(self, locals) <= b(self, locals);},
'>=':function(self, locals, a, b) {return a(self, locals) >= b(self, locals);},
'&&':function(self, locals, a, b) {return a(self, locals) && b(self, locals);},
'||':function(self, locals, a, b) {return a(self, locals) || b(self, locals);},
'!':function(self, locals, a) {return !a(self, locals);},
//Tokenized as operators but parsed as assignment/filters
'=':true,
'|':true
});
var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
/////////////////////////////////////////
/**
* @constructor
*/
var Lexer = function(options) {
this.options = options;
};
Lexer.prototype = {
constructor: Lexer,
lex: function(text) {
this.text = text;
this.index = 0;
this.tokens = [];
while (this.index < this.text.length) {
var ch = this.text.charAt(this.index);
if (ch === '"' || ch === "'") {
this.readString(ch);
} else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
this.readNumber();
} else if (this.isIdent(ch)) {
this.readIdent();
} else if (this.is(ch, '(){}[].,;:?')) {
this.tokens.push({index: this.index, text: ch});
this.index++;
} else if (this.isWhitespace(ch)) {
this.index++;
} else {
var ch2 = ch + this.peek();
var ch3 = ch2 + this.peek(2);
var op1 = OPERATORS[ch];
var op2 = OPERATORS[ch2];
var op3 = OPERATORS[ch3];
if (op1 || op2 || op3) {
var token = op3 ? ch3 : (op2 ? ch2 : ch);
this.tokens.push({index: this.index, text: token, operator: true});
this.index += token.length;
} else {
this.throwError('Unexpected next character ', this.index, this.index + 1);
}
}
}
return this.tokens;
},
is: function(ch, chars) {
return chars.indexOf(ch) !== -1;
},
peek: function(i) {
var num = i || 1;
return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
},
isNumber: function(ch) {
return ('0' <= ch && ch <= '9') && typeof ch === "string";
},
isWhitespace: function(ch) {
// IE treats non-breaking space as \u00A0
return (ch === ' ' || ch === '\r' || ch === '\t' ||
ch === '\n' || ch === '\v' || ch === '\u00A0');
},
isIdent: function(ch) {
return ('a' <= ch && ch <= 'z' ||
'A' <= ch && ch <= 'Z' ||
'_' === ch || ch === '$');
},
isExpOperator: function(ch) {
return (ch === '-' || ch === '+' || this.isNumber(ch));
},
throwError: function(error, start, end) {
end = end || this.index;
var colStr = (isDefined(start)
? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
: ' ' + end);
throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
error, colStr, this.text);
},
readNumber: function() {
var number = '';
var start = this.index;
while (this.index < this.text.length) {
var ch = lowercase(this.text.charAt(this.index));
if (ch == '.' || this.isNumber(ch)) {
number += ch;
} else {
var peekCh = this.peek();
if (ch == 'e' && this.isExpOperator(peekCh)) {
number += ch;
} else if (this.isExpOperator(ch) &&
peekCh && this.isNumber(peekCh) &&
number.charAt(number.length - 1) == 'e') {
number += ch;
} else if (this.isExpOperator(ch) &&
(!peekCh || !this.isNumber(peekCh)) &&
number.charAt(number.length - 1) == 'e') {
this.throwError('Invalid exponent');
} else {
break;
}
}
this.index++;
}
this.tokens.push({
index: start,
text: number,
constant: true,
value: Number(number)
});
},
readIdent: function() {
var start = this.index;
while (this.index < this.text.length) {
var ch = this.text.charAt(this.index);
if (!(this.isIdent(ch) || this.isNumber(ch))) {
break;
}
this.index++;
}
this.tokens.push({
index: start,
text: this.text.slice(start, this.index),
identifier: true
});
},
readString: function(quote) {
var start = this.index;
this.index++;
var string = '';
var rawString = quote;
var escape = false;
while (this.index < this.text.length) {
var ch = this.text.charAt(this.index);
rawString += ch;
if (escape) {
if (ch === 'u') {
var hex = this.text.substring(this.index + 1, this.index + 5);
if (!hex.match(/[\da-f]{4}/i))
this.throwError('Invalid unicode escape [\\u' + hex + ']');
this.index += 4;
string += String.fromCharCode(parseInt(hex, 16));
} else {
var rep = ESCAPE[ch];
string = string + (rep || ch);
}
escape = false;
} else if (ch === '\\') {
escape = true;
} else if (ch === quote) {
this.index++;
this.tokens.push({
index: start,
text: rawString,
constant: true,
value: string
});
return;
} else {
string += ch;
}
this.index++;
}
this.throwError('Unterminated quote', start);
}
};
function isConstant(exp) {
return exp.constant;
}
/**
* @constructor
*/
var Parser = function(lexer, $filter, options) {
this.lexer = lexer;
this.$filter = $filter;
this.options = options;
};
Parser.ZERO = extend(function() {
return 0;
}, {
sharedGetter: true,
constant: true
});
Parser.prototype = {
constructor: Parser,
parse: function(text) {
this.text = text;
this.tokens = this.lexer.lex(text);
var value = this.statements();
if (this.tokens.length !== 0) {
this.throwError('is an unexpected token', this.tokens[0]);
}
value.literal = !!value.literal;
value.constant = !!value.constant;
return value;
},
primary: function() {
var primary;
if (this.expect('(')) {
primary = this.filterChain();
this.consume(')');
} else if (this.expect('[')) {
primary = this.arrayDeclaration();
} else if (this.expect('{')) {
primary = this.object();
} else if (this.peek().identifier && this.peek().text in CONSTANTS) {
primary = CONSTANTS[this.consume().text];
} else if (this.peek().identifier) {
primary = this.identifier();
} else if (this.peek().constant) {
primary = this.constant();
} else {
this.throwError('not a primary expression', this.peek());
}
var next, context;
while ((next = this.expect('(', '[', '.'))) {
if (next.text === '(') {
primary = this.functionCall(primary, context);
context = null;
} else if (next.text === '[') {
context = primary;
primary = this.objectIndex(primary);
} else if (next.text === '.') {
context = primary;
primary = this.fieldAccess(primary);
} else {
this.throwError('IMPOSSIBLE');
}
}
return primary;
},
throwError: function(msg, token) {
throw $parseMinErr('syntax',
'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
},
peekToken: function() {
if (this.tokens.length === 0)
throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
return this.tokens[0];
},
peek: function(e1, e2, e3, e4) {
return this.peekAhead(0, e1, e2, e3, e4);
},
peekAhead: function(i, e1, e2, e3, e4) {
if (this.tokens.length > i) {
var token = this.tokens[i];
var t = token.text;
if (t === e1 || t === e2 || t === e3 || t === e4 ||
(!e1 && !e2 && !e3 && !e4)) {
return token;
}
}
return false;
},
expect: function(e1, e2, e3, e4) {
var token = this.peek(e1, e2, e3, e4);
if (token) {
this.tokens.shift();
return token;
}
return false;
},
consume: function(e1) {
if (this.tokens.length === 0) {
throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
}
var token = this.expect(e1);
if (!token) {
this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
}
return token;
},
unaryFn: function(op, right) {
var fn = OPERATORS[op];
return extend(function $parseUnaryFn(self, locals) {
return fn(self, locals, right);
}, {
constant:right.constant,
inputs: [right]
});
},
binaryFn: function(left, op, right, isBranching) {
var fn = OPERATORS[op];
return extend(function $parseBinaryFn(self, locals) {
return fn(self, locals, left, right);
}, {
constant: left.constant && right.constant,
inputs: !isBranching && [left, right]
});
},
identifier: function() {
var id = this.consume().text;
//Continue reading each `.identifier` unless it is a method invocation
while (this.peek('.') && this.peekAhead(1).identifier && !this.peekAhead(2, '(')) {
id += this.consume().text + this.consume().text;
}
return getterFn(id, this.options, this.text);
},
constant: function() {
var value = this.consume().value;
return extend(function $parseConstant() {
return value;
}, {
constant: true,
literal: true
});
},
statements: function() {
var statements = [];
while (true) {
if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
statements.push(this.filterChain());
if (!this.expect(';')) {
// optimize for the common case where there is only one statement.
// TODO(size): maybe we should not support multiple statements?
return (statements.length === 1)
? statements[0]
: function $parseStatements(self, locals) {
var value;
for (var i = 0, ii = statements.length; i < ii; i++) {
value = statements[i](self, locals);
}
return value;
};
}
}
},
filterChain: function() {
var left = this.expression();
var token;
while ((token = this.expect('|'))) {
left = this.filter(left);
}
return left;
},
filter: function(inputFn) {
var fn = this.$filter(this.consume().text);
var argsFn;
var args;
if (this.peek(':')) {
argsFn = [];
args = []; // we can safely reuse the array
while (this.expect(':')) {
argsFn.push(this.expression());
}
}
var inputs = [inputFn].concat(argsFn || []);
return extend(function $parseFilter(self, locals) {
var input = inputFn(self, locals);
if (args) {
args[0] = input;
var i = argsFn.length;
while (i--) {
args[i + 1] = argsFn[i](self, locals);
}
return fn.apply(undefined, args);
}
return fn(input);
}, {
constant: !fn.$stateful && inputs.every(isConstant),
inputs: !fn.$stateful && inputs
});
},
expression: function() {
return this.assignment();
},
assignment: function() {
var left = this.ternary();
var right;
var token;
if ((token = this.expect('='))) {
if (!left.assign) {
this.throwError('implies assignment but [' +
this.text.substring(0, token.index) + '] can not be assigned to', token);
}
right = this.ternary();
return extend(function $parseAssignment(scope, locals) {
return left.assign(scope, right(scope, locals), locals);
}, {
inputs: [left, right]
});
}
return left;
},
ternary: function() {
var left = this.logicalOR();
var middle;
var token;
if ((token = this.expect('?'))) {
middle = this.assignment();
if (this.consume(':')) {
var right = this.assignment();
return extend(function $parseTernary(self, locals) {
return left(self, locals) ? middle(self, locals) : right(self, locals);
}, {
constant: left.constant && middle.constant && right.constant
});
}
}
return left;
},
logicalOR: function() {
var left = this.logicalAND();
var token;
while ((token = this.expect('||'))) {
left = this.binaryFn(left, token.text, this.logicalAND(), true);
}
return left;
},
logicalAND: function() {
var left = this.equality();
var token;
while ((token = this.expect('&&'))) {
left = this.binaryFn(left, token.text, this.equality(), true);
}
return left;
},
equality: function() {
var left = this.relational();
var token;
while ((token = this.expect('==','!=','===','!=='))) {
left = this.binaryFn(left, token.text, this.relational());
}
return left;
},
relational: function() {
var left = this.additive();
var token;
while ((token = this.expect('<', '>', '<=', '>='))) {
left = this.binaryFn(left, token.text, this.additive());
}
return left;
},
additive: function() {
var left = this.multiplicative();
var token;
while ((token = this.expect('+','-'))) {
left = this.binaryFn(left, token.text, this.multiplicative());
}
return left;
},
multiplicative: function() {
var left = this.unary();
var token;
while ((token = this.expect('*','/','%'))) {
left = this.binaryFn(left, token.text, this.unary());
}
return left;
},
unary: function() {
var token;
if (this.expect('+')) {
return this.primary();
} else if ((token = this.expect('-'))) {
return this.binaryFn(Parser.ZERO, token.text, this.unary());
} else if ((token = this.expect('!'))) {
return this.unaryFn(token.text, this.unary());
} else {
return this.primary();
}
},
fieldAccess: function(object) {
var getter = this.identifier();
return extend(function $parseFieldAccess(scope, locals, self) {
var o = self || object(scope, locals);
return (o == null) ? undefined : getter(o);
}, {
assign: function(scope, value, locals) {
var o = object(scope, locals);
if (!o) object.assign(scope, o = {}, locals);
return getter.assign(o, value);
}
});
},
objectIndex: function(obj) {
var expression = this.text;
var indexFn = this.expression();
this.consume(']');
return extend(function $parseObjectIndex(self, locals) {
var o = obj(self, locals),
i = indexFn(self, locals),
v;
ensureSafeMemberName(i, expression);
if (!o) return undefined;
v = ensureSafeObject(o[i], expression);
return v;
}, {
assign: function(self, value, locals) {
var key = ensureSafeMemberName(indexFn(self, locals), expression);
// prevent overwriting of Function.constructor which would break ensureSafeObject check
var o = ensureSafeObject(obj(self, locals), expression);
if (!o) obj.assign(self, o = {}, locals);
return o[key] = value;
}
});
},
functionCall: function(fnGetter, contextGetter) {
var argsFn = [];
if (this.peekToken().text !== ')') {
do {
argsFn.push(this.expression());
} while (this.expect(','));
}
this.consume(')');
var expressionText = this.text;
// we can safely reuse the array across invocations
var args = argsFn.length ? [] : null;
return function $parseFunctionCall(scope, locals) {
var context = contextGetter ? contextGetter(scope, locals) : isDefined(contextGetter) ? undefined : scope;
var fn = fnGetter(scope, locals, context) || noop;
if (args) {
var i = argsFn.length;
while (i--) {
args[i] = ensureSafeObject(argsFn[i](scope, locals), expressionText);
}
}
ensureSafeObject(context, expressionText);
ensureSafeFunction(fn, expressionText);
// IE doesn't have apply for some native functions
var v = fn.apply
? fn.apply(context, args)
: fn(args[0], args[1], args[2], args[3], args[4]);
if (args) {
// Free-up the memory (arguments of the last function call).
args.length = 0;
}
return ensureSafeObject(v, expressionText);
};
},
// This is used with json array declaration
arrayDeclaration: function() {
var elementFns = [];
if (this.peekToken().text !== ']') {
do {
if (this.peek(']')) {
// Support trailing commas per ES5.1.
break;
}
elementFns.push(this.expression());
} while (this.expect(','));
}
this.consume(']');
return extend(function $parseArrayLiteral(self, locals) {
var array = [];
for (var i = 0, ii = elementFns.length; i < ii; i++) {
array.push(elementFns[i](self, locals));
}
return array;
}, {
literal: true,
constant: elementFns.every(isConstant),
inputs: elementFns
});
},
object: function() {
var keys = [], valueFns = [];
if (this.peekToken().text !== '}') {
do {
if (this.peek('}')) {
// Support trailing commas per ES5.1.
break;
}
var token = this.consume();
if (token.constant) {
keys.push(token.value);
} else if (token.identifier) {
keys.push(token.text);
} else {
this.throwError("invalid key", token);
}
this.consume(':');
valueFns.push(this.expression());
} while (this.expect(','));
}
this.consume('}');
return extend(function $parseObjectLiteral(self, locals) {
var object = {};
for (var i = 0, ii = valueFns.length; i < ii; i++) {
object[keys[i]] = valueFns[i](self, locals);
}
return object;
}, {
literal: true,
constant: valueFns.every(isConstant),
inputs: valueFns
});
}
};
//////////////////////////////////////////////////
// Parser helper functions
//////////////////////////////////////////////////
function setter(obj, locals, path, setValue, fullExp) {
ensureSafeObject(obj, fullExp);
ensureSafeObject(locals, fullExp);
var element = path.split('.'), key;
for (var i = 0; element.length > 1; i++) {
key = ensureSafeMemberName(element.shift(), fullExp);
var propertyObj = (i === 0 && locals && locals[key]) || obj[key];
if (!propertyObj) {
propertyObj = {};
obj[key] = propertyObj;
}
obj = ensureSafeObject(propertyObj, fullExp);
}
key = ensureSafeMemberName(element.shift(), fullExp);
ensureSafeObject(obj[key], fullExp);
obj[key] = setValue;
return setValue;
}
var getterFnCacheDefault = createMap();
var getterFnCacheExpensive = createMap();
function isPossiblyDangerousMemberName(name) {
return name == 'constructor';
}
/**
* Implementation of the "Black Hole" variant from:
* - http://jsperf.com/angularjs-parse-getter/4
* - http://jsperf.com/path-guide-simplified/7
*/
function cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp, expensiveChecks) {
ensureSafeMemberName(key0, fullExp);
ensureSafeMemberName(key1, fullExp);
ensureSafeMemberName(key2, fullExp);
ensureSafeMemberName(key3, fullExp);
ensureSafeMemberName(key4, fullExp);
var eso = function(o) {
return ensureSafeObject(o, fullExp);
};
var eso0 = (expensiveChecks || isPossiblyDangerousMemberName(key0)) ? eso : identity;
var eso1 = (expensiveChecks || isPossiblyDangerousMemberName(key1)) ? eso : identity;
var eso2 = (expensiveChecks || isPossiblyDangerousMemberName(key2)) ? eso : identity;
var eso3 = (expensiveChecks || isPossiblyDangerousMemberName(key3)) ? eso : identity;
var eso4 = (expensiveChecks || isPossiblyDangerousMemberName(key4)) ? eso : identity;
return function cspSafeGetter(scope, locals) {
var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope;
if (pathVal == null) return pathVal;
pathVal = eso0(pathVal[key0]);
if (!key1) return pathVal;
if (pathVal == null) return undefined;
pathVal = eso1(pathVal[key1]);
if (!key2) return pathVal;
if (pathVal == null) return undefined;
pathVal = eso2(pathVal[key2]);
if (!key3) return pathVal;
if (pathVal == null) return undefined;
pathVal = eso3(pathVal[key3]);
if (!key4) return pathVal;
if (pathVal == null) return undefined;
pathVal = eso4(pathVal[key4]);
return pathVal;
};
}
function getterFnWithEnsureSafeObject(fn, fullExpression) {
return function(s, l) {
return fn(s, l, ensureSafeObject, fullExpression);
};
}
function getterFn(path, options, fullExp) {
var expensiveChecks = options.expensiveChecks;
var getterFnCache = (expensiveChecks ? getterFnCacheExpensive : getterFnCacheDefault);
var fn = getterFnCache[path];
if (fn) return fn;
var pathKeys = path.split('.'),
pathKeysLength = pathKeys.length;
// http://jsperf.com/angularjs-parse-getter/6
if (options.csp) {
if (pathKeysLength < 6) {
fn = cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp, expensiveChecks);
} else {
fn = function cspSafeGetter(scope, locals) {
var i = 0, val;
do {
val = cspSafeGetterFn(pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++],
pathKeys[i++], fullExp, expensiveChecks)(scope, locals);
locals = undefined; // clear after first iteration
scope = val;
} while (i < pathKeysLength);
return val;
};
}
} else {
var code = '';
if (expensiveChecks) {
code += 's = eso(s, fe);\nl = eso(l, fe);\n';
}
var needsEnsureSafeObject = expensiveChecks;
forEach(pathKeys, function(key, index) {
ensureSafeMemberName(key, fullExp);
var lookupJs = (index
// we simply dereference 's' on any .dot notation
? 's'
// but if we are first then we check locals first, and if so read it first
: '((l&&l.hasOwnProperty("' + key + '"))?l:s)') + '.' + key;
if (expensiveChecks || isPossiblyDangerousMemberName(key)) {
lookupJs = 'eso(' + lookupJs + ', fe)';
needsEnsureSafeObject = true;
}
code += 'if(s == null) return undefined;\n' +
's=' + lookupJs + ';\n';
});
code += 'return s;';
/* jshint -W054 */
var evaledFnGetter = new Function('s', 'l', 'eso', 'fe', code); // s=scope, l=locals, eso=ensureSafeObject
/* jshint +W054 */
evaledFnGetter.toString = valueFn(code);
if (needsEnsureSafeObject) {
evaledFnGetter = getterFnWithEnsureSafeObject(evaledFnGetter, fullExp);
}
fn = evaledFnGetter;
}
fn.sharedGetter = true;
fn.assign = function(self, value, locals) {
return setter(self, locals, path, value, path);
};
getterFnCache[path] = fn;
return fn;
}
var objectValueOf = Object.prototype.valueOf;
function getValueOf(value) {
return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
}
///////////////////////////////////
/**
* @ngdoc service
* @name $parse
* @kind function
*
* @description
*
* Converts Angular {@link guide/expression expression} into a function.
*
* ```js
* var getter = $parse('user.name');
* var setter = getter.assign;
* var context = {user:{name:'angular'}};
* var locals = {user:{name:'local'}};
*
* expect(getter(context)).toEqual('angular');
* setter(context, 'newValue');
* expect(context.user.name).toEqual('newValue');
* expect(getter(context, locals)).toEqual('local');
* ```
*
*
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context` – `{object}` – an object against which any expressions embedded in the strings
* are evaluated against (typically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*
* The returned function also has the following properties:
* * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
* literal.
* * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
* constant literals.
* * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
* set to a function to change its value on the given context.
*
*/
/**
* @ngdoc provider
* @name $parseProvider
*
* @description
* `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
* service.
*/
function $ParseProvider() {
var cacheDefault = createMap();
var cacheExpensive = createMap();
this.$get = ['$filter', '$sniffer', function($filter, $sniffer) {
var $parseOptions = {
csp: $sniffer.csp,
expensiveChecks: false
},
$parseOptionsExpensive = {
csp: $sniffer.csp,
expensiveChecks: true
};
function wrapSharedExpression(exp) {
var wrapped = exp;
if (exp.sharedGetter) {
wrapped = function $parseWrapper(self, locals) {
return exp(self, locals);
};
wrapped.literal = exp.literal;
wrapped.constant = exp.constant;
wrapped.assign = exp.assign;
}
return wrapped;
}
return function $parse(exp, interceptorFn, expensiveChecks) {
var parsedExpression, oneTime, cacheKey;
switch (typeof exp) {
case 'string':
cacheKey = exp = exp.trim();
var cache = (expensiveChecks ? cacheExpensive : cacheDefault);
parsedExpression = cache[cacheKey];
if (!parsedExpression) {
if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
oneTime = true;
exp = exp.substring(2);
}
var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;
var lexer = new Lexer(parseOptions);
var parser = new Parser(lexer, $filter, parseOptions);
parsedExpression = parser.parse(exp);
if (parsedExpression.constant) {
parsedExpression.$$watchDelegate = constantWatchDelegate;
} else if (oneTime) {
//oneTime is not part of the exp passed to the Parser so we may have to
//wrap the parsedExpression before adding a $$watchDelegate
parsedExpression = wrapSharedExpression(parsedExpression);
parsedExpression.$$watchDelegate = parsedExpression.literal ?
oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
} else if (parsedExpression.inputs) {
parsedExpression.$$watchDelegate = inputsWatchDelegate;
}
cache[cacheKey] = parsedExpression;
}
return addInterceptor(parsedExpression, interceptorFn);
case 'function':
return addInterceptor(exp, interceptorFn);
default:
return addInterceptor(noop, interceptorFn);
}
};
function collectExpressionInputs(inputs, list) {
for (var i = 0, ii = inputs.length; i < ii; i++) {
var input = inputs[i];
if (!input.constant) {
if (input.inputs) {
collectExpressionInputs(input.inputs, list);
} else if (list.indexOf(input) === -1) { // TODO(perf) can we do better?
list.push(input);
}
}
}
return list;
}
function expressionInputDirtyCheck(newValue, oldValueOfValue) {
if (newValue == null || oldValueOfValue == null) { // null/undefined
return newValue === oldValueOfValue;
}
if (typeof newValue === 'object') {
// attempt to convert the value to a primitive type
// TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
// be cheaply dirty-checked
newValue = getValueOf(newValue);
if (typeof newValue === 'object') {
// objects/arrays are not supported - deep-watching them would be too expensive
return false;
}
// fall-through to the primitive equality check
}
//Primitive or NaN
return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
}
function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression) {
var inputExpressions = parsedExpression.$$inputs ||
(parsedExpression.$$inputs = collectExpressionInputs(parsedExpression.inputs, []));
var lastResult;
if (inputExpressions.length === 1) {
var oldInputValue = expressionInputDirtyCheck; // init to something unique so that equals check fails
inputExpressions = inputExpressions[0];
return scope.$watch(function expressionInputWatch(scope) {
var newInputValue = inputExpressions(scope);
if (!expressionInputDirtyCheck(newInputValue, oldInputValue)) {
lastResult = parsedExpression(scope);
oldInputValue = newInputValue && getValueOf(newInputValue);
}
return lastResult;
}, listener, objectEquality);
}
var oldInputValueOfValues = [];
for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
}
return scope.$watch(function expressionInputsWatch(scope) {
var changed = false;
for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
var newInputValue = inputExpressions[i](scope);
if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {
oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
}
}
if (changed) {
lastResult = parsedExpression(scope);
}
return lastResult;
}, listener, objectEquality);
}
function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) {
var unwatch, lastValue;
return unwatch = scope.$watch(function oneTimeWatch(scope) {
return parsedExpression(scope);
}, function oneTimeListener(value, old, scope) {
lastValue = value;
if (isFunction(listener)) {
listener.apply(this, arguments);
}
if (isDefined(value)) {
scope.$$postDigest(function() {
if (isDefined(lastValue)) {
unwatch();
}
});
}
}, objectEquality);
}
function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
var unwatch, lastValue;
return unwatch = scope.$watch(function oneTimeWatch(scope) {
return parsedExpression(scope);
}, function oneTimeListener(value, old, scope) {
lastValue = value;
if (isFunction(listener)) {
listener.call(this, value, old, scope);
}
if (isAllDefined(value)) {
scope.$$postDigest(function() {
if (isAllDefined(lastValue)) unwatch();
});
}
}, objectEquality);
function isAllDefined(value) {
var allDefined = true;
forEach(value, function(val) {
if (!isDefined(val)) allDefined = false;
});
return allDefined;
}
}
function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
var unwatch;
return unwatch = scope.$watch(function constantWatch(scope) {
return parsedExpression(scope);
}, function constantListener(value, old, scope) {
if (isFunction(listener)) {
listener.apply(this, arguments);
}
unwatch();
}, objectEquality);
}
function addInterceptor(parsedExpression, interceptorFn) {
if (!interceptorFn) return parsedExpression;
var watchDelegate = parsedExpression.$$watchDelegate;
var regularWatch =
watchDelegate !== oneTimeLiteralWatchDelegate &&
watchDelegate !== oneTimeWatchDelegate;
var fn = regularWatch ? function regularInterceptedExpression(scope, locals) {
var value = parsedExpression(scope, locals);
return interceptorFn(value, scope, locals);
} : function oneTimeInterceptedExpression(scope, locals) {
var value = parsedExpression(scope, locals);
var result = interceptorFn(value, scope, locals);
// we only return the interceptor's result if the
// initial value is defined (for bind-once)
return isDefined(value) ? result : value;
};
// Propagate $$watchDelegates other then inputsWatchDelegate
if (parsedExpression.$$watchDelegate &&
parsedExpression.$$watchDelegate !== inputsWatchDelegate) {
fn.$$watchDelegate = parsedExpression.$$watchDelegate;
} else if (!interceptorFn.$stateful) {
// If there is an interceptor, but no watchDelegate then treat the interceptor like
// we treat filters - it is assumed to be a pure function unless flagged with $stateful
fn.$$watchDelegate = inputsWatchDelegate;
fn.inputs = [parsedExpression];
}
return fn;
}
}];
}
/**
* @ngdoc service
* @name $q
* @requires $rootScope
*
* @description
* A service that helps you run functions asynchronously, and use their return values (or exceptions)
* when they are done processing.
*
* This is an implementation of promises/deferred objects inspired by
* [Kris Kowal's Q](https://github.com/kriskowal/q).
*
* $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
* implementations, and the other which resembles ES6 promises to some degree.
*
* # $q constructor
*
* The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
* function as the first argument. This is similar to the native Promise implementation from ES6 Harmony,
* see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
*
* While the constructor-style use is supported, not all of the supporting methods from ES6 Harmony promises are
* available yet.
*
* It can be used like so:
*
* ```js
* // for the purpose of this example let's assume that variables `$q` and `okToGreet`
* // are available in the current lexical scope (they could have been injected or passed in).
*
* function asyncGreet(name) {
* // perform some asynchronous operation, resolve or reject the promise when appropriate.
* return $q(function(resolve, reject) {
* setTimeout(function() {
* if (okToGreet(name)) {
* resolve('Hello, ' + name + '!');
* } else {
* reject('Greeting ' + name + ' is not allowed.');
* }
* }, 1000);
* });
* }
*
* var promise = asyncGreet('Robin Hood');
* promise.then(function(greeting) {
* alert('Success: ' + greeting);
* }, function(reason) {
* alert('Failed: ' + reason);
* });
* ```
*
* Note: progress/notify callbacks are not currently supported via the ES6-style interface.
*
* However, the more traditional CommonJS-style usage is still available, and documented below.
*
* [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
* interface for interacting with an object that represents the result of an action that is
* performed asynchronously, and may or may not be finished at any given point in time.
*
* From the perspective of dealing with error handling, deferred and promise APIs are to
* asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
*
* ```js
* // for the purpose of this example let's assume that variables `$q` and `okToGreet`
* // are available in the current lexical scope (they could have been injected or passed in).
*
* function asyncGreet(name) {
* var deferred = $q.defer();
*
* setTimeout(function() {
* deferred.notify('About to greet ' + name + '.');
*
* if (okToGreet(name)) {
* deferred.resolve('Hello, ' + name + '!');
* } else {
* deferred.reject('Greeting ' + name + ' is not allowed.');
* }
* }, 1000);
*
* return deferred.promise;
* }
*
* var promise = asyncGreet('Robin Hood');
* promise.then(function(greeting) {
* alert('Success: ' + greeting);
* }, function(reason) {
* alert('Failed: ' + reason);
* }, function(update) {
* alert('Got notification: ' + update);
* });
* ```
*
* At first it might not be obvious why this extra complexity is worth the trouble. The payoff
* comes in the way of guarantees that promise and deferred APIs make, see
* https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
*
* Additionally the promise api allows for composition that is very hard to do with the
* traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
* For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
* section on serial or parallel joining of promises.
*
* # The Deferred API
*
* A new instance of deferred is constructed by calling `$q.defer()`.
*
* The purpose of the deferred object is to expose the associated Promise instance as well as APIs
* that can be used for signaling the successful or unsuccessful completion, as well as the status
* of the task.
*
* **Methods**
*
* - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
* constructed via `$q.reject`, the promise will be rejected instead.
* - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
* resolving it with a rejection constructed via `$q.reject`.
* - `notify(value)` - provides updates on the status of the promise's execution. This may be called
* multiple times before the promise is either resolved or rejected.
*
* **Properties**
*
* - promise – `{Promise}` – promise object associated with this deferred.
*
*
* # The Promise API
*
* A new promise instance is created when a deferred instance is created and can be retrieved by
* calling `deferred.promise`.
*
* The purpose of the promise object is to allow for interested parties to get access to the result
* of the deferred task when it completes.
*
* **Methods**
*
* - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
* will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
* as soon as the result is available. The callbacks are called with a single argument: the result
* or rejection reason. Additionally, the notify callback may be called zero or more times to
* provide a progress indication, before the promise is resolved or rejected.
*
* This method *returns a new promise* which is resolved or rejected via the return value of the
* `successCallback`, `errorCallback`. It also notifies via the return value of the
* `notifyCallback` method. The promise cannot be resolved or rejected from the notifyCallback
* method.
*
* - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
*
* - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,
* but to do so without modifying the final value. This is useful to release resources or do some
* clean-up that needs to be done whether the promise was rejected or resolved. See the [full
* specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
* more information.
*
* # Chaining promises
*
* Because calling the `then` method of a promise returns a new derived promise, it is easily
* possible to create a chain of promises:
*
* ```js
* promiseB = promiseA.then(function(result) {
* return result + 1;
* });
*
* // promiseB will be resolved immediately after promiseA is resolved and its value
* // will be the result of promiseA incremented by 1
* ```
*
* It is possible to create chains of any length and since a promise can be resolved with another
* promise (which will defer its resolution further), it is possible to pause/defer resolution of
* the promises at any point in the chain. This makes it possible to implement powerful APIs like
* $http's response interceptors.
*
*
* # Differences between Kris Kowal's Q and $q
*
* There are two main differences:
*
* - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
* mechanism in angular, which means faster propagation of resolution or rejection into your
* models and avoiding unnecessary browser repaints, which would result in flickering UI.
* - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
* all the important functionality needed for common async tasks.
*
* # Testing
*
* ```js
* it('should simulate promise', inject(function($q, $rootScope) {
* var deferred = $q.defer();
* var promise = deferred.promise;
* var resolvedValue;
*
* promise.then(function(value) { resolvedValue = value; });
* expect(resolvedValue).toBeUndefined();
*
* // Simulate resolving of promise
* deferred.resolve(123);
* // Note that the 'then' function does not get called synchronously.
* // This is because we want the promise API to always be async, whether or not
* // it got called synchronously or asynchronously.
* expect(resolvedValue).toBeUndefined();
*
* // Propagate promise resolution to 'then' functions using $apply().
* $rootScope.$apply();
* expect(resolvedValue).toEqual(123);
* }));
* ```
*
* @param {function(function, function)} resolver Function which is responsible for resolving or
* rejecting the newly created promise. The first parameter is a function which resolves the
* promise, the second parameter is a function which rejects the promise.
*
* @returns {Promise} The newly created promise.
*/
function $QProvider() {
this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
return qFactory(function(callback) {
$rootScope.$evalAsync(callback);
}, $exceptionHandler);
}];
}
function $$QProvider() {
this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
return qFactory(function(callback) {
$browser.defer(callback);
}, $exceptionHandler);
}];
}
/**
* Constructs a promise manager.
*
* @param {function(function)} nextTick Function for executing functions in the next turn.
* @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
* debugging purposes.
* @returns {object} Promise manager.
*/
function qFactory(nextTick, exceptionHandler) {
var $qMinErr = minErr('$q', TypeError);
function callOnce(self, resolveFn, rejectFn) {
var called = false;
function wrap(fn) {
return function(value) {
if (called) return;
called = true;
fn.call(self, value);
};
}
return [wrap(resolveFn), wrap(rejectFn)];
}
/**
* @ngdoc method
* @name ng.$q#defer
* @kind function
*
* @description
* Creates a `Deferred` object which represents a task which will finish in the future.
*
* @returns {Deferred} Returns a new instance of deferred.
*/
var defer = function() {
return new Deferred();
};
function Promise() {
this.$$state = { status: 0 };
}
Promise.prototype = {
then: function(onFulfilled, onRejected, progressBack) {
var result = new Deferred();
this.$$state.pending = this.$$state.pending || [];
this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
return result.promise;
},
"catch": function(callback) {
return this.then(null, callback);
},
"finally": function(callback, progressBack) {
return this.then(function(value) {
return handleCallback(value, true, callback);
}, function(error) {
return handleCallback(error, false, callback);
}, progressBack);
}
};
//Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native
function simpleBind(context, fn) {
return function(value) {
fn.call(context, value);
};
}
function processQueue(state) {
var fn, promise, pending;
pending = state.pending;
state.processScheduled = false;
state.pending = undefined;
for (var i = 0, ii = pending.length; i < ii; ++i) {
promise = pending[i][0];
fn = pending[i][state.status];
try {
if (isFunction(fn)) {
promise.resolve(fn(state.value));
} else if (state.status === 1) {
promise.resolve(state.value);
} else {
promise.reject(state.value);
}
} catch (e) {
promise.reject(e);
exceptionHandler(e);
}
}
}
function scheduleProcessQueue(state) {
if (state.processScheduled || !state.pending) return;
state.processScheduled = true;
nextTick(function() { processQueue(state); });
}
function Deferred() {
this.promise = new Promise();
//Necessary to support unbound execution :/
this.resolve = simpleBind(this, this.resolve);
this.reject = simpleBind(this, this.reject);
this.notify = simpleBind(this, this.notify);
}
Deferred.prototype = {
resolve: function(val) {
if (this.promise.$$state.status) return;
if (val === this.promise) {
this.$$reject($qMinErr(
'qcycle',
"Expected promise to be resolved with value other than itself '{0}'",
val));
} else {
this.$$resolve(val);
}
},
$$resolve: function(val) {
var then, fns;
fns = callOnce(this, this.$$resolve, this.$$reject);
try {
if ((isObject(val) || isFunction(val))) then = val && val.then;
if (isFunction(then)) {
this.promise.$$state.status = -1;
then.call(val, fns[0], fns[1], this.notify);
} else {
this.promise.$$state.value = val;
this.promise.$$state.status = 1;
scheduleProcessQueue(this.promise.$$state);
}
} catch (e) {
fns[1](e);
exceptionHandler(e);
}
},
reject: function(reason) {
if (this.promise.$$state.status) return;
this.$$reject(reason);
},
$$reject: function(reason) {
this.promise.$$state.value = reason;
this.promise.$$state.status = 2;
scheduleProcessQueue(this.promise.$$state);
},
notify: function(progress) {
var callbacks = this.promise.$$state.pending;
if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) {
nextTick(function() {
var callback, result;
for (var i = 0, ii = callbacks.length; i < ii; i++) {
result = callbacks[i][0];
callback = callbacks[i][3];
try {
result.notify(isFunction(callback) ? callback(progress) : progress);
} catch (e) {
exceptionHandler(e);
}
}
});
}
}
};
/**
* @ngdoc method
* @name $q#reject
* @kind function
*
* @description
* Creates a promise that is resolved as rejected with the specified `reason`. This api should be
* used to forward rejection in a chain of promises. If you are dealing with the last promise in
* a promise chain, you don't need to worry about it.
*
* When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
* `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
* a promise error callback and you want to forward the error to the promise derived from the
* current promise, you have to "rethrow" the error by returning a rejection constructed via
* `reject`.
*
* ```js
* promiseB = promiseA.then(function(result) {
* // success: do something and resolve promiseB
* // with the old or a new result
* return result;
* }, function(reason) {
* // error: handle the error if possible and
* // resolve promiseB with newPromiseOrValue,
* // otherwise forward the rejection to promiseB
* if (canHandle(reason)) {
* // handle the error and recover
* return newPromiseOrValue;
* }
* return $q.reject(reason);
* });
* ```
*
* @param {*} reason Constant, message, exception or an object representing the rejection reason.
* @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
*/
var reject = function(reason) {
var result = new Deferred();
result.reject(reason);
return result.promise;
};
var makePromise = function makePromise(value, resolved) {
var result = new Deferred();
if (resolved) {
result.resolve(value);
} else {
result.reject(value);
}
return result.promise;
};
var handleCallback = function handleCallback(value, isResolved, callback) {
var callbackOutput = null;
try {
if (isFunction(callback)) callbackOutput = callback();
} catch (e) {
return makePromise(e, false);
}
if (isPromiseLike(callbackOutput)) {
return callbackOutput.then(function() {
return makePromise(value, isResolved);
}, function(error) {
return makePromise(error, false);
});
} else {
return makePromise(value, isResolved);
}
};
/**
* @ngdoc method
* @name $q#when
* @kind function
*
* @description
* Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
* This is useful when you are dealing with an object that might or might not be a promise, or if
* the promise comes from a source that can't be trusted.
*
* @param {*} value Value or a promise
* @returns {Promise} Returns a promise of the passed value or promise
*/
var when = function(value, callback, errback, progressBack) {
var result = new Deferred();
result.resolve(value);
return result.promise.then(callback, errback, progressBack);
};
/**
* @ngdoc method
* @name $q#all
* @kind function
*
* @description
* Combines multiple promises into a single promise that is resolved when all of the input
* promises are resolved.
*
* @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
* @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
* each value corresponding to the promise at the same index/key in the `promises` array/hash.
* If any of the promises is resolved with a rejection, this resulting promise will be rejected
* with the same rejection value.
*/
function all(promises) {
var deferred = new Deferred(),
counter = 0,
results = isArray(promises) ? [] : {};
forEach(promises, function(promise, key) {
counter++;
when(promise).then(function(value) {
if (results.hasOwnProperty(key)) return;
results[key] = value;
if (!(--counter)) deferred.resolve(results);
}, function(reason) {
if (results.hasOwnProperty(key)) return;
deferred.reject(reason);
});
});
if (counter === 0) {
deferred.resolve(results);
}
return deferred.promise;
}
var $Q = function Q(resolver) {
if (!isFunction(resolver)) {
throw $qMinErr('norslvr', "Expected resolverFn, got '{0}'", resolver);
}
if (!(this instanceof Q)) {
// More useful when $Q is the Promise itself.
return new Q(resolver);
}
var deferred = new Deferred();
function resolveFn(value) {
deferred.resolve(value);
}
function rejectFn(reason) {
deferred.reject(reason);
}
resolver(resolveFn, rejectFn);
return deferred.promise;
};
$Q.defer = defer;
$Q.reject = reject;
$Q.when = when;
$Q.all = all;
return $Q;
}
function $$RAFProvider() { //rAF
this.$get = ['$window', '$timeout', function($window, $timeout) {
var requestAnimationFrame = $window.requestAnimationFrame ||
$window.webkitRequestAnimationFrame;
var cancelAnimationFrame = $window.cancelAnimationFrame ||
$window.webkitCancelAnimationFrame ||
$window.webkitCancelRequestAnimationFrame;
var rafSupported = !!requestAnimationFrame;
var raf = rafSupported
? function(fn) {
var id = requestAnimationFrame(fn);
return function() {
cancelAnimationFrame(id);
};
}
: function(fn) {
var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
return function() {
$timeout.cancel(timer);
};
};
raf.supported = rafSupported;
return raf;
}];
}
/**
* DESIGN NOTES
*
* The design decisions behind the scope are heavily favored for speed and memory consumption.
*
* The typical use of scope is to watch the expressions, which most of the time return the same
* value as last time so we optimize the operation.
*
* Closures construction is expensive in terms of speed as well as memory:
* - No closures, instead use prototypical inheritance for API
* - Internal state needs to be stored on scope directly, which means that private state is
* exposed as $$____ properties
*
* Loop operations are optimized by using while(count--) { ... }
* - this means that in order to keep the same order of execution as addition we have to add
* items to the array at the beginning (unshift) instead of at the end (push)
*
* Child scopes are created and removed often
* - Using an array would be slow since inserts in middle are expensive so we use linked list
*
* There are few watches then a lot of observers. This is why you don't want the observer to be
* implemented in the same way as watch. Watch requires return of initialization function which
* are expensive to construct.
*/
/**
* @ngdoc provider
* @name $rootScopeProvider
* @description
*
* Provider for the $rootScope service.
*/
/**
* @ngdoc method
* @name $rootScopeProvider#digestTtl
* @description
*
* Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
* assuming that the model is unstable.
*
* The current default is 10 iterations.
*
* In complex applications it's possible that the dependencies between `$watch`s will result in
* several digest iterations. However if an application needs more than the default 10 digest
* iterations for its model to stabilize then you should investigate what is causing the model to
* continuously change during the digest.
*
* Increasing the TTL could have performance implications, so you should not change it without
* proper justification.
*
* @param {number} limit The number of digest iterations.
*/
/**
* @ngdoc service
* @name $rootScope
* @description
*
* Every application has a single root {@link ng.$rootScope.Scope scope}.
* All other scopes are descendant scopes of the root scope. Scopes provide separation
* between the model and the view, via a mechanism for watching the model for changes.
* They also provide an event emission/broadcast and subscription facility. See the
* {@link guide/scope developer guide on scopes}.
*/
function $RootScopeProvider() {
var TTL = 10;
var $rootScopeMinErr = minErr('$rootScope');
var lastDirtyWatch = null;
var applyAsyncId = null;
this.digestTtl = function(value) {
if (arguments.length) {
TTL = value;
}
return TTL;
};
function createChildScopeClass(parent) {
function ChildScope() {
this.$$watchers = this.$$nextSibling =
this.$$childHead = this.$$childTail = null;
this.$$listeners = {};
this.$$listenerCount = {};
this.$$watchersCount = 0;
this.$id = nextUid();
this.$$ChildScope = null;
}
ChildScope.prototype = parent;
return ChildScope;
}
this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser',
function($injector, $exceptionHandler, $parse, $browser) {
function destroyChildScope($event) {
$event.currentScope.$$destroyed = true;
}
/**
* @ngdoc type
* @name $rootScope.Scope
*
* @description
* A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
* {@link auto.$injector $injector}. Child scopes are created using the
* {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
* compiled HTML template is executed.)
*
* Here is a simple scope snippet to show how you can interact with the scope.
* ```html
* <file src="./test/ng/rootScopeSpec.js" tag="docs1" />
* ```
*
* # Inheritance
* A scope can inherit from a parent scope, as in this example:
* ```js
var parent = $rootScope;
var child = parent.$new();
parent.salutation = "Hello";
expect(child.salutation).toEqual('Hello');
child.salutation = "Welcome";
expect(child.salutation).toEqual('Welcome');
expect(parent.salutation).toEqual('Hello');
* ```
*
* When interacting with `Scope` in tests, additional helper methods are available on the
* instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
* details.
*
*
* @param {Object.<string, function()>=} providers Map of service factory which need to be
* provided for the current scope. Defaults to {@link ng}.
* @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
* append/override services provided by `providers`. This is handy
* when unit-testing and having the need to override a default
* service.
* @returns {Object} Newly created scope.
*
*/
function Scope() {
this.$id = nextUid();
this.$$phase = this.$parent = this.$$watchers =
this.$$nextSibling = this.$$prevSibling =
this.$$childHead = this.$$childTail = null;
this.$root = this;
this.$$destroyed = false;
this.$$listeners = {};
this.$$listenerCount = {};
this.$$isolateBindings = null;
}
/**
* @ngdoc property
* @name $rootScope.Scope#$id
*
* @description
* Unique scope ID (monotonically increasing) useful for debugging.
*/
/**
* @ngdoc property
* @name $rootScope.Scope#$parent
*
* @description
* Reference to the parent scope.
*/
/**
* @ngdoc property
* @name $rootScope.Scope#$root
*
* @description
* Reference to the root scope.
*/
Scope.prototype = {
constructor: Scope,
/**
* @ngdoc method
* @name $rootScope.Scope#$new
* @kind function
*
* @description
* Creates a new child {@link ng.$rootScope.Scope scope}.
*
* The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
* The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
*
* {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
* desired for the scope and its child scopes to be permanently detached from the parent and
* thus stop participating in model change detection and listener notification by invoking.
*
* @param {boolean} isolate If true, then the scope does not prototypically inherit from the
* parent scope. The scope is isolated, as it can not see parent scope properties.
* When creating widgets, it is useful for the widget to not accidentally read parent
* state.
*
* @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
* of the newly created scope. Defaults to `this` scope if not provided.
* This is used when creating a transclude scope to correctly place it
* in the scope hierarchy while maintaining the correct prototypical
* inheritance.
*
* @returns {Object} The newly created child scope.
*
*/
$new: function(isolate, parent) {
var child;
parent = parent || this;
if (isolate) {
child = new Scope();
child.$root = this.$root;
} else {
// Only create a child scope class if somebody asks for one,
// but cache it to allow the VM to optimize lookups.
if (!this.$$ChildScope) {
this.$$ChildScope = createChildScopeClass(this);
}
child = new this.$$ChildScope();
}
child.$parent = parent;
child.$$prevSibling = parent.$$childTail;
if (parent.$$childHead) {
parent.$$childTail.$$nextSibling = child;
parent.$$childTail = child;
} else {
parent.$$childHead = parent.$$childTail = child;
}
// When the new scope is not isolated or we inherit from `this`, and
// the parent scope is destroyed, the property `$$destroyed` is inherited
// prototypically. In all other cases, this property needs to be set
// when the parent scope is destroyed.
// The listener needs to be added after the parent is set
if (isolate || parent != this) child.$on('$destroy', destroyChildScope);
return child;
},
/**
* @ngdoc method
* @name $rootScope.Scope#$watch
* @kind function
*
* @description
* Registers a `listener` callback to be executed whenever the `watchExpression` changes.
*
* - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
* $digest()} and should return the value that will be watched. (Since
* {@link ng.$rootScope.Scope#$digest $digest()} reruns when it detects changes the
* `watchExpression` can execute multiple times per
* {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.)
* - The `listener` is called only when the value from the current `watchExpression` and the
* previous call to `watchExpression` are not equal (with the exception of the initial run,
* see below). Inequality is determined according to reference inequality,
* [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
* via the `!==` Javascript operator, unless `objectEquality == true`
* (see next point)
* - When `objectEquality == true`, inequality of the `watchExpression` is determined
* according to the {@link angular.equals} function. To save the value of the object for
* later comparison, the {@link angular.copy} function is used. This therefore means that
* watching complex objects will have adverse memory and performance implications.
* - The watch `listener` may change the model, which may trigger other `listener`s to fire.
* This is achieved by rerunning the watchers until no changes are detected. The rerun
* iteration limit is 10 to prevent an infinite loop deadlock.
*
*
* If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
* you can register a `watchExpression` function with no `listener`. (Since `watchExpression`
* can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a
* change is detected, be prepared for multiple calls to your listener.)
*
* After a watcher is registered with the scope, the `listener` fn is called asynchronously
* (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
* watcher. In rare cases, this is undesirable because the listener is called when the result
* of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
* can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
* listener was called due to initialization.
*
*
*
* # Example
* ```js
// let's assume that scope was dependency injected as the $rootScope
var scope = $rootScope;
scope.name = 'misko';
scope.counter = 0;
expect(scope.counter).toEqual(0);
scope.$watch('name', function(newValue, oldValue) {
scope.counter = scope.counter + 1;
});
expect(scope.counter).toEqual(0);
scope.$digest();
// the listener is always called during the first $digest loop after it was registered
expect(scope.counter).toEqual(1);
scope.$digest();
// but now it will not be called unless the value changes
expect(scope.counter).toEqual(1);
scope.name = 'adam';
scope.$digest();
expect(scope.counter).toEqual(2);
// Using a function as a watchExpression
var food;
scope.foodCounter = 0;
expect(scope.foodCounter).toEqual(0);
scope.$watch(
// This function returns the value being watched. It is called for each turn of the $digest loop
function() { return food; },
// This is the change listener, called when the value returned from the above function changes
function(newValue, oldValue) {
if ( newValue !== oldValue ) {
// Only increment the counter if the value changed
scope.foodCounter = scope.foodCounter + 1;
}
}
);
// No digest has been run so the counter will be zero
expect(scope.foodCounter).toEqual(0);
// Run the digest but since food has not changed count will still be zero
scope.$digest();
expect(scope.foodCounter).toEqual(0);
// Update food and run digest. Now the counter will increment
food = 'cheeseburger';
scope.$digest();
expect(scope.foodCounter).toEqual(1);
* ```
*
*
*
* @param {(function()|string)} watchExpression Expression that is evaluated on each
* {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
* a call to the `listener`.
*
* - `string`: Evaluated as {@link guide/expression expression}
* - `function(scope)`: called with current `scope` as a parameter.
* @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
* of `watchExpression` changes.
*
* - `newVal` contains the current value of the `watchExpression`
* - `oldVal` contains the previous value of the `watchExpression`
* - `scope` refers to the current scope
* @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of
* comparing for reference equality.
* @returns {function()} Returns a deregistration function for this listener.
*/
$watch: function(watchExp, listener, objectEquality) {
var get = $parse(watchExp);
if (get.$$watchDelegate) {
return get.$$watchDelegate(this, listener, objectEquality, get);
}
var scope = this,
array = scope.$$watchers,
watcher = {
fn: listener,
last: initWatchVal,
get: get,
exp: watchExp,
eq: !!objectEquality
};
lastDirtyWatch = null;
if (!isFunction(listener)) {
watcher.fn = noop;
}
if (!array) {
array = scope.$$watchers = [];
}
// we use unshift since we use a while loop in $digest for speed.
// the while loop reads in reverse order.
array.unshift(watcher);
return function deregisterWatch() {
arrayRemove(array, watcher);
lastDirtyWatch = null;
};
},
/**
* @ngdoc method
* @name $rootScope.Scope#$watchGroup
* @kind function
*
* @description
* A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
* If any one expression in the collection changes the `listener` is executed.
*
* - The items in the `watchExpressions` array are observed via standard $watch operation and are examined on every
* call to $digest() to see if any items changes.
* - The `listener` is called whenever any expression in the `watchExpressions` array changes.
*
* @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
* watched using {@link ng.$rootScope.Scope#$watch $watch()}
*
* @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
* expression in `watchExpressions` changes
* The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
* those of `watchExpression`
* and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
* those of `watchExpression`
* The `scope` refers to the current scope.
* @returns {function()} Returns a de-registration function for all listeners.
*/
$watchGroup: function(watchExpressions, listener) {
var oldValues = new Array(watchExpressions.length);
var newValues = new Array(watchExpressions.length);
var deregisterFns = [];
var self = this;
var changeReactionScheduled = false;
var firstRun = true;
if (!watchExpressions.length) {
// No expressions means we call the listener ASAP
var shouldCall = true;
self.$evalAsync(function() {
if (shouldCall) listener(newValues, newValues, self);
});
return function deregisterWatchGroup() {
shouldCall = false;
};
}
if (watchExpressions.length === 1) {
// Special case size of one
return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
newValues[0] = value;
oldValues[0] = oldValue;
listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
});
}
forEach(watchExpressions, function(expr, i) {
var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
newValues[i] = value;
oldValues[i] = oldValue;
if (!changeReactionScheduled) {
changeReactionScheduled = true;
self.$evalAsync(watchGroupAction);
}
});
deregisterFns.push(unwatchFn);
});
function watchGroupAction() {
changeReactionScheduled = false;
if (firstRun) {
firstRun = false;
listener(newValues, newValues, self);
} else {
listener(newValues, oldValues, self);
}
}
return function deregisterWatchGroup() {
while (deregisterFns.length) {
deregisterFns.shift()();
}
};
},
/**
* @ngdoc method
* @name $rootScope.Scope#$watchCollection
* @kind function
*
* @description
* Shallow watches the properties of an object and fires whenever any of the properties change
* (for arrays, this implies watching the array items; for object maps, this implies watching
* the properties). If a change is detected, the `listener` callback is fired.
*
* - The `obj` collection is observed via standard $watch operation and is examined on every
* call to $digest() to see if any items have been added, removed, or moved.
* - The `listener` is called whenever anything within the `obj` has changed. Examples include
* adding, removing, and moving items belonging to an object or array.
*
*
* # Example
* ```js
$scope.names = ['igor', 'matias', 'misko', 'james'];
$scope.dataCount = 4;
$scope.$watchCollection('names', function(newNames, oldNames) {
$scope.dataCount = newNames.length;
});
expect($scope.dataCount).toEqual(4);
$scope.$digest();
//still at 4 ... no changes
expect($scope.dataCount).toEqual(4);
$scope.names.pop();
$scope.$digest();
//now there's been a change
expect($scope.dataCount).toEqual(3);
* ```
*
*
* @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
* expression value should guide to an object or an array which is observed on each
* {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
* collection will trigger a call to the `listener`.
*
* @param {function(newCollection, oldCollection, scope)} listener a callback function called
* when a change is detected.
* - The `newCollection` object is the newly modified data obtained from the `obj` expression
* - The `oldCollection` object is a copy of the former collection data.
* Due to performance considerations, the`oldCollection` value is computed only if the
* `listener` function declares two or more arguments.
* - The `scope` argument refers to the current scope.
*
* @returns {function()} Returns a de-registration function for this listener. When the
* de-registration function is executed, the internal watch operation is terminated.
*/
$watchCollection: function(obj, listener) {
$watchCollectionInterceptor.$stateful = true;
var self = this;
// the current value, updated on each dirty-check run
var newValue;
// a shallow copy of the newValue from the last dirty-check run,
// updated to match newValue during dirty-check run
var oldValue;
// a shallow copy of the newValue from when the last change happened
var veryOldValue;
// only track veryOldValue if the listener is asking for it
var trackVeryOldValue = (listener.length > 1);
var changeDetected = 0;
var changeDetector = $parse(obj, $watchCollectionInterceptor);
var internalArray = [];
var internalObject = {};
var initRun = true;
var oldLength = 0;
function $watchCollectionInterceptor(_value) {
newValue = _value;
var newLength, key, bothNaN, newItem, oldItem;
// If the new value is undefined, then return undefined as the watch may be a one-time watch
if (isUndefined(newValue)) return;
if (!isObject(newValue)) { // if primitive
if (oldValue !== newValue) {
oldValue = newValue;
changeDetected++;
}
} else if (isArrayLike(newValue)) {
if (oldValue !== internalArray) {
// we are transitioning from something which was not an array into array.
oldValue = internalArray;
oldLength = oldValue.length = 0;
changeDetected++;
}
newLength = newValue.length;
if (oldLength !== newLength) {
// if lengths do not match we need to trigger change notification
changeDetected++;
oldValue.length = oldLength = newLength;
}
// copy the items to oldValue and look for changes.
for (var i = 0; i < newLength; i++) {
oldItem = oldValue[i];
newItem = newValue[i];
bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
if (!bothNaN && (oldItem !== newItem)) {
changeDetected++;
oldValue[i] = newItem;
}
}
} else {
if (oldValue !== internalObject) {
// we are transitioning from something which was not an object into object.
oldValue = internalObject = {};
oldLength = 0;
changeDetected++;
}
// copy the items to oldValue and look for changes.
newLength = 0;
for (key in newValue) {
if (newValue.hasOwnProperty(key)) {
newLength++;
newItem = newValue[key];
oldItem = oldValue[key];
if (key in oldValue) {
bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
if (!bothNaN && (oldItem !== newItem)) {
changeDetected++;
oldValue[key] = newItem;
}
} else {
oldLength++;
oldValue[key] = newItem;
changeDetected++;
}
}
}
if (oldLength > newLength) {
// we used to have more keys, need to find them and destroy them.
changeDetected++;
for (key in oldValue) {
if (!newValue.hasOwnProperty(key)) {
oldLength--;
delete oldValue[key];
}
}
}
}
return changeDetected;
}
function $watchCollectionAction() {
if (initRun) {
initRun = false;
listener(newValue, newValue, self);
} else {
listener(newValue, veryOldValue, self);
}
// make a copy for the next time a collection is changed
if (trackVeryOldValue) {
if (!isObject(newValue)) {
//primitive
veryOldValue = newValue;
} else if (isArrayLike(newValue)) {
veryOldValue = new Array(newValue.length);
for (var i = 0; i < newValue.length; i++) {
veryOldValue[i] = newValue[i];
}
} else { // if object
veryOldValue = {};
for (var key in newValue) {
if (hasOwnProperty.call(newValue, key)) {
veryOldValue[key] = newValue[key];
}
}
}
}
}
return this.$watch(changeDetector, $watchCollectionAction);
},
/**
* @ngdoc method
* @name $rootScope.Scope#$digest
* @kind function
*
* @description
* Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
* its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
* the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
* until no more listeners are firing. This means that it is possible to get into an infinite
* loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
* iterations exceeds 10.
*
* Usually, you don't call `$digest()` directly in
* {@link ng.directive:ngController controllers} or in
* {@link ng.$compileProvider#directive directives}.
* Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
* a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
*
* If you want to be notified whenever `$digest()` is called,
* you can register a `watchExpression` function with
* {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
*
* In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
*
* # Example
* ```js
var scope = ...;
scope.name = 'misko';
scope.counter = 0;
expect(scope.counter).toEqual(0);
scope.$watch('name', function(newValue, oldValue) {
scope.counter = scope.counter + 1;
});
expect(scope.counter).toEqual(0);
scope.$digest();
// the listener is always called during the first $digest loop after it was registered
expect(scope.counter).toEqual(1);
scope.$digest();
// but now it will not be called unless the value changes
expect(scope.counter).toEqual(1);
scope.name = 'adam';
scope.$digest();
expect(scope.counter).toEqual(2);
* ```
*
*/
$digest: function() {
var watch, value, last,
watchers,
length,
dirty, ttl = TTL,
next, current, target = this,
watchLog = [],
logIdx, logMsg, asyncTask;
beginPhase('$digest');
// Check for changes to browser url that happened in sync before the call to $digest
$browser.$$checkUrlChange();
if (this === $rootScope && applyAsyncId !== null) {
// If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
// cancel the scheduled $apply and flush the queue of expressions to be evaluated.
$browser.defer.cancel(applyAsyncId);
flushApplyAsync();
}
lastDirtyWatch = null;
do { // "while dirty" loop
dirty = false;
current = target;
while (asyncQueue.length) {
try {
asyncTask = asyncQueue.shift();
asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals);
} catch (e) {
$exceptionHandler(e);
}
lastDirtyWatch = null;
}
traverseScopesLoop:
do { // "traverse the scopes" loop
if ((watchers = current.$$watchers)) {
// process our watches
length = watchers.length;
while (length--) {
try {
watch = watchers[length];
// Most common watches are on primitives, in which case we can short
// circuit it with === operator, only when === fails do we use .equals
if (watch) {
if ((value = watch.get(current)) !== (last = watch.last) &&
!(watch.eq
? equals(value, last)
: (typeof value === 'number' && typeof last === 'number'
&& isNaN(value) && isNaN(last)))) {
dirty = true;
lastDirtyWatch = watch;
watch.last = watch.eq ? copy(value, null) : value;
watch.fn(value, ((last === initWatchVal) ? value : last), current);
if (ttl < 5) {
logIdx = 4 - ttl;
if (!watchLog[logIdx]) watchLog[logIdx] = [];
watchLog[logIdx].push({
msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
newVal: value,
oldVal: last
});
}
} else if (watch === lastDirtyWatch) {
// If the most recently dirty watcher is now clean, short circuit since the remaining watchers
// have already been tested.
dirty = false;
break traverseScopesLoop;
}
}
} catch (e) {
$exceptionHandler(e);
}
}
}
// Insanity Warning: scope depth-first traversal
// yes, this code is a bit crazy, but it works and we have tests to prove it!
// this piece should be kept in sync with the traversal in $broadcast
if (!(next = (current.$$childHead ||
(current !== target && current.$$nextSibling)))) {
while (current !== target && !(next = current.$$nextSibling)) {
current = current.$parent;
}
}
} while ((current = next));
// `break traverseScopesLoop;` takes us to here
if ((dirty || asyncQueue.length) && !(ttl--)) {
clearPhase();
throw $rootScopeMinErr('infdig',
'{0} $digest() iterations reached. Aborting!\n' +
'Watchers fired in the last 5 iterations: {1}',
TTL, watchLog);
}
} while (dirty || asyncQueue.length);
clearPhase();
while (postDigestQueue.length) {
try {
postDigestQueue.shift()();
} catch (e) {
$exceptionHandler(e);
}
}
},
/**
* @ngdoc event
* @name $rootScope.Scope#$destroy
* @eventType broadcast on scope being destroyed
*
* @description
* Broadcasted when a scope and its children are being destroyed.
*
* Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
* clean up DOM bindings before an element is removed from the DOM.
*/
/**
* @ngdoc method
* @name $rootScope.Scope#$destroy
* @kind function
*
* @description
* Removes the current scope (and all of its children) from the parent scope. Removal implies
* that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
* propagate to the current scope and its children. Removal also implies that the current
* scope is eligible for garbage collection.
*
* The `$destroy()` is usually used by directives such as
* {@link ng.directive:ngRepeat ngRepeat} for managing the
* unrolling of the loop.
*
* Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
* Application code can register a `$destroy` event handler that will give it a chance to
* perform any necessary cleanup.
*
* Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
* clean up DOM bindings before an element is removed from the DOM.
*/
$destroy: function() {
// we can't destroy the root scope or a scope that has been already destroyed
if (this.$$destroyed) return;
var parent = this.$parent;
this.$broadcast('$destroy');
this.$$destroyed = true;
if (this === $rootScope) return;
for (var eventName in this.$$listenerCount) {
decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
}
// sever all the references to parent scopes (after this cleanup, the current scope should
// not be retained by any of our references and should be eligible for garbage collection)
if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
// Disable listeners, watchers and apply/digest methods
this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
this.$on = this.$watch = this.$watchGroup = function() { return noop; };
this.$$listeners = {};
// All of the code below is bogus code that works around V8's memory leak via optimized code
// and inline caches.
//
// see:
// - https://code.google.com/p/v8/issues/detail?id=2073#c26
// - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
// - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead =
this.$$childTail = this.$root = this.$$watchers = null;
},
/**
* @ngdoc method
* @name $rootScope.Scope#$eval
* @kind function
*
* @description
* Executes the `expression` on the current scope and returns the result. Any exceptions in
* the expression are propagated (uncaught). This is useful when evaluating Angular
* expressions.
*
* # Example
* ```js
var scope = ng.$rootScope.Scope();
scope.a = 1;
scope.b = 2;
expect(scope.$eval('a+b')).toEqual(3);
expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
* ```
*
* @param {(string|function())=} expression An angular expression to be executed.
*
* - `string`: execute using the rules as defined in {@link guide/expression expression}.
* - `function(scope)`: execute the function with the current `scope` parameter.
*
* @param {(object)=} locals Local variables object, useful for overriding values in scope.
* @returns {*} The result of evaluating the expression.
*/
$eval: function(expr, locals) {
return $parse(expr)(this, locals);
},
/**
* @ngdoc method
* @name $rootScope.Scope#$evalAsync
* @kind function
*
* @description
* Executes the expression on the current scope at a later point in time.
*
* The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
* that:
*
* - it will execute after the function that scheduled the guide (preferably before DOM
* rendering).
* - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
* `expression` execution.
*
* Any exceptions from the execution of the expression are forwarded to the
* {@link ng.$exceptionHandler $exceptionHandler} service.
*
* __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
* will be scheduled. However, it is encouraged to always call code that changes the model
* from within an `$apply` call. That includes code evaluated via `$evalAsync`.
*
* @param {(string|function())=} expression An angular expression to be executed.
*
* - `string`: execute using the rules as defined in {@link guide/expression expression}.
* - `function(scope)`: execute the function with the current `scope` parameter.
*
* @param {(object)=} locals Local variables object, useful for overriding values in scope.
*/
$evalAsync: function(expr, locals) {
// if we are outside of an $digest loop and this is the first time we are scheduling async
// task also schedule async auto-flush
if (!$rootScope.$$phase && !asyncQueue.length) {
$browser.defer(function() {
if (asyncQueue.length) {
$rootScope.$digest();
}
});
}
asyncQueue.push({scope: this, expression: expr, locals: locals});
},
$$postDigest: function(fn) {
postDigestQueue.push(fn);
},
/**
* @ngdoc method
* @name $rootScope.Scope#$apply
* @kind function
*
* @description
* `$apply()` is used to execute an expression in angular from outside of the angular
* framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
* Because we are calling into the angular framework we need to perform proper scope life
* cycle of {@link ng.$exceptionHandler exception handling},
* {@link ng.$rootScope.Scope#$digest executing watches}.
*
* ## Life cycle
*
* # Pseudo-Code of `$apply()`
* ```js
function $apply(expr) {
try {
return $eval(expr);
} catch (e) {
$exceptionHandler(e);
} finally {
$root.$digest();
}
}
* ```
*
*
* Scope's `$apply()` method transitions through the following stages:
*
* 1. The {@link guide/expression expression} is executed using the
* {@link ng.$rootScope.Scope#$eval $eval()} method.
* 2. Any exceptions from the execution of the expression are forwarded to the
* {@link ng.$exceptionHandler $exceptionHandler} service.
* 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
* expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
*
*
* @param {(string|function())=} exp An angular expression to be executed.
*
* - `string`: execute using the rules as defined in {@link guide/expression expression}.
* - `function(scope)`: execute the function with current `scope` parameter.
*
* @returns {*} The result of evaluating the expression.
*/
$apply: function(expr) {
try {
beginPhase('$apply');
return this.$eval(expr);
} catch (e) {
$exceptionHandler(e);
} finally {
clearPhase();
try {
$rootScope.$digest();
} catch (e) {
$exceptionHandler(e);
throw e;
}
}
},
/**
* @ngdoc method
* @name $rootScope.Scope#$applyAsync
* @kind function
*
* @description
* Schedule the invocation of $apply to occur at a later time. The actual time difference
* varies across browsers, but is typically around ~10 milliseconds.
*
* This can be used to queue up multiple expressions which need to be evaluated in the same
* digest.
*
* @param {(string|function())=} exp An angular expression to be executed.
*
* - `string`: execute using the rules as defined in {@link guide/expression expression}.
* - `function(scope)`: execute the function with current `scope` parameter.
*/
$applyAsync: function(expr) {
var scope = this;
expr && applyAsyncQueue.push($applyAsyncExpression);
scheduleApplyAsync();
function $applyAsyncExpression() {
scope.$eval(expr);
}
},
/**
* @ngdoc method
* @name $rootScope.Scope#$on
* @kind function
*
* @description
* Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
* discussion of event life cycle.
*
* The event listener function format is: `function(event, args...)`. The `event` object
* passed into the listener has the following attributes:
*
* - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
* `$broadcast`-ed.
* - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
* event propagates through the scope hierarchy, this property is set to null.
* - `name` - `{string}`: name of the event.
* - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
* further event propagation (available only for events that were `$emit`-ed).
* - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
* to true.
* - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
*
* @param {string} name Event name to listen on.
* @param {function(event, ...args)} listener Function to call when the event is emitted.
* @returns {function()} Returns a deregistration function for this listener.
*/
$on: function(name, listener) {
var namedListeners = this.$$listeners[name];
if (!namedListeners) {
this.$$listeners[name] = namedListeners = [];
}
namedListeners.push(listener);
var current = this;
do {
if (!current.$$listenerCount[name]) {
current.$$listenerCount[name] = 0;
}
current.$$listenerCount[name]++;
} while ((current = current.$parent));
var self = this;
return function() {
var indexOfListener = namedListeners.indexOf(listener);
if (indexOfListener !== -1) {
namedListeners[indexOfListener] = null;
decrementListenerCount(self, 1, name);
}
};
},
/**
* @ngdoc method
* @name $rootScope.Scope#$emit
* @kind function
*
* @description
* Dispatches an event `name` upwards through the scope hierarchy notifying the
* registered {@link ng.$rootScope.Scope#$on} listeners.
*
* The event life cycle starts at the scope on which `$emit` was called. All
* {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
* notified. Afterwards, the event traverses upwards toward the root scope and calls all
* registered listeners along the way. The event will stop propagating if one of the listeners
* cancels it.
*
* Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
* onto the {@link ng.$exceptionHandler $exceptionHandler} service.
*
* @param {string} name Event name to emit.
* @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
* @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
*/
$emit: function(name, args) {
var empty = [],
namedListeners,
scope = this,
stopPropagation = false,
event = {
name: name,
targetScope: scope,
stopPropagation: function() {stopPropagation = true;},
preventDefault: function() {
event.defaultPrevented = true;
},
defaultPrevented: false
},
listenerArgs = concat([event], arguments, 1),
i, length;
do {
namedListeners = scope.$$listeners[name] || empty;
event.currentScope = scope;
for (i = 0, length = namedListeners.length; i < length; i++) {
// if listeners were deregistered, defragment the array
if (!namedListeners[i]) {
namedListeners.splice(i, 1);
i--;
length--;
continue;
}
try {
//allow all listeners attached to the current scope to run
namedListeners[i].apply(null, listenerArgs);
} catch (e) {
$exceptionHandler(e);
}
}
//if any listener on the current scope stops propagation, prevent bubbling
if (stopPropagation) {
event.currentScope = null;
return event;
}
//traverse upwards
scope = scope.$parent;
} while (scope);
event.currentScope = null;
return event;
},
/**
* @ngdoc method
* @name $rootScope.Scope#$broadcast
* @kind function
*
* @description
* Dispatches an event `name` downwards to all child scopes (and their children) notifying the
* registered {@link ng.$rootScope.Scope#$on} listeners.
*
* The event life cycle starts at the scope on which `$broadcast` was called. All
* {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
* notified. Afterwards, the event propagates to all direct and indirect scopes of the current
* scope and calls all registered listeners along the way. The event cannot be canceled.
*
* Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
* onto the {@link ng.$exceptionHandler $exceptionHandler} service.
*
* @param {string} name Event name to broadcast.
* @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
* @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
*/
$broadcast: function(name, args) {
var target = this,
current = target,
next = target,
event = {
name: name,
targetScope: target,
preventDefault: function() {
event.defaultPrevented = true;
},
defaultPrevented: false
};
if (!target.$$listenerCount[name]) return event;
var listenerArgs = concat([event], arguments, 1),
listeners, i, length;
//down while you can, then up and next sibling or up and next sibling until back at root
while ((current = next)) {
event.currentScope = current;
listeners = current.$$listeners[name] || [];
for (i = 0, length = listeners.length; i < length; i++) {
// if listeners were deregistered, defragment the array
if (!listeners[i]) {
listeners.splice(i, 1);
i--;
length--;
continue;
}
try {
listeners[i].apply(null, listenerArgs);
} catch (e) {
$exceptionHandler(e);
}
}
// Insanity Warning: scope depth-first traversal
// yes, this code is a bit crazy, but it works and we have tests to prove it!
// this piece should be kept in sync with the traversal in $digest
// (though it differs due to having the extra check for $$listenerCount)
if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
(current !== target && current.$$nextSibling)))) {
while (current !== target && !(next = current.$$nextSibling)) {
current = current.$parent;
}
}
}
event.currentScope = null;
return event;
}
};
var $rootScope = new Scope();
//The internal queues. Expose them on the $rootScope for debugging/testing purposes.
var asyncQueue = $rootScope.$$asyncQueue = [];
var postDigestQueue = $rootScope.$$postDigestQueue = [];
var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
return $rootScope;
function beginPhase(phase) {
if ($rootScope.$$phase) {
throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
}
$rootScope.$$phase = phase;
}
function clearPhase() {
$rootScope.$$phase = null;
}
function decrementListenerCount(current, count, name) {
do {
current.$$listenerCount[name] -= count;
if (current.$$listenerCount[name] === 0) {
delete current.$$listenerCount[name];
}
} while ((current = current.$parent));
}
/**
* function used as an initial value for watchers.
* because it's unique we can easily tell it apart from other values
*/
function initWatchVal() {}
function flushApplyAsync() {
while (applyAsyncQueue.length) {
try {
applyAsyncQueue.shift()();
} catch (e) {
$exceptionHandler(e);
}
}
applyAsyncId = null;
}
function scheduleApplyAsync() {
if (applyAsyncId === null) {
applyAsyncId = $browser.defer(function() {
$rootScope.$apply(flushApplyAsync);
});
}
}
}];
}
/**
* @description
* Private service to sanitize uris for links and images. Used by $compile and $sanitize.
*/
function $$SanitizeUriProvider() {
var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
/**
* @description
* Retrieves or overrides the default regular expression that is used for whitelisting of safe
* urls during a[href] sanitization.
*
* The sanitization is a security measure aimed at prevent XSS attacks via html links.
*
* Any url about to be assigned to a[href] via data-binding is first normalized and turned into
* an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
* regular expression. If a match is found, the original url is written into the dom. Otherwise,
* the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
*
* @param {RegExp=} regexp New regexp to whitelist urls with.
* @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
* chaining otherwise.
*/
this.aHrefSanitizationWhitelist = function(regexp) {
if (isDefined(regexp)) {
aHrefSanitizationWhitelist = regexp;
return this;
}
return aHrefSanitizationWhitelist;
};
/**
* @description
* Retrieves or overrides the default regular expression that is used for whitelisting of safe
* urls during img[src] sanitization.
*
* The sanitization is a security measure aimed at prevent XSS attacks via html links.
*
* Any url about to be assigned to img[src] via data-binding is first normalized and turned into
* an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
* regular expression. If a match is found, the original url is written into the dom. Otherwise,
* the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
*
* @param {RegExp=} regexp New regexp to whitelist urls with.
* @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
* chaining otherwise.
*/
this.imgSrcSanitizationWhitelist = function(regexp) {
if (isDefined(regexp)) {
imgSrcSanitizationWhitelist = regexp;
return this;
}
return imgSrcSanitizationWhitelist;
};
this.$get = function() {
return function sanitizeUri(uri, isImage) {
var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
var normalizedVal;
normalizedVal = urlResolve(uri).href;
if (normalizedVal !== '' && !normalizedVal.match(regex)) {
return 'unsafe:' + normalizedVal;
}
return uri;
};
};
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Any commits to this file should be reviewed with security in mind. *
* Changes to this file can potentially create security vulnerabilities. *
* An approval from 2 Core members with history of modifying *
* this file is required. *
* *
* Does the change somehow allow for arbitrary javascript to be executed? *
* Or allows for someone to change the prototype of built-in objects? *
* Or gives undesired access to variables likes document or window? *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
var $sceMinErr = minErr('$sce');
var SCE_CONTEXTS = {
HTML: 'html',
CSS: 'css',
URL: 'url',
// RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
// url. (e.g. ng-include, script src, templateUrl)
RESOURCE_URL: 'resourceUrl',
JS: 'js'
};
// Helper functions follow.
function adjustMatcher(matcher) {
if (matcher === 'self') {
return matcher;
} else if (isString(matcher)) {
// Strings match exactly except for 2 wildcards - '*' and '**'.
// '*' matches any character except those from the set ':/.?&'.
// '**' matches any character (like .* in a RegExp).
// More than 2 *'s raises an error as it's ill defined.
if (matcher.indexOf('***') > -1) {
throw $sceMinErr('iwcard',
'Illegal sequence *** in string matcher. String: {0}', matcher);
}
matcher = escapeForRegexp(matcher).
replace('\\*\\*', '.*').
replace('\\*', '[^:/.?&;]*');
return new RegExp('^' + matcher + '$');
} else if (isRegExp(matcher)) {
// The only other type of matcher allowed is a Regexp.
// Match entire URL / disallow partial matches.
// Flags are reset (i.e. no global, ignoreCase or multiline)
return new RegExp('^' + matcher.source + '$');
} else {
throw $sceMinErr('imatcher',
'Matchers may only be "self", string patterns or RegExp objects');
}
}
function adjustMatchers(matchers) {
var adjustedMatchers = [];
if (isDefined(matchers)) {
forEach(matchers, function(matcher) {
adjustedMatchers.push(adjustMatcher(matcher));
});
}
return adjustedMatchers;
}
/**
* @ngdoc service
* @name $sceDelegate
* @kind function
*
* @description
*
* `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
* Contextual Escaping (SCE)} services to AngularJS.
*
* Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
* the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
* because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
* override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
* work because `$sce` delegates to `$sceDelegate` for these operations.
*
* Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
*
* The default instance of `$sceDelegate` should work out of the box with little pain. While you
* can override it completely to change the behavior of `$sce`, the common case would
* involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
* your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
* templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
* $sceDelegateProvider.resourceUrlWhitelist} and {@link
* ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
*/
/**
* @ngdoc provider
* @name $sceDelegateProvider
* @description
*
* The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
* $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
* that the URLs used for sourcing Angular templates are safe. Refer {@link
* ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
* {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
*
* For the general details about this service in Angular, read the main page for {@link ng.$sce
* Strict Contextual Escaping (SCE)}.
*
* **Example**: Consider the following case. <a name="example"></a>
*
* - your app is hosted at url `http://myapp.example.com/`
* - but some of your templates are hosted on other domains you control such as
* `http://srv01.assets.example.com/`, `http://srv02.assets.example.com/`, etc.
* - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
*
* Here is what a secure configuration for this scenario might look like:
*
* ```
* angular.module('myApp', []).config(function($sceDelegateProvider) {
* $sceDelegateProvider.resourceUrlWhitelist([
* // Allow same origin resource loads.
* 'self',
* // Allow loading from our assets domain. Notice the difference between * and **.
* 'http://srv*.assets.example.com/**'
* ]);
*
* // The blacklist overrides the whitelist so the open redirect here is blocked.
* $sceDelegateProvider.resourceUrlBlacklist([
* 'http://myapp.example.com/clickThru**'
* ]);
* });
* ```
*/
function $SceDelegateProvider() {
this.SCE_CONTEXTS = SCE_CONTEXTS;
// Resource URLs can also be trusted by policy.
var resourceUrlWhitelist = ['self'],
resourceUrlBlacklist = [];
/**
* @ngdoc method
* @name $sceDelegateProvider#resourceUrlWhitelist
* @kind function
*
* @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
* provided. This must be an array or null. A snapshot of this array is used so further
* changes to the array are ignored.
*
* Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
* allowed in this array.
*
* Note: **an empty whitelist array will block all URLs**!
*
* @return {Array} the currently set whitelist array.
*
* The **default value** when no whitelist has been explicitly set is `['self']` allowing only
* same origin resource requests.
*
* @description
* Sets/Gets the whitelist of trusted resource URLs.
*/
this.resourceUrlWhitelist = function(value) {
if (arguments.length) {
resourceUrlWhitelist = adjustMatchers(value);
}
return resourceUrlWhitelist;
};
/**
* @ngdoc method
* @name $sceDelegateProvider#resourceUrlBlacklist
* @kind function
*
* @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
* provided. This must be an array or null. A snapshot of this array is used so further
* changes to the array are ignored.
*
* Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
* allowed in this array.
*
* The typical usage for the blacklist is to **block
* [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
* these would otherwise be trusted but actually return content from the redirected domain.
*
* Finally, **the blacklist overrides the whitelist** and has the final say.
*
* @return {Array} the currently set blacklist array.
*
* The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
* is no blacklist.)
*
* @description
* Sets/Gets the blacklist of trusted resource URLs.
*/
this.resourceUrlBlacklist = function(value) {
if (arguments.length) {
resourceUrlBlacklist = adjustMatchers(value);
}
return resourceUrlBlacklist;
};
this.$get = ['$injector', function($injector) {
var htmlSanitizer = function htmlSanitizer(html) {
throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
};
if ($injector.has('$sanitize')) {
htmlSanitizer = $injector.get('$sanitize');
}
function matchUrl(matcher, parsedUrl) {
if (matcher === 'self') {
return urlIsSameOrigin(parsedUrl);
} else {
// definitely a regex. See adjustMatchers()
return !!matcher.exec(parsedUrl.href);
}
}
function isResourceUrlAllowedByPolicy(url) {
var parsedUrl = urlResolve(url.toString());
var i, n, allowed = false;
// Ensure that at least one item from the whitelist allows this url.
for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
allowed = true;
break;
}
}
if (allowed) {
// Ensure that no item from the blacklist blocked this url.
for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
allowed = false;
break;
}
}
}
return allowed;
}
function generateHolderType(Base) {
var holderType = function TrustedValueHolderType(trustedValue) {
this.$$unwrapTrustedValue = function() {
return trustedValue;
};
};
if (Base) {
holderType.prototype = new Base();
}
holderType.prototype.valueOf = function sceValueOf() {
return this.$$unwrapTrustedValue();
};
holderType.prototype.toString = function sceToString() {
return this.$$unwrapTrustedValue().toString();
};
return holderType;
}
var trustedValueHolderBase = generateHolderType(),
byType = {};
byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
/**
* @ngdoc method
* @name $sceDelegate#trustAs
*
* @description
* Returns an object that is trusted by angular for use in specified strict
* contextual escaping contexts (such as ng-bind-html, ng-include, any src
* attribute interpolation, any dom event binding attribute interpolation
* such as for onclick, etc.) that uses the provided value.
* See {@link ng.$sce $sce} for enabling strict contextual escaping.
*
* @param {string} type The kind of context in which this value is safe for use. e.g. url,
* resourceUrl, html, js and css.
* @param {*} value The value that that should be considered trusted/safe.
* @returns {*} A value that can be used to stand in for the provided `value` in places
* where Angular expects a $sce.trustAs() return value.
*/
function trustAs(type, trustedValue) {
var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
if (!Constructor) {
throw $sceMinErr('icontext',
'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
type, trustedValue);
}
if (trustedValue === null || trustedValue === undefined || trustedValue === '') {
return trustedValue;
}
// All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
// mutable objects, we ensure here that the value passed in is actually a string.
if (typeof trustedValue !== 'string') {
throw $sceMinErr('itype',
'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
type);
}
return new Constructor(trustedValue);
}
/**
* @ngdoc method
* @name $sceDelegate#valueOf
*
* @description
* If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
* `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
* ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
*
* If the passed parameter is not a value that had been returned by {@link
* ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
*
* @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
* call or anything else.
* @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
* `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
* `value` unchanged.
*/
function valueOf(maybeTrusted) {
if (maybeTrusted instanceof trustedValueHolderBase) {
return maybeTrusted.$$unwrapTrustedValue();
} else {
return maybeTrusted;
}
}
/**
* @ngdoc method
* @name $sceDelegate#getTrusted
*
* @description
* Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
* returns the originally supplied value if the queried context type is a supertype of the
* created type. If this condition isn't satisfied, throws an exception.
*
* @param {string} type The kind of context in which this value is to be used.
* @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
* `$sceDelegate.trustAs`} call.
* @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
* `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
*/
function getTrusted(type, maybeTrusted) {
if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') {
return maybeTrusted;
}
var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
if (constructor && maybeTrusted instanceof constructor) {
return maybeTrusted.$$unwrapTrustedValue();
}
// If we get here, then we may only take one of two actions.
// 1. sanitize the value for the requested type, or
// 2. throw an exception.
if (type === SCE_CONTEXTS.RESOURCE_URL) {
if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
return maybeTrusted;
} else {
throw $sceMinErr('insecurl',
'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
maybeTrusted.toString());
}
} else if (type === SCE_CONTEXTS.HTML) {
return htmlSanitizer(maybeTrusted);
}
throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
}
return { trustAs: trustAs,
getTrusted: getTrusted,
valueOf: valueOf };
}];
}
/**
* @ngdoc provider
* @name $sceProvider
* @description
*
* The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
* - enable/disable Strict Contextual Escaping (SCE) in a module
* - override the default implementation with a custom delegate
*
* Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
*/
/* jshint maxlen: false*/
/**
* @ngdoc service
* @name $sce
* @kind function
*
* @description
*
* `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
*
* # Strict Contextual Escaping
*
* Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
* contexts to result in a value that is marked as safe to use for that context. One example of
* such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
* to these contexts as privileged or SCE contexts.
*
* As of version 1.2, Angular ships with SCE enabled by default.
*
* Note: When enabled (the default), IE<11 in quirks mode is not supported. In this mode, IE<11 allow
* one to execute arbitrary javascript by the use of the expression() syntax. Refer
* <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
* You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
* to the top of your HTML document.
*
* SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
* security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
*
* Here's an example of a binding in a privileged context:
*
* ```
* <input ng-model="userHtml">
* <div ng-bind-html="userHtml"></div>
* ```
*
* Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
* disabled, this application allows the user to render arbitrary HTML into the DIV.
* In a more realistic example, one may be rendering user comments, blog articles, etc. via
* bindings. (HTML is just one example of a context where rendering user controlled input creates
* security vulnerabilities.)
*
* For the case of HTML, you might use a library, either on the client side, or on the server side,
* to sanitize unsafe HTML before binding to the value and rendering it in the document.
*
* How would you ensure that every place that used these types of bindings was bound to a value that
* was sanitized by your library (or returned as safe for rendering by your server?) How can you
* ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
* properties/fields and forgot to update the binding to the sanitized value?
*
* To be secure by default, you want to ensure that any such bindings are disallowed unless you can
* determine that something explicitly says it's safe to use a value for binding in that
* context. You can then audit your code (a simple grep would do) to ensure that this is only done
* for those values that you can easily tell are safe - because they were received from your server,
* sanitized by your library, etc. You can organize your codebase to help with this - perhaps
* allowing only the files in a specific directory to do this. Ensuring that the internal API
* exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
*
* In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
* (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
* obtain values that will be accepted by SCE / privileged contexts.
*
*
* ## How does it work?
*
* In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
* $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
* ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
* {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
*
* As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
* ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
* simplified):
*
* ```
* var ngBindHtmlDirective = ['$sce', function($sce) {
* return function(scope, element, attr) {
* scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
* element.html(value || '');
* });
* };
* }];
* ```
*
* ## Impact on loading templates
*
* This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
* `templateUrl`'s specified by {@link guide/directive directives}.
*
* By default, Angular only loads templates from the same domain and protocol as the application
* document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
* $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
* protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
* them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
*
* *Please note*:
* The browser's
* [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
* and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
* policy apply in addition to this and may further restrict whether the template is successfully
* loaded. This means that without the right CORS policy, loading templates from a different domain
* won't work on all browsers. Also, loading templates from `file://` URL does not work on some
* browsers.
*
* ## This feels like too much overhead
*
* It's important to remember that SCE only applies to interpolation expressions.
*
* If your expressions are constant literals, they're automatically trusted and you don't need to
* call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
* `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
*
* Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
* through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
*
* The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
* templates in `ng-include` from your application's domain without having to even know about SCE.
* It blocks loading templates from other domains or loading templates over http from an https
* served document. You can change these by setting your own custom {@link
* ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
* ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
*
* This significantly reduces the overhead. It is far easier to pay the small overhead and have an
* application that's secure and can be audited to verify that with much more ease than bolting
* security onto an application later.
*
* <a name="contexts"></a>
* ## What trusted context types are supported?
*
* | Context | Notes |
* |---------------------|----------------|
* | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. If an unsafe value is encountered and the {@link ngSanitize $sanitize} module is present this will sanitize the value instead of throwing an error. |
* | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
* | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (`<a href=` and `<img src=` sanitize their urls and don't constitute an SCE context. |
* | `$sce.RESOURCE_URL` | For URLs that are not only safe to follow as links, but whose contents are also safe to include in your application. Examples include `ng-include`, `src` / `ngSrc` bindings for tags other than `IMG` (e.g. `IFRAME`, `OBJECT`, etc.) <br><br>Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. |
* | `$sce.JS` | For JavaScript that is safe to execute in your application's context. Currently unused. Feel free to use it in your own directives. |
*
* ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
*
* Each element in these arrays must be one of the following:
*
* - **'self'**
* - The special **string**, `'self'`, can be used to match against all URLs of the **same
* domain** as the application document using the **same protocol**.
* - **String** (except the special value `'self'`)
* - The string is matched against the full *normalized / absolute URL* of the resource
* being tested (substring matches are not good enough.)
* - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
* match themselves.
* - `*`: matches zero or more occurrences of any character other than one of the following 6
* characters: '`:`', '`/`', '`.`', '`?`', '`&`' and ';'. It's a useful wildcard for use
* in a whitelist.
* - `**`: matches zero or more occurrences of *any* character. As such, it's not
* not appropriate to use in for a scheme, domain, etc. as it would match too much. (e.g.
* http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
* not have been the intention.) Its usage at the very end of the path is ok. (e.g.
* http://foo.example.com/templates/**).
* - **RegExp** (*see caveat below*)
* - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
* (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
* accidentally introduce a bug when one updates a complex expression (imho, all regexes should
* have good test coverage.). For instance, the use of `.` in the regex is correct only in a
* small number of cases. A `.` character in the regex used when matching the scheme or a
* subdomain could be matched against a `:` or literal `.` that was likely not intended. It
* is highly recommended to use the string patterns and only fall back to regular expressions
* if they as a last resort.
* - The regular expression must be an instance of RegExp (i.e. not a string.) It is
* matched against the **entire** *normalized / absolute URL* of the resource being tested
* (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
* present on the RegExp (such as multiline, global, ignoreCase) are ignored.
* - If you are generating your JavaScript from some other templating engine (not
* recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
* remember to escape your regular expression (and be aware that you might need more than
* one level of escaping depending on your templating engine and the way you interpolated
* the value.) Do make use of your platform's escaping mechanism as it might be good
* enough before coding your own. e.g. Ruby has
* [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
* and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
* Javascript lacks a similar built in function for escaping. Take a look at Google
* Closure library's [goog.string.regExpEscape(s)](
* http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
*
* Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
*
* ## Show me an example using SCE.
*
* <example module="mySceApp" deps="angular-sanitize.js">
* <file name="index.html">
* <div ng-controller="AppController as myCtrl">
* <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
* <b>User comments</b><br>
* By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
* $sanitize is available. If $sanitize isn't available, this results in an error instead of an
* exploit.
* <div class="well">
* <div ng-repeat="userComment in myCtrl.userComments">
* <b>{{userComment.name}}</b>:
* <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
* <br>
* </div>
* </div>
* </div>
* </file>
*
* <file name="script.js">
* angular.module('mySceApp', ['ngSanitize'])
* .controller('AppController', ['$http', '$templateCache', '$sce',
* function($http, $templateCache, $sce) {
* var self = this;
* $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
* self.userComments = userComments;
* });
* self.explicitlyTrustedHtml = $sce.trustAsHtml(
* '<span onmouseover="this.textContent="Explicitly trusted HTML bypasses ' +
* 'sanitization."">Hover over this text.</span>');
* }]);
* </file>
*
* <file name="test_data.json">
* [
* { "name": "Alice",
* "htmlComment":
* "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
* },
* { "name": "Bob",
* "htmlComment": "<i>Yes!</i> Am I the only other one?"
* }
* ]
* </file>
*
* <file name="protractor.js" type="protractor">
* describe('SCE doc demo', function() {
* it('should sanitize untrusted values', function() {
* expect(element.all(by.css('.htmlComment')).first().getInnerHtml())
* .toBe('<span>Is <i>anyone</i> reading this?</span>');
* });
*
* it('should NOT sanitize explicitly trusted values', function() {
* expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(
* '<span onmouseover="this.textContent="Explicitly trusted HTML bypasses ' +
* 'sanitization."">Hover over this text.</span>');
* });
* });
* </file>
* </example>
*
*
*
* ## Can I disable SCE completely?
*
* Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
* for little coding overhead. It will be much harder to take an SCE disabled application and
* either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
* for cases where you have a lot of existing code that was written before SCE was introduced and
* you're migrating them a module at a time.
*
* That said, here's how you can completely disable SCE:
*
* ```
* angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
* // Completely disable SCE. For demonstration purposes only!
* // Do not use in new projects.
* $sceProvider.enabled(false);
* });
* ```
*
*/
/* jshint maxlen: 100 */
function $SceProvider() {
var enabled = true;
/**
* @ngdoc method
* @name $sceProvider#enabled
* @kind function
*
* @param {boolean=} value If provided, then enables/disables SCE.
* @return {boolean} true if SCE is enabled, false otherwise.
*
* @description
* Enables/disables SCE and returns the current value.
*/
this.enabled = function(value) {
if (arguments.length) {
enabled = !!value;
}
return enabled;
};
/* Design notes on the default implementation for SCE.
*
* The API contract for the SCE delegate
* -------------------------------------
* The SCE delegate object must provide the following 3 methods:
*
* - trustAs(contextEnum, value)
* This method is used to tell the SCE service that the provided value is OK to use in the
* contexts specified by contextEnum. It must return an object that will be accepted by
* getTrusted() for a compatible contextEnum and return this value.
*
* - valueOf(value)
* For values that were not produced by trustAs(), return them as is. For values that were
* produced by trustAs(), return the corresponding input value to trustAs. Basically, if
* trustAs is wrapping the given values into some type, this operation unwraps it when given
* such a value.
*
* - getTrusted(contextEnum, value)
* This function should return the a value that is safe to use in the context specified by
* contextEnum or throw and exception otherwise.
*
* NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
* opaque or wrapped in some holder object. That happens to be an implementation detail. For
* instance, an implementation could maintain a registry of all trusted objects by context. In
* such a case, trustAs() would return the same object that was passed in. getTrusted() would
* return the same object passed in if it was found in the registry under a compatible context or
* throw an exception otherwise. An implementation might only wrap values some of the time based
* on some criteria. getTrusted() might return a value and not throw an exception for special
* constants or objects even if not wrapped. All such implementations fulfill this contract.
*
*
* A note on the inheritance model for SCE contexts
* ------------------------------------------------
* I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
* is purely an implementation details.
*
* The contract is simply this:
*
* getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
* will also succeed.
*
* Inheritance happens to capture this in a natural way. In some future, we
* may not use inheritance anymore. That is OK because no code outside of
* sce.js and sceSpecs.js would need to be aware of this detail.
*/
this.$get = ['$parse', '$sceDelegate', function(
$parse, $sceDelegate) {
// Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow
// the "expression(javascript expression)" syntax which is insecure.
if (enabled && msie < 8) {
throw $sceMinErr('iequirks',
'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
}
var sce = shallowCopy(SCE_CONTEXTS);
/**
* @ngdoc method
* @name $sce#isEnabled
* @kind function
*
* @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
* have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
*
* @description
* Returns a boolean indicating if SCE is enabled.
*/
sce.isEnabled = function() {
return enabled;
};
sce.trustAs = $sceDelegate.trustAs;
sce.getTrusted = $sceDelegate.getTrusted;
sce.valueOf = $sceDelegate.valueOf;
if (!enabled) {
sce.trustAs = sce.getTrusted = function(type, value) { return value; };
sce.valueOf = identity;
}
/**
* @ngdoc method
* @name $sce#parseAs
*
* @description
* Converts Angular {@link guide/expression expression} into a function. This is like {@link
* ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
* wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
* *result*)}
*
* @param {string} type The kind of SCE context in which this result will be used.
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context` – `{object}` – an object against which any expressions embedded in the strings
* are evaluated against (typically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*/
sce.parseAs = function sceParseAs(type, expr) {
var parsed = $parse(expr);
if (parsed.literal && parsed.constant) {
return parsed;
} else {
return $parse(expr, function(value) {
return sce.getTrusted(type, value);
});
}
};
/**
* @ngdoc method
* @name $sce#trustAs
*
* @description
* Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,
* returns an object that is trusted by angular for use in specified strict contextual
* escaping contexts (such as ng-bind-html, ng-include, any src attribute
* interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
* that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
* escaping.
*
* @param {string} type The kind of context in which this value is safe for use. e.g. url,
* resource_url, html, js and css.
* @param {*} value The value that that should be considered trusted/safe.
* @returns {*} A value that can be used to stand in for the provided `value` in places
* where Angular expects a $sce.trustAs() return value.
*/
/**
* @ngdoc method
* @name $sce#trustAsHtml
*
* @description
* Shorthand method. `$sce.trustAsHtml(value)` →
* {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
*
* @param {*} value The value to trustAs.
* @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
* $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
* only accept expressions that are either literal constants or are the
* return value of {@link ng.$sce#trustAs $sce.trustAs}.)
*/
/**
* @ngdoc method
* @name $sce#trustAsUrl
*
* @description
* Shorthand method. `$sce.trustAsUrl(value)` →
* {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
*
* @param {*} value The value to trustAs.
* @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
* $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
* only accept expressions that are either literal constants or are the
* return value of {@link ng.$sce#trustAs $sce.trustAs}.)
*/
/**
* @ngdoc method
* @name $sce#trustAsResourceUrl
*
* @description
* Shorthand method. `$sce.trustAsResourceUrl(value)` →
* {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
*
* @param {*} value The value to trustAs.
* @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
* $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
* only accept expressions that are either literal constants or are the return
* value of {@link ng.$sce#trustAs $sce.trustAs}.)
*/
/**
* @ngdoc method
* @name $sce#trustAsJs
*
* @description
* Shorthand method. `$sce.trustAsJs(value)` →
* {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
*
* @param {*} value The value to trustAs.
* @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
* $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
* only accept expressions that are either literal constants or are the
* return value of {@link ng.$sce#trustAs $sce.trustAs}.)
*/
/**
* @ngdoc method
* @name $sce#getTrusted
*
* @description
* Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
* takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
* originally supplied value if the queried context type is a supertype of the created type.
* If this condition isn't satisfied, throws an exception.
*
* @param {string} type The kind of context in which this value is to be used.
* @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
* call.
* @returns {*} The value the was originally provided to
* {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
* Otherwise, throws an exception.
*/
/**
* @ngdoc method
* @name $sce#getTrustedHtml
*
* @description
* Shorthand method. `$sce.getTrustedHtml(value)` →
* {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
*
* @param {*} value The value to pass to `$sce.getTrusted`.
* @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
*/
/**
* @ngdoc method
* @name $sce#getTrustedCss
*
* @description
* Shorthand method. `$sce.getTrustedCss(value)` →
* {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
*
* @param {*} value The value to pass to `$sce.getTrusted`.
* @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
*/
/**
* @ngdoc method
* @name $sce#getTrustedUrl
*
* @description
* Shorthand method. `$sce.getTrustedUrl(value)` →
* {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
*
* @param {*} value The value to pass to `$sce.getTrusted`.
* @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
*/
/**
* @ngdoc method
* @name $sce#getTrustedResourceUrl
*
* @description
* Shorthand method. `$sce.getTrustedResourceUrl(value)` →
* {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
*
* @param {*} value The value to pass to `$sceDelegate.getTrusted`.
* @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
*/
/**
* @ngdoc method
* @name $sce#getTrustedJs
*
* @description
* Shorthand method. `$sce.getTrustedJs(value)` →
* {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
*
* @param {*} value The value to pass to `$sce.getTrusted`.
* @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
*/
/**
* @ngdoc method
* @name $sce#parseAsHtml
*
* @description
* Shorthand method. `$sce.parseAsHtml(expression string)` →
* {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
*
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context` – `{object}` – an object against which any expressions embedded in the strings
* are evaluated against (typically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*/
/**
* @ngdoc method
* @name $sce#parseAsCss
*
* @description
* Shorthand method. `$sce.parseAsCss(value)` →
* {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
*
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context` – `{object}` – an object against which any expressions embedded in the strings
* are evaluated against (typically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*/
/**
* @ngdoc method
* @name $sce#parseAsUrl
*
* @description
* Shorthand method. `$sce.parseAsUrl(value)` →
* {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
*
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context` – `{object}` – an object against which any expressions embedded in the strings
* are evaluated against (typically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*/
/**
* @ngdoc method
* @name $sce#parseAsResourceUrl
*
* @description
* Shorthand method. `$sce.parseAsResourceUrl(value)` →
* {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
*
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context` – `{object}` – an object against which any expressions embedded in the strings
* are evaluated against (typically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*/
/**
* @ngdoc method
* @name $sce#parseAsJs
*
* @description
* Shorthand method. `$sce.parseAsJs(value)` →
* {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
*
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context` – `{object}` – an object against which any expressions embedded in the strings
* are evaluated against (typically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*/
// Shorthand delegations.
var parse = sce.parseAs,
getTrusted = sce.getTrusted,
trustAs = sce.trustAs;
forEach(SCE_CONTEXTS, function(enumValue, name) {
var lName = lowercase(name);
sce[camelCase("parse_as_" + lName)] = function(expr) {
return parse(enumValue, expr);
};
sce[camelCase("get_trusted_" + lName)] = function(value) {
return getTrusted(enumValue, value);
};
sce[camelCase("trust_as_" + lName)] = function(value) {
return trustAs(enumValue, value);
};
});
return sce;
}];
}
/**
* !!! This is an undocumented "private" service !!!
*
* @name $sniffer
* @requires $window
* @requires $document
*
* @property {boolean} history Does the browser support html5 history api ?
* @property {boolean} transitions Does the browser support CSS transition events ?
* @property {boolean} animations Does the browser support CSS animation events ?
*
* @description
* This is very simple implementation of testing browser's features.
*/
function $SnifferProvider() {
this.$get = ['$window', '$document', function($window, $document) {
var eventSupport = {},
android =
int((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
document = $document[0] || {},
vendorPrefix,
vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/,
bodyStyle = document.body && document.body.style,
transitions = false,
animations = false,
match;
if (bodyStyle) {
for (var prop in bodyStyle) {
if (match = vendorRegex.exec(prop)) {
vendorPrefix = match[0];
vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
break;
}
}
if (!vendorPrefix) {
vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
}
transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
if (android && (!transitions || !animations)) {
transitions = isString(document.body.style.webkitTransition);
animations = isString(document.body.style.webkitAnimation);
}
}
return {
// Android has history.pushState, but it does not update location correctly
// so let's not use the history API at all.
// http://code.google.com/p/android/issues/detail?id=17471
// https://github.com/angular/angular.js/issues/904
// older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
// so let's not use the history API also
// We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
// jshint -W018
history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),
// jshint +W018
hasEvent: function(event) {
// IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
// it. In particular the event is not fired when backspace or delete key are pressed or
// when cut operation is performed.
// IE10+ implements 'input' event but it erroneously fires under various situations,
// e.g. when placeholder changes, or a form is focused.
if (event === 'input' && msie <= 11) return false;
if (isUndefined(eventSupport[event])) {
var divElm = document.createElement('div');
eventSupport[event] = 'on' + event in divElm;
}
return eventSupport[event];
},
csp: csp(),
vendorPrefix: vendorPrefix,
transitions: transitions,
animations: animations,
android: android
};
}];
}
var $compileMinErr = minErr('$compile');
/**
* @ngdoc service
* @name $templateRequest
*
* @description
* The `$templateRequest` service downloads the provided template using `$http` and, upon success,
* stores the contents inside of `$templateCache`. If the HTTP request fails or the response data
* of the HTTP request is empty, a `$compile` error will be thrown (the exception can be thwarted
* by setting the 2nd parameter of the function to true).
*
* @param {string} tpl The HTTP request template URL
* @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
*
* @return {Promise} the HTTP Promise for the given.
*
* @property {number} totalPendingRequests total amount of pending template requests being downloaded.
*/
function $TemplateRequestProvider() {
this.$get = ['$templateCache', '$http', '$q', function($templateCache, $http, $q) {
function handleRequestFn(tpl, ignoreRequestError) {
handleRequestFn.totalPendingRequests++;
var transformResponse = $http.defaults && $http.defaults.transformResponse;
if (isArray(transformResponse)) {
transformResponse = transformResponse.filter(function(transformer) {
return transformer !== defaultHttpResponseTransform;
});
} else if (transformResponse === defaultHttpResponseTransform) {
transformResponse = null;
}
var httpOptions = {
cache: $templateCache,
transformResponse: transformResponse
};
return $http.get(tpl, httpOptions)
['finally'](function() {
handleRequestFn.totalPendingRequests--;
})
.then(function(response) {
return response.data;
}, handleError);
function handleError(resp) {
if (!ignoreRequestError) {
throw $compileMinErr('tpload', 'Failed to load template: {0}', tpl);
}
return $q.reject(resp);
}
}
handleRequestFn.totalPendingRequests = 0;
return handleRequestFn;
}];
}
function $$TestabilityProvider() {
this.$get = ['$rootScope', '$browser', '$location',
function($rootScope, $browser, $location) {
/**
* @name $testability
*
* @description
* The private $$testability service provides a collection of methods for use when debugging
* or by automated test and debugging tools.
*/
var testability = {};
/**
* @name $$testability#findBindings
*
* @description
* Returns an array of elements that are bound (via ng-bind or {{}})
* to expressions matching the input.
*
* @param {Element} element The element root to search from.
* @param {string} expression The binding expression to match.
* @param {boolean} opt_exactMatch If true, only returns exact matches
* for the expression. Filters and whitespace are ignored.
*/
testability.findBindings = function(element, expression, opt_exactMatch) {
var bindings = element.getElementsByClassName('ng-binding');
var matches = [];
forEach(bindings, function(binding) {
var dataBinding = angular.element(binding).data('$binding');
if (dataBinding) {
forEach(dataBinding, function(bindingName) {
if (opt_exactMatch) {
var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
if (matcher.test(bindingName)) {
matches.push(binding);
}
} else {
if (bindingName.indexOf(expression) != -1) {
matches.push(binding);
}
}
});
}
});
return matches;
};
/**
* @name $$testability#findModels
*
* @description
* Returns an array of elements that are two-way found via ng-model to
* expressions matching the input.
*
* @param {Element} element The element root to search from.
* @param {string} expression The model expression to match.
* @param {boolean} opt_exactMatch If true, only returns exact matches
* for the expression.
*/
testability.findModels = function(element, expression, opt_exactMatch) {
var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
for (var p = 0; p < prefixes.length; ++p) {
var attributeEquals = opt_exactMatch ? '=' : '*=';
var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
var elements = element.querySelectorAll(selector);
if (elements.length) {
return elements;
}
}
};
/**
* @name $$testability#getLocation
*
* @description
* Shortcut for getting the location in a browser agnostic way. Returns
* the path, search, and hash. (e.g. /path?a=b#hash)
*/
testability.getLocation = function() {
return $location.url();
};
/**
* @name $$testability#setLocation
*
* @description
* Shortcut for navigating to a location without doing a full page reload.
*
* @param {string} url The location url (path, search and hash,
* e.g. /path?a=b#hash) to go to.
*/
testability.setLocation = function(url) {
if (url !== $location.url()) {
$location.url(url);
$rootScope.$digest();
}
};
/**
* @name $$testability#whenStable
*
* @description
* Calls the callback when $timeout and $http requests are completed.
*
* @param {function} callback
*/
testability.whenStable = function(callback) {
$browser.notifyWhenNoOutstandingRequests(callback);
};
return testability;
}];
}
function $TimeoutProvider() {
this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
function($rootScope, $browser, $q, $$q, $exceptionHandler) {
var deferreds = {};
/**
* @ngdoc service
* @name $timeout
*
* @description
* Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
* block and delegates any exceptions to
* {@link ng.$exceptionHandler $exceptionHandler} service.
*
* The return value of registering a timeout function is a promise, which will be resolved when
* the timeout is reached and the timeout function is executed.
*
* To cancel a timeout request, call `$timeout.cancel(promise)`.
*
* In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
* synchronously flush the queue of deferred functions.
*
* @param {function()} fn A function, whose execution should be delayed.
* @param {number=} [delay=0] Delay in milliseconds.
* @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
* will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
* @returns {Promise} Promise that will be resolved when the timeout is reached. The value this
* promise will be resolved with is the return value of the `fn` function.
*
*/
function timeout(fn, delay, invokeApply) {
var skipApply = (isDefined(invokeApply) && !invokeApply),
deferred = (skipApply ? $$q : $q).defer(),
promise = deferred.promise,
timeoutId;
timeoutId = $browser.defer(function() {
try {
deferred.resolve(fn());
} catch (e) {
deferred.reject(e);
$exceptionHandler(e);
}
finally {
delete deferreds[promise.$$timeoutId];
}
if (!skipApply) $rootScope.$apply();
}, delay);
promise.$$timeoutId = timeoutId;
deferreds[timeoutId] = deferred;
return promise;
}
/**
* @ngdoc method
* @name $timeout#cancel
*
* @description
* Cancels a task associated with the `promise`. As a result of this, the promise will be
* resolved with a rejection.
*
* @param {Promise=} promise Promise returned by the `$timeout` function.
* @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
* canceled.
*/
timeout.cancel = function(promise) {
if (promise && promise.$$timeoutId in deferreds) {
deferreds[promise.$$timeoutId].reject('canceled');
delete deferreds[promise.$$timeoutId];
return $browser.defer.cancel(promise.$$timeoutId);
}
return false;
};
return timeout;
}];
}
// NOTE: The usage of window and document instead of $window and $document here is
// deliberate. This service depends on the specific behavior of anchor nodes created by the
// browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
// cause us to break tests. In addition, when the browser resolves a URL for XHR, it
// doesn't know about mocked locations and resolves URLs to the real document - which is
// exactly the behavior needed here. There is little value is mocking these out for this
// service.
var urlParsingNode = document.createElement("a");
var originUrl = urlResolve(window.location.href);
/**
*
* Implementation Notes for non-IE browsers
* ----------------------------------------
* Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
* results both in the normalizing and parsing of the URL. Normalizing means that a relative
* URL will be resolved into an absolute URL in the context of the application document.
* Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
* properties are all populated to reflect the normalized URL. This approach has wide
* compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
* http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
*
* Implementation Notes for IE
* ---------------------------
* IE >= 8 and <= 10 normalizes the URL when assigned to the anchor node similar to the other
* browsers. However, the parsed components will not be set if the URL assigned did not specify
* them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
* work around that by performing the parsing in a 2nd step by taking a previously normalized
* URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
* properties such as protocol, hostname, port, etc.
*
* IE7 does not normalize the URL when assigned to an anchor node. (Apparently, it does, if one
* uses the inner HTML approach to assign the URL as part of an HTML snippet -
* http://stackoverflow.com/a/472729) However, setting img[src] does normalize the URL.
* Unfortunately, setting img[src] to something like "javascript:foo" on IE throws an exception.
* Since the primary usage for normalizing URLs is to sanitize such URLs, we can't use that
* method and IE < 8 is unsupported.
*
* References:
* http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
* http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
* http://url.spec.whatwg.org/#urlutils
* https://github.com/angular/angular.js/pull/2902
* http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
*
* @kind function
* @param {string} url The URL to be parsed.
* @description Normalizes and parses a URL.
* @returns {object} Returns the normalized URL as a dictionary.
*
* | member name | Description |
* |---------------|----------------|
* | href | A normalized version of the provided URL if it was not an absolute URL |
* | protocol | The protocol including the trailing colon |
* | host | The host and port (if the port is non-default) of the normalizedUrl |
* | search | The search params, minus the question mark |
* | hash | The hash string, minus the hash symbol
* | hostname | The hostname
* | port | The port, without ":"
* | pathname | The pathname, beginning with "/"
*
*/
function urlResolve(url) {
var href = url;
if (msie) {
// Normalize before parse. Refer Implementation Notes on why this is
// done in two steps on IE.
urlParsingNode.setAttribute("href", href);
href = urlParsingNode.href;
}
urlParsingNode.setAttribute('href', href);
// urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
return {
href: urlParsingNode.href,
protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
host: urlParsingNode.host,
search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
hostname: urlParsingNode.hostname,
port: urlParsingNode.port,
pathname: (urlParsingNode.pathname.charAt(0) === '/')
? urlParsingNode.pathname
: '/' + urlParsingNode.pathname
};
}
/**
* Parse a request URL and determine whether this is a same-origin request as the application document.
*
* @param {string|object} requestUrl The url of the request as a string that will be resolved
* or a parsed URL object.
* @returns {boolean} Whether the request is for the same origin as the application document.
*/
function urlIsSameOrigin(requestUrl) {
var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
return (parsed.protocol === originUrl.protocol &&
parsed.host === originUrl.host);
}
/**
* @ngdoc service
* @name $window
*
* @description
* A reference to the browser's `window` object. While `window`
* is globally available in JavaScript, it causes testability problems, because
* it is a global variable. In angular we always refer to it through the
* `$window` service, so it may be overridden, removed or mocked for testing.
*
* Expressions, like the one defined for the `ngClick` directive in the example
* below, are evaluated with respect to the current scope. Therefore, there is
* no risk of inadvertently coding in a dependency on a global value in such an
* expression.
*
* @example
<example module="windowExample">
<file name="index.html">
<script>
angular.module('windowExample', [])
.controller('ExampleController', ['$scope', '$window', function($scope, $window) {
$scope.greeting = 'Hello, World!';
$scope.doGreeting = function(greeting) {
$window.alert(greeting);
};
}]);
</script>
<div ng-controller="ExampleController">
<input type="text" ng-model="greeting" />
<button ng-click="doGreeting(greeting)">ALERT</button>
</div>
</file>
<file name="protractor.js" type="protractor">
it('should display the greeting in the input box', function() {
element(by.model('greeting')).sendKeys('Hello, E2E Tests');
// If we click the button it will block the test runner
// element(':button').click();
});
</file>
</example>
*/
function $WindowProvider() {
this.$get = valueFn(window);
}
/* global currencyFilter: true,
dateFilter: true,
filterFilter: true,
jsonFilter: true,
limitToFilter: true,
lowercaseFilter: true,
numberFilter: true,
orderByFilter: true,
uppercaseFilter: true,
*/
/**
* @ngdoc provider
* @name $filterProvider
* @description
*
* Filters are just functions which transform input to an output. However filters need to be
* Dependency Injected. To achieve this a filter definition consists of a factory function which is
* annotated with dependencies and is responsible for creating a filter function.
*
* ```js
* // Filter registration
* function MyModule($provide, $filterProvider) {
* // create a service to demonstrate injection (not always needed)
* $provide.value('greet', function(name){
* return 'Hello ' + name + '!';
* });
*
* // register a filter factory which uses the
* // greet service to demonstrate DI.
* $filterProvider.register('greet', function(greet){
* // return the filter function which uses the greet service
* // to generate salutation
* return function(text) {
* // filters need to be forgiving so check input validity
* return text && greet(text) || text;
* };
* });
* }
* ```
*
* The filter function is registered with the `$injector` under the filter name suffix with
* `Filter`.
*
* ```js
* it('should be the same instance', inject(
* function($filterProvider) {
* $filterProvider.register('reverse', function(){
* return ...;
* });
* },
* function($filter, reverseFilter) {
* expect($filter('reverse')).toBe(reverseFilter);
* });
* ```
*
*
* For more information about how angular filters work, and how to create your own filters, see
* {@link guide/filter Filters} in the Angular Developer Guide.
*/
/**
* @ngdoc service
* @name $filter
* @kind function
* @description
* Filters are used for formatting data displayed to the user.
*
* The general syntax in templates is as follows:
*
* {{ expression [| filter_name[:parameter_value] ... ] }}
*
* @param {String} name Name of the filter function to retrieve
* @return {Function} the filter function
* @example
<example name="$filter" module="filterExample">
<file name="index.html">
<div ng-controller="MainCtrl">
<h3>{{ originalText }}</h3>
<h3>{{ filteredText }}</h3>
</div>
</file>
<file name="script.js">
angular.module('filterExample', [])
.controller('MainCtrl', function($scope, $filter) {
$scope.originalText = 'hello';
$scope.filteredText = $filter('uppercase')($scope.originalText);
});
</file>
</example>
*/
$FilterProvider.$inject = ['$provide'];
function $FilterProvider($provide) {
var suffix = 'Filter';
/**
* @ngdoc method
* @name $filterProvider#register
* @param {string|Object} name Name of the filter function, or an object map of filters where
* the keys are the filter names and the values are the filter factories.
* @returns {Object} Registered filter instance, or if a map of filters was provided then a map
* of the registered filter instances.
*/
function register(name, factory) {
if (isObject(name)) {
var filters = {};
forEach(name, function(filter, key) {
filters[key] = register(key, filter);
});
return filters;
} else {
return $provide.factory(name + suffix, factory);
}
}
this.register = register;
this.$get = ['$injector', function($injector) {
return function(name) {
return $injector.get(name + suffix);
};
}];
////////////////////////////////////////
/* global
currencyFilter: false,
dateFilter: false,
filterFilter: false,
jsonFilter: false,
limitToFilter: false,
lowercaseFilter: false,
numberFilter: false,
orderByFilter: false,
uppercaseFilter: false,
*/
register('currency', currencyFilter);
register('date', dateFilter);
register('filter', filterFilter);
register('json', jsonFilter);
register('limitTo', limitToFilter);
register('lowercase', lowercaseFilter);
register('number', numberFilter);
register('orderBy', orderByFilter);
register('uppercase', uppercaseFilter);
}
/**
* @ngdoc filter
* @name filter
* @kind function
*
* @description
* Selects a subset of items from `array` and returns it as a new array.
*
* @param {Array} array The source array.
* @param {string|Object|function()} expression The predicate to be used for selecting items from
* `array`.
*
* Can be one of:
*
* - `string`: The string is used for matching against the contents of the `array`. All strings or
* objects with string properties in `array` that match this string will be returned. This also
* applies to nested object properties.
* The predicate can be negated by prefixing the string with `!`.
*
* - `Object`: A pattern object can be used to filter specific properties on objects contained
* by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
* which have property `name` containing "M" and property `phone` containing "1". A special
* property name `$` can be used (as in `{$:"text"}`) to accept a match against any
* property of the object or its nested object properties. That's equivalent to the simple
* substring match with a `string` as described above. The predicate can be negated by prefixing
* the string with `!`.
* For example `{name: "!M"}` predicate will return an array of items which have property `name`
* not containing "M".
*
* Note that a named property will match properties on the same level only, while the special
* `$` property will match properties on the same level or deeper. E.g. an array item like
* `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but
* **will** be matched by `{$: 'John'}`.
*
* - `function(value, index)`: A predicate function can be used to write arbitrary filters. The
* function is called for each element of `array`. The final result is an array of those
* elements that the predicate returned true for.
*
* @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
* determining if the expected value (from the filter expression) and actual value (from
* the object in the array) should be considered a match.
*
* Can be one of:
*
* - `function(actual, expected)`:
* The function will be given the object value and the predicate value to compare and
* should return true if both values should be considered equal.
*
* - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.
* This is essentially strict comparison of expected and actual.
*
* - `false|undefined`: A short hand for a function which will look for a substring match in case
* insensitive way.
*
* @example
<example>
<file name="index.html">
<div ng-init="friends = [{name:'John', phone:'555-1276'},
{name:'Mary', phone:'800-BIG-MARY'},
{name:'Mike', phone:'555-4321'},
{name:'Adam', phone:'555-5678'},
{name:'Julie', phone:'555-8765'},
{name:'Juliette', phone:'555-5678'}]"></div>
Search: <input ng-model="searchText">
<table id="searchTextResults">
<tr><th>Name</th><th>Phone</th></tr>
<tr ng-repeat="friend in friends | filter:searchText">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
</tr>
</table>
<hr>
Any: <input ng-model="search.$"> <br>
Name only <input ng-model="search.name"><br>
Phone only <input ng-model="search.phone"><br>
Equality <input type="checkbox" ng-model="strict"><br>
<table id="searchObjResults">
<tr><th>Name</th><th>Phone</th></tr>
<tr ng-repeat="friendObj in friends | filter:search:strict">
<td>{{friendObj.name}}</td>
<td>{{friendObj.phone}}</td>
</tr>
</table>
</file>
<file name="protractor.js" type="protractor">
var expectFriendNames = function(expectedNames, key) {
element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
arr.forEach(function(wd, i) {
expect(wd.getText()).toMatch(expectedNames[i]);
});
});
};
it('should search across all fields when filtering with a string', function() {
var searchText = element(by.model('searchText'));
searchText.clear();
searchText.sendKeys('m');
expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
searchText.clear();
searchText.sendKeys('76');
expectFriendNames(['John', 'Julie'], 'friend');
});
it('should search in specific fields when filtering with a predicate object', function() {
var searchAny = element(by.model('search.$'));
searchAny.clear();
searchAny.sendKeys('i');
expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
});
it('should use a equal comparison when comparator is true', function() {
var searchName = element(by.model('search.name'));
var strict = element(by.model('strict'));
searchName.clear();
searchName.sendKeys('Julie');
strict.click();
expectFriendNames(['Julie'], 'friendObj');
});
</file>
</example>
*/
function filterFilter() {
return function(array, expression, comparator) {
if (!isArray(array)) return array;
var predicateFn;
var matchAgainstAnyProp;
switch (typeof expression) {
case 'function':
predicateFn = expression;
break;
case 'boolean':
case 'number':
case 'string':
matchAgainstAnyProp = true;
//jshint -W086
case 'object':
//jshint +W086
predicateFn = createPredicateFn(expression, comparator, matchAgainstAnyProp);
break;
default:
return array;
}
return array.filter(predicateFn);
};
}
// Helper functions for `filterFilter`
function createPredicateFn(expression, comparator, matchAgainstAnyProp) {
var shouldMatchPrimitives = isObject(expression) && ('$' in expression);
var predicateFn;
if (comparator === true) {
comparator = equals;
} else if (!isFunction(comparator)) {
comparator = function(actual, expected) {
if (isObject(actual) || isObject(expected)) {
// Prevent an object to be considered equal to a string like `'[object'`
return false;
}
actual = lowercase('' + actual);
expected = lowercase('' + expected);
return actual.indexOf(expected) !== -1;
};
}
predicateFn = function(item) {
if (shouldMatchPrimitives && !isObject(item)) {
return deepCompare(item, expression.$, comparator, false);
}
return deepCompare(item, expression, comparator, matchAgainstAnyProp);
};
return predicateFn;
}
function deepCompare(actual, expected, comparator, matchAgainstAnyProp, dontMatchWholeObject) {
var actualType = (actual !== null) ? typeof actual : 'null';
var expectedType = (expected !== null) ? typeof expected : 'null';
if ((expectedType === 'string') && (expected.charAt(0) === '!')) {
return !deepCompare(actual, expected.substring(1), comparator, matchAgainstAnyProp);
} else if (isArray(actual)) {
// In case `actual` is an array, consider it a match
// if ANY of it's items matches `expected`
return actual.some(function(item) {
return deepCompare(item, expected, comparator, matchAgainstAnyProp);
});
}
switch (actualType) {
case 'object':
var key;
if (matchAgainstAnyProp) {
for (key in actual) {
if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, true)) {
return true;
}
}
return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, false);
} else if (expectedType === 'object') {
for (key in expected) {
var expectedVal = expected[key];
if (isFunction(expectedVal) || isUndefined(expectedVal)) {
continue;
}
var matchAnyProperty = key === '$';
var actualVal = matchAnyProperty ? actual : actual[key];
if (!deepCompare(actualVal, expectedVal, comparator, matchAnyProperty, matchAnyProperty)) {
return false;
}
}
return true;
} else {
return comparator(actual, expected);
}
break;
case 'function':
return false;
default:
return comparator(actual, expected);
}
}
/**
* @ngdoc filter
* @name currency
* @kind function
*
* @description
* Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
* symbol for current locale is used.
*
* @param {number} amount Input to filter.
* @param {string=} symbol Currency symbol or identifier to be displayed.
* @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale
* @returns {string} Formatted number.
*
*
* @example
<example module="currencyExample">
<file name="index.html">
<script>
angular.module('currencyExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.amount = 1234.56;
}]);
</script>
<div ng-controller="ExampleController">
<input type="number" ng-model="amount"> <br>
default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span>
no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
</div>
</file>
<file name="protractor.js" type="protractor">
it('should init with 1234.56', function() {
expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
});
it('should update', function() {
if (browser.params.browser == 'safari') {
// Safari does not understand the minus key. See
// https://github.com/angular/protractor/issues/481
return;
}
element(by.model('amount')).clear();
element(by.model('amount')).sendKeys('-1234');
expect(element(by.id('currency-default')).getText()).toBe('($1,234.00)');
expect(element(by.id('currency-custom')).getText()).toBe('(USD$1,234.00)');
expect(element(by.id('currency-no-fractions')).getText()).toBe('(USD$1,234)');
});
</file>
</example>
*/
currencyFilter.$inject = ['$locale'];
function currencyFilter($locale) {
var formats = $locale.NUMBER_FORMATS;
return function(amount, currencySymbol, fractionSize) {
if (isUndefined(currencySymbol)) {
currencySymbol = formats.CURRENCY_SYM;
}
if (isUndefined(fractionSize)) {
fractionSize = formats.PATTERNS[1].maxFrac;
}
// if null or undefined pass it through
return (amount == null)
? amount
: formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
replace(/\u00A4/g, currencySymbol);
};
}
/**
* @ngdoc filter
* @name number
* @kind function
*
* @description
* Formats a number as text.
*
* If the input is not a number an empty string is returned.
*
* @param {number|string} number Number to format.
* @param {(number|string)=} fractionSize Number of decimal places to round the number to.
* If this is not provided then the fraction size is computed from the current locale's number
* formatting pattern. In the case of the default locale, it will be 3.
* @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
*
* @example
<example module="numberFilterExample">
<file name="index.html">
<script>
angular.module('numberFilterExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.val = 1234.56789;
}]);
</script>
<div ng-controller="ExampleController">
Enter number: <input ng-model='val'><br>
Default formatting: <span id='number-default'>{{val | number}}</span><br>
No fractions: <span>{{val | number:0}}</span><br>
Negative number: <span>{{-val | number:4}}</span>
</div>
</file>
<file name="protractor.js" type="protractor">
it('should format numbers', function() {
expect(element(by.id('number-default')).getText()).toBe('1,234.568');
expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
});
it('should update', function() {
element(by.model('val')).clear();
element(by.model('val')).sendKeys('3374.333');
expect(element(by.id('number-default')).getText()).toBe('3,374.333');
expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
});
</file>
</example>
*/
numberFilter.$inject = ['$locale'];
function numberFilter($locale) {
var formats = $locale.NUMBER_FORMATS;
return function(number, fractionSize) {
// if null or undefined pass it through
return (number == null)
? number
: formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
fractionSize);
};
}
var DECIMAL_SEP = '.';
function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
if (!isFinite(number) || isObject(number)) return '';
var isNegative = number < 0;
number = Math.abs(number);
var numStr = number + '',
formatedText = '',
parts = [];
var hasExponent = false;
if (numStr.indexOf('e') !== -1) {
var match = numStr.match(/([\d\.]+)e(-?)(\d+)/);
if (match && match[2] == '-' && match[3] > fractionSize + 1) {
number = 0;
} else {
formatedText = numStr;
hasExponent = true;
}
}
if (!hasExponent) {
var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
// determine fractionSize if it is not specified
if (isUndefined(fractionSize)) {
fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
}
// safely round numbers in JS without hitting imprecisions of floating-point arithmetics
// inspired by:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize);
var fraction = ('' + number).split(DECIMAL_SEP);
var whole = fraction[0];
fraction = fraction[1] || '';
var i, pos = 0,
lgroup = pattern.lgSize,
group = pattern.gSize;
if (whole.length >= (lgroup + group)) {
pos = whole.length - lgroup;
for (i = 0; i < pos; i++) {
if ((pos - i) % group === 0 && i !== 0) {
formatedText += groupSep;
}
formatedText += whole.charAt(i);
}
}
for (i = pos; i < whole.length; i++) {
if ((whole.length - i) % lgroup === 0 && i !== 0) {
formatedText += groupSep;
}
formatedText += whole.charAt(i);
}
// format fraction part.
while (fraction.length < fractionSize) {
fraction += '0';
}
if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize);
} else {
if (fractionSize > 0 && number < 1) {
formatedText = number.toFixed(fractionSize);
number = parseFloat(formatedText);
}
}
if (number === 0) {
isNegative = false;
}
parts.push(isNegative ? pattern.negPre : pattern.posPre,
formatedText,
isNegative ? pattern.negSuf : pattern.posSuf);
return parts.join('');
}
function padNumber(num, digits, trim) {
var neg = '';
if (num < 0) {
neg = '-';
num = -num;
}
num = '' + num;
while (num.length < digits) num = '0' + num;
if (trim)
num = num.substr(num.length - digits);
return neg + num;
}
function dateGetter(name, size, offset, trim) {
offset = offset || 0;
return function(date) {
var value = date['get' + name]();
if (offset > 0 || value > -offset)
value += offset;
if (value === 0 && offset == -12) value = 12;
return padNumber(value, size, trim);
};
}
function dateStrGetter(name, shortForm) {
return function(date, formats) {
var value = date['get' + name]();
var get = uppercase(shortForm ? ('SHORT' + name) : name);
return formats[get][value];
};
}
function timeZoneGetter(date) {
var zone = -1 * date.getTimezoneOffset();
var paddedZone = (zone >= 0) ? "+" : "";
paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
padNumber(Math.abs(zone % 60), 2);
return paddedZone;
}
function getFirstThursdayOfYear(year) {
// 0 = index of January
var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
// 4 = index of Thursday (+1 to account for 1st = 5)
// 11 = index of *next* Thursday (+1 account for 1st = 12)
return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
}
function getThursdayThisWeek(datetime) {
return new Date(datetime.getFullYear(), datetime.getMonth(),
// 4 = index of Thursday
datetime.getDate() + (4 - datetime.getDay()));
}
function weekGetter(size) {
return function(date) {
var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
thisThurs = getThursdayThisWeek(date);
var diff = +thisThurs - +firstThurs,
result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
return padNumber(result, size);
};
}
function ampmGetter(date, formats) {
return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
}
function eraGetter(date, formats) {
return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];
}
function longEraGetter(date, formats) {
return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];
}
var DATE_FORMATS = {
yyyy: dateGetter('FullYear', 4),
yy: dateGetter('FullYear', 2, 0, true),
y: dateGetter('FullYear', 1),
MMMM: dateStrGetter('Month'),
MMM: dateStrGetter('Month', true),
MM: dateGetter('Month', 2, 1),
M: dateGetter('Month', 1, 1),
dd: dateGetter('Date', 2),
d: dateGetter('Date', 1),
HH: dateGetter('Hours', 2),
H: dateGetter('Hours', 1),
hh: dateGetter('Hours', 2, -12),
h: dateGetter('Hours', 1, -12),
mm: dateGetter('Minutes', 2),
m: dateGetter('Minutes', 1),
ss: dateGetter('Seconds', 2),
s: dateGetter('Seconds', 1),
// while ISO 8601 requires fractions to be prefixed with `.` or `,`
// we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
sss: dateGetter('Milliseconds', 3),
EEEE: dateStrGetter('Day'),
EEE: dateStrGetter('Day', true),
a: ampmGetter,
Z: timeZoneGetter,
ww: weekGetter(2),
w: weekGetter(1),
G: eraGetter,
GG: eraGetter,
GGG: eraGetter,
GGGG: longEraGetter
};
var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,
NUMBER_STRING = /^\-?\d+$/;
/**
* @ngdoc filter
* @name date
* @kind function
*
* @description
* Formats `date` to a string based on the requested `format`.
*
* `format` string can be composed of the following elements:
*
* * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
* * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
* * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
* * `'MMMM'`: Month in year (January-December)
* * `'MMM'`: Month in year (Jan-Dec)
* * `'MM'`: Month in year, padded (01-12)
* * `'M'`: Month in year (1-12)
* * `'dd'`: Day in month, padded (01-31)
* * `'d'`: Day in month (1-31)
* * `'EEEE'`: Day in Week,(Sunday-Saturday)
* * `'EEE'`: Day in Week, (Sun-Sat)
* * `'HH'`: Hour in day, padded (00-23)
* * `'H'`: Hour in day (0-23)
* * `'hh'`: Hour in AM/PM, padded (01-12)
* * `'h'`: Hour in AM/PM, (1-12)
* * `'mm'`: Minute in hour, padded (00-59)
* * `'m'`: Minute in hour (0-59)
* * `'ss'`: Second in minute, padded (00-59)
* * `'s'`: Second in minute (0-59)
* * `'sss'`: Millisecond in second, padded (000-999)
* * `'a'`: AM/PM marker
* * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
* * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year
* * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year
* * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')
* * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')
*
* `format` string can also be one of the following predefined
* {@link guide/i18n localizable formats}:
*
* * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
* (e.g. Sep 3, 2010 12:05:08 PM)
* * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)
* * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale
* (e.g. Friday, September 3, 2010)
* * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
* * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
* * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
* * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
* * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
*
* `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
* `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
* (e.g. `"h 'o''clock'"`).
*
* @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
* number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
* shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
* specified in the string input, the time is considered to be in the local timezone.
* @param {string=} format Formatting rules (see Description). If not specified,
* `mediumDate` is used.
* @param {string=} timezone Timezone to be used for formatting. Right now, only `'UTC'` is supported.
* If not specified, the timezone of the browser will be used.
* @returns {string} Formatted string or the input if input is not recognized as date/millis.
*
* @example
<example>
<file name="index.html">
<span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
<span>{{1288323623006 | date:'medium'}}</span><br>
<span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
<span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
<span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
<span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
<span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
<span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
</file>
<file name="protractor.js" type="protractor">
it('should format date', function() {
expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
});
</file>
</example>
*/
dateFilter.$inject = ['$locale'];
function dateFilter($locale) {
var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
// 1 2 3 4 5 6 7 8 9 10 11
function jsonStringToDate(string) {
var match;
if (match = string.match(R_ISO8601_STR)) {
var date = new Date(0),
tzHour = 0,
tzMin = 0,
dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
timeSetter = match[8] ? date.setUTCHours : date.setHours;
if (match[9]) {
tzHour = int(match[9] + match[10]);
tzMin = int(match[9] + match[11]);
}
dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3]));
var h = int(match[4] || 0) - tzHour;
var m = int(match[5] || 0) - tzMin;
var s = int(match[6] || 0);
var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
timeSetter.call(date, h, m, s, ms);
return date;
}
return string;
}
return function(date, format, timezone) {
var text = '',
parts = [],
fn, match;
format = format || 'mediumDate';
format = $locale.DATETIME_FORMATS[format] || format;
if (isString(date)) {
date = NUMBER_STRING.test(date) ? int(date) : jsonStringToDate(date);
}
if (isNumber(date)) {
date = new Date(date);
}
if (!isDate(date)) {
return date;
}
while (format) {
match = DATE_FORMATS_SPLIT.exec(format);
if (match) {
parts = concat(parts, match, 1);
format = parts.pop();
} else {
parts.push(format);
format = null;
}
}
if (timezone && timezone === 'UTC') {
date = new Date(date.getTime());
date.setMinutes(date.getMinutes() + date.getTimezoneOffset());
}
forEach(parts, function(value) {
fn = DATE_FORMATS[value];
text += fn ? fn(date, $locale.DATETIME_FORMATS)
: value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
});
return text;
};
}
/**
* @ngdoc filter
* @name json
* @kind function
*
* @description
* Allows you to convert a JavaScript object into JSON string.
*
* This filter is mostly useful for debugging. When using the double curly {{value}} notation
* the binding is automatically converted to JSON.
*
* @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
* @param {number=} spacing The number of spaces to use per indentation, defaults to 2.
* @returns {string} JSON string.
*
*
* @example
<example>
<file name="index.html">
<pre id="default-spacing">{{ {'name':'value'} | json }}</pre>
<pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre>
</file>
<file name="protractor.js" type="protractor">
it('should jsonify filtered objects', function() {
expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
});
</file>
</example>
*
*/
function jsonFilter() {
return function(object, spacing) {
if (isUndefined(spacing)) {
spacing = 2;
}
return toJson(object, spacing);
};
}
/**
* @ngdoc filter
* @name lowercase
* @kind function
* @description
* Converts string to lowercase.
* @see angular.lowercase
*/
var lowercaseFilter = valueFn(lowercase);
/**
* @ngdoc filter
* @name uppercase
* @kind function
* @description
* Converts string to uppercase.
* @see angular.uppercase
*/
var uppercaseFilter = valueFn(uppercase);
/**
* @ngdoc filter
* @name limitTo
* @kind function
*
* @description
* Creates a new array or string containing only a specified number of elements. The elements
* are taken from either the beginning or the end of the source array, string or number, as specified by
* the value and sign (positive or negative) of `limit`. If a number is used as input, it is
* converted to a string.
*
* @param {Array|string|number} input Source array, string or number to be limited.
* @param {string|number} limit The length of the returned array or string. If the `limit` number
* is positive, `limit` number of items from the beginning of the source array/string are copied.
* If the number is negative, `limit` number of items from the end of the source array/string
* are copied. The `limit` will be trimmed if it exceeds `array.length`
* @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
* had less than `limit` elements.
*
* @example
<example module="limitToExample">
<file name="index.html">
<script>
angular.module('limitToExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.numbers = [1,2,3,4,5,6,7,8,9];
$scope.letters = "abcdefghi";
$scope.longNumber = 2345432342;
$scope.numLimit = 3;
$scope.letterLimit = 3;
$scope.longNumberLimit = 3;
}]);
</script>
<div ng-controller="ExampleController">
Limit {{numbers}} to: <input type="number" step="1" ng-model="numLimit">
<p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
Limit {{letters}} to: <input type="number" step="1" ng-model="letterLimit">
<p>Output letters: {{ letters | limitTo:letterLimit }}</p>
Limit {{longNumber}} to: <input type="number" step="1" ng-model="longNumberLimit">
<p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
</div>
</file>
<file name="protractor.js" type="protractor">
var numLimitInput = element(by.model('numLimit'));
var letterLimitInput = element(by.model('letterLimit'));
var longNumberLimitInput = element(by.model('longNumberLimit'));
var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
it('should limit the number array to first three items', function() {
expect(numLimitInput.getAttribute('value')).toBe('3');
expect(letterLimitInput.getAttribute('value')).toBe('3');
expect(longNumberLimitInput.getAttribute('value')).toBe('3');
expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
expect(limitedLetters.getText()).toEqual('Output letters: abc');
expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
});
// There is a bug in safari and protractor that doesn't like the minus key
// it('should update the output when -3 is entered', function() {
// numLimitInput.clear();
// numLimitInput.sendKeys('-3');
// letterLimitInput.clear();
// letterLimitInput.sendKeys('-3');
// longNumberLimitInput.clear();
// longNumberLimitInput.sendKeys('-3');
// expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
// expect(limitedLetters.getText()).toEqual('Output letters: ghi');
// expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
// });
it('should not exceed the maximum size of input array', function() {
numLimitInput.clear();
numLimitInput.sendKeys('100');
letterLimitInput.clear();
letterLimitInput.sendKeys('100');
longNumberLimitInput.clear();
longNumberLimitInput.sendKeys('100');
expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
});
</file>
</example>
*/
function limitToFilter() {
return function(input, limit) {
if (isNumber(input)) input = input.toString();
if (!isArray(input) && !isString(input)) return input;
if (Math.abs(Number(limit)) === Infinity) {
limit = Number(limit);
} else {
limit = int(limit);
}
//NaN check on limit
if (limit) {
return limit > 0 ? input.slice(0, limit) : input.slice(limit);
} else {
return isString(input) ? "" : [];
}
};
}
/**
* @ngdoc filter
* @name orderBy
* @kind function
*
* @description
* Orders a specified `array` by the `expression` predicate. It is ordered alphabetically
* for strings and numerically for numbers. Note: if you notice numbers are not being sorted
* correctly, make sure they are actually being saved as numbers and not strings.
*
* @param {Array} array The array to sort.
* @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be
* used by the comparator to determine the order of elements.
*
* Can be one of:
*
* - `function`: Getter function. The result of this function will be sorted using the
* `<`, `=`, `>` operator.
* - `string`: An Angular expression. The result of this expression is used to compare elements
* (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by
* 3 first characters of a property called `name`). The result of a constant expression
* is interpreted as a property name to be used in comparisons (for example `"special name"`
* to sort object by the value of their `special name` property). An expression can be
* optionally prefixed with `+` or `-` to control ascending or descending sort order
* (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array
* element itself is used to compare where sorting.
* - `Array`: An array of function or string predicates. The first predicate in the array
* is used for sorting, but when two items are equivalent, the next predicate is used.
*
* If the predicate is missing or empty then it defaults to `'+'`.
*
* @param {boolean=} reverse Reverse the order of the array.
* @returns {Array} Sorted copy of the source array.
*
*
* @example
* The example below demonstrates a simple ngRepeat, where the data is sorted
* by age in descending order (predicate is set to `'-age'`).
* `reverse` is not set, which means it defaults to `false`.
<example module="orderByExample">
<file name="index.html">
<script>
angular.module('orderByExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.friends =
[{name:'John', phone:'555-1212', age:10},
{name:'Mary', phone:'555-9876', age:19},
{name:'Mike', phone:'555-4321', age:21},
{name:'Adam', phone:'555-5678', age:35},
{name:'Julie', phone:'555-8765', age:29}];
}]);
</script>
<div ng-controller="ExampleController">
<table class="friend">
<tr>
<th>Name</th>
<th>Phone Number</th>
<th>Age</th>
</tr>
<tr ng-repeat="friend in friends | orderBy:'-age'">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<td>{{friend.age}}</td>
</tr>
</table>
</div>
</file>
</example>
*
* The predicate and reverse parameters can be controlled dynamically through scope properties,
* as shown in the next example.
* @example
<example module="orderByExample">
<file name="index.html">
<script>
angular.module('orderByExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.friends =
[{name:'John', phone:'555-1212', age:10},
{name:'Mary', phone:'555-9876', age:19},
{name:'Mike', phone:'555-4321', age:21},
{name:'Adam', phone:'555-5678', age:35},
{name:'Julie', phone:'555-8765', age:29}];
$scope.predicate = '-age';
}]);
</script>
<div ng-controller="ExampleController">
<pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
<hr/>
[ <a href="" ng-click="predicate=''">unsorted</a> ]
<table class="friend">
<tr>
<th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a>
(<a href="" ng-click="predicate = '-name'; reverse=false">^</a>)</th>
<th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th>
<th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th>
</tr>
<tr ng-repeat="friend in friends | orderBy:predicate:reverse">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<td>{{friend.age}}</td>
</tr>
</table>
</div>
</file>
</example>
*
* It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the
* filter routine with `$filter('orderBy')`, and calling the returned filter routine with the
* desired parameters.
*
* Example:
*
* @example
<example module="orderByExample">
<file name="index.html">
<div ng-controller="ExampleController">
<table class="friend">
<tr>
<th><a href="" ng-click="reverse=false;order('name', false)">Name</a>
(<a href="" ng-click="order('-name',false)">^</a>)</th>
<th><a href="" ng-click="reverse=!reverse;order('phone', reverse)">Phone Number</a></th>
<th><a href="" ng-click="reverse=!reverse;order('age',reverse)">Age</a></th>
</tr>
<tr ng-repeat="friend in friends">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<td>{{friend.age}}</td>
</tr>
</table>
</div>
</file>
<file name="script.js">
angular.module('orderByExample', [])
.controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {
var orderBy = $filter('orderBy');
$scope.friends = [
{ name: 'John', phone: '555-1212', age: 10 },
{ name: 'Mary', phone: '555-9876', age: 19 },
{ name: 'Mike', phone: '555-4321', age: 21 },
{ name: 'Adam', phone: '555-5678', age: 35 },
{ name: 'Julie', phone: '555-8765', age: 29 }
];
$scope.order = function(predicate, reverse) {
$scope.friends = orderBy($scope.friends, predicate, reverse);
};
$scope.order('-age',false);
}]);
</file>
</example>
*/
orderByFilter.$inject = ['$parse'];
function orderByFilter($parse) {
return function(array, sortPredicate, reverseOrder) {
if (!(isArrayLike(array))) return array;
sortPredicate = isArray(sortPredicate) ? sortPredicate : [sortPredicate];
if (sortPredicate.length === 0) { sortPredicate = ['+']; }
sortPredicate = sortPredicate.map(function(predicate) {
var descending = false, get = predicate || identity;
if (isString(predicate)) {
if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
descending = predicate.charAt(0) == '-';
predicate = predicate.substring(1);
}
if (predicate === '') {
// Effectively no predicate was passed so we compare identity
return reverseComparator(compare, descending);
}
get = $parse(predicate);
if (get.constant) {
var key = get();
return reverseComparator(function(a, b) {
return compare(a[key], b[key]);
}, descending);
}
}
return reverseComparator(function(a, b) {
return compare(get(a),get(b));
}, descending);
});
return slice.call(array).sort(reverseComparator(comparator, reverseOrder));
function comparator(o1, o2) {
for (var i = 0; i < sortPredicate.length; i++) {
var comp = sortPredicate[i](o1, o2);
if (comp !== 0) return comp;
}
return 0;
}
function reverseComparator(comp, descending) {
return descending
? function(a, b) {return comp(b,a);}
: comp;
}
function isPrimitive(value) {
switch (typeof value) {
case 'number': /* falls through */
case 'boolean': /* falls through */
case 'string':
return true;
default:
return false;
}
}
function objectToString(value) {
if (value === null) return 'null';
if (typeof value.valueOf === 'function') {
value = value.valueOf();
if (isPrimitive(value)) return value;
}
if (typeof value.toString === 'function') {
value = value.toString();
if (isPrimitive(value)) return value;
}
return '';
}
function compare(v1, v2) {
var t1 = typeof v1;
var t2 = typeof v2;
if (t1 === t2 && t1 === "object") {
v1 = objectToString(v1);
v2 = objectToString(v2);
}
if (t1 === t2) {
if (t1 === "string") {
v1 = v1.toLowerCase();
v2 = v2.toLowerCase();
}
if (v1 === v2) return 0;
return v1 < v2 ? -1 : 1;
} else {
return t1 < t2 ? -1 : 1;
}
}
};
}
function ngDirective(directive) {
if (isFunction(directive)) {
directive = {
link: directive
};
}
directive.restrict = directive.restrict || 'AC';
return valueFn(directive);
}
/**
* @ngdoc directive
* @name a
* @restrict E
*
* @description
* Modifies the default behavior of the html A tag so that the default action is prevented when
* the href attribute is empty.
*
* This change permits the easy creation of action links with the `ngClick` directive
* without changing the location or causing page reloads, e.g.:
* `<a href="" ng-click="list.addItem()">Add Item</a>`
*/
var htmlAnchorDirective = valueFn({
restrict: 'E',
compile: function(element, attr) {
if (!attr.href && !attr.xlinkHref && !attr.name) {
return function(scope, element) {
// If the linked element is not an anchor tag anymore, do nothing
if (element[0].nodeName.toLowerCase() !== 'a') return;
// SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
'xlink:href' : 'href';
element.on('click', function(event) {
// if we have no href url, then don't navigate anywhere.
if (!element.attr(href)) {
event.preventDefault();
}
});
};
}
}
});
/**
* @ngdoc directive
* @name ngHref
* @restrict A
* @priority 99
*
* @description
* Using Angular markup like `{{hash}}` in an href attribute will
* make the link go to the wrong URL if the user clicks it before
* Angular has a chance to replace the `{{hash}}` markup with its
* value. Until Angular replaces the markup the link will be broken
* and will most likely return a 404 error. The `ngHref` directive
* solves this problem.
*
* The wrong way to write it:
* ```html
* <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
* ```
*
* The correct way to write it:
* ```html
* <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
* ```
*
* @element A
* @param {template} ngHref any string which can contain `{{}}` markup.
*
* @example
* This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
* in links and their different behaviors:
<example>
<file name="index.html">
<input ng-model="value" /><br />
<a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
<a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
<a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
<a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
<a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
<a id="link-6" ng-href="{{value}}">link</a> (link, change location)
</file>
<file name="protractor.js" type="protractor">
it('should execute ng-click but not reload when href without value', function() {
element(by.id('link-1')).click();
expect(element(by.model('value')).getAttribute('value')).toEqual('1');
expect(element(by.id('link-1')).getAttribute('href')).toBe('');
});
it('should execute ng-click but not reload when href empty string', function() {
element(by.id('link-2')).click();
expect(element(by.model('value')).getAttribute('value')).toEqual('2');
expect(element(by.id('link-2')).getAttribute('href')).toBe('');
});
it('should execute ng-click and change url when ng-href specified', function() {
expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
element(by.id('link-3')).click();
// At this point, we navigate away from an Angular page, so we need
// to use browser.driver to get the base webdriver.
browser.wait(function() {
return browser.driver.getCurrentUrl().then(function(url) {
return url.match(/\/123$/);
});
}, 5000, 'page should navigate to /123');
});
xit('should execute ng-click but not reload when href empty string and name specified', function() {
element(by.id('link-4')).click();
expect(element(by.model('value')).getAttribute('value')).toEqual('4');
expect(element(by.id('link-4')).getAttribute('href')).toBe('');
});
it('should execute ng-click but not reload when no href but name specified', function() {
element(by.id('link-5')).click();
expect(element(by.model('value')).getAttribute('value')).toEqual('5');
expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
});
it('should only change url when only ng-href', function() {
element(by.model('value')).clear();
element(by.model('value')).sendKeys('6');
expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
element(by.id('link-6')).click();
// At this point, we navigate away from an Angular page, so we need
// to use browser.driver to get the base webdriver.
browser.wait(function() {
return browser.driver.getCurrentUrl().then(function(url) {
return url.match(/\/6$/);
});
}, 5000, 'page should navigate to /6');
});
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngSrc
* @restrict A
* @priority 99
*
* @description
* Using Angular markup like `{{hash}}` in a `src` attribute doesn't
* work right: The browser will fetch from the URL with the literal
* text `{{hash}}` until Angular replaces the expression inside
* `{{hash}}`. The `ngSrc` directive solves this problem.
*
* The buggy way to write it:
* ```html
* <img src="http://www.gravatar.com/avatar/{{hash}}"/>
* ```
*
* The correct way to write it:
* ```html
* <img ng-src="http://www.gravatar.com/avatar/{{hash}}"/>
* ```
*
* @element IMG
* @param {template} ngSrc any string which can contain `{{}}` markup.
*/
/**
* @ngdoc directive
* @name ngSrcset
* @restrict A
* @priority 99
*
* @description
* Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
* work right: The browser will fetch from the URL with the literal
* text `{{hash}}` until Angular replaces the expression inside
* `{{hash}}`. The `ngSrcset` directive solves this problem.
*
* The buggy way to write it:
* ```html
* <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/>
* ```
*
* The correct way to write it:
* ```html
* <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/>
* ```
*
* @element IMG
* @param {template} ngSrcset any string which can contain `{{}}` markup.
*/
/**
* @ngdoc directive
* @name ngDisabled
* @restrict A
* @priority 100
*
* @description
*
* This directive sets the `disabled` attribute on the element if the
* {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.
*
* A special directive is necessary because we cannot use interpolation inside the `disabled`
* attribute. The following example would make the button enabled on Chrome/Firefox
* but not on older IEs:
*
* ```html
* <!-- See below for an example of ng-disabled being used correctly -->
* <div ng-init="isDisabled = false">
* <button disabled="{{isDisabled}}">Disabled</button>
* </div>
* ```
*
* This is because the HTML specification does not require browsers to preserve the values of
* boolean attributes such as `disabled` (Their presence means true and their absence means false.)
* If we put an Angular interpolation expression into such an attribute then the
* binding information would be lost when the browser removes the attribute.
*
* @example
<example>
<file name="index.html">
Click me to toggle: <input type="checkbox" ng-model="checked"><br/>
<button ng-model="button" ng-disabled="checked">Button</button>
</file>
<file name="protractor.js" type="protractor">
it('should toggle button', function() {
expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
element(by.model('checked')).click();
expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
});
</file>
</example>
*
* @element INPUT
* @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
* then the `disabled` attribute will be set on the element
*/
/**
* @ngdoc directive
* @name ngChecked
* @restrict A
* @priority 100
*
* @description
* The HTML specification does not require browsers to preserve the values of boolean attributes
* such as checked. (Their presence means true and their absence means false.)
* If we put an Angular interpolation expression into such an attribute then the
* binding information would be lost when the browser removes the attribute.
* The `ngChecked` directive solves this problem for the `checked` attribute.
* This complementary directive is not removed by the browser and so provides
* a permanent reliable place to store the binding information.
* @example
<example>
<file name="index.html">
Check me to check both: <input type="checkbox" ng-model="master"><br/>
<input id="checkSlave" type="checkbox" ng-checked="master">
</file>
<file name="protractor.js" type="protractor">
it('should check both checkBoxes', function() {
expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
element(by.model('master')).click();
expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
});
</file>
</example>
*
* @element INPUT
* @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
* then special attribute "checked" will be set on the element
*/
/**
* @ngdoc directive
* @name ngReadonly
* @restrict A
* @priority 100
*
* @description
* The HTML specification does not require browsers to preserve the values of boolean attributes
* such as readonly. (Their presence means true and their absence means false.)
* If we put an Angular interpolation expression into such an attribute then the
* binding information would be lost when the browser removes the attribute.
* The `ngReadonly` directive solves this problem for the `readonly` attribute.
* This complementary directive is not removed by the browser and so provides
* a permanent reliable place to store the binding information.
* @example
<example>
<file name="index.html">
Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/>
<input type="text" ng-readonly="checked" value="I'm Angular"/>
</file>
<file name="protractor.js" type="protractor">
it('should toggle readonly attr', function() {
expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
element(by.model('checked')).click();
expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
});
</file>
</example>
*
* @element INPUT
* @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
* then special attribute "readonly" will be set on the element
*/
/**
* @ngdoc directive
* @name ngSelected
* @restrict A
* @priority 100
*
* @description
* The HTML specification does not require browsers to preserve the values of boolean attributes
* such as selected. (Their presence means true and their absence means false.)
* If we put an Angular interpolation expression into such an attribute then the
* binding information would be lost when the browser removes the attribute.
* The `ngSelected` directive solves this problem for the `selected` attribute.
* This complementary directive is not removed by the browser and so provides
* a permanent reliable place to store the binding information.
*
* @example
<example>
<file name="index.html">
Check me to select: <input type="checkbox" ng-model="selected"><br/>
<select>
<option>Hello!</option>
<option id="greet" ng-selected="selected">Greetings!</option>
</select>
</file>
<file name="protractor.js" type="protractor">
it('should select Greetings!', function() {
expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
element(by.model('selected')).click();
expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
});
</file>
</example>
*
* @element OPTION
* @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
* then special attribute "selected" will be set on the element
*/
/**
* @ngdoc directive
* @name ngOpen
* @restrict A
* @priority 100
*
* @description
* The HTML specification does not require browsers to preserve the values of boolean attributes
* such as open. (Their presence means true and their absence means false.)
* If we put an Angular interpolation expression into such an attribute then the
* binding information would be lost when the browser removes the attribute.
* The `ngOpen` directive solves this problem for the `open` attribute.
* This complementary directive is not removed by the browser and so provides
* a permanent reliable place to store the binding information.
* @example
<example>
<file name="index.html">
Check me check multiple: <input type="checkbox" ng-model="open"><br/>
<details id="details" ng-open="open">
<summary>Show/Hide me</summary>
</details>
</file>
<file name="protractor.js" type="protractor">
it('should toggle open', function() {
expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
element(by.model('open')).click();
expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
});
</file>
</example>
*
* @element DETAILS
* @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
* then special attribute "open" will be set on the element
*/
var ngAttributeAliasDirectives = {};
// boolean attrs are evaluated
forEach(BOOLEAN_ATTR, function(propName, attrName) {
// binding to multiple is not supported
if (propName == "multiple") return;
var normalized = directiveNormalize('ng-' + attrName);
ngAttributeAliasDirectives[normalized] = function() {
return {
restrict: 'A',
priority: 100,
link: function(scope, element, attr) {
scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
attr.$set(attrName, !!value);
});
}
};
};
});
// aliased input attrs are evaluated
forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
ngAttributeAliasDirectives[ngAttr] = function() {
return {
priority: 100,
link: function(scope, element, attr) {
//special case ngPattern when a literal regular expression value
//is used as the expression (this way we don't have to watch anything).
if (ngAttr === "ngPattern" && attr.ngPattern.charAt(0) == "/") {
var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
if (match) {
attr.$set("ngPattern", new RegExp(match[1], match[2]));
return;
}
}
scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
attr.$set(ngAttr, value);
});
}
};
};
});
// ng-src, ng-srcset, ng-href are interpolated
forEach(['src', 'srcset', 'href'], function(attrName) {
var normalized = directiveNormalize('ng-' + attrName);
ngAttributeAliasDirectives[normalized] = function() {
return {
priority: 99, // it needs to run after the attributes are interpolated
link: function(scope, element, attr) {
var propName = attrName,
name = attrName;
if (attrName === 'href' &&
toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
name = 'xlinkHref';
attr.$attr[name] = 'xlink:href';
propName = null;
}
attr.$observe(normalized, function(value) {
if (!value) {
if (attrName === 'href') {
attr.$set(name, null);
}
return;
}
attr.$set(name, value);
// on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
// then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
// to set the property as well to achieve the desired effect.
// we use attr[attrName] value since $set can sanitize the url.
if (msie && propName) element.prop(propName, attr[name]);
});
}
};
};
});
/* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true
*/
var nullFormCtrl = {
$addControl: noop,
$$renameControl: nullFormRenameControl,
$removeControl: noop,
$setValidity: noop,
$setDirty: noop,
$setPristine: noop,
$setSubmitted: noop
},
SUBMITTED_CLASS = 'ng-submitted';
function nullFormRenameControl(control, name) {
control.$name = name;
}
/**
* @ngdoc type
* @name form.FormController
*
* @property {boolean} $pristine True if user has not interacted with the form yet.
* @property {boolean} $dirty True if user has already interacted with the form.
* @property {boolean} $valid True if all of the containing forms and controls are valid.
* @property {boolean} $invalid True if at least one containing control or form is invalid.
* @property {boolean} $submitted True if user has submitted the form even if its invalid.
*
* @property {Object} $error Is an object hash, containing references to controls or
* forms with failing validators, where:
*
* - keys are validation tokens (error names),
* - values are arrays of controls or forms that have a failing validator for given error name.
*
* Built-in validation tokens:
*
* - `email`
* - `max`
* - `maxlength`
* - `min`
* - `minlength`
* - `number`
* - `pattern`
* - `required`
* - `url`
* - `date`
* - `datetimelocal`
* - `time`
* - `week`
* - `month`
*
* @description
* `FormController` keeps track of all its controls and nested forms as well as the state of them,
* such as being valid/invalid or dirty/pristine.
*
* Each {@link ng.directive:form form} directive creates an instance
* of `FormController`.
*
*/
//asks for $scope to fool the BC controller module
FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
function FormController(element, attrs, $scope, $animate, $interpolate) {
var form = this,
controls = [];
var parentForm = form.$$parentForm = element.parent().controller('form') || nullFormCtrl;
// init state
form.$error = {};
form.$$success = {};
form.$pending = undefined;
form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope);
form.$dirty = false;
form.$pristine = true;
form.$valid = true;
form.$invalid = false;
form.$submitted = false;
parentForm.$addControl(form);
/**
* @ngdoc method
* @name form.FormController#$rollbackViewValue
*
* @description
* Rollback all form controls pending updates to the `$modelValue`.
*
* Updates may be pending by a debounced event or because the input is waiting for a some future
* event defined in `ng-model-options`. This method is typically needed by the reset button of
* a form that uses `ng-model-options` to pend updates.
*/
form.$rollbackViewValue = function() {
forEach(controls, function(control) {
control.$rollbackViewValue();
});
};
/**
* @ngdoc method
* @name form.FormController#$commitViewValue
*
* @description
* Commit all form controls pending updates to the `$modelValue`.
*
* Updates may be pending by a debounced event or because the input is waiting for a some future
* event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
* usually handles calling this in response to input events.
*/
form.$commitViewValue = function() {
forEach(controls, function(control) {
control.$commitViewValue();
});
};
/**
* @ngdoc method
* @name form.FormController#$addControl
*
* @description
* Register a control with the form.
*
* Input elements using ngModelController do this automatically when they are linked.
*/
form.$addControl = function(control) {
// Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
// and not added to the scope. Now we throw an error.
assertNotHasOwnProperty(control.$name, 'input');
controls.push(control);
if (control.$name) {
form[control.$name] = control;
}
};
// Private API: rename a form control
form.$$renameControl = function(control, newName) {
var oldName = control.$name;
if (form[oldName] === control) {
delete form[oldName];
}
form[newName] = control;
control.$name = newName;
};
/**
* @ngdoc method
* @name form.FormController#$removeControl
*
* @description
* Deregister a control from the form.
*
* Input elements using ngModelController do this automatically when they are destroyed.
*/
form.$removeControl = function(control) {
if (control.$name && form[control.$name] === control) {
delete form[control.$name];
}
forEach(form.$pending, function(value, name) {
form.$setValidity(name, null, control);
});
forEach(form.$error, function(value, name) {
form.$setValidity(name, null, control);
});
forEach(form.$$success, function(value, name) {
form.$setValidity(name, null, control);
});
arrayRemove(controls, control);
};
/**
* @ngdoc method
* @name form.FormController#$setValidity
*
* @description
* Sets the validity of a form control.
*
* This method will also propagate to parent forms.
*/
addSetValidityMethod({
ctrl: this,
$element: element,
set: function(object, property, controller) {
var list = object[property];
if (!list) {
object[property] = [controller];
} else {
var index = list.indexOf(controller);
if (index === -1) {
list.push(controller);
}
}
},
unset: function(object, property, controller) {
var list = object[property];
if (!list) {
return;
}
arrayRemove(list, controller);
if (list.length === 0) {
delete object[property];
}
},
parentForm: parentForm,
$animate: $animate
});
/**
* @ngdoc method
* @name form.FormController#$setDirty
*
* @description
* Sets the form to a dirty state.
*
* This method can be called to add the 'ng-dirty' class and set the form to a dirty
* state (ng-dirty class). This method will also propagate to parent forms.
*/
form.$setDirty = function() {
$animate.removeClass(element, PRISTINE_CLASS);
$animate.addClass(element, DIRTY_CLASS);
form.$dirty = true;
form.$pristine = false;
parentForm.$setDirty();
};
/**
* @ngdoc method
* @name form.FormController#$setPristine
*
* @description
* Sets the form to its pristine state.
*
* This method can be called to remove the 'ng-dirty' class and set the form to its pristine
* state (ng-pristine class). This method will also propagate to all the controls contained
* in this form.
*
* Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
* saving or resetting it.
*/
form.$setPristine = function() {
$animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
form.$dirty = false;
form.$pristine = true;
form.$submitted = false;
forEach(controls, function(control) {
control.$setPristine();
});
};
/**
* @ngdoc method
* @name form.FormController#$setUntouched
*
* @description
* Sets the form to its untouched state.
*
* This method can be called to remove the 'ng-touched' class and set the form controls to their
* untouched state (ng-untouched class).
*
* Setting a form controls back to their untouched state is often useful when setting the form
* back to its pristine state.
*/
form.$setUntouched = function() {
forEach(controls, function(control) {
control.$setUntouched();
});
};
/**
* @ngdoc method
* @name form.FormController#$setSubmitted
*
* @description
* Sets the form to its submitted state.
*/
form.$setSubmitted = function() {
$animate.addClass(element, SUBMITTED_CLASS);
form.$submitted = true;
parentForm.$setSubmitted();
};
}
/**
* @ngdoc directive
* @name ngForm
* @restrict EAC
*
* @description
* Nestable alias of {@link ng.directive:form `form`} directive. HTML
* does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
* sub-group of controls needs to be determined.
*
* Note: the purpose of `ngForm` is to group controls,
* but not to be a replacement for the `<form>` tag with all of its capabilities
* (e.g. posting to the server, ...).
*
* @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
* related scope, under this name.
*
*/
/**
* @ngdoc directive
* @name form
* @restrict E
*
* @description
* Directive that instantiates
* {@link form.FormController FormController}.
*
* If the `name` attribute is specified, the form controller is published onto the current scope under
* this name.
*
* # Alias: {@link ng.directive:ngForm `ngForm`}
*
* In Angular, forms can be nested. This means that the outer form is valid when all of the child
* forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
* Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to
* `<form>` but can be nested. This allows you to have nested forms, which is very useful when
* using Angular validation directives in forms that are dynamically generated using the
* {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name`
* attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an
* `ngForm` directive and nest these in an outer `form` element.
*
*
* # CSS classes
* - `ng-valid` is set if the form is valid.
* - `ng-invalid` is set if the form is invalid.
* - `ng-pristine` is set if the form is pristine.
* - `ng-dirty` is set if the form is dirty.
* - `ng-submitted` is set if the form was submitted.
*
* Keep in mind that ngAnimate can detect each of these classes when added and removed.
*
*
* # Submitting a form and preventing the default action
*
* Since the role of forms in client-side Angular applications is different than in classical
* roundtrip apps, it is desirable for the browser not to translate the form submission into a full
* page reload that sends the data to the server. Instead some javascript logic should be triggered
* to handle the form submission in an application-specific way.
*
* For this reason, Angular prevents the default action (form submission to the server) unless the
* `<form>` element has an `action` attribute specified.
*
* You can use one of the following two ways to specify what javascript method should be called when
* a form is submitted:
*
* - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
* - {@link ng.directive:ngClick ngClick} directive on the first
* button or input field of type submit (input[type=submit])
*
* To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
* or {@link ng.directive:ngClick ngClick} directives.
* This is because of the following form submission rules in the HTML specification:
*
* - If a form has only one input field then hitting enter in this field triggers form submit
* (`ngSubmit`)
* - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
* doesn't trigger submit
* - if a form has one or more input fields and one or more buttons or input[type=submit] then
* hitting enter in any of the input fields will trigger the click handler on the *first* button or
* input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
*
* Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
* submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
* to have access to the updated model.
*
* ## Animation Hooks
*
* Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
* These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
* other validations that are performed within the form. Animations in ngForm are similar to how
* they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
* as JS animations.
*
* The following example shows a simple way to utilize CSS transitions to style a form element
* that has been rendered as invalid after it has been validated:
*
* <pre>
* //be sure to include ngAnimate as a module to hook into more
* //advanced animations
* .my-form {
* transition:0.5s linear all;
* background: white;
* }
* .my-form.ng-invalid {
* background: red;
* color:white;
* }
* </pre>
*
* @example
<example deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
<file name="index.html">
<script>
angular.module('formExample', [])
.controller('FormController', ['$scope', function($scope) {
$scope.userType = 'guest';
}]);
</script>
<style>
.my-form {
-webkit-transition:all linear 0.5s;
transition:all linear 0.5s;
background: transparent;
}
.my-form.ng-invalid {
background: red;
}
</style>
<form name="myForm" ng-controller="FormController" class="my-form">
userType: <input name="input" ng-model="userType" required>
<span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
<tt>userType = {{userType}}</tt><br>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
</form>
</file>
<file name="protractor.js" type="protractor">
it('should initialize to model', function() {
var userType = element(by.binding('userType'));
var valid = element(by.binding('myForm.input.$valid'));
expect(userType.getText()).toContain('guest');
expect(valid.getText()).toContain('true');
});
it('should be invalid if empty', function() {
var userType = element(by.binding('userType'));
var valid = element(by.binding('myForm.input.$valid'));
var userInput = element(by.model('userType'));
userInput.clear();
userInput.sendKeys('');
expect(userType.getText()).toEqual('userType =');
expect(valid.getText()).toContain('false');
});
</file>
</example>
*
* @param {string=} name Name of the form. If specified, the form controller will be published into
* related scope, under this name.
*/
var formDirectiveFactory = function(isNgForm) {
return ['$timeout', function($timeout) {
var formDirective = {
name: 'form',
restrict: isNgForm ? 'EAC' : 'E',
controller: FormController,
compile: function ngFormCompile(formElement, attr) {
// Setup initial state of the control
formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);
return {
pre: function ngFormPreLink(scope, formElement, attr, controller) {
// if `action` attr is not present on the form, prevent the default action (submission)
if (!('action' in attr)) {
// we can't use jq events because if a form is destroyed during submission the default
// action is not prevented. see #1238
//
// IE 9 is not affected because it doesn't fire a submit event and try to do a full
// page reload if the form was destroyed by submission of the form via a click handler
// on a button in the form. Looks like an IE9 specific bug.
var handleFormSubmission = function(event) {
scope.$apply(function() {
controller.$commitViewValue();
controller.$setSubmitted();
});
event.preventDefault();
};
addEventListenerFn(formElement[0], 'submit', handleFormSubmission);
// unregister the preventDefault listener so that we don't not leak memory but in a
// way that will achieve the prevention of the default action.
formElement.on('$destroy', function() {
$timeout(function() {
removeEventListenerFn(formElement[0], 'submit', handleFormSubmission);
}, 0, false);
});
}
var parentFormCtrl = controller.$$parentForm;
if (nameAttr) {
setter(scope, null, controller.$name, controller, controller.$name);
attr.$observe(nameAttr, function(newValue) {
if (controller.$name === newValue) return;
setter(scope, null, controller.$name, undefined, controller.$name);
parentFormCtrl.$$renameControl(controller, newValue);
setter(scope, null, controller.$name, controller, controller.$name);
});
}
formElement.on('$destroy', function() {
parentFormCtrl.$removeControl(controller);
if (nameAttr) {
setter(scope, null, attr[nameAttr], undefined, controller.$name);
}
extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
});
}
};
}
};
return formDirective;
}];
};
var formDirective = formDirectiveFactory();
var ngFormDirective = formDirectiveFactory(true);
/* global VALID_CLASS: false,
INVALID_CLASS: false,
PRISTINE_CLASS: false,
DIRTY_CLASS: false,
UNTOUCHED_CLASS: false,
TOUCHED_CLASS: false,
$ngModelMinErr: false,
*/
// Regex code is obtained from SO: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
var ISO_DATE_REGEXP = /\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/;
var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/;
var DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})$/;
var DATETIMELOCAL_REGEXP = /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
var WEEK_REGEXP = /^(\d{4})-W(\d\d)$/;
var MONTH_REGEXP = /^(\d{4})-(\d\d)$/;
var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
var inputType = {
/**
* @ngdoc input
* @name input[text]
*
* @description
* Standard HTML text input with angular data binding, inherited by most of the `input` elements.
*
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Adds `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
* any length.
* @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
* that contains the regular expression body that will be converted to a regular expression
* as in the ngPattern directive.
* @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
* a RegExp found by evaluating the Angular expression given in the attribute value.
* If the expression evaluates to a RegExp object then this is used directly.
* If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$`
* characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
* @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
* This parameter is ignored for input[type=password] controls, which will never trim the
* input.
*
* @example
<example name="text-input-directive" module="textInputExample">
<file name="index.html">
<script>
angular.module('textInputExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.example = {
text: 'guest',
word: /^\s*\w*\s*$/
};
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
Single word: <input type="text" name="input" ng-model="example.text"
ng-pattern="example.word" required ng-trim="false">
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.pattern">
Single word only!</span>
<tt>text = {{example.text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var text = element(by.binding('example.text'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('example.text'));
it('should initialize to model', function() {
expect(text.getText()).toContain('guest');
expect(valid.getText()).toContain('true');
});
it('should be invalid if empty', function() {
input.clear();
input.sendKeys('');
expect(text.getText()).toEqual('text =');
expect(valid.getText()).toContain('false');
});
it('should be invalid if multi word', function() {
input.clear();
input.sendKeys('hello world');
expect(valid.getText()).toContain('false');
});
</file>
</example>
*/
'text': textInputType,
/**
* @ngdoc input
* @name input[date]
*
* @description
* Input with date validation and transformation. In browsers that do not yet support
* the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
* date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
* modern browsers do not yet support this input type, it is important to provide cues to users on the
* expected input format via a placeholder or label.
*
* The model must always be a Date object, otherwise Angular will throw an error.
* Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
*
* The timezone to be used to read/write the `Date` instance in the model can be defined using
* {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
* valid ISO date string (yyyy-MM-dd).
* @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
* a valid ISO date string (yyyy-MM-dd).
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="date-input-directive" module="dateInputExample">
<file name="index.html">
<script>
angular.module('dateInputExample', [])
.controller('DateController', ['$scope', function($scope) {
$scope.example = {
value: new Date(2013, 9, 22)
};
}]);
</script>
<form name="myForm" ng-controller="DateController as dateCtrl">
Pick a date in 2013:
<input type="date" id="exampleInput" name="input" ng-model="example.value"
placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.date">
Not a valid date!</span>
<tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var value = element(by.binding('example.value | date: "yyyy-MM-dd"'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('example.value'));
// currently protractor/webdriver does not support
// sending keys to all known HTML5 input controls
// for various browsers (see https://github.com/angular/protractor/issues/562).
function setInput(val) {
// set the value of the element and force validation.
var scr = "var ipt = document.getElementById('exampleInput'); " +
"ipt.value = '" + val + "';" +
"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
browser.executeScript(scr);
}
it('should initialize to model', function() {
expect(value.getText()).toContain('2013-10-22');
expect(valid.getText()).toContain('myForm.input.$valid = true');
});
it('should be invalid if empty', function() {
setInput('');
expect(value.getText()).toEqual('value =');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
it('should be invalid if over max', function() {
setInput('2015-01-01');
expect(value.getText()).toContain('');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
</file>
</example>
*/
'date': createDateInputType('date', DATE_REGEXP,
createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
'yyyy-MM-dd'),
/**
* @ngdoc input
* @name input[datetime-local]
*
* @description
* Input with datetime validation and transformation. In browsers that do not yet support
* the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
* local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
*
* The model must always be a Date object, otherwise Angular will throw an error.
* Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
*
* The timezone to be used to read/write the `Date` instance in the model can be defined using
* {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
* valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).
* @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
* a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="datetimelocal-input-directive" module="dateExample">
<file name="index.html">
<script>
angular.module('dateExample', [])
.controller('DateController', ['$scope', function($scope) {
$scope.example = {
value: new Date(2010, 11, 28, 14, 57)
};
}]);
</script>
<form name="myForm" ng-controller="DateController as dateCtrl">
Pick a date between in 2013:
<input type="datetime-local" id="exampleInput" name="input" ng-model="example.value"
placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.datetimelocal">
Not a valid date!</span>
<tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('example.value'));
// currently protractor/webdriver does not support
// sending keys to all known HTML5 input controls
// for various browsers (https://github.com/angular/protractor/issues/562).
function setInput(val) {
// set the value of the element and force validation.
var scr = "var ipt = document.getElementById('exampleInput'); " +
"ipt.value = '" + val + "';" +
"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
browser.executeScript(scr);
}
it('should initialize to model', function() {
expect(value.getText()).toContain('2010-12-28T14:57:00');
expect(valid.getText()).toContain('myForm.input.$valid = true');
});
it('should be invalid if empty', function() {
setInput('');
expect(value.getText()).toEqual('value =');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
it('should be invalid if over max', function() {
setInput('2015-01-01T23:59:00');
expect(value.getText()).toContain('');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
</file>
</example>
*/
'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
'yyyy-MM-ddTHH:mm:ss.sss'),
/**
* @ngdoc input
* @name input[time]
*
* @description
* Input with time validation and transformation. In browsers that do not yet support
* the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
* local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
* Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
*
* The model must always be a Date object, otherwise Angular will throw an error.
* Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
*
* The timezone to be used to read/write the `Date` instance in the model can be defined using
* {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
* valid ISO time format (HH:mm:ss).
* @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be a
* valid ISO time format (HH:mm:ss).
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="time-input-directive" module="timeExample">
<file name="index.html">
<script>
angular.module('timeExample', [])
.controller('DateController', ['$scope', function($scope) {
$scope.example = {
value: new Date(1970, 0, 1, 14, 57, 0)
};
}]);
</script>
<form name="myForm" ng-controller="DateController as dateCtrl">
Pick a between 8am and 5pm:
<input type="time" id="exampleInput" name="input" ng-model="example.value"
placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.time">
Not a valid date!</span>
<tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var value = element(by.binding('example.value | date: "HH:mm:ss"'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('example.value'));
// currently protractor/webdriver does not support
// sending keys to all known HTML5 input controls
// for various browsers (https://github.com/angular/protractor/issues/562).
function setInput(val) {
// set the value of the element and force validation.
var scr = "var ipt = document.getElementById('exampleInput'); " +
"ipt.value = '" + val + "';" +
"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
browser.executeScript(scr);
}
it('should initialize to model', function() {
expect(value.getText()).toContain('14:57:00');
expect(valid.getText()).toContain('myForm.input.$valid = true');
});
it('should be invalid if empty', function() {
setInput('');
expect(value.getText()).toEqual('value =');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
it('should be invalid if over max', function() {
setInput('23:59:00');
expect(value.getText()).toContain('');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
</file>
</example>
*/
'time': createDateInputType('time', TIME_REGEXP,
createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
'HH:mm:ss.sss'),
/**
* @ngdoc input
* @name input[week]
*
* @description
* Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
* the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
* week format (yyyy-W##), for example: `2013-W02`.
*
* The model must always be a Date object, otherwise Angular will throw an error.
* Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
*
* The timezone to be used to read/write the `Date` instance in the model can be defined using
* {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
* valid ISO week format (yyyy-W##).
* @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
* a valid ISO week format (yyyy-W##).
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="week-input-directive" module="weekExample">
<file name="index.html">
<script>
angular.module('weekExample', [])
.controller('DateController', ['$scope', function($scope) {
$scope.example = {
value: new Date(2013, 0, 3)
};
}]);
</script>
<form name="myForm" ng-controller="DateController as dateCtrl">
Pick a date between in 2013:
<input id="exampleInput" type="week" name="input" ng-model="example.value"
placeholder="YYYY-W##" min="2012-W32" max="2013-W52" required />
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.week">
Not a valid date!</span>
<tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var value = element(by.binding('example.value | date: "yyyy-Www"'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('example.value'));
// currently protractor/webdriver does not support
// sending keys to all known HTML5 input controls
// for various browsers (https://github.com/angular/protractor/issues/562).
function setInput(val) {
// set the value of the element and force validation.
var scr = "var ipt = document.getElementById('exampleInput'); " +
"ipt.value = '" + val + "';" +
"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
browser.executeScript(scr);
}
it('should initialize to model', function() {
expect(value.getText()).toContain('2013-W01');
expect(valid.getText()).toContain('myForm.input.$valid = true');
});
it('should be invalid if empty', function() {
setInput('');
expect(value.getText()).toEqual('value =');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
it('should be invalid if over max', function() {
setInput('2015-W01');
expect(value.getText()).toContain('');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
</file>
</example>
*/
'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
/**
* @ngdoc input
* @name input[month]
*
* @description
* Input with month validation and transformation. In browsers that do not yet support
* the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
* month format (yyyy-MM), for example: `2009-01`.
*
* The model must always be a Date object, otherwise Angular will throw an error.
* Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
* If the model is not set to the first of the month, the next view to model update will set it
* to the first of the month.
*
* The timezone to be used to read/write the `Date` instance in the model can be defined using
* {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be
* a valid ISO month format (yyyy-MM).
* @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must
* be a valid ISO month format (yyyy-MM).
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="month-input-directive" module="monthExample">
<file name="index.html">
<script>
angular.module('monthExample', [])
.controller('DateController', ['$scope', function($scope) {
$scope.example = {
value: new Date(2013, 9, 1)
};
}]);
</script>
<form name="myForm" ng-controller="DateController as dateCtrl">
Pick a month in 2013:
<input id="exampleInput" type="month" name="input" ng-model="example.value"
placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.month">
Not a valid month!</span>
<tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var value = element(by.binding('example.value | date: "yyyy-MM"'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('example.value'));
// currently protractor/webdriver does not support
// sending keys to all known HTML5 input controls
// for various browsers (https://github.com/angular/protractor/issues/562).
function setInput(val) {
// set the value of the element and force validation.
var scr = "var ipt = document.getElementById('exampleInput'); " +
"ipt.value = '" + val + "';" +
"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
browser.executeScript(scr);
}
it('should initialize to model', function() {
expect(value.getText()).toContain('2013-10');
expect(valid.getText()).toContain('myForm.input.$valid = true');
});
it('should be invalid if empty', function() {
setInput('');
expect(value.getText()).toEqual('value =');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
it('should be invalid if over max', function() {
setInput('2015-01');
expect(value.getText()).toContain('');
expect(valid.getText()).toContain('myForm.input.$valid = false');
});
</file>
</example>
*/
'month': createDateInputType('month', MONTH_REGEXP,
createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
'yyyy-MM'),
/**
* @ngdoc input
* @name input[number]
*
* @description
* Text input with number validation and transformation. Sets the `number` validation
* error if not a valid number.
*
* The model must always be a number, otherwise Angular will throw an error.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
* @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
* any length.
* @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
* that contains the regular expression body that will be converted to a regular expression
* as in the ngPattern directive.
* @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
* a RegExp found by evaluating the Angular expression given in the attribute value.
* If the expression evaluates to a RegExp object then this is used directly.
* If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$`
* characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="number-input-directive" module="numberExample">
<file name="index.html">
<script>
angular.module('numberExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.example = {
value: 12
};
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
Number: <input type="number" name="input" ng-model="example.value"
min="0" max="99" required>
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.number">
Not valid number!</span>
<tt>value = {{example.value}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var value = element(by.binding('example.value'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('example.value'));
it('should initialize to model', function() {
expect(value.getText()).toContain('12');
expect(valid.getText()).toContain('true');
});
it('should be invalid if empty', function() {
input.clear();
input.sendKeys('');
expect(value.getText()).toEqual('value =');
expect(valid.getText()).toContain('false');
});
it('should be invalid if over max', function() {
input.clear();
input.sendKeys('123');
expect(value.getText()).toEqual('value =');
expect(valid.getText()).toContain('false');
});
</file>
</example>
*/
'number': numberInputType,
/**
* @ngdoc input
* @name input[url]
*
* @description
* Text input with URL validation. Sets the `url` validation error key if the content is not a
* valid URL.
*
* <div class="alert alert-warning">
* **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
* used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
* the built-in validators (see the {@link guide/forms Forms guide})
* </div>
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
* any length.
* @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
* that contains the regular expression body that will be converted to a regular expression
* as in the ngPattern directive.
* @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
* a RegExp found by evaluating the Angular expression given in the attribute value.
* If the expression evaluates to a RegExp object then this is used directly.
* If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$`
* characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="url-input-directive" module="urlExample">
<file name="index.html">
<script>
angular.module('urlExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.url = {
text: 'http://google.com'
};
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
URL: <input type="url" name="input" ng-model="url.text" required>
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.url">
Not valid url!</span>
<tt>text = {{url.text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var text = element(by.binding('url.text'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('url.text'));
it('should initialize to model', function() {
expect(text.getText()).toContain('http://google.com');
expect(valid.getText()).toContain('true');
});
it('should be invalid if empty', function() {
input.clear();
input.sendKeys('');
expect(text.getText()).toEqual('text =');
expect(valid.getText()).toContain('false');
});
it('should be invalid if not url', function() {
input.clear();
input.sendKeys('box');
expect(valid.getText()).toContain('false');
});
</file>
</example>
*/
'url': urlInputType,
/**
* @ngdoc input
* @name input[email]
*
* @description
* Text input with email validation. Sets the `email` validation error key if not a valid email
* address.
*
* <div class="alert alert-warning">
* **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
* used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
* use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
* </div>
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
* any length.
* @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
* that contains the regular expression body that will be converted to a regular expression
* as in the ngPattern directive.
* @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
* a RegExp found by evaluating the Angular expression given in the attribute value.
* If the expression evaluates to a RegExp object then this is used directly.
* If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$`
* characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="email-input-directive" module="emailExample">
<file name="index.html">
<script>
angular.module('emailExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.email = {
text: 'me@example.com'
};
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
Email: <input type="email" name="input" ng-model="email.text" required>
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.email">
Not valid email!</span>
<tt>text = {{email.text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
var text = element(by.binding('email.text'));
var valid = element(by.binding('myForm.input.$valid'));
var input = element(by.model('email.text'));
it('should initialize to model', function() {
expect(text.getText()).toContain('me@example.com');
expect(valid.getText()).toContain('true');
});
it('should be invalid if empty', function() {
input.clear();
input.sendKeys('');
expect(text.getText()).toEqual('text =');
expect(valid.getText()).toContain('false');
});
it('should be invalid if not email', function() {
input.clear();
input.sendKeys('xxx');
expect(valid.getText()).toContain('false');
});
</file>
</example>
*/
'email': emailInputType,
/**
* @ngdoc input
* @name input[radio]
*
* @description
* HTML radio button.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string} value The value to which the expression should be set when selected.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
* @param {string} ngValue Angular expression which sets the value to which the expression should
* be set when selected.
*
* @example
<example name="radio-input-directive" module="radioExample">
<file name="index.html">
<script>
angular.module('radioExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.color = {
name: 'blue'
};
$scope.specialValue = {
"id": "12345",
"value": "green"
};
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
<input type="radio" ng-model="color.name" value="red"> Red <br/>
<input type="radio" ng-model="color.name" ng-value="specialValue"> Green <br/>
<input type="radio" ng-model="color.name" value="blue"> Blue <br/>
<tt>color = {{color.name | json}}</tt><br/>
</form>
Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
</file>
<file name="protractor.js" type="protractor">
it('should change state', function() {
var color = element(by.binding('color.name'));
expect(color.getText()).toContain('blue');
element.all(by.model('color.name')).get(0).click();
expect(color.getText()).toContain('red');
});
</file>
</example>
*/
'radio': radioInputType,
/**
* @ngdoc input
* @name input[checkbox]
*
* @description
* HTML checkbox.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {expression=} ngTrueValue The value to which the expression should be set when selected.
* @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<example name="checkbox-input-directive" module="checkboxExample">
<file name="index.html">
<script>
angular.module('checkboxExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.checkboxModel = {
value1 : true,
value2 : 'YES'
};
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
Value1: <input type="checkbox" ng-model="checkboxModel.value1"> <br/>
Value2: <input type="checkbox" ng-model="checkboxModel.value2"
ng-true-value="'YES'" ng-false-value="'NO'"> <br/>
<tt>value1 = {{checkboxModel.value1}}</tt><br/>
<tt>value2 = {{checkboxModel.value2}}</tt><br/>
</form>
</file>
<file name="protractor.js" type="protractor">
it('should change state', function() {
var value1 = element(by.binding('checkboxModel.value1'));
var value2 = element(by.binding('checkboxModel.value2'));
expect(value1.getText()).toContain('true');
expect(value2.getText()).toContain('YES');
element(by.model('checkboxModel.value1')).click();
element(by.model('checkboxModel.value2')).click();
expect(value1.getText()).toContain('false');
expect(value2.getText()).toContain('NO');
});
</file>
</example>
*/
'checkbox': checkboxInputType,
'hidden': noop,
'button': noop,
'submit': noop,
'reset': noop,
'file': noop
};
function stringBasedInputType(ctrl) {
ctrl.$formatters.push(function(value) {
return ctrl.$isEmpty(value) ? value : value.toString();
});
}
function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
stringBasedInputType(ctrl);
}
function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
var type = lowercase(element[0].type);
// In composition mode, users are still inputing intermediate text buffer,
// hold the listener until composition is done.
// More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
if (!$sniffer.android) {
var composing = false;
element.on('compositionstart', function(data) {
composing = true;
});
element.on('compositionend', function() {
composing = false;
listener();
});
}
var listener = function(ev) {
if (timeout) {
$browser.defer.cancel(timeout);
timeout = null;
}
if (composing) return;
var value = element.val(),
event = ev && ev.type;
// By default we will trim the value
// If the attribute ng-trim exists we will avoid trimming
// If input type is 'password', the value is never trimmed
if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
value = trim(value);
}
// If a control is suffering from bad input (due to native validators), browsers discard its
// value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
// control's value is the same empty value twice in a row.
if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
ctrl.$setViewValue(value, event);
}
};
// if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
// input event on backspace, delete or cut
if ($sniffer.hasEvent('input')) {
element.on('input', listener);
} else {
var timeout;
var deferListener = function(ev, input, origValue) {
if (!timeout) {
timeout = $browser.defer(function() {
timeout = null;
if (!input || input.value !== origValue) {
listener(ev);
}
});
}
};
element.on('keydown', function(event) {
var key = event.keyCode;
// ignore
// command modifiers arrows
if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
deferListener(event, this, this.value);
});
// if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
if ($sniffer.hasEvent('paste')) {
element.on('paste cut', deferListener);
}
}
// if user paste into input using mouse on older browser
// or form autocomplete on newer browser, we need "change" event to catch it
element.on('change', listener);
ctrl.$render = function() {
element.val(ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue);
};
}
function weekParser(isoWeek, existingDate) {
if (isDate(isoWeek)) {
return isoWeek;
}
if (isString(isoWeek)) {
WEEK_REGEXP.lastIndex = 0;
var parts = WEEK_REGEXP.exec(isoWeek);
if (parts) {
var year = +parts[1],
week = +parts[2],
hours = 0,
minutes = 0,
seconds = 0,
milliseconds = 0,
firstThurs = getFirstThursdayOfYear(year),
addDays = (week - 1) * 7;
if (existingDate) {
hours = existingDate.getHours();
minutes = existingDate.getMinutes();
seconds = existingDate.getSeconds();
milliseconds = existingDate.getMilliseconds();
}
return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
}
}
return NaN;
}
function createDateParser(regexp, mapping) {
return function(iso, date) {
var parts, map;
if (isDate(iso)) {
return iso;
}
if (isString(iso)) {
// When a date is JSON'ified to wraps itself inside of an extra
// set of double quotes. This makes the date parsing code unable
// to match the date string and parse it as a date.
if (iso.charAt(0) == '"' && iso.charAt(iso.length - 1) == '"') {
iso = iso.substring(1, iso.length - 1);
}
if (ISO_DATE_REGEXP.test(iso)) {
return new Date(iso);
}
regexp.lastIndex = 0;
parts = regexp.exec(iso);
if (parts) {
parts.shift();
if (date) {
map = {
yyyy: date.getFullYear(),
MM: date.getMonth() + 1,
dd: date.getDate(),
HH: date.getHours(),
mm: date.getMinutes(),
ss: date.getSeconds(),
sss: date.getMilliseconds() / 1000
};
} else {
map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
}
forEach(parts, function(part, index) {
if (index < mapping.length) {
map[mapping[index]] = +part;
}
});
return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
}
}
return NaN;
};
}
function createDateInputType(type, regexp, parseDate, format) {
return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
badInputChecker(scope, element, attr, ctrl);
baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
var timezone = ctrl && ctrl.$options && ctrl.$options.timezone;
var previousDate;
ctrl.$$parserName = type;
ctrl.$parsers.push(function(value) {
if (ctrl.$isEmpty(value)) return null;
if (regexp.test(value)) {
// Note: We cannot read ctrl.$modelValue, as there might be a different
// parser/formatter in the processing chain so that the model
// contains some different data format!
var parsedDate = parseDate(value, previousDate);
if (timezone === 'UTC') {
parsedDate.setMinutes(parsedDate.getMinutes() - parsedDate.getTimezoneOffset());
}
return parsedDate;
}
return undefined;
});
ctrl.$formatters.push(function(value) {
if (value && !isDate(value)) {
throw $ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
}
if (isValidDate(value)) {
previousDate = value;
if (previousDate && timezone === 'UTC') {
var timezoneOffset = 60000 * previousDate.getTimezoneOffset();
previousDate = new Date(previousDate.getTime() + timezoneOffset);
}
return $filter('date')(value, format, timezone);
} else {
previousDate = null;
return '';
}
});
if (isDefined(attr.min) || attr.ngMin) {
var minVal;
ctrl.$validators.min = function(value) {
return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
};
attr.$observe('min', function(val) {
minVal = parseObservedDateValue(val);
ctrl.$validate();
});
}
if (isDefined(attr.max) || attr.ngMax) {
var maxVal;
ctrl.$validators.max = function(value) {
return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
};
attr.$observe('max', function(val) {
maxVal = parseObservedDateValue(val);
ctrl.$validate();
});
}
function isValidDate(value) {
// Invalid Date: getTime() returns NaN
return value && !(value.getTime && value.getTime() !== value.getTime());
}
function parseObservedDateValue(val) {
return isDefined(val) ? (isDate(val) ? val : parseDate(val)) : undefined;
}
};
}
function badInputChecker(scope, element, attr, ctrl) {
var node = element[0];
var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
if (nativeValidation) {
ctrl.$parsers.push(function(value) {
var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
// Detect bug in FF35 for input[email] (https://bugzilla.mozilla.org/show_bug.cgi?id=1064430):
// - also sets validity.badInput (should only be validity.typeMismatch).
// - see http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#e-mail-state-(type=email)
// - can ignore this case as we can still read out the erroneous email...
return validity.badInput && !validity.typeMismatch ? undefined : value;
});
}
}
function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
badInputChecker(scope, element, attr, ctrl);
baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
ctrl.$$parserName = 'number';
ctrl.$parsers.push(function(value) {
if (ctrl.$isEmpty(value)) return null;
if (NUMBER_REGEXP.test(value)) return parseFloat(value);
return undefined;
});
ctrl.$formatters.push(function(value) {
if (!ctrl.$isEmpty(value)) {
if (!isNumber(value)) {
throw $ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
}
value = value.toString();
}
return value;
});
if (isDefined(attr.min) || attr.ngMin) {
var minVal;
ctrl.$validators.min = function(value) {
return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
};
attr.$observe('min', function(val) {
if (isDefined(val) && !isNumber(val)) {
val = parseFloat(val, 10);
}
minVal = isNumber(val) && !isNaN(val) ? val : undefined;
// TODO(matsko): implement validateLater to reduce number of validations
ctrl.$validate();
});
}
if (isDefined(attr.max) || attr.ngMax) {
var maxVal;
ctrl.$validators.max = function(value) {
return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
};
attr.$observe('max', function(val) {
if (isDefined(val) && !isNumber(val)) {
val = parseFloat(val, 10);
}
maxVal = isNumber(val) && !isNaN(val) ? val : undefined;
// TODO(matsko): implement validateLater to reduce number of validations
ctrl.$validate();
});
}
}
function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
// Note: no badInputChecker here by purpose as `url` is only a validation
// in browsers, i.e. we can always read out input.value even if it is not valid!
baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
stringBasedInputType(ctrl);
ctrl.$$parserName = 'url';
ctrl.$validators.url = function(modelValue, viewValue) {
var value = modelValue || viewValue;
return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
};
}
function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
// Note: no badInputChecker here by purpose as `url` is only a validation
// in browsers, i.e. we can always read out input.value even if it is not valid!
baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
stringBasedInputType(ctrl);
ctrl.$$parserName = 'email';
ctrl.$validators.email = function(modelValue, viewValue) {
var value = modelValue || viewValue;
return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
};
}
function radioInputType(scope, element, attr, ctrl) {
// make the name unique, if not defined
if (isUndefined(attr.name)) {
element.attr('name', nextUid());
}
var listener = function(ev) {
if (element[0].checked) {
ctrl.$setViewValue(attr.value, ev && ev.type);
}
};
element.on('click', listener);
ctrl.$render = function() {
var value = attr.value;
element[0].checked = (value == ctrl.$viewValue);
};
attr.$observe('value', ctrl.$render);
}
function parseConstantExpr($parse, context, name, expression, fallback) {
var parseFn;
if (isDefined(expression)) {
parseFn = $parse(expression);
if (!parseFn.constant) {
throw minErr('ngModel')('constexpr', 'Expected constant expression for `{0}`, but saw ' +
'`{1}`.', name, expression);
}
return parseFn(context);
}
return fallback;
}
function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
var listener = function(ev) {
ctrl.$setViewValue(element[0].checked, ev && ev.type);
};
element.on('click', listener);
ctrl.$render = function() {
element[0].checked = ctrl.$viewValue;
};
// Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
// This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
// it to a boolean.
ctrl.$isEmpty = function(value) {
return value === false;
};
ctrl.$formatters.push(function(value) {
return equals(value, trueValue);
});
ctrl.$parsers.push(function(value) {
return value ? trueValue : falseValue;
});
}
/**
* @ngdoc directive
* @name textarea
* @restrict E
*
* @description
* HTML textarea element control with angular data-binding. The data-binding and validation
* properties of this element are exactly the same as those of the
* {@link ng.directive:input input element}.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
* length.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
* @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
*/
/**
* @ngdoc directive
* @name input
* @restrict E
*
* @description
* HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
* input state control, and validation.
* Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
*
* <div class="alert alert-warning">
* **Note:** Not every feature offered is available for all input types.
* Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
* </div>
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {boolean=} ngRequired Sets `required` attribute if set to true
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
* length.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
* @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
* This parameter is ignored for input[type=password] controls, which will never trim the
* input.
*
* @example
<example name="input-directive" module="inputExample">
<file name="index.html">
<script>
angular.module('inputExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.user = {name: 'guest', last: 'visitor'};
}]);
</script>
<div ng-controller="ExampleController">
<form name="myForm">
User name: <input type="text" name="userName" ng-model="user.name" required>
<span class="error" ng-show="myForm.userName.$error.required">
Required!</span><br>
Last name: <input type="text" name="lastName" ng-model="user.last"
ng-minlength="3" ng-maxlength="10">
<span class="error" ng-show="myForm.lastName.$error.minlength">
Too short!</span>
<span class="error" ng-show="myForm.lastName.$error.maxlength">
Too long!</span><br>
</form>
<hr>
<tt>user = {{user}}</tt><br/>
<tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br>
<tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br>
<tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br>
<tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
<tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br>
<tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br>
</div>
</file>
<file name="protractor.js" type="protractor">
var user = element(by.exactBinding('user'));
var userNameValid = element(by.binding('myForm.userName.$valid'));
var lastNameValid = element(by.binding('myForm.lastName.$valid'));
var lastNameError = element(by.binding('myForm.lastName.$error'));
var formValid = element(by.binding('myForm.$valid'));
var userNameInput = element(by.model('user.name'));
var userLastInput = element(by.model('user.last'));
it('should initialize to model', function() {
expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
expect(userNameValid.getText()).toContain('true');
expect(formValid.getText()).toContain('true');
});
it('should be invalid if empty when required', function() {
userNameInput.clear();
userNameInput.sendKeys('');
expect(user.getText()).toContain('{"last":"visitor"}');
expect(userNameValid.getText()).toContain('false');
expect(formValid.getText()).toContain('false');
});
it('should be valid if empty when min length is set', function() {
userLastInput.clear();
userLastInput.sendKeys('');
expect(user.getText()).toContain('{"name":"guest","last":""}');
expect(lastNameValid.getText()).toContain('true');
expect(formValid.getText()).toContain('true');
});
it('should be invalid if less than required min length', function() {
userLastInput.clear();
userLastInput.sendKeys('xx');
expect(user.getText()).toContain('{"name":"guest"}');
expect(lastNameValid.getText()).toContain('false');
expect(lastNameError.getText()).toContain('minlength');
expect(formValid.getText()).toContain('false');
});
it('should be invalid if longer than max length', function() {
userLastInput.clear();
userLastInput.sendKeys('some ridiculously long name');
expect(user.getText()).toContain('{"name":"guest"}');
expect(lastNameValid.getText()).toContain('false');
expect(lastNameError.getText()).toContain('maxlength');
expect(formValid.getText()).toContain('false');
});
</file>
</example>
*/
var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
function($browser, $sniffer, $filter, $parse) {
return {
restrict: 'E',
require: ['?ngModel'],
link: {
pre: function(scope, element, attr, ctrls) {
if (ctrls[0]) {
(inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
$browser, $filter, $parse);
}
}
}
};
}];
var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
/**
* @ngdoc directive
* @name ngValue
*
* @description
* Binds the given expression to the value of `<option>` or {@link input[radio] `input[radio]`},
* so that when the element is selected, the {@link ngModel `ngModel`} of that element is set to
* the bound value.
*
* `ngValue` is useful when dynamically generating lists of radio buttons using
* {@link ngRepeat `ngRepeat`}, as shown below.
*
* Likewise, `ngValue` can be used to generate `<option>` elements for
* the {@link select `select`} element. In that case however, only strings are supported
* for the `value `attribute, so the resulting `ngModel` will always be a string.
* Support for `select` models with non-string values is available via `ngOptions`.
*
* @element input
* @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
* of the `input` element
*
* @example
<example name="ngValue-directive" module="valueExample">
<file name="index.html">
<script>
angular.module('valueExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.names = ['pizza', 'unicorns', 'robots'];
$scope.my = { favorite: 'unicorns' };
}]);
</script>
<form ng-controller="ExampleController">
<h2>Which is your favorite?</h2>
<label ng-repeat="name in names" for="{{name}}">
{{name}}
<input type="radio"
ng-model="my.favorite"
ng-value="name"
id="{{name}}"
name="favorite">
</label>
<div>You chose {{my.favorite}}</div>
</form>
</file>
<file name="protractor.js" type="protractor">
var favorite = element(by.binding('my.favorite'));
it('should initialize to model', function() {
expect(favorite.getText()).toContain('unicorns');
});
it('should bind the values to the inputs', function() {
element.all(by.model('my.favorite')).get(0).click();
expect(favorite.getText()).toContain('pizza');
});
</file>
</example>
*/
var ngValueDirective = function() {
return {
restrict: 'A',
priority: 100,
compile: function(tpl, tplAttr) {
if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
return function ngValueConstantLink(scope, elm, attr) {
attr.$set('value', scope.$eval(attr.ngValue));
};
} else {
return function ngValueLink(scope, elm, attr) {
scope.$watch(attr.ngValue, function valueWatchAction(value) {
attr.$set('value', value);
});
};
}
}
};
};
/**
* @ngdoc directive
* @name ngBind
* @restrict AC
*
* @description
* The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
* with the value of a given expression, and to update the text content when the value of that
* expression changes.
*
* Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
* `{{ expression }}` which is similar but less verbose.
*
* It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
* displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
* element attribute, it makes the bindings invisible to the user while the page is loading.
*
* An alternative solution to this problem would be using the
* {@link ng.directive:ngCloak ngCloak} directive.
*
*
* @element ANY
* @param {expression} ngBind {@link guide/expression Expression} to guide.
*
* @example
* Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
<example module="bindExample">
<file name="index.html">
<script>
angular.module('bindExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.name = 'Whirled';
}]);
</script>
<div ng-controller="ExampleController">
Enter name: <input type="text" ng-model="name"><br>
Hello <span ng-bind="name"></span>!
</div>
</file>
<file name="protractor.js" type="protractor">
it('should check ng-bind', function() {
var nameInput = element(by.model('name'));
expect(element(by.binding('name')).getText()).toBe('Whirled');
nameInput.clear();
nameInput.sendKeys('world');
expect(element(by.binding('name')).getText()).toBe('world');
});
</file>
</example>
*/
var ngBindDirective = ['$compile', function($compile) {
return {
restrict: 'AC',
compile: function ngBindCompile(templateElement) {
$compile.$$addBindingClass(templateElement);
return function ngBindLink(scope, element, attr) {
$compile.$$addBindingInfo(element, attr.ngBind);
element = element[0];
scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
element.textContent = value === undefined ? '' : value;
});
};
}
};
}];
/**
* @ngdoc directive
* @name ngBindTemplate
*
* @description
* The `ngBindTemplate` directive specifies that the element
* text content should be replaced with the interpolation of the template
* in the `ngBindTemplate` attribute.
* Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
* expressions. This directive is needed since some HTML elements
* (such as TITLE and OPTION) cannot contain SPAN elements.
*
* @element ANY
* @param {string} ngBindTemplate template of form
* <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
*
* @example
* Try it here: enter text in text box and watch the greeting change.
<example module="bindExample">
<file name="index.html">
<script>
angular.module('bindExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.salutation = 'Hello';
$scope.name = 'World';
}]);
</script>
<div ng-controller="ExampleController">
Salutation: <input type="text" ng-model="salutation"><br>
Name: <input type="text" ng-model="name"><br>
<pre ng-bind-template="{{salutation}} {{name}}!"></pre>
</div>
</file>
<file name="protractor.js" type="protractor">
it('should check ng-bind', function() {
var salutationElem = element(by.binding('salutation'));
var salutationInput = element(by.model('salutation'));
var nameInput = element(by.model('name'));
expect(salutationElem.getText()).toBe('Hello World!');
salutationInput.clear();
salutationInput.sendKeys('Greetings');
nameInput.clear();
nameInput.sendKeys('user');
expect(salutationElem.getText()).toBe('Greetings user!');
});
</file>
</example>
*/
var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
return {
compile: function ngBindTemplateCompile(templateElement) {
$compile.$$addBindingClass(templateElement);
return function ngBindTemplateLink(scope, element, attr) {
var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
$compile.$$addBindingInfo(element, interpolateFn.expressions);
element = element[0];
attr.$observe('ngBindTemplate', function(value) {
element.textContent = value === undefined ? '' : value;
});
};
}
};
}];
/**
* @ngdoc directive
* @name ngBindHtml
*
* @description
* Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
* the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
* To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
* ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
* in your module's dependencies, you need to include "angular-sanitize.js" in your application.
*
* You may also bypass sanitization for values you know are safe. To do so, bind to
* an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
* under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
*
* Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
* will have an exception (instead of an exploit.)
*
* @element ANY
* @param {expression} ngBindHtml {@link guide/expression Expression} to guide.
*
* @example
<example module="bindHtmlExample" deps="angular-sanitize.js">
<file name="index.html">
<div ng-controller="ExampleController">
<p ng-bind-html="myHTML"></p>
</div>
</file>
<file name="script.js">
angular.module('bindHtmlExample', ['ngSanitize'])
.controller('ExampleController', ['$scope', function($scope) {
$scope.myHTML =
'I am an <code>HTML</code>string with ' +
'<a href="#">links!</a> and other <em>stuff</em>';
}]);
</file>
<file name="protractor.js" type="protractor">
it('should check ng-bind-html', function() {
expect(element(by.binding('myHTML')).getText()).toBe(
'I am an HTMLstring with links! and other stuff');
});
</file>
</example>
*/
var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
return {
restrict: 'A',
compile: function ngBindHtmlCompile(tElement, tAttrs) {
var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function getStringValue(value) {
return (value || '').toString();
});
$compile.$$addBindingClass(tElement);
return function ngBindHtmlLink(scope, element, attr) {
$compile.$$addBindingInfo(element, attr.ngBindHtml);
scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
// we re-guide the expr because we want a TrustedValueHolderType
// for $sce, not a string
element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || '');
});
};
}
};
}];
/**
* @ngdoc directive
* @name ngChange
*
* @description
* Evaluate the given expression when the user changes the input.
* The expression is evaluated immediately, unlike the JavaScript onchange event
* which only triggers at the end of a change (usually, when the user leaves the
* form element or presses the return key).
*
* The `ngChange` expression is only evaluated when a change in the input value causes
* a new value to be committed to the model.
*
* It will not be evaluated:
* * if the value returned from the `$parsers` transformation pipeline has not changed
* * if the input has continued to be invalid since the model will stay `null`
* * if the model is changed programmatically and not by a change to the input value
*
*
* Note, this directive requires `ngModel` to be present.
*
* @element input
* @param {expression} ngChange {@link guide/expression Expression} to guide upon change
* in input value.
*
* @example
* <example name="ngChange-directive" module="changeExample">
* <file name="index.html">
* <script>
* angular.module('changeExample', [])
* .controller('ExampleController', ['$scope', function($scope) {
* $scope.counter = 0;
* $scope.change = function() {
* $scope.counter++;
* };
* }]);
* </script>
* <div ng-controller="ExampleController">
* <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
* <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
* <label for="ng-change-example2">Confirmed</label><br />
* <tt>debug = {{confirmed}}</tt><br/>
* <tt>counter = {{counter}}</tt><br/>
* </div>
* </file>
* <file name="protractor.js" type="protractor">
* var counter = element(by.binding('counter'));
* var debug = element(by.binding('confirmed'));
*
* it('should guide the expression if changing from view', function() {
* expect(counter.getText()).toContain('0');
*
* element(by.id('ng-change-example1')).click();
*
* expect(counter.getText()).toContain('1');
* expect(debug.getText()).toContain('true');
* });
*
* it('should not guide the expression if changing from model', function() {
* element(by.id('ng-change-example2')).click();
* expect(counter.getText()).toContain('0');
* expect(debug.getText()).toContain('true');
* });
* </file>
* </example>
*/
var ngChangeDirective = valueFn({
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attr, ctrl) {
ctrl.$viewChangeListeners.push(function() {
scope.$eval(attr.ngChange);
});
}
});
function classDirective(name, selector) {
name = 'ngClass' + name;
return ['$animate', function($animate) {
return {
restrict: 'AC',
link: function(scope, element, attr) {
var oldVal;
scope.$watch(attr[name], ngClassWatchAction, true);
attr.$observe('class', function(value) {
ngClassWatchAction(scope.$eval(attr[name]));
});
if (name !== 'ngClass') {
scope.$watch('$index', function($index, old$index) {
// jshint bitwise: false
var mod = $index & 1;
if (mod !== (old$index & 1)) {
var classes = arrayClasses(scope.$eval(attr[name]));
mod === selector ?
addClasses(classes) :
removeClasses(classes);
}
});
}
function addClasses(classes) {
var newClasses = digestClassCounts(classes, 1);
attr.$addClass(newClasses);
}
function removeClasses(classes) {
var newClasses = digestClassCounts(classes, -1);
attr.$removeClass(newClasses);
}
function digestClassCounts(classes, count) {
var classCounts = element.data('$classCounts') || {};
var classesToUpdate = [];
forEach(classes, function(className) {
if (count > 0 || classCounts[className]) {
classCounts[className] = (classCounts[className] || 0) + count;
if (classCounts[className] === +(count > 0)) {
classesToUpdate.push(className);
}
}
});
element.data('$classCounts', classCounts);
return classesToUpdate.join(' ');
}
function updateClasses(oldClasses, newClasses) {
var toAdd = arrayDifference(newClasses, oldClasses);
var toRemove = arrayDifference(oldClasses, newClasses);
toAdd = digestClassCounts(toAdd, 1);
toRemove = digestClassCounts(toRemove, -1);
if (toAdd && toAdd.length) {
$animate.addClass(element, toAdd);
}
if (toRemove && toRemove.length) {
$animate.removeClass(element, toRemove);
}
}
function ngClassWatchAction(newVal) {
if (selector === true || scope.$index % 2 === selector) {
var newClasses = arrayClasses(newVal || []);
if (!oldVal) {
addClasses(newClasses);
} else if (!equals(newVal,oldVal)) {
var oldClasses = arrayClasses(oldVal);
updateClasses(oldClasses, newClasses);
}
}
oldVal = shallowCopy(newVal);
}
}
};
function arrayDifference(tokens1, tokens2) {
var values = [];
outer:
for (var i = 0; i < tokens1.length; i++) {
var token = tokens1[i];
for (var j = 0; j < tokens2.length; j++) {
if (token == tokens2[j]) continue outer;
}
values.push(token);
}
return values;
}
function arrayClasses(classVal) {
if (isArray(classVal)) {
return classVal;
} else if (isString(classVal)) {
return classVal.split(' ');
} else if (isObject(classVal)) {
var classes = [];
forEach(classVal, function(v, k) {
if (v) {
classes = classes.concat(k.split(' '));
}
});
return classes;
}
return classVal;
}
}];
}
/**
* @ngdoc directive
* @name ngClass
* @restrict AC
*
* @description
* The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
* an expression that represents all classes to be added.
*
* The directive operates in three different ways, depending on which of three types the expression
* evaluates to:
*
* 1. If the expression evaluates to a string, the string should be one or more space-delimited class
* names.
*
* 2. If the expression evaluates to an array, each element of the array should be a string that is
* one or more space-delimited class names.
*
* 3. If the expression evaluates to an object, then for each key-value pair of the
* object with a truthy value the corresponding key is used as a class name.
*
* The directive won't add duplicate classes if a particular class was already set.
*
* When the expression changes, the previously added classes are removed and only then the
* new classes are added.
*
* @animations
* **add** - happens just before the class is applied to the elements
*
* **remove** - happens just before the class is removed from the element
*
* @element ANY
* @param {expression} ngClass {@link guide/expression Expression} to eval. The result
* of the guide can be a string representing space delimited class
* names, an array, or a map of class names to boolean values. In the case of a map, the
* names of the properties whose values are truthy will be added as css classes to the
* element.
*
* @example Example that demonstrates basic bindings via ngClass directive.
<example>
<file name="index.html">
<p ng-class="{strike: deleted, bold: important, red: error}">Map Syntax Example</p>
<input type="checkbox" ng-model="deleted"> deleted (apply "strike" class)<br>
<input type="checkbox" ng-model="important"> important (apply "bold" class)<br>
<input type="checkbox" ng-model="error"> error (apply "red" class)
<hr>
<p ng-class="style">Using String Syntax</p>
<input type="text" ng-model="style" placeholder="Type: bold strike red">
<hr>
<p ng-class="[style1, style2, style3]">Using Array Syntax</p>
<input ng-model="style1" placeholder="Type: bold, strike or red"><br>
<input ng-model="style2" placeholder="Type: bold, strike or red"><br>
<input ng-model="style3" placeholder="Type: bold, strike or red"><br>
</file>
<file name="style.css">
.strike {
text-decoration: line-through;
}
.bold {
font-weight: bold;
}
.red {
color: red;
}
</file>
<file name="protractor.js" type="protractor">
var ps = element.all(by.css('p'));
it('should let you toggle the class', function() {
expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
expect(ps.first().getAttribute('class')).not.toMatch(/red/);
element(by.model('important')).click();
expect(ps.first().getAttribute('class')).toMatch(/bold/);
element(by.model('error')).click();
expect(ps.first().getAttribute('class')).toMatch(/red/);
});
it('should let you toggle string example', function() {
expect(ps.get(1).getAttribute('class')).toBe('');
element(by.model('style')).clear();
element(by.model('style')).sendKeys('red');
expect(ps.get(1).getAttribute('class')).toBe('red');
});
it('array example should have 3 classes', function() {
expect(ps.last().getAttribute('class')).toBe('');
element(by.model('style1')).sendKeys('bold');
element(by.model('style2')).sendKeys('strike');
element(by.model('style3')).sendKeys('red');
expect(ps.last().getAttribute('class')).toBe('bold strike red');
});
</file>
</example>
## Animations
The example below demonstrates how to perform animations using ngClass.
<example module="ngAnimate" deps="angular-animate.js" animations="true">
<file name="index.html">
<input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
<input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
<br>
<span class="base-class" ng-class="myVar">Sample Text</span>
</file>
<file name="style.css">
.base-class {
-webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
}
.base-class.my-class {
color: red;
font-size:3em;
}
</file>
<file name="protractor.js" type="protractor">
it('should check ng-class', function() {
expect(element(by.css('.base-class')).getAttribute('class')).not.
toMatch(/my-class/);
element(by.id('setbtn')).click();
expect(element(by.css('.base-class')).getAttribute('class')).
toMatch(/my-class/);
element(by.id('clearbtn')).click();
expect(element(by.css('.base-class')).getAttribute('class')).not.
toMatch(/my-class/);
});
</file>
</example>
## ngClass and pre-existing CSS3 Transitions/Animations
The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
to view the step by step details of {@link ng.$animate#addClass $animate.addClass} and
{@link ng.$animate#removeClass $animate.removeClass}.
*/
var ngClassDirective = classDirective('', true);
/**
* @ngdoc directive
* @name ngClassOdd
* @restrict AC
*
* @description
* The `ngClassOdd` and `ngClassEven` directives work exactly as
* {@link ng.directive:ngClass ngClass}, except they work in
* conjunction with `ngRepeat` and take effect only on odd (even) rows.
*
* This directive can be applied only within the scope of an
* {@link ng.directive:ngRepeat ngRepeat}.
*
* @element ANY
* @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
* of the guide can be a string representing space delimited class names or an array.
*
* @example
<example>
<file name="index.html">
<ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
<li ng-repeat="name in names">
<span ng-class-odd="'odd'" ng-class-even="'even'">
{{name}}
</span>
</li>
</ol>
</file>
<file name="style.css">
.odd {
color: red;
}
.even {
color: blue;
}
</file>
<file name="protractor.js" type="protractor">
it('should check ng-class-odd and ng-class-even', function() {
expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
toMatch(/odd/);
expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
toMatch(/even/);
});
</file>
</example>
*/
var ngClassOddDirective = classDirective('Odd', 0);
/**
* @ngdoc directive
* @name ngClassEven
* @restrict AC
*
* @description
* The `ngClassOdd` and `ngClassEven` directives work exactly as
* {@link ng.directive:ngClass ngClass}, except they work in
* conjunction with `ngRepeat` and take effect only on odd (even) rows.
*
* This directive can be applied only within the scope of an
* {@link ng.directive:ngRepeat ngRepeat}.
*
* @element ANY
* @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
* result of the guide can be a string representing space delimited class names or an array.
*
* @example
<example>
<file name="index.html">
<ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
<li ng-repeat="name in names">
<span ng-class-odd="'odd'" ng-class-even="'even'">
{{name}}
</span>
</li>
</ol>
</file>
<file name="style.css">
.odd {
color: red;
}
.even {
color: blue;
}
</file>
<file name="protractor.js" type="protractor">
it('should check ng-class-odd and ng-class-even', function() {
expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
toMatch(/odd/);
expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
toMatch(/even/);
});
</file>
</example>
*/
var ngClassEvenDirective = classDirective('Even', 1);
/**
* @ngdoc directive
* @name ngCloak
* @restrict AC
*
* @description
* The `ngCloak` directive is used to prevent the Angular html template from being briefly
* displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
* directive to avoid the undesirable flicker effect caused by the html template display.
*
* The directive can be applied to the `<body>` element, but the preferred usage is to apply
* multiple `ngCloak` directives to small portions of the page to permit progressive rendering
* of the browser view.
*
* `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
* `angular.min.js`.
* For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
*
* ```css
* [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
* display: none !important;
* }
* ```
*
* When this css rule is loaded by the browser, all html elements (including their children) that
* are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
* during the compilation of the template it deletes the `ngCloak` element attribute, making
* the compiled element visible.
*
* For the best result, the `angular.js` script must be loaded in the head section of the html
* document; alternatively, the css rule above must be included in the external stylesheet of the
* application.
*
* Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they
* cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css
* class `ng-cloak` in addition to the `ngCloak` directive as shown in the example below.
*
* @element ANY
*
* @example
<example>
<file name="index.html">
<div id="template1" ng-cloak>{{ 'hello' }}</div>
<div id="template2" ng-cloak class="ng-cloak">{{ 'hello IE7' }}</div>
</file>
<file name="protractor.js" type="protractor">
it('should remove the template directive and css class', function() {
expect($('#template1').getAttribute('ng-cloak')).
toBeNull();
expect($('#template2').getAttribute('ng-cloak')).
toBeNull();
});
</file>
</example>
*
*/
var ngCloakDirective = ngDirective({
compile: function(element, attr) {
attr.$set('ngCloak', undefined);
element.removeClass('ng-cloak');
}
});
/**
* @ngdoc directive
* @name ngController
*
* @description
* The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
* supports the principles behind the Model-View-Controller design pattern.
*
* MVC components in angular:
*
* * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
* are accessed through bindings.
* * View — The template (HTML with data bindings) that is rendered into the View.
* * Controller — The `ngController` directive specifies a Controller class; the class contains business
* logic behind the application to decorate the scope with functions and values
*
* Note that you can also attach controllers to the DOM by declaring it in a route definition
* via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
* again using `ng-controller` in the template itself. This will cause the controller to be attached
* and executed twice.
*
* @element ANY
* @scope
* @priority 500
* @param {expression} ngController Name of a constructor function registered with the current
* {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
* that on the current scope evaluates to a constructor function.
*
* The controller instance can be published into a scope property by specifying
* `ng-controller="as propertyName"`.
*
* If the current `$controllerProvider` is configured to use globals (via
* {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
* also be the name of a globally accessible constructor function (not recommended).
*
* @example
* Here is a simple form for editing user contact information. Adding, removing, clearing, and
* greeting are methods declared on the controller (see source tab). These methods can
* easily be called from the angular markup. Any changes to the data are automatically reflected
* in the View without the need for a manual update.
*
* Two different declaration styles are included below:
*
* * one binds methods and properties directly onto the controller using `this`:
* `ng-controller="SettingsController1 as settings"`
* * one injects `$scope` into the controller:
* `ng-controller="SettingsController2"`
*
* The second option is more common in the Angular community, and is generally used in boilerplates
* and in this guide. However, there are advantages to binding properties directly to the controller
* and avoiding scope.
*
* * Using `controller as` makes it obvious which controller you are accessing in the template when
* multiple controllers apply to an element.
* * If you are writing your controllers as classes you have easier access to the properties and
* methods, which will appear on the scope, from inside the controller code.
* * Since there is always a `.` in the bindings, you don't have to worry about prototypal
* inheritance masking primitives.
*
* This example demonstrates the `controller as` syntax.
*
* <example name="ngControllerAs" module="controllerAsExample">
* <file name="index.html">
* <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
* Name: <input type="text" ng-model="settings.name"/>
* [ <a href="" ng-click="settings.greet()">greet</a> ]<br/>
* Contact:
* <ul>
* <li ng-repeat="contact in settings.contacts">
* <select ng-model="contact.type">
* <option>phone</option>
* <option>email</option>
* </select>
* <input type="text" ng-model="contact.value"/>
* [ <a href="" ng-click="settings.clearContact(contact)">clear</a>
* | <a href="" ng-click="settings.removeContact(contact)">X</a> ]
* </li>
* <li>[ <a href="" ng-click="settings.addContact()">add</a> ]</li>
* </ul>
* </div>
* </file>
* <file name="app.js">
* angular.module('controllerAsExample', [])
* .controller('SettingsController1', SettingsController1);
*
* function SettingsController1() {
* this.name = "John Smith";
* this.contacts = [
* {type: 'phone', value: '408 555 1212'},
* {type: 'email', value: 'john.smith@example.org'} ];
* }
*
* SettingsController1.prototype.greet = function() {
* alert(this.name);
* };
*
* SettingsController1.prototype.addContact = function() {
* this.contacts.push({type: 'email', value: 'yourname@example.org'});
* };
*
* SettingsController1.prototype.removeContact = function(contactToRemove) {
* var index = this.contacts.indexOf(contactToRemove);
* this.contacts.splice(index, 1);
* };
*
* SettingsController1.prototype.clearContact = function(contact) {
* contact.type = 'phone';
* contact.value = '';
* };
* </file>
* <file name="protractor.js" type="protractor">
* it('should check controller as', function() {
* var container = element(by.id('ctrl-as-exmpl'));
* expect(container.element(by.model('settings.name'))
* .getAttribute('value')).toBe('John Smith');
*
* var firstRepeat =
* container.element(by.repeater('contact in settings.contacts').row(0));
* var secondRepeat =
* container.element(by.repeater('contact in settings.contacts').row(1));
*
* expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
* .toBe('408 555 1212');
*
* expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
* .toBe('john.smith@example.org');
*
* firstRepeat.element(by.linkText('clear')).click();
*
* expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
* .toBe('');
*
* container.element(by.linkText('add')).click();
*
* expect(container.element(by.repeater('contact in settings.contacts').row(2))
* .element(by.model('contact.value'))
* .getAttribute('value'))
* .toBe('yourname@example.org');
* });
* </file>
* </example>
*
* This example demonstrates the "attach to `$scope`" style of controller.
*
* <example name="ngController" module="controllerExample">
* <file name="index.html">
* <div id="ctrl-exmpl" ng-controller="SettingsController2">
* Name: <input type="text" ng-model="name"/>
* [ <a href="" ng-click="greet()">greet</a> ]<br/>
* Contact:
* <ul>
* <li ng-repeat="contact in contacts">
* <select ng-model="contact.type">
* <option>phone</option>
* <option>email</option>
* </select>
* <input type="text" ng-model="contact.value"/>
* [ <a href="" ng-click="clearContact(contact)">clear</a>
* | <a href="" ng-click="removeContact(contact)">X</a> ]
* </li>
* <li>[ <a href="" ng-click="addContact()">add</a> ]</li>
* </ul>
* </div>
* </file>
* <file name="app.js">
* angular.module('controllerExample', [])
* .controller('SettingsController2', ['$scope', SettingsController2]);
*
* function SettingsController2($scope) {
* $scope.name = "John Smith";
* $scope.contacts = [
* {type:'phone', value:'408 555 1212'},
* {type:'email', value:'john.smith@example.org'} ];
*
* $scope.greet = function() {
* alert($scope.name);
* };
*
* $scope.addContact = function() {
* $scope.contacts.push({type:'email', value:'yourname@example.org'});
* };
*
* $scope.removeContact = function(contactToRemove) {
* var index = $scope.contacts.indexOf(contactToRemove);
* $scope.contacts.splice(index, 1);
* };
*
* $scope.clearContact = function(contact) {
* contact.type = 'phone';
* contact.value = '';
* };
* }
* </file>
* <file name="protractor.js" type="protractor">
* it('should check controller', function() {
* var container = element(by.id('ctrl-exmpl'));
*
* expect(container.element(by.model('name'))
* .getAttribute('value')).toBe('John Smith');
*
* var firstRepeat =
* container.element(by.repeater('contact in contacts').row(0));
* var secondRepeat =
* container.element(by.repeater('contact in contacts').row(1));
*
* expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
* .toBe('408 555 1212');
* expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
* .toBe('john.smith@example.org');
*
* firstRepeat.element(by.linkText('clear')).click();
*
* expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
* .toBe('');
*
* container.element(by.linkText('add')).click();
*
* expect(container.element(by.repeater('contact in contacts').row(2))
* .element(by.model('contact.value'))
* .getAttribute('value'))
* .toBe('yourname@example.org');
* });
* </file>
*</example>
*/
var ngControllerDirective = [function() {
return {
restrict: 'A',
scope: true,
controller: '@',
priority: 500
};
}];
/**
* @ngdoc directive
* @name ngCsp
*
* @element html
* @description
* Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support.
*
* This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
*
* CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things).
* For Angular to be CSP compatible there are only two things that we need to do differently:
*
* - don't use `Function` constructor to generate optimized value getters
* - don't inject custom stylesheet into the document
*
* AngularJS uses `Function(string)` generated functions as a speed optimization. Applying the `ngCsp`
* directive will cause Angular to use CSP compatibility mode. When this mode is on AngularJS will
* guide all expressions up to 30% slower than in non-CSP mode, but no security violations will
* be raised.
*
* CSP forbids JavaScript to inline stylesheet rules. In non CSP mode Angular automatically
* includes some CSS rules (e.g. {@link ng.directive:ngCloak ngCloak}).
* To make those directives work in CSP mode, include the `angular-csp.css` manually.
*
* Angular tries to autodetect if CSP is active and automatically turn on the CSP-safe mode. This
* autodetection however triggers a CSP error to be logged in the console:
*
* ```
* Refused to guide a string as JavaScript because 'unsafe-eval' is not an allowed source of
* script in the following Content Security Policy directive: "default-src 'self'". Note that
* 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
* ```
*
* This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
* directive on the root element of the application or on the `angular.js` script tag, whichever
* appears first in the html document.
*
* *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
*
* @example
* This example shows how to apply the `ngCsp` directive to the `html` tag.
```html
<!doctype html>
<html ng-app ng-csp>
...
...
</html>
```
* @example
// Note: the suffix `.csp` in the example name triggers
// csp mode in our http server!
<example name="example.csp" module="cspExample" ng-csp="true">
<file name="index.html">
<div ng-controller="MainController as ctrl">
<div>
<button ng-click="ctrl.inc()" id="inc">Increment</button>
<span id="counter">
{{ctrl.counter}}
</span>
</div>
<div>
<button ng-click="ctrl.evil()" id="evil">Evil</button>
<span id="evilError">
{{ctrl.evilError}}
</span>
</div>
</div>
</file>
<file name="script.js">
angular.module('cspExample', [])
.controller('MainController', function() {
this.counter = 0;
this.inc = function() {
this.counter++;
};
this.evil = function() {
// jshint evil:true
try {
eval('1+2');
} catch (e) {
this.evilError = e.message;
}
};
});
</file>
<file name="protractor.js" type="protractor">
var util, webdriver;
var incBtn = element(by.id('inc'));
var counter = element(by.id('counter'));
var evilBtn = element(by.id('evil'));
var evilError = element(by.id('evilError'));
function getAndClearSevereErrors() {
return browser.manage().logs().get('browser').then(function(browserLog) {
return browserLog.filter(function(logEntry) {
return logEntry.level.value > webdriver.logging.Level.WARNING.value;
});
});
}
function clearErrors() {
getAndClearSevereErrors();
}
function expectNoErrors() {
getAndClearSevereErrors().then(function(filteredLog) {
expect(filteredLog.length).toEqual(0);
if (filteredLog.length) {
console.log('browser console errors: ' + util.inspect(filteredLog));
}
});
}
function expectError(regex) {
getAndClearSevereErrors().then(function(filteredLog) {
var found = false;
filteredLog.forEach(function(log) {
if (log.message.match(regex)) {
found = true;
}
});
if (!found) {
throw new Error('expected an error that matches ' + regex);
}
});
}
beforeEach(function() {
util = require('util');
webdriver = require('protractor/node_modules/selenium-webdriver');
});
// For now, we only test on Chrome,
// as Safari does not load the page with Protractor's injected scripts,
// and Firefox webdriver always disables content security policy (#6358)
if (browser.params.browser !== 'chrome') {
return;
}
it('should not report errors when the page is loaded', function() {
// clear errors so we are not dependent on previous tests
clearErrors();
// Need to reload the page as the page is already loaded when
// we come here
browser.driver.getCurrentUrl().then(function(url) {
browser.get(url);
});
expectNoErrors();
});
it('should guide expressions', function() {
expect(counter.getText()).toEqual('0');
incBtn.click();
expect(counter.getText()).toEqual('1');
expectNoErrors();
});
it('should throw and report an error when using "eval"', function() {
evilBtn.click();
expect(evilError.getText()).toMatch(/Content Security Policy/);
expectError(/Content Security Policy/);
});
</file>
</example>
*/
// ngCsp is not implemented as a proper directive any more, because we need it be processed while we
// bootstrap the system (before $parse is instantiated), for this reason we just have
// the csp.isActive() fn that looks for ng-csp attribute anywhere in the current doc
/**
* @ngdoc directive
* @name ngClick
*
* @description
* The ngClick directive allows you to specify custom behavior when
* an element is clicked.
*
* @element ANY
* @priority 0
* @param {expression} ngClick {@link guide/expression Expression} to guide upon
* click. ({@link guide/expression#-event- Event object is available as `$event`})
*
* @example
<example>
<file name="index.html">
<button ng-click="count = count + 1" ng-init="count=0">
Increment
</button>
<span>
count: {{count}}
</span>
</file>
<file name="protractor.js" type="protractor">
it('should check ng-click', function() {
expect(element(by.binding('count')).getText()).toMatch('0');
element(by.css('button')).click();
expect(element(by.binding('count')).getText()).toMatch('1');
});
</file>
</example>
*/
/*
* A collection of directives that allows creation of custom event handlers that are defined as
* angular expressions and are compiled and executed within the current scope.
*/
var ngEventDirectives = {};
// For events that might fire synchronously during DOM manipulation
// we need to execute their event handlers asynchronously using $evalAsync,
// so that they are not executed in an inconsistent state.
var forceAsyncEvents = {
'blur': true,
'focus': true
};
forEach(
'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
function(eventName) {
var directiveName = directiveNormalize('ng-' + eventName);
ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
return {
restrict: 'A',
compile: function($element, attr) {
// We expose the powerful $event object on the scope that provides access to the Window,
// etc. that isn't protected by the fast paths in $parse. We explicitly request better
// checks at the cost of speed since event handler expressions are not executed as
// frequently as regular change detection.
var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);
return function ngEventHandler(scope, element) {
element.on(eventName, function(event) {
var callback = function() {
fn(scope, {$event:event});
};
if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
scope.$evalAsync(callback);
} else {
scope.$apply(callback);
}
});
};
}
};
}];
}
);
/**
* @ngdoc directive
* @name ngDblclick
*
* @description
* The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
*
* @element ANY
* @priority 0
* @param {expression} ngDblclick {@link guide/expression Expression} to guide upon
* a dblclick. (The Event object is available as `$event`)
*
* @example
<example>
<file name="index.html">
<button ng-dblclick="count = count + 1" ng-init="count=0">
Increment (on double click)
</button>
count: {{count}}
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngMousedown
*
* @description
* The ngMousedown directive allows you to specify custom behavior on mousedown event.
*
* @element ANY
* @priority 0
* @param {expression} ngMousedown {@link guide/expression Expression} to guide upon
* mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
*
* @example
<example>
<file name="index.html">
<button ng-mousedown="count = count + 1" ng-init="count=0">
Increment (on mouse down)
</button>
count: {{count}}
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngMouseup
*
* @description
* Specify custom behavior on mouseup event.
*
* @element ANY
* @priority 0
* @param {expression} ngMouseup {@link guide/expression Expression} to guide upon
* mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
*
* @example
<example>
<file name="index.html">
<button ng-mouseup="count = count + 1" ng-init="count=0">
Increment (on mouse up)
</button>
count: {{count}}
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngMouseover
*
* @description
* Specify custom behavior on mouseover event.
*
* @element ANY
* @priority 0
* @param {expression} ngMouseover {@link guide/expression Expression} to guide upon
* mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
*
* @example
<example>
<file name="index.html">
<button ng-mouseover="count = count + 1" ng-init="count=0">
Increment (when mouse is over)
</button>
count: {{count}}
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngMouseenter
*
* @description
* Specify custom behavior on mouseenter event.
*
* @element ANY
* @priority 0
* @param {expression} ngMouseenter {@link guide/expression Expression} to guide upon
* mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
*
* @example
<example>
<file name="index.html">
<button ng-mouseenter="count = count + 1" ng-init="count=0">
Increment (when mouse enters)
</button>
count: {{count}}
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngMouseleave
*
* @description
* Specify custom behavior on mouseleave event.
*
* @element ANY
* @priority 0
* @param {expression} ngMouseleave {@link guide/expression Expression} to guide upon
* mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
*
* @example
<example>
<file name="index.html">
<button ng-mouseleave="count = count + 1" ng-init="count=0">
Increment (when mouse leaves)
</button>
count: {{count}}
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngMousemove
*
* @description
* Specify custom behavior on mousemove event.
*
* @element ANY
* @priority 0
* @param {expression} ngMousemove {@link guide/expression Expression} to guide upon
* mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
*
* @example
<example>
<file name="index.html">
<button ng-mousemove="count = count + 1" ng-init="count=0">
Increment (when mouse moves)
</button>
count: {{count}}
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngKeydown
*
* @description
* Specify custom behavior on keydown event.
*
* @element ANY
* @priority 0
* @param {expression} ngKeydown {@link guide/expression Expression} to guide upon
* keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
*
* @example
<example>
<file name="index.html">
<input ng-keydown="count = count + 1" ng-init="count=0">
key down count: {{count}}
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngKeyup
*
* @description
* Specify custom behavior on keyup event.
*
* @element ANY
* @priority 0
* @param {expression} ngKeyup {@link guide/expression Expression} to guide upon
* keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
*
* @example
<example>
<file name="index.html">
<p>Typing in the input box below updates the key count</p>
<input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
<p>Typing in the input box below updates the keycode</p>
<input ng-keyup="event=$event">
<p>event keyCode: {{ event.keyCode }}</p>
<p>event altKey: {{ event.altKey }}</p>
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngKeypress
*
* @description
* Specify custom behavior on keypress event.
*
* @element ANY
* @param {expression} ngKeypress {@link guide/expression Expression} to guide upon
* keypress. ({@link guide/expression#-event- Event object is available as `$event`}
* and can be interrogated for keyCode, altKey, etc.)
*
* @example
<example>
<file name="index.html">
<input ng-keypress="count = count + 1" ng-init="count=0">
key press count: {{count}}
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngSubmit
*
* @description
* Enables binding angular expressions to onsubmit events.
*
* Additionally it prevents the default action (which for form means sending the request to the
* server and reloading the current page), but only if the form does not contain `action`,
* `data-action`, or `x-action` attributes.
*
* <div class="alert alert-warning">
* **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
* `ngSubmit` handlers together. See the
* {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
* for a detailed discussion of when `ngSubmit` may be triggered.
* </div>
*
* @element form
* @priority 0
* @param {expression} ngSubmit {@link guide/expression Expression} to eval.
* ({@link guide/expression#-event- Event object is available as `$event`})
*
* @example
<example module="submitExample">
<file name="index.html">
<script>
angular.module('submitExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.list = [];
$scope.text = 'hello';
$scope.submit = function() {
if ($scope.text) {
$scope.list.push(this.text);
$scope.text = '';
}
};
}]);
</script>
<form ng-submit="submit()" ng-controller="ExampleController">
Enter text and hit enter:
<input type="text" ng-model="text" name="text" />
<input type="submit" id="submit" value="Submit" />
<pre>list={{list}}</pre>
</form>
</file>
<file name="protractor.js" type="protractor">
it('should check ng-submit', function() {
expect(element(by.binding('list')).getText()).toBe('list=[]');
element(by.css('#submit')).click();
expect(element(by.binding('list')).getText()).toContain('hello');
expect(element(by.model('text')).getAttribute('value')).toBe('');
});
it('should ignore empty strings', function() {
expect(element(by.binding('list')).getText()).toBe('list=[]');
element(by.css('#submit')).click();
element(by.css('#submit')).click();
expect(element(by.binding('list')).getText()).toContain('hello');
});
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngFocus
*
* @description
* Specify custom behavior on focus event.
*
* Note: As the `focus` event is executed synchronously when calling `input.focus()`
* AngularJS executes the expression using `scope.$evalAsync` if the event is fired
* during an `$apply` to ensure a consistent state.
*
* @element window, input, select, textarea, a
* @priority 0
* @param {expression} ngFocus {@link guide/expression Expression} to guide upon
* focus. ({@link guide/expression#-event- Event object is available as `$event`})
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ngBlur
*
* @description
* Specify custom behavior on blur event.
*
* A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
* an element has lost focus.
*
* Note: As the `blur` event is executed synchronously also during DOM manipulations
* (e.g. removing a focussed input),
* AngularJS executes the expression using `scope.$evalAsync` if the event is fired
* during an `$apply` to ensure a consistent state.
*
* @element window, input, select, textarea, a
* @priority 0
* @param {expression} ngBlur {@link guide/expression Expression} to guide upon
* blur. ({@link guide/expression#-event- Event object is available as `$event`})
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ngCopy
*
* @description
* Specify custom behavior on copy event.
*
* @element window, input, select, textarea, a
* @priority 0
* @param {expression} ngCopy {@link guide/expression Expression} to guide upon
* copy. ({@link guide/expression#-event- Event object is available as `$event`})
*
* @example
<example>
<file name="index.html">
<input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
copied: {{copied}}
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngCut
*
* @description
* Specify custom behavior on cut event.
*
* @element window, input, select, textarea, a
* @priority 0
* @param {expression} ngCut {@link guide/expression Expression} to guide upon
* cut. ({@link guide/expression#-event- Event object is available as `$event`})
*
* @example
<example>
<file name="index.html">
<input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
cut: {{cut}}
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngPaste
*
* @description
* Specify custom behavior on paste event.
*
* @element window, input, select, textarea, a
* @priority 0
* @param {expression} ngPaste {@link guide/expression Expression} to guide upon
* paste. ({@link guide/expression#-event- Event object is available as `$event`})
*
* @example
<example>
<file name="index.html">
<input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
pasted: {{paste}}
</file>
</example>
*/
/**
* @ngdoc directive
* @name ngIf
* @restrict A
*
* @description
* The `ngIf` directive removes or recreates a portion of the DOM tree based on an
* {expression}. If the expression assigned to `ngIf` evaluates to a false
* value then the element is removed from the DOM, otherwise a clone of the
* element is reinserted into the DOM.
*
* `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
* element in the DOM rather than changing its visibility via the `display` css property. A common
* case when this difference is significant is when using css selectors that rely on an element's
* position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
*
* Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
* is created when the element is restored. The scope created within `ngIf` inherits from
* its parent scope using
* [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
* An important implication of this is if `ngModel` is used within `ngIf` to bind to
* a javascript primitive defined in the parent scope. In this case any modifications made to the
* variable within the child scope will override (hide) the value in the parent scope.
*
* Also, `ngIf` recreates elements using their compiled state. An example of this behavior
* is if an element's class attribute is directly modified after it's compiled, using something like
* jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
* the added class will be lost because the original compiled state is used to regenerate the element.
*
* Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
* and `leave` effects.
*
* @animations
* enter - happens just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container
* leave - happens just before the `ngIf` contents are removed from the DOM
*
* @element ANY
* @scope
* @priority 600
* @param {expression} ngIf If the {@link guide/expression expression} is falsy then
* the element is removed from the DOM tree. If it is truthy a copy of the compiled
* element is added to the DOM tree.
*
* @example
<example module="ngAnimate" deps="angular-animate.js" animations="true">
<file name="index.html">
Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /><br/>
Show when checked:
<span ng-if="checked" class="animate-if">
This is removed when the checkbox is unchecked.
</span>
</file>
<file name="animations.css">
.animate-if {
background:white;
border:1px solid black;
padding:10px;
}
.animate-if.ng-enter, .animate-if.ng-leave {
-webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
}
.animate-if.ng-enter,
.animate-if.ng-leave.ng-leave-active {
opacity:0;
}
.animate-if.ng-leave,
.animate-if.ng-enter.ng-enter-active {
opacity:1;
}
</file>
</example>
*/
var ngIfDirective = ['$animate', function($animate) {
return {
multiElement: true,
transclude: 'element',
priority: 600,
terminal: true,
restrict: 'A',
$$tlb: true,
link: function($scope, $element, $attr, ctrl, $transclude) {
var block, childScope, previousElements;
$scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
if (value) {
if (!childScope) {
$transclude(function(clone, newScope) {
childScope = newScope;
clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ');
// Note: We only need the first/last node of the cloned nodes.
// However, we need to keep the reference to the jqlite wrapper as it might be changed later
// by a directive with templateUrl when its template arrives.
block = {
clone: clone
};
$animate.enter(clone, $element.parent(), $element);
});
}
} else {
if (previousElements) {
previousElements.remove();
previousElements = null;
}
if (childScope) {
childScope.$destroy();
childScope = null;
}
if (block) {
previousElements = getBlockNodes(block.clone);
$animate.leave(previousElements).then(function() {
previousElements = null;
});
block = null;
}
}
});
}
};
}];
/**
* @ngdoc directive
* @name ngInclude
* @restrict ECA
*
* @description
* Fetches, compiles and includes an external HTML fragment.
*
* By default, the template URL is restricted to the same domain and protocol as the
* application document. This is done by calling {@link $sce#getTrustedResourceUrl
* $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
* you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
* {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
* ng.$sce Strict Contextual Escaping}.
*
* In addition, the browser's
* [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
* and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
* policy may further restrict whether the template is successfully loaded.
* For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
* access on some browsers.
*
* @animations
* enter - animation is used to bring new content into the browser.
* leave - animation is used to animate existing content away.
*
* The enter and leave animation occur concurrently.
*
* @scope
* @priority 400
*
* @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
* make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
* @param {string=} onload Expression to guide when a new partial is loaded.
*
* @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
* $anchorScroll} to scroll the viewport after the content is loaded.
*
* - If the attribute is not set, disable scrolling.
* - If the attribute is set without value, enable scrolling.
* - Otherwise enable scrolling only if the expression evaluates to truthy value.
*
* @example
<example module="includeExample" deps="angular-animate.js" animations="true">
<file name="index.html">
<div ng-controller="ExampleController">
<select ng-model="template" ng-options="t.name for t in templates">
<option value="">(blank)</option>
</select>
url of the template: <code>{{template.url}}</code>
<hr/>
<div class="slide-animate-container">
<div class="slide-animate" ng-include="template.url"></div>
</div>
</div>
</file>
<file name="script.js">
angular.module('includeExample', ['ngAnimate'])
.controller('ExampleController', ['$scope', function($scope) {
$scope.templates =
[ { name: 'template1.html', url: 'template1.html'},
{ name: 'template2.html', url: 'template2.html'} ];
$scope.template = $scope.templates[0];
}]);
</file>
<file name="template1.html">
Content of template1.html
</file>
<file name="template2.html">
Content of template2.html
</file>
<file name="animations.css">
.slide-animate-container {
position:relative;
background:white;
border:1px solid black;
height:40px;
overflow:hidden;
}
.slide-animate {
padding:10px;
}
.slide-animate.ng-enter, .slide-animate.ng-leave {
-webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
display:block;
padding:10px;
}
.slide-animate.ng-enter {
top:-50px;
}
.slide-animate.ng-enter.ng-enter-active {
top:0;
}
.slide-animate.ng-leave {
top:0;
}
.slide-animate.ng-leave.ng-leave-active {
top:50px;
}
</file>
<file name="protractor.js" type="protractor">
var templateSelect = element(by.model('template'));
var includeElem = element(by.css('[ng-include]'));
it('should load template1.html', function() {
expect(includeElem.getText()).toMatch(/Content of template1.html/);
});
it('should load template2.html', function() {
if (browser.params.browser == 'firefox') {
// Firefox can't handle using selects
// See https://github.com/angular/protractor/issues/480
return;
}
templateSelect.click();
templateSelect.all(by.css('option')).get(2).click();
expect(includeElem.getText()).toMatch(/Content of template2.html/);
});
it('should change to blank', function() {
if (browser.params.browser == 'firefox') {
// Firefox can't handle using selects
return;
}
templateSelect.click();
templateSelect.all(by.css('option')).get(0).click();
expect(includeElem.isPresent()).toBe(false);
});
</file>
</example>
*/
/**
* @ngdoc event
* @name ngInclude#$includeContentRequested
* @eventType emit on the scope ngInclude was declared in
* @description
* Emitted every time the ngInclude content is requested.
*
* @param {Object} angularEvent Synthetic event object.
* @param {String} src URL of content to load.
*/
/**
* @ngdoc event
* @name ngInclude#$includeContentLoaded
* @eventType emit on the current ngInclude scope
* @description
* Emitted every time the ngInclude content is reloaded.
*
* @param {Object} angularEvent Synthetic event object.
* @param {String} src URL of content to load.
*/
/**
* @ngdoc event
* @name ngInclude#$includeContentError
* @eventType emit on the scope ngInclude was declared in
* @description
* Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)
*
* @param {Object} angularEvent Synthetic event object.
* @param {String} src URL of content to load.
*/
var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate', '$sce',
function($templateRequest, $anchorScroll, $animate, $sce) {
return {
restrict: 'ECA',
priority: 400,
terminal: true,
transclude: 'element',
controller: angular.noop,
compile: function(element, attr) {
var srcExp = attr.ngInclude || attr.src,
onloadExp = attr.onload || '',
autoScrollExp = attr.autoscroll;
return function(scope, $element, $attr, ctrl, $transclude) {
var changeCounter = 0,
currentScope,
previousElement,
currentElement;
var cleanupLastIncludeContent = function() {
if (previousElement) {
previousElement.remove();
previousElement = null;
}
if (currentScope) {
currentScope.$destroy();
currentScope = null;
}
if (currentElement) {
$animate.leave(currentElement).then(function() {
previousElement = null;
});
previousElement = currentElement;
currentElement = null;
}
};
scope.$watch($sce.parseAsResourceUrl(srcExp), function ngIncludeWatchAction(src) {
var afterAnimation = function() {
if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
$anchorScroll();
}
};
var thisChangeId = ++changeCounter;
if (src) {
//set the 2nd param to true to ignore the template request error so that the inner
//contents and scope can be cleaned up.
$templateRequest(src, true).then(function(response) {
if (thisChangeId !== changeCounter) return;
var newScope = scope.$new();
ctrl.template = response;
// Note: This will also link all children of ng-include that were contained in the original
// html. If that content contains controllers, ... they could pollute/change the scope.
// However, using ng-include on an element with additional content does not make sense...
// Note: We can't remove them in the cloneAttchFn of $transclude as that
// function is called before linking the content, which would apply child
// directives to non existing elements.
var clone = $transclude(newScope, function(clone) {
cleanupLastIncludeContent();
$animate.enter(clone, null, $element).then(afterAnimation);
});
currentScope = newScope;
currentElement = clone;
currentScope.$emit('$includeContentLoaded', src);
scope.$eval(onloadExp);
}, function() {
if (thisChangeId === changeCounter) {
cleanupLastIncludeContent();
scope.$emit('$includeContentError', src);
}
});
scope.$emit('$includeContentRequested', src);
} else {
cleanupLastIncludeContent();
ctrl.template = null;
}
});
};
}
};
}];
// This directive is called during the $transclude call of the first `ngInclude` directive.
// It will replace and compile the content of the element with the loaded template.
// We need this directive so that the element content is already filled when
// the link function of another directive on the same element as ngInclude
// is called.
var ngIncludeFillContentDirective = ['$compile',
function($compile) {
return {
restrict: 'ECA',
priority: -400,
require: 'ngInclude',
link: function(scope, $element, $attr, ctrl) {
if (/SVG/.test($element[0].toString())) {
// WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
// support innerHTML, so detect this here and try to generate the contents
// specially.
$element.empty();
$compile(jqLiteBuildFragment(ctrl.template, document).childNodes)(scope,
function namespaceAdaptedClone(clone) {
$element.append(clone);
}, {futureParentElement: $element});
return;
}
$element.html(ctrl.template);
$compile($element.contents())(scope);
}
};
}];
/**
* @ngdoc directive
* @name ngInit
* @restrict AC
*
* @description
* The `ngInit` directive allows you to guide an expression in the
* current scope.
*
* <div class="alert alert-error">
* The only appropriate use of `ngInit` is for aliasing special properties of
* {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you
* should use {@link guide/controller controllers} rather than `ngInit`
* to initialize values on a scope.
* </div>
* <div class="alert alert-warning">
* **Note**: If you have assignment in `ngInit` along with {@link ng.$filter `$filter`}, make
* sure you have parenthesis for correct precedence:
* <pre class="prettyprint">
* `<div ng-init="test1 = (data | orderBy:'name')"></div>`
* </pre>
* </div>
*
* @priority 450
*
* @element ANY
* @param {expression} ngInit {@link guide/expression Expression} to eval.
*
* @example
<example module="initExample">
<file name="index.html">
<script>
angular.module('initExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.list = [['a', 'b'], ['c', 'd']];
}]);
</script>
<div ng-controller="ExampleController">
<div ng-repeat="innerList in list" ng-init="outerIndex = $index">
<div ng-repeat="value in innerList" ng-init="innerIndex = $index">
<span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
</div>
</div>
</div>
</file>
<file name="protractor.js" type="protractor">
it('should alias index positions', function() {
var elements = element.all(by.css('.example-init'));
expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
});
</file>
</example>
*/
var ngInitDirective = ngDirective({
priority: 450,
compile: function() {
return {
pre: function(scope, element, attrs) {
scope.$eval(attrs.ngInit);
}
};
}
});
/**
* @ngdoc directive
* @name ngList
*
* @description
* Text input that converts between a delimited string and an array of strings. The default
* delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
* delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
*
* The behaviour of the directive is affected by the use of the `ngTrim` attribute.
* * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
* list item is respected. This implies that the user of the directive is responsible for
* dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
* tab or newline character.
* * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
* when joining the list items back together) and whitespace around each list item is stripped
* before it is added to the model.
*
* ### Example with Validation
*
* <example name="ngList-directive" module="listExample">
* <file name="app.js">
* angular.module('listExample', [])
* .controller('ExampleController', ['$scope', function($scope) {
* $scope.names = ['morpheus', 'neo', 'trinity'];
* }]);
* </file>
* <file name="index.html">
* <form name="myForm" ng-controller="ExampleController">
* List: <input name="namesInput" ng-model="names" ng-list required>
* <span class="error" ng-show="myForm.namesInput.$error.required">
* Required!</span>
* <br>
* <tt>names = {{names}}</tt><br/>
* <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
* <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
* <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
* <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
* </form>
* </file>
* <file name="protractor.js" type="protractor">
* var listInput = element(by.model('names'));
* var names = element(by.exactBinding('names'));
* var valid = element(by.binding('myForm.namesInput.$valid'));
* var error = element(by.css('span.error'));
*
* it('should initialize to model', function() {
* expect(names.getText()).toContain('["morpheus","neo","trinity"]');
* expect(valid.getText()).toContain('true');
* expect(error.getCssValue('display')).toBe('none');
* });
*
* it('should be invalid if empty', function() {
* listInput.clear();
* listInput.sendKeys('');
*
* expect(names.getText()).toContain('');
* expect(valid.getText()).toContain('false');
* expect(error.getCssValue('display')).not.toBe('none');
* });
* </file>
* </example>
*
* ### Example - splitting on whitespace
* <example name="ngList-directive-newlines">
* <file name="index.html">
* <textarea ng-model="list" ng-list=" " ng-trim="false"></textarea>
* <pre>{{ list | json }}</pre>
* </file>
* <file name="protractor.js" type="protractor">
* it("should split the text by newlines", function() {
* var listInput = element(by.model('list'));
* var output = element(by.binding('list | json'));
* listInput.sendKeys('abc\ndef\nghi');
* expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
* });
* </file>
* </example>
*
* @element input
* @param {string=} ngList optional delimiter that should be used to split the value.
*/
var ngListDirective = function() {
return {
restrict: 'A',
priority: 100,
require: 'ngModel',
link: function(scope, element, attr, ctrl) {
// We want to control whitespace trimming so we use this convoluted approach
// to access the ngList attribute, which doesn't pre-trim the attribute
var ngList = element.attr(attr.$attr.ngList) || ', ';
var trimValues = attr.ngTrim !== 'false';
var separator = trimValues ? trim(ngList) : ngList;
var parse = function(viewValue) {
// If the viewValue is invalid (say required but empty) it will be `undefined`
if (isUndefined(viewValue)) return;
var list = [];
if (viewValue) {
forEach(viewValue.split(separator), function(value) {
if (value) list.push(trimValues ? trim(value) : value);
});
}
return list;
};
ctrl.$parsers.push(parse);
ctrl.$formatters.push(function(value) {
if (isArray(value)) {
return value.join(ngList);
}
return undefined;
});
// Override the standard $isEmpty because an empty array means the input is empty.
ctrl.$isEmpty = function(value) {
return !value || !value.length;
};
}
};
};
/* global VALID_CLASS: true,
INVALID_CLASS: true,
PRISTINE_CLASS: true,
DIRTY_CLASS: true,
UNTOUCHED_CLASS: true,
TOUCHED_CLASS: true,
*/
var VALID_CLASS = 'ng-valid',
INVALID_CLASS = 'ng-invalid',
PRISTINE_CLASS = 'ng-pristine',
DIRTY_CLASS = 'ng-dirty',
UNTOUCHED_CLASS = 'ng-untouched',
TOUCHED_CLASS = 'ng-touched',
PENDING_CLASS = 'ng-pending';
var $ngModelMinErr = new minErr('ngModel');
/**
* @ngdoc type
* @name ngModel.NgModelController
*
* @property {string} $viewValue Actual string value in the view.
* @property {*} $modelValue The value in the model that the control is bound to.
* @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
the control reads value from the DOM. The functions are called in array order, each passing
its return value through to the next. The last return value is forwarded to the
{@link ngModel.NgModelController#$validators `$validators`} collection.
Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
`$viewValue`}.
Returning `undefined` from a parser means a parse error occurred. In that case,
no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
is set to `true`. The parse error is stored in `ngModel.$error.parse`.
*
* @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
the model value changes. The functions are called in reverse array order, each passing the value through to the
next. The last return value is used as the actual DOM value.
Used to format / convert values for display in the control.
* ```js
* function formatter(value) {
* if (value) {
* return value.toUpperCase();
* }
* }
* ngModel.$formatters.push(formatter);
* ```
*
* @property {Object.<string, function>} $validators A collection of validators that are applied
* whenever the model value changes. The key value within the object refers to the name of the
* validator while the function refers to the validation operation. The validation operation is
* provided with the model value as an argument and must return a true or false value depending
* on the response of that validation.
*
* ```js
* ngModel.$validators.validCharacters = function(modelValue, viewValue) {
* var value = modelValue || viewValue;
* return /[0-9]+/.test(value) &&
* /[a-z]+/.test(value) &&
* /[A-Z]+/.test(value) &&
* /\W+/.test(value);
* };
* ```
*
* @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
* perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
* is expected to return a promise when it is run during the model validation process. Once the promise
* is delivered then the validation status will be set to true when fulfilled and false when rejected.
* When the asynchronous validators are triggered, each of the validators will run in parallel and the model
* value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
* is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
* will only run once all synchronous validators have passed.
*
* Please note that if $http is used then it is important that the server returns a success HTTP response code
* in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
*
* ```js
* ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
* var value = modelValue || viewValue;
*
* // Lookup user by username
* return $http.get('/api/users/' + value).
* then(function resolved() {
* //username exists, this means validation fails
* return $q.reject('exists');
* }, function rejected() {
* //username does not exist, therefore this validation passes
* return true;
* });
* };
* ```
*
* @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
* view value has changed. It is called with no arguments, and its return value is ignored.
* This can be used in place of additional $watches against the model value.
*
* @property {Object} $error An object hash with all failing validator ids as keys.
* @property {Object} $pending An object hash with all pending validator ids as keys.
*
* @property {boolean} $untouched True if control has not lost focus yet.
* @property {boolean} $touched True if control has lost focus.
* @property {boolean} $pristine True if user has not interacted with the control yet.
* @property {boolean} $dirty True if user has already interacted with the control.
* @property {boolean} $valid True if there is no error.
* @property {boolean} $invalid True if at least one error on the control.
* @property {string} $name The name attribute of the control.
*
* @description
*
* `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
* The controller contains services for data-binding, validation, CSS updates, and value formatting
* and parsing. It purposefully does not contain any logic which deals with DOM rendering or
* listening to DOM events.
* Such DOM related logic should be provided by other directives which make use of
* `NgModelController` for data-binding to control elements.
* Angular provides this DOM logic for most {@link input `input`} elements.
* At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
* custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
*
* @example
* ### Custom Control Example
* This example shows how to use `NgModelController` with a custom control to achieve
* data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
* collaborate together to achieve the desired result.
*
* `contenteditable` is an HTML5 attribute, which tells the browser to let the element
* contents be edited in place by the user.
*
* We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
* module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
* However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
* that content using the `$sce` service.
*
* <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
<file name="style.css">
[contenteditable] {
border: 1px solid black;
background-color: white;
min-height: 20px;
}
.ng-invalid {
border: 1px solid red;
}
</file>
<file name="script.js">
angular.module('customControl', ['ngSanitize']).
directive('contenteditable', ['$sce', function($sce) {
return {
restrict: 'A', // only activate on element attribute
require: '?ngModel', // get a hold of NgModelController
link: function(scope, element, attrs, ngModel) {
if (!ngModel) return; // do nothing if no ng-model
// Specify how UI should be updated
ngModel.$render = function() {
element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
};
// Listen for change events to enable binding
element.on('blur keyup change', function() {
scope.$evalAsync(read);
});
read(); // initialize
// Write data to the model
function read() {
var html = element.html();
// When we clear the content editable the browser leaves a <br> behind
// If strip-br attribute is provided then we strip this out
if ( attrs.stripBr && html == '<br>' ) {
html = '';
}
ngModel.$setViewValue(html);
}
}
};
}]);
</file>
<file name="index.html">
<form name="myForm">
<div contenteditable
name="myWidget" ng-model="userContent"
strip-br="true"
required>Change me!</div>
<span ng-show="myForm.myWidget.$error.required">Required!</span>
<hr>
<textarea ng-model="userContent"></textarea>
</form>
</file>
<file name="protractor.js" type="protractor">
it('should data-bind and become invalid', function() {
if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {
// SafariDriver can't handle contenteditable
// and Firefox driver can't clear contenteditables very well
return;
}
var contentEditable = element(by.css('[contenteditable]'));
var content = 'Change me!';
expect(contentEditable.getText()).toEqual(content);
contentEditable.clear();
contentEditable.sendKeys(protractor.Key.BACK_SPACE);
expect(contentEditable.getText()).toEqual('');
expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
});
</file>
* </example>
*
*
*/
var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate',
function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) {
this.$viewValue = Number.NaN;
this.$modelValue = Number.NaN;
this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
this.$validators = {};
this.$asyncValidators = {};
this.$parsers = [];
this.$formatters = [];
this.$viewChangeListeners = [];
this.$untouched = true;
this.$touched = false;
this.$pristine = true;
this.$dirty = false;
this.$valid = true;
this.$invalid = false;
this.$error = {}; // keep invalid keys here
this.$$success = {}; // keep valid keys here
this.$pending = undefined; // keep pending keys here
this.$name = $interpolate($attr.name || '', false)($scope);
var parsedNgModel = $parse($attr.ngModel),
parsedNgModelAssign = parsedNgModel.assign,
ngModelGet = parsedNgModel,
ngModelSet = parsedNgModelAssign,
pendingDebounce = null,
parserValid,
ctrl = this;
this.$$setOptions = function(options) {
ctrl.$options = options;
if (options && options.getterSetter) {
var invokeModelGetter = $parse($attr.ngModel + '()'),
invokeModelSetter = $parse($attr.ngModel + '($$$p)');
ngModelGet = function($scope) {
var modelValue = parsedNgModel($scope);
if (isFunction(modelValue)) {
modelValue = invokeModelGetter($scope);
}
return modelValue;
};
ngModelSet = function($scope, newValue) {
if (isFunction(parsedNgModel($scope))) {
invokeModelSetter($scope, {$$$p: ctrl.$modelValue});
} else {
parsedNgModelAssign($scope, ctrl.$modelValue);
}
};
} else if (!parsedNgModel.assign) {
throw $ngModelMinErr('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
$attr.ngModel, startingTag($element));
}
};
/**
* @ngdoc method
* @name ngModel.NgModelController#$render
*
* @description
* Called when the view needs to be updated. It is expected that the user of the ng-model
* directive will implement this method.
*
* The `$render()` method is invoked in the following situations:
*
* * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
* committed value then `$render()` is called to update the input control.
* * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
* the `$viewValue` are different to last time.
*
* Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
* `$modelValue` and `$viewValue` are actually different to their previous value. If `$modelValue`
* or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
* invoked if you only change a property on the objects.
*/
this.$render = noop;
/**
* @ngdoc method
* @name ngModel.NgModelController#$isEmpty
*
* @description
* This is called when we need to determine if the value of an input is empty.
*
* For instance, the required directive does this to work out if the input has data or not.
*
* The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
*
* You can override this for input directives whose concept of being empty is different to the
* default. The `checkboxInputType` directive does this because in its case a value of `false`
* implies empty.
*
* @param {*} value The value of the input to check for emptiness.
* @returns {boolean} True if `value` is "empty".
*/
this.$isEmpty = function(value) {
return isUndefined(value) || value === '' || value === null || value !== value;
};
var parentForm = $element.inheritedData('$formController') || nullFormCtrl,
currentValidationRunId = 0;
/**
* @ngdoc method
* @name ngModel.NgModelController#$setValidity
*
* @description
* Change the validity state, and notify the form.
*
* This method can be called within $parsers/$formatters or a custom validation implementation.
* However, in most cases it should be sufficient to use the `ngModel.$validators` and
* `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
*
* @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
* to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
* (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
* The `validationErrorKey` should be in camelCase and will get converted into dash-case
* for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
* class and can be bound to as `{{someForm.someControl.$error.myError}}` .
* @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
* or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
* Skipped is used by Angular when validators do not run because of parse errors and
* when `$asyncValidators` do not run because any of the `$validators` failed.
*/
addSetValidityMethod({
ctrl: this,
$element: $element,
set: function(object, property) {
object[property] = true;
},
unset: function(object, property) {
delete object[property];
},
parentForm: parentForm,
$animate: $animate
});
/**
* @ngdoc method
* @name ngModel.NgModelController#$setPristine
*
* @description
* Sets the control to its pristine state.
*
* This method can be called to remove the `ng-dirty` class and set the control to its pristine
* state (`ng-pristine` class). A model is considered to be pristine when the control
* has not been changed from when first compiled.
*/
this.$setPristine = function() {
ctrl.$dirty = false;
ctrl.$pristine = true;
$animate.removeClass($element, DIRTY_CLASS);
$animate.addClass($element, PRISTINE_CLASS);
};
/**
* @ngdoc method
* @name ngModel.NgModelController#$setDirty
*
* @description
* Sets the control to its dirty state.
*
* This method can be called to remove the `ng-pristine` class and set the control to its dirty
* state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
* from when first compiled.
*/
this.$setDirty = function() {
ctrl.$dirty = true;
ctrl.$pristine = false;
$animate.removeClass($element, PRISTINE_CLASS);
$animate.addClass($element, DIRTY_CLASS);
parentForm.$setDirty();
};
/**
* @ngdoc method
* @name ngModel.NgModelController#$setUntouched
*
* @description
* Sets the control to its untouched state.
*
* This method can be called to remove the `ng-touched` class and set the control to its
* untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
* by default, however this function can be used to restore that state if the model has
* already been touched by the user.
*/
this.$setUntouched = function() {
ctrl.$touched = false;
ctrl.$untouched = true;
$animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS);
};
/**
* @ngdoc method
* @name ngModel.NgModelController#$setTouched
*
* @description
* Sets the control to its touched state.
*
* This method can be called to remove the `ng-untouched` class and set the control to its
* touched state (`ng-touched` class). A model is considered to be touched when the user has
* first focused the control element and then shifted focus away from the control (blur event).
*/
this.$setTouched = function() {
ctrl.$touched = true;
ctrl.$untouched = false;
$animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS);
};
/**
* @ngdoc method
* @name ngModel.NgModelController#$rollbackViewValue
*
* @description
* Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
* which may be caused by a pending debounced event or because the input is waiting for a some
* future event.
*
* If you have an input that uses `ng-model-options` to set up debounced events or events such
* as blur you can have a situation where there is a period when the `$viewValue`
* is out of synch with the ngModel's `$modelValue`.
*
* In this case, you can run into difficulties if you try to update the ngModel's `$modelValue`
* programmatically before these debounced/future events have resolved/occurred, because Angular's
* dirty checking mechanism is not able to tell whether the model has actually changed or not.
*
* The `$rollbackViewValue()` method should be called before programmatically changing the model of an
* input which may have such events pending. This is important in order to make sure that the
* input field will be updated with the new model value and any pending operations are cancelled.
*
* <example name="ng-model-cancel-update" module="cancel-update-example">
* <file name="app.js">
* angular.module('cancel-update-example', [])
*
* .controller('CancelUpdateController', ['$scope', function($scope) {
* $scope.resetWithCancel = function(e) {
* if (e.keyCode == 27) {
* $scope.myForm.myInput1.$rollbackViewValue();
* $scope.myValue = '';
* }
* };
* $scope.resetWithoutCancel = function(e) {
* if (e.keyCode == 27) {
* $scope.myValue = '';
* }
* };
* }]);
* </file>
* <file name="index.html">
* <div ng-controller="CancelUpdateController">
* <p>Try typing something in each input. See that the model only updates when you
* blur off the input.
* </p>
* <p>Now see what happens if you start typing then press the Escape key</p>
*
* <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
* <p>With $rollbackViewValue()</p>
* <input name="myInput1" ng-model="myValue" ng-keydown="resetWithCancel($event)"><br/>
* myValue: "{{ myValue }}"
*
* <p>Without $rollbackViewValue()</p>
* <input name="myInput2" ng-model="myValue" ng-keydown="resetWithoutCancel($event)"><br/>
* myValue: "{{ myValue }}"
* </form>
* </div>
* </file>
* </example>
*/
this.$rollbackViewValue = function() {
$timeout.cancel(pendingDebounce);
ctrl.$viewValue = ctrl.$$lastCommittedViewValue;
ctrl.$render();
};
/**
* @ngdoc method
* @name ngModel.NgModelController#$validate
*
* @description
* Runs each of the registered validators (first synchronous validators and then
* asynchronous validators).
* If the validity changes to invalid, the model will be set to `undefined`,
* unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
* If the validity changes to valid, it will set the model to the last available valid
* modelValue, i.e. either the last parsed value or the last value set from the scope.
*/
this.$validate = function() {
// ignore $validate before model is initialized
if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
return;
}
var viewValue = ctrl.$$lastCommittedViewValue;
// Note: we use the $$rawModelValue as $modelValue might have been
// set to undefined during a view -> model update that found validation
// errors. We can't parse the view here, since that could change
// the model although neither viewValue nor the model on the scope changed
var modelValue = ctrl.$$rawModelValue;
var prevValid = ctrl.$valid;
var prevModelValue = ctrl.$modelValue;
var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
ctrl.$$runValidators(modelValue, viewValue, function(allValid) {
// If there was no change in validity, don't update the model
// This prevents changing an invalid modelValue to undefined
if (!allowInvalid && prevValid !== allValid) {
// Note: Don't check ctrl.$valid here, as we could have
// external validators (e.g. calculated on the server),
// that just call $setValidity and need the model value
// to calculate their validity.
ctrl.$modelValue = allValid ? modelValue : undefined;
if (ctrl.$modelValue !== prevModelValue) {
ctrl.$$writeModelToScope();
}
}
});
};
this.$$runValidators = function(modelValue, viewValue, doneCallback) {
currentValidationRunId++;
var localValidationRunId = currentValidationRunId;
// check parser error
if (!processParseErrors()) {
validationDone(false);
return;
}
if (!processSyncValidators()) {
validationDone(false);
return;
}
processAsyncValidators();
function processParseErrors() {
var errorKey = ctrl.$$parserName || 'parse';
if (parserValid === undefined) {
setValidity(errorKey, null);
} else {
if (!parserValid) {
forEach(ctrl.$validators, function(v, name) {
setValidity(name, null);
});
forEach(ctrl.$asyncValidators, function(v, name) {
setValidity(name, null);
});
}
// Set the parse error last, to prevent unsetting it, should a $validators key == parserName
setValidity(errorKey, parserValid);
return parserValid;
}
return true;
}
function processSyncValidators() {
var syncValidatorsValid = true;
forEach(ctrl.$validators, function(validator, name) {
var result = validator(modelValue, viewValue);
syncValidatorsValid = syncValidatorsValid && result;
setValidity(name, result);
});
if (!syncValidatorsValid) {
forEach(ctrl.$asyncValidators, function(v, name) {
setValidity(name, null);
});
return false;
}
return true;
}
function processAsyncValidators() {
var validatorPromises = [];
var allValid = true;
forEach(ctrl.$asyncValidators, function(validator, name) {
var promise = validator(modelValue, viewValue);
if (!isPromiseLike(promise)) {
throw $ngModelMinErr("$asyncValidators",
"Expected asynchronous validator to return a promise but got '{0}' instead.", promise);
}
setValidity(name, undefined);
validatorPromises.push(promise.then(function() {
setValidity(name, true);
}, function(error) {
allValid = false;
setValidity(name, false);
}));
});
if (!validatorPromises.length) {
validationDone(true);
} else {
$q.all(validatorPromises).then(function() {
validationDone(allValid);
}, noop);
}
}
function setValidity(name, isValid) {
if (localValidationRunId === currentValidationRunId) {
ctrl.$setValidity(name, isValid);
}
}
function validationDone(allValid) {
if (localValidationRunId === currentValidationRunId) {
doneCallback(allValid);
}
}
};
/**
* @ngdoc method
* @name ngModel.NgModelController#$commitViewValue
*
* @description
* Commit a pending update to the `$modelValue`.
*
* Updates may be pending by a debounced event or because the input is waiting for a some future
* event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
* usually handles calling this in response to input events.
*/
this.$commitViewValue = function() {
var viewValue = ctrl.$viewValue;
$timeout.cancel(pendingDebounce);
// If the view value has not changed then we should just exit, except in the case where there is
// a native validator on the element. In this case the validation state may have changed even though
// the viewValue has stayed empty.
if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) {
return;
}
ctrl.$$lastCommittedViewValue = viewValue;
// change to dirty
if (ctrl.$pristine) {
this.$setDirty();
}
this.$$parseAndValidate();
};
this.$$parseAndValidate = function() {
var viewValue = ctrl.$$lastCommittedViewValue;
var modelValue = viewValue;
parserValid = isUndefined(modelValue) ? undefined : true;
if (parserValid) {
for (var i = 0; i < ctrl.$parsers.length; i++) {
modelValue = ctrl.$parsers[i](modelValue);
if (isUndefined(modelValue)) {
parserValid = false;
break;
}
}
}
if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
// ctrl.$modelValue has not been touched yet...
ctrl.$modelValue = ngModelGet($scope);
}
var prevModelValue = ctrl.$modelValue;
var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
ctrl.$$rawModelValue = modelValue;
if (allowInvalid) {
ctrl.$modelValue = modelValue;
writeToModelIfNeeded();
}
// Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.
// This can happen if e.g. $setViewValue is called from inside a parser
ctrl.$$runValidators(modelValue, ctrl.$$lastCommittedViewValue, function(allValid) {
if (!allowInvalid) {
// Note: Don't check ctrl.$valid here, as we could have
// external validators (e.g. calculated on the server),
// that just call $setValidity and need the model value
// to calculate their validity.
ctrl.$modelValue = allValid ? modelValue : undefined;
writeToModelIfNeeded();
}
});
function writeToModelIfNeeded() {
if (ctrl.$modelValue !== prevModelValue) {
ctrl.$$writeModelToScope();
}
}
};
this.$$writeModelToScope = function() {
ngModelSet($scope, ctrl.$modelValue);
forEach(ctrl.$viewChangeListeners, function(listener) {
try {
listener();
} catch (e) {
$exceptionHandler(e);
}
});
};
/**
* @ngdoc method
* @name ngModel.NgModelController#$setViewValue
*
* @description
* Update the view value.
*
* This method should be called when an input directive want to change the view value; typically,
* this is done from within a DOM event handler.
*
* For example {@link ng.directive:input input} calls it when the value of the input changes and
* {@link ng.directive:select select} calls it when an option is selected.
*
* If the new `value` is an object (rather than a string or a number), we should make a copy of the
* object before passing it to `$setViewValue`. This is because `ngModel` does not perform a deep
* watch of objects, it only looks for a change of identity. If you only change the property of
* the object then ngModel will not realise that the object has changed and will not invoke the
* `$parsers` and `$validators` pipelines.
*
* For this reason, you should not change properties of the copy once it has been passed to
* `$setViewValue`. Otherwise you may cause the model value on the scope to change incorrectly.
*
* When this method is called, the new `value` will be staged for committing through the `$parsers`
* and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
* value sent directly for processing, finally to be applied to `$modelValue` and then the
* **expression** specified in the `ng-model` attribute.
*
* Lastly, all the registered change listeners, in the `$viewChangeListeners` list, are called.
*
* In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
* and the `default` trigger is not listed, all those actions will remain pending until one of the
* `updateOn` events is triggered on the DOM element.
* All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
* directive is used with a custom debounce for this particular event.
*
* Note that calling this function does not trigger a `$digest`.
*
* @param {string} value Value from the view.
* @param {string} trigger Event that triggered the update.
*/
this.$setViewValue = function(value, trigger) {
ctrl.$viewValue = value;
if (!ctrl.$options || ctrl.$options.updateOnDefault) {
ctrl.$$debounceViewValueCommit(trigger);
}
};
this.$$debounceViewValueCommit = function(trigger) {
var debounceDelay = 0,
options = ctrl.$options,
debounce;
if (options && isDefined(options.debounce)) {
debounce = options.debounce;
if (isNumber(debounce)) {
debounceDelay = debounce;
} else if (isNumber(debounce[trigger])) {
debounceDelay = debounce[trigger];
} else if (isNumber(debounce['default'])) {
debounceDelay = debounce['default'];
}
}
$timeout.cancel(pendingDebounce);
if (debounceDelay) {
pendingDebounce = $timeout(function() {
ctrl.$commitViewValue();
}, debounceDelay);
} else if ($rootScope.$$phase) {
ctrl.$commitViewValue();
} else {
$scope.$apply(function() {
ctrl.$commitViewValue();
});
}
};
// model -> value
// Note: we cannot use a normal scope.$watch as we want to detect the following:
// 1. scope value is 'a'
// 2. user enters 'b'
// 3. ng-change kicks in and reverts scope value to 'a'
// -> scope value did not change since the last digest as
// ng-change executes in apply phase
// 4. view should be changed back to 'a'
$scope.$watch(function ngModelWatch() {
var modelValue = ngModelGet($scope);
// if scope model value and ngModel value are out of sync
// TODO(perf): why not move this to the action fn?
if (modelValue !== ctrl.$modelValue) {
ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;
parserValid = undefined;
var formatters = ctrl.$formatters,
idx = formatters.length;
var viewValue = modelValue;
while (idx--) {
viewValue = formatters[idx](viewValue);
}
if (ctrl.$viewValue !== viewValue) {
ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
ctrl.$render();
ctrl.$$runValidators(modelValue, viewValue, noop);
}
}
return modelValue;
});
}];
/**
* @ngdoc directive
* @name ngModel
*
* @element input
* @priority 1
*
* @description
* The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
* property on the scope using {@link ngModel.NgModelController NgModelController},
* which is created and exposed by this directive.
*
* `ngModel` is responsible for:
*
* - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
* require.
* - Providing validation behavior (i.e. required, number, email, url).
* - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
* - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`, `ng-untouched`) including animations.
* - Registering the control with its parent {@link ng.directive:form form}.
*
* Note: `ngModel` will try to bind to the property given by evaluating the expression on the
* current scope. If the property doesn't already exist on this scope, it will be created
* implicitly and added to the scope.
*
* For best practices on using `ngModel`, see:
*
* - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
*
* For basic examples, how to use `ngModel`, see:
*
* - {@link ng.directive:input input}
* - {@link input[text] text}
* - {@link input[checkbox] checkbox}
* - {@link input[radio] radio}
* - {@link input[number] number}
* - {@link input[email] email}
* - {@link input[url] url}
* - {@link input[date] date}
* - {@link input[datetime-local] datetime-local}
* - {@link input[time] time}
* - {@link input[month] month}
* - {@link input[week] week}
* - {@link ng.directive:select select}
* - {@link ng.directive:textarea textarea}
*
* # CSS classes
* The following CSS classes are added and removed on the associated input/select/textarea element
* depending on the validity of the model.
*
* - `ng-valid`: the model is valid
* - `ng-invalid`: the model is invalid
* - `ng-valid-[key]`: for each valid key added by `$setValidity`
* - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
* - `ng-pristine`: the control hasn't been interacted with yet
* - `ng-dirty`: the control has been interacted with
* - `ng-touched`: the control has been blurred
* - `ng-untouched`: the control hasn't been blurred
* - `ng-pending`: any `$asyncValidators` are unfulfilled
*
* Keep in mind that ngAnimate can detect each of these classes when added and removed.
*
* ## Animation Hooks
*
* Animations within models are triggered when any of the associated CSS classes are added and removed
* on the input element which is attached to the model. These classes are: `.ng-pristine`, `.ng-dirty`,
* `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
* The animations that are triggered within ngModel are similar to how they work in ngClass and
* animations can be hooked into using CSS transitions, keyframes as well as JS animations.
*
* The following example shows a simple way to utilize CSS transitions to style an input element
* that has been rendered as invalid after it has been validated:
*
* <pre>
* //be sure to include ngAnimate as a module to hook into more
* //advanced animations
* .my-input {
* transition:0.5s linear all;
* background: white;
* }
* .my-input.ng-invalid {
* background: red;
* color:white;
* }
* </pre>
*
* @example
* <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample">
<file name="index.html">
<script>
angular.module('inputExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.val = '1';
}]);
</script>
<style>
.my-input {
-webkit-transition:all linear 0.5s;
transition:all linear 0.5s;
background: transparent;
}
.my-input.ng-invalid {
color:white;
background: red;
}
</style>
Update input to see transitions when valid/invalid.
Integer is a valid value.
<form name="testForm" ng-controller="ExampleController">
<input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input" />
</form>
</file>
* </example>
*
* ## Binding to a getter/setter
*
* Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
* function that returns a representation of the model when called with zero arguments, and sets
* the internal state of a model when called with an argument. It's sometimes useful to use this
* for models that have an internal representation that's different than what the model exposes
* to the view.
*
* <div class="alert alert-success">
* **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
* frequently than other parts of your code.
* </div>
*
* You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
* has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
* a `<form>`, which will enable this behavior for all `<input>`s within it. See
* {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
*
* The following example shows how to use `ngModel` with a getter/setter:
*
* @example
* <example name="ngModel-getter-setter" module="getterSetterExample">
<file name="index.html">
<div ng-controller="ExampleController">
<form name="userForm">
Name:
<input type="text" name="userName"
ng-model="user.name"
ng-model-options="{ getterSetter: true }" />
</form>
<pre>user.name = <span ng-bind="user.name()"></span></pre>
</div>
</file>
<file name="app.js">
angular.module('getterSetterExample', [])
.controller('ExampleController', ['$scope', function($scope) {
var _name = 'Brian';
$scope.user = {
name: function(newName) {
if (angular.isDefined(newName)) {
_name = newName;
}
return _name;
}
};
}]);
</file>
* </example>
*/
var ngModelDirective = ['$rootScope', function($rootScope) {
return {
restrict: 'A',
require: ['ngModel', '^?form', '^?ngModelOptions'],
controller: NgModelController,
// Prelink needs to run before any input directive
// so that we can set the NgModelOptions in NgModelController
// before anyone else uses it.
priority: 1,
compile: function ngModelCompile(element) {
// Setup initial state of the control
element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
return {
pre: function ngModelPreLink(scope, element, attr, ctrls) {
var modelCtrl = ctrls[0],
formCtrl = ctrls[1] || nullFormCtrl;
modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options);
// notify others, especially parent forms
formCtrl.$addControl(modelCtrl);
attr.$observe('name', function(newValue) {
if (modelCtrl.$name !== newValue) {
formCtrl.$$renameControl(modelCtrl, newValue);
}
});
scope.$on('$destroy', function() {
formCtrl.$removeControl(modelCtrl);
});
},
post: function ngModelPostLink(scope, element, attr, ctrls) {
var modelCtrl = ctrls[0];
if (modelCtrl.$options && modelCtrl.$options.updateOn) {
element.on(modelCtrl.$options.updateOn, function(ev) {
modelCtrl.$$debounceViewValueCommit(ev && ev.type);
});
}
element.on('blur', function(ev) {
if (modelCtrl.$touched) return;
if ($rootScope.$$phase) {
scope.$evalAsync(modelCtrl.$setTouched);
} else {
scope.$apply(modelCtrl.$setTouched);
}
});
}
};
}
};
}];
var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
/**
* @ngdoc directive
* @name ngModelOptions
*
* @description
* Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of
* events that will trigger a model update and/or a debouncing delay so that the actual update only
* takes place when a timer expires; this timer will be reset after another change takes place.
*
* Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
* be different than the value in the actual model. This means that if you update the model you
* should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in
* order to make sure it is synchronized with the model and that any debounced action is canceled.
*
* The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`}
* method is by making sure the input is placed inside a form that has a `name` attribute. This is
* important because `form` controllers are published to the related scope under the name in their
* `name` attribute.
*
* Any pending changes will take place immediately when an enclosing form is submitted via the
* `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
* to have access to the updated model.
*
* `ngModelOptions` has an effect on the element it's declared on and its descendants.
*
* @param {Object} ngModelOptions options to apply to the current model. Valid keys are:
* - `updateOn`: string specifying which event should the input be bound to. You can set several
* events using an space delimited list. There is a special event called `default` that
* matches the default events belonging of the control.
* - `debounce`: integer value which contains the debounce model update value in milliseconds. A
* value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
* custom value for each event. For example:
* `ng-model-options="{ updateOn: 'default blur', debounce: {'default': 500, 'blur': 0} }"`
* - `allowInvalid`: boolean value which indicates that the model can be set with values that did
* not validate correctly instead of the default behavior of setting the model to undefined.
* - `getterSetter`: boolean value which determines whether or not to treat functions bound to
`ngModel` as getters/setters.
* - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
* `<input type="date">`, `<input type="time">`, ... . Right now, the only supported value is `'UTC'`,
* otherwise the default timezone of the browser will be used.
*
* @example
The following example shows how to override immediate updates. Changes on the inputs within the
form will update the model only when the control loses focus (blur event). If `escape` key is
pressed while the input field is focused, the value is reset to the value in the current model.
<example name="ngModelOptions-directive-blur" module="optionsExample">
<file name="index.html">
<div ng-controller="ExampleController">
<form name="userForm">
Name:
<input type="text" name="userName"
ng-model="user.name"
ng-model-options="{ updateOn: 'blur' }"
ng-keyup="cancel($event)" /><br />
Other data:
<input type="text" ng-model="user.data" /><br />
</form>
<pre>user.name = <span ng-bind="user.name"></span></pre>
</div>
</file>
<file name="app.js">
angular.module('optionsExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.user = { name: 'say', data: '' };
$scope.cancel = function(e) {
if (e.keyCode == 27) {
$scope.userForm.userName.$rollbackViewValue();
}
};
}]);
</file>
<file name="protractor.js" type="protractor">
var model = element(by.binding('user.name'));
var input = element(by.model('user.name'));
var other = element(by.model('user.data'));
it('should allow custom events', function() {
input.sendKeys(' hello');
input.click();
expect(model.getText()).toEqual('say');
other.click();
expect(model.getText()).toEqual('say hello');
});
it('should $rollbackViewValue when model changes', function() {
input.sendKeys(' hello');
expect(input.getAttribute('value')).toEqual('say hello');
input.sendKeys(protractor.Key.ESCAPE);
expect(input.getAttribute('value')).toEqual('say');
other.click();
expect(model.getText()).toEqual('say');
});
</file>
</example>
This one shows how to debounce model changes. Model will be updated only 1 sec after last change.
If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
<example name="ngModelOptions-directive-debounce" module="optionsExample">
<file name="index.html">
<div ng-controller="ExampleController">
<form name="userForm">
Name:
<input type="text" name="userName"
ng-model="user.name"
ng-model-options="{ debounce: 1000 }" />
<button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button><br />
</form>
<pre>user.name = <span ng-bind="user.name"></span></pre>
</div>
</file>
<file name="app.js">
angular.module('optionsExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.user = { name: 'say' };
}]);
</file>
</example>
This one shows how to bind to getter/setters:
<example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
<file name="index.html">
<div ng-controller="ExampleController">
<form name="userForm">
Name:
<input type="text" name="userName"
ng-model="user.name"
ng-model-options="{ getterSetter: true }" />
</form>
<pre>user.name = <span ng-bind="user.name()"></span></pre>
</div>
</file>
<file name="app.js">
angular.module('getterSetterExample', [])
.controller('ExampleController', ['$scope', function($scope) {
var _name = 'Brian';
$scope.user = {
name: function(newName) {
return angular.isDefined(newName) ? (_name = newName) : _name;
}
};
}]);
</file>
</example>
*/
var ngModelOptionsDirective = function() {
return {
restrict: 'A',
controller: ['$scope', '$attrs', function($scope, $attrs) {
var that = this;
this.$options = $scope.$eval($attrs.ngModelOptions);
// Allow adding/overriding bound events
if (this.$options.updateOn !== undefined) {
this.$options.updateOnDefault = false;
// extract "default" pseudo-event from list of events that can trigger a model update
this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() {
that.$options.updateOnDefault = true;
return ' ';
}));
} else {
this.$options.updateOnDefault = true;
}
}]
};
};
// helper methods
function addSetValidityMethod(context) {
var ctrl = context.ctrl,
$element = context.$element,
classCache = {},
set = context.set,
unset = context.unset,
parentForm = context.parentForm,
$animate = context.$animate;
classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS));
ctrl.$setValidity = setValidity;
function setValidity(validationErrorKey, state, controller) {
if (state === undefined) {
createAndSet('$pending', validationErrorKey, controller);
} else {
unsetAndCleanup('$pending', validationErrorKey, controller);
}
if (!isBoolean(state)) {
unset(ctrl.$error, validationErrorKey, controller);
unset(ctrl.$$success, validationErrorKey, controller);
} else {
if (state) {
unset(ctrl.$error, validationErrorKey, controller);
set(ctrl.$$success, validationErrorKey, controller);
} else {
set(ctrl.$error, validationErrorKey, controller);
unset(ctrl.$$success, validationErrorKey, controller);
}
}
if (ctrl.$pending) {
cachedToggleClass(PENDING_CLASS, true);
ctrl.$valid = ctrl.$invalid = undefined;
toggleValidationCss('', null);
} else {
cachedToggleClass(PENDING_CLASS, false);
ctrl.$valid = isObjectEmpty(ctrl.$error);
ctrl.$invalid = !ctrl.$valid;
toggleValidationCss('', ctrl.$valid);
}
// re-read the state as the set/unset methods could have
// combined state in ctrl.$error[validationError] (used for forms),
// where setting/unsetting only increments/decrements the value,
// and does not replace it.
var combinedState;
if (ctrl.$pending && ctrl.$pending[validationErrorKey]) {
combinedState = undefined;
} else if (ctrl.$error[validationErrorKey]) {
combinedState = false;
} else if (ctrl.$$success[validationErrorKey]) {
combinedState = true;
} else {
combinedState = null;
}
toggleValidationCss(validationErrorKey, combinedState);
parentForm.$setValidity(validationErrorKey, combinedState, ctrl);
}
function createAndSet(name, value, controller) {
if (!ctrl[name]) {
ctrl[name] = {};
}
set(ctrl[name], value, controller);
}
function unsetAndCleanup(name, value, controller) {
if (ctrl[name]) {
unset(ctrl[name], value, controller);
}
if (isObjectEmpty(ctrl[name])) {
ctrl[name] = undefined;
}
}
function cachedToggleClass(className, switchValue) {
if (switchValue && !classCache[className]) {
$animate.addClass($element, className);
classCache[className] = true;
} else if (!switchValue && classCache[className]) {
$animate.removeClass($element, className);
classCache[className] = false;
}
}
function toggleValidationCss(validationErrorKey, isValid) {
validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true);
cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false);
}
}
function isObjectEmpty(obj) {
if (obj) {
for (var prop in obj) {
return false;
}
}
return true;
}
/**
* @ngdoc directive
* @name ngNonBindable
* @restrict AC
* @priority 1000
*
* @description
* The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
* DOM element. This is useful if the element contains what appears to be Angular directives and
* bindings but which should be ignored by Angular. This could be the case if you have a site that
* displays snippets of code, for instance.
*
* @element ANY
*
* @example
* In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
* but the one wrapped in `ngNonBindable` is left alone.
*
* @example
<example>
<file name="index.html">
<div>Normal: {{1 + 2}}</div>
<div ng-non-bindable>Ignored: {{1 + 2}}</div>
</file>
<file name="protractor.js" type="protractor">
it('should check ng-non-bindable', function() {
expect(element(by.binding('1 + 2')).getText()).toContain('3');
expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
});
</file>
</example>
*/
var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
/**
* @ngdoc directive
* @name ngPluralize
* @restrict EA
*
* @description
* `ngPluralize` is a directive that displays messages according to en-US localization rules.
* These rules are bundled with angular.js, but can be overridden
* (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
* by specifying the mappings between
* [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
* and the strings to be displayed.
*
* # Plural categories and explicit number rules
* There are two
* [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
* in Angular's default en-US locale: "one" and "other".
*
* While a plural category may match many numbers (for example, in en-US locale, "other" can match
* any number that is not 1), an explicit number rule can only match one number. For example, the
* explicit number rule for "3" matches the number 3. There are examples of plural categories
* and explicit number rules throughout the rest of this documentation.
*
* # Configuring ngPluralize
* You configure ngPluralize by providing 2 attributes: `count` and `when`.
* You can also provide an optional attribute, `offset`.
*
* The value of the `count` attribute can be either a string or an {@link guide/expression
* Angular expression}; these are evaluated on the current scope for its bound value.
*
* The `when` attribute specifies the mappings between plural categories and the actual
* string to be displayed. The value of the attribute should be a JSON object.
*
* The following example shows how to configure ngPluralize:
*
* ```html
* <ng-pluralize count="personCount"
when="{'0': 'Nobody is viewing.',
* 'one': '1 person is viewing.',
* 'other': '{} people are viewing.'}">
* </ng-pluralize>
*```
*
* In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
* specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
* would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
* other numbers, for example 12, so that instead of showing "12 people are viewing", you can
* show "a dozen people are viewing".
*
* You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
* into pluralized strings. In the previous example, Angular will replace `{}` with
* <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
* for <span ng-non-bindable>{{numberExpression}}</span>.
*
* # Configuring ngPluralize with offset
* The `offset` attribute allows further customization of pluralized text, which can result in
* a better user experience. For example, instead of the message "4 people are viewing this document",
* you might display "John, Kate and 2 others are viewing this document".
* The offset attribute allows you to offset a number by any desired value.
* Let's take a look at an example:
*
* ```html
* <ng-pluralize count="personCount" offset=2
* when="{'0': 'Nobody is viewing.',
* '1': '{{person1}} is viewing.',
* '2': '{{person1}} and {{person2}} are viewing.',
* 'one': '{{person1}}, {{person2}} and one other person are viewing.',
* 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
* </ng-pluralize>
* ```
*
* Notice that we are still using two plural categories(one, other), but we added
* three explicit number rules 0, 1 and 2.
* When one person, perhaps John, views the document, "John is viewing" will be shown.
* When three people view the document, no explicit number rule is found, so
* an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
* In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
* is shown.
*
* Note that when you specify offsets, you must provide explicit number rules for
* numbers from 0 up to and including the offset. If you use an offset of 3, for example,
* you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
* plural categories "one" and "other".
*
* @param {string|expression} count The variable to be bound to.
* @param {string} when The mapping between plural category to its corresponding strings.
* @param {number=} offset Offset to deduct from the total number.
*
* @example
<example module="pluralizeExample">
<file name="index.html">
<script>
angular.module('pluralizeExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.person1 = 'Igor';
$scope.person2 = 'Misko';
$scope.personCount = 1;
}]);
</script>
<div ng-controller="ExampleController">
Person 1:<input type="text" ng-model="person1" value="Igor" /><br/>
Person 2:<input type="text" ng-model="person2" value="Misko" /><br/>
Number of People:<input type="text" ng-model="personCount" value="1" /><br/>
<!--- Example with simple pluralization rules for en locale --->
Without Offset:
<ng-pluralize count="personCount"
when="{'0': 'Nobody is viewing.',
'one': '1 person is viewing.',
'other': '{} people are viewing.'}">
</ng-pluralize><br>
<!--- Example with offset --->
With Offset(2):
<ng-pluralize count="personCount" offset=2
when="{'0': 'Nobody is viewing.',
'1': '{{person1}} is viewing.',
'2': '{{person1}} and {{person2}} are viewing.',
'one': '{{person1}}, {{person2}} and one other person are viewing.',
'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
</ng-pluralize>
</div>
</file>
<file name="protractor.js" type="protractor">
it('should show correct pluralized string', function() {
var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
var withOffset = element.all(by.css('ng-pluralize')).get(1);
var countInput = element(by.model('personCount'));
expect(withoutOffset.getText()).toEqual('1 person is viewing.');
expect(withOffset.getText()).toEqual('Igor is viewing.');
countInput.clear();
countInput.sendKeys('0');
expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
expect(withOffset.getText()).toEqual('Nobody is viewing.');
countInput.clear();
countInput.sendKeys('2');
expect(withoutOffset.getText()).toEqual('2 people are viewing.');
expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
countInput.clear();
countInput.sendKeys('3');
expect(withoutOffset.getText()).toEqual('3 people are viewing.');
expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
countInput.clear();
countInput.sendKeys('4');
expect(withoutOffset.getText()).toEqual('4 people are viewing.');
expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
});
it('should show data-bound names', function() {
var withOffset = element.all(by.css('ng-pluralize')).get(1);
var personCount = element(by.model('personCount'));
var person1 = element(by.model('person1'));
var person2 = element(by.model('person2'));
personCount.clear();
personCount.sendKeys('4');
person1.clear();
person1.sendKeys('Di');
person2.clear();
person2.sendKeys('Vojta');
expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
});
</file>
</example>
*/
var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) {
var BRACE = /{}/g,
IS_WHEN = /^when(Minus)?(.+)$/;
return {
restrict: 'EA',
link: function(scope, element, attr) {
var numberExp = attr.count,
whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
offset = attr.offset || 0,
whens = scope.$eval(whenExp) || {},
whensExpFns = {},
startSymbol = $interpolate.startSymbol(),
endSymbol = $interpolate.endSymbol(),
braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
watchRemover = angular.noop,
lastCount;
forEach(attr, function(expression, attributeName) {
var tmpMatch = IS_WHEN.exec(attributeName);
if (tmpMatch) {
var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
whens[whenKey] = element.attr(attr.$attr[attributeName]);
}
});
forEach(whens, function(expression, key) {
whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
});
scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
var count = parseFloat(newVal);
var countIsNaN = isNaN(count);
if (!countIsNaN && !(count in whens)) {
// If an explicit number rule such as 1, 2, 3... is defined, just use it.
// Otherwise, check it against pluralization rules in $locale service.
count = $locale.pluralCat(count - offset);
}
// If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
// In JS `NaN !== NaN`, so we have to exlicitly check.
if ((count !== lastCount) && !(countIsNaN && isNaN(lastCount))) {
watchRemover();
watchRemover = scope.$watch(whensExpFns[count], updateElementText);
lastCount = count;
}
});
function updateElementText(newText) {
element.text(newText || '');
}
}
};
}];
/**
* @ngdoc directive
* @name ngRepeat
*
* @description
* The `ngRepeat` directive instantiates a template once per item from a collection. Each template
* instance gets its own scope, where the given loop variable is set to the current collection item,
* and `$index` is set to the item index or key.
*
* Special properties are exposed on the local scope of each template instance, including:
*
* | Variable | Type | Details |
* |-----------|-----------------|-----------------------------------------------------------------------------|
* | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
* | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
* | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
* | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
* | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
* | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
*
* Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
* This may be useful when, for instance, nesting ngRepeats.
*
* # Iterating over object properties
*
* It is possible to get `ngRepeat` to iterate over the properties of an object using the following
* syntax:
*
* ```js
* <div ng-repeat="(key, value) in myObj"> ... </div>
* ```
*
* You need to be aware that the JavaScript specification does not define what order
* it will return the keys for an object. In order to have a guaranteed deterministic order
* for the keys, Angular versions up to and including 1.3 **sort the keys alphabetically**.
*
* If this is not desired, the recommended workaround is to convert your object into an array
* that is sorted into the order that you prefer before providing it to `ngRepeat`. You could
* do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)
* or implement a `$watch` on the object yourself.
*
* In version 1.4 we will remove the sorting, since it seems that browsers generally follow the
* strategy of providing keys in the order in which they were defined, although there are exceptions
* when keys are deleted and reinstated.
*
*
* # Tracking and Duplicates
*
* When the contents of the collection change, `ngRepeat` makes the corresponding changes to the DOM:
*
* * When an item is added, a new instance of the template is added to the DOM.
* * When an item is removed, its template instance is removed from the DOM.
* * When items are reordered, their respective templates are reordered in the DOM.
*
* By default, `ngRepeat` does not allow duplicate items in arrays. This is because when
* there are duplicates, it is not possible to maintain a one-to-one mapping between collection
* items and DOM elements.
*
* If you do need to repeat duplicate items, you can substitute the default tracking behavior
* with your own using the `track by` expression.
*
* For example, you may track items by the index of each item in the collection, using the
* special scope property `$index`:
* ```html
* <div ng-repeat="n in [42, 42, 43, 43] track by $index">
* {{n}}
* </div>
* ```
*
* You may use arbitrary expressions in `track by`, including references to custom functions
* on the scope:
* ```html
* <div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)">
* {{n}}
* </div>
* ```
*
* If you are working with objects that have an identifier property, you can track
* by the identifier instead of the whole object. Should you reload your data later, `ngRepeat`
* will not have to rebuild the DOM elements for items it has already rendered, even if the
* JavaScript objects in the collection have been substituted for new ones:
* ```html
* <div ng-repeat="model in collection track by model.id">
* {{model.name}}
* </div>
* ```
*
* When no `track by` expression is provided, it is equivalent to tracking by the built-in
* `$id` function, which tracks items by their identity:
* ```html
* <div ng-repeat="obj in collection track by $id(obj)">
* {{obj.prop}}
* </div>
* ```
*
* # Special repeat start and end points
* To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
* the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
* The **ng-repeat-start** directive works the same as **ng-repeat**, but will repeat all the HTML code (including the tag it's defined on)
* up to and including the ending HTML tag where **ng-repeat-end** is placed.
*
* The example below makes use of this feature:
* ```html
* <header ng-repeat-start="item in items">
* Header {{ item }}
* </header>
* <div class="body">
* Body {{ item }}
* </div>
* <footer ng-repeat-end>
* Footer {{ item }}
* </footer>
* ```
*
* And with an input of {@type ['A','B']} for the items variable in the example above, the output will guide to:
* ```html
* <header>
* Header A
* </header>
* <div class="body">
* Body A
* </div>
* <footer>
* Footer A
* </footer>
* <header>
* Header B
* </header>
* <div class="body">
* Body B
* </div>
* <footer>
* Footer B
* </footer>
* ```
*
* The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
* as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
*
* @animations
* **.enter** - when a new item is added to the list or when an item is revealed after a filter
*
* **.leave** - when an item is removed from the list or when an item is filtered out
*
* **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered
*
* @element ANY
* @scope
* @priority 1000
* @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
* formats are currently supported:
*
* * `variable in expression` – where variable is the user defined loop variable and `expression`
* is a scope expression giving the collection to enumerate.
*
* For example: `album in artist.albums`.
*
* * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
* and `expression` is the scope expression giving the collection to enumerate.
*
* For example: `(name, age) in {'adam':10, 'amalie':12}`.
*
* * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression
* which can be used to associate the objects in the collection with the DOM elements. If no tracking expression
* is specified, ng-repeat associates elements by identity. It is an error to have
* more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are
* mapped to the same DOM element, which is not possible.) If filters are used in the expression, they should be
* applied before the tracking expression.
*
* For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
* will be associated by item identity in the array.
*
* For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
* `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
* with the corresponding item in the array by identity. Moving the same object in array would move the DOM
* element in the same way in the DOM.
*
* For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
* case the object identity does not matter. Two objects are considered equivalent as long as their `id`
* property is same.
*
* For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
* to items in conjunction with a tracking expression.
*
* * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
* intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
* when a filter is active on the repeater, but the filtered result set is empty.
*
* For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
* the items have been processed through the filter.
*
* @example
* This example initializes the scope to a list of names and
* then uses `ngRepeat` to display every person:
<example module="ngAnimate" deps="angular-animate.js" animations="true">
<file name="index.html">
<div ng-init="friends = [
{name:'John', age:25, gender:'boy'},
{name:'Jessie', age:30, gender:'girl'},
{name:'Johanna', age:28, gender:'girl'},
{name:'Joy', age:15, gender:'girl'},
{name:'Mary', age:28, gender:'girl'},
{name:'Peter', age:95, gender:'boy'},
{name:'Sebastian', age:50, gender:'boy'},
{name:'Erika', age:27, gender:'girl'},
{name:'Patrick', age:40, gender:'boy'},
{name:'Samantha', age:60, gender:'girl'}
]">
I have {{friends.length}} friends. They are:
<input type="search" ng-model="q" placeholder="filter friends..." />
<ul class="example-animate-container">
<li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
[{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
</li>
<li class="animate-repeat" ng-if="results.length == 0">
<strong>No results found...</strong>
</li>
</ul>
</div>
</file>
<file name="animations.css">
.example-animate-container {
background:white;
border:1px solid black;
list-style:none;
margin:0;
padding:0 10px;
}
.animate-repeat {
line-height:40px;
list-style:none;
box-sizing:border-box;
}
.animate-repeat.ng-move,
.animate-repeat.ng-enter,
.animate-repeat.ng-leave {
-webkit-transition:all linear 0.5s;
transition:all linear 0.5s;
}
.animate-repeat.ng-leave.ng-leave-active,
.animate-repeat.ng-move,
.animate-repeat.ng-enter {
opacity:0;
max-height:0;
}
.animate-repeat.ng-leave,
.animate-repeat.ng-move.ng-move-active,
.animate-repeat.ng-enter.ng-enter-active {
opacity:1;
max-height:40px;
}
</file>
<file name="protractor.js" type="protractor">
var friends = element.all(by.repeater('friend in friends'));
it('should render initial data set', function() {
expect(friends.count()).toBe(10);
expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
expect(element(by.binding('friends.length')).getText())
.toMatch("I have 10 friends. They are:");
});
it('should update repeater when filter predicate changes', function() {
expect(friends.count()).toBe(10);
element(by.model('q')).sendKeys('ma');
expect(friends.count()).toBe(2);
expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
});
</file>
</example>
*/
var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
var NG_REMOVED = '$$NG_REMOVED';
var ngRepeatMinErr = minErr('ngRepeat');
var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
// TODO(perf): generate setters to shave off ~40ms or 1-1.5%
scope[valueIdentifier] = value;
if (keyIdentifier) scope[keyIdentifier] = key;
scope.$index = index;
scope.$first = (index === 0);
scope.$last = (index === (arrayLength - 1));
scope.$middle = !(scope.$first || scope.$last);
// jshint bitwise: false
scope.$odd = !(scope.$even = (index&1) === 0);
// jshint bitwise: true
};
var getBlockStart = function(block) {
return block.clone[0];
};
var getBlockEnd = function(block) {
return block.clone[block.clone.length - 1];
};
return {
restrict: 'A',
multiElement: true,
transclude: 'element',
priority: 1000,
terminal: true,
$$tlb: true,
compile: function ngRepeatCompile($element, $attr) {
var expression = $attr.ngRepeat;
var ngRepeatEndComment = document.createComment(' end ngRepeat: ' + expression + ' ');
var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+track\s+by\s+([\s\S]+?))?\s*$/);
if (!match) {
throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
expression);
}
var lhs = match[1];
var rhs = match[2];
var aliasAs = match[3];
var trackByExp = match[4];
match = lhs.match(/^(?:(\s*[\$\w]+)|\(\s*([\$\w]+)\s*,\s*([\$\w]+)\s*\))$/);
if (!match) {
throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
lhs);
}
var valueIdentifier = match[3] || match[1];
var keyIdentifier = match[2];
if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
/^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) {
throw ngRepeatMinErr('badident', "alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.",
aliasAs);
}
var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
var hashFnLocals = {$id: hashKey};
if (trackByExp) {
trackByExpGetter = $parse(trackByExp);
} else {
trackByIdArrayFn = function(key, value) {
return hashKey(value);
};
trackByIdObjFn = function(key) {
return key;
};
}
return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
if (trackByExpGetter) {
trackByIdExpFn = function(key, value, index) {
// assign key, value, and $index to the locals so that they can be used in hash functions
if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
hashFnLocals[valueIdentifier] = value;
hashFnLocals.$index = index;
return trackByExpGetter($scope, hashFnLocals);
};
}
// Store a list of elements from previous run. This is a hash where key is the item from the
// iterator, and the value is objects with following properties.
// - scope: bound scope
// - element: previous element.
// - index: position
//
// We are using no-proto object so that we don't need to guard against inherited props via
// hasOwnProperty.
var lastBlockMap = createMap();
//watch props
$scope.$watchCollection(rhs, function ngRepeatAction(collection) {
var index, length,
previousNode = $element[0], // node that cloned nodes should be inserted after
// initialized to the comment node anchor
nextNode,
// Same as lastBlockMap but it has the current state. It will become the
// lastBlockMap on the next iteration.
nextBlockMap = createMap(),
collectionLength,
key, value, // key/value of iteration
trackById,
trackByIdFn,
collectionKeys,
block, // last object information {scope, element, id}
nextBlockOrder,
elementsToRemove;
if (aliasAs) {
$scope[aliasAs] = collection;
}
if (isArrayLike(collection)) {
collectionKeys = collection;
trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
} else {
trackByIdFn = trackByIdExpFn || trackByIdObjFn;
// if object, extract keys, sort them and use to determine order of iteration over obj props
collectionKeys = [];
for (var itemKey in collection) {
if (collection.hasOwnProperty(itemKey) && itemKey.charAt(0) != '$') {
collectionKeys.push(itemKey);
}
}
collectionKeys.sort();
}
collectionLength = collectionKeys.length;
nextBlockOrder = new Array(collectionLength);
// locate existing items
for (index = 0; index < collectionLength; index++) {
key = (collection === collectionKeys) ? index : collectionKeys[index];
value = collection[key];
trackById = trackByIdFn(key, value, index);
if (lastBlockMap[trackById]) {
// found previously seen block
block = lastBlockMap[trackById];
delete lastBlockMap[trackById];
nextBlockMap[trackById] = block;
nextBlockOrder[index] = block;
} else if (nextBlockMap[trackById]) {
// if collision detected. restore lastBlockMap and throw an error
forEach(nextBlockOrder, function(block) {
if (block && block.scope) lastBlockMap[block.id] = block;
});
throw ngRepeatMinErr('dupes',
"Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}",
expression, trackById, value);
} else {
// new never before seen block
nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
nextBlockMap[trackById] = true;
}
}
// remove leftover items
for (var blockKey in lastBlockMap) {
block = lastBlockMap[blockKey];
elementsToRemove = getBlockNodes(block.clone);
$animate.leave(elementsToRemove);
if (elementsToRemove[0].parentNode) {
// if the element was not removed yet because of pending animation, mark it as deleted
// so that we can ignore it later
for (index = 0, length = elementsToRemove.length; index < length; index++) {
elementsToRemove[index][NG_REMOVED] = true;
}
}
block.scope.$destroy();
}
// we are not using forEach for perf reasons (trying to avoid #call)
for (index = 0; index < collectionLength; index++) {
key = (collection === collectionKeys) ? index : collectionKeys[index];
value = collection[key];
block = nextBlockOrder[index];
if (block.scope) {
// if we have already seen this object, then we need to reuse the
// associated scope/element
nextNode = previousNode;
// skip nodes that are already pending removal via leave animation
do {
nextNode = nextNode.nextSibling;
} while (nextNode && nextNode[NG_REMOVED]);
if (getBlockStart(block) != nextNode) {
// existing item which got moved
$animate.move(getBlockNodes(block.clone), null, jqLite(previousNode));
}
previousNode = getBlockEnd(block);
updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
} else {
// new item which we don't know about
$transclude(function ngRepeatTransclude(clone, scope) {
block.scope = scope;
// http://jsperf.com/clone-vs-createcomment
var endNode = ngRepeatEndComment.cloneNode(false);
clone[clone.length++] = endNode;
// TODO(perf): support naked previousNode in `enter` to avoid creation of jqLite wrapper?
$animate.enter(clone, null, jqLite(previousNode));
previousNode = endNode;
// Note: We only need the first/last node of the cloned nodes.
// However, we need to keep the reference to the jqlite wrapper as it might be changed later
// by a directive with templateUrl when its template arrives.
block.clone = clone;
nextBlockMap[block.id] = block;
updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
});
}
}
lastBlockMap = nextBlockMap;
});
};
}
};
}];
var NG_HIDE_CLASS = 'ng-hide';
var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
/**
* @ngdoc directive
* @name ngShow
*
* @description
* The `ngShow` directive shows or hides the given HTML element based on the expression
* provided to the `ngShow` attribute. The element is shown or hidden by removing or adding
* the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
* in AngularJS and sets the display style to none (using an !important flag).
* For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
*
* ```html
* <!-- when $scope.myValue is truthy (element is visible) -->
* <div ng-show="myValue"></div>
*
* <!-- when $scope.myValue is falsy (element is hidden) -->
* <div ng-show="myValue" class="ng-hide"></div>
* ```
*
* When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class
* attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed
* from the element causing the element not to appear hidden.
*
* ## Why is !important used?
*
* You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
* can be easily overridden by heavier selectors. For example, something as simple
* as changing the display style on a HTML list item would make hidden elements appear visible.
* This also becomes a bigger issue when dealing with CSS frameworks.
*
* By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
* specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
* styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
*
* ### Overriding `.ng-hide`
*
* By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
* the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
* class CSS. Note that the selector that needs to be used is actually `.ng-hide:not(.ng-hide-animate)` to cope
* with extra animation classes that can be added.
*
* ```css
* .ng-hide:not(.ng-hide-animate) {
* /* this is just another form of hiding an element */
* display: block!important;
* position: absolute;
* top: -9999px;
* left: -9999px;
* }
* ```
*
* By default you don't need to override in CSS anything and the animations will work around the display style.
*
* ## A note about animations with `ngShow`
*
* Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
* is true and false. This system works like the animation system present with ngClass except that
* you must also include the !important flag to override the display property
* so that you can perform an animation when the element is hidden during the time of the animation.
*
* ```css
* //
* //a working example can be found at the bottom of this page
* //
* .my-element.ng-hide-add, .my-element.ng-hide-remove {
* /* this is required as of 1.3x to properly
* apply all styling in a show/hide animation */
* transition: 0s linear all;
* }
*
* .my-element.ng-hide-add-active,
* .my-element.ng-hide-remove-active {
* /* the transition is defined in the active class */
* transition: 1s linear all;
* }
*
* .my-element.ng-hide-add { ... }
* .my-element.ng-hide-add.ng-hide-add-active { ... }
* .my-element.ng-hide-remove { ... }
* .my-element.ng-hide-remove.ng-hide-remove-active { ... }
* ```
*
* Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
* property to block during animation states--ngAnimate will handle the style toggling automatically for you.
*
* @animations
* addClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a truthy value and the just before contents are set to visible
* removeClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden
*
* @element ANY
* @param {expression} ngShow If the {@link guide/expression expression} is truthy
* then the element is shown or hidden respectively.
*
* @example
<example module="ngAnimate" deps="angular-animate.js" animations="true">
<file name="index.html">
Click me: <input type="checkbox" ng-model="checked"><br/>
<div>
Show:
<div class="check-element animate-show" ng-show="checked">
<span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
</div>
</div>
<div>
Hide:
<div class="check-element animate-show" ng-hide="checked">
<span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
</div>
</div>
</file>
<file name="glyphicons.css">
@import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
</file>
<file name="animations.css">
.animate-show {
line-height: 20px;
opacity: 1;
padding: 10px;
border: 1px solid black;
background: white;
}
.animate-show.ng-hide-add.ng-hide-add-active,
.animate-show.ng-hide-remove.ng-hide-remove-active {
-webkit-transition: all linear 0.5s;
transition: all linear 0.5s;
}
.animate-show.ng-hide {
line-height: 0;
opacity: 0;
padding: 0 10px;
}
.check-element {
padding: 10px;
border: 1px solid black;
background: white;
}
</file>
<file name="protractor.js" type="protractor">
var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
it('should check ng-show / ng-hide', function() {
expect(thumbsUp.isDisplayed()).toBeFalsy();
expect(thumbsDown.isDisplayed()).toBeTruthy();
element(by.model('checked')).click();
expect(thumbsUp.isDisplayed()).toBeTruthy();
expect(thumbsDown.isDisplayed()).toBeFalsy();
});
</file>
</example>
*/
var ngShowDirective = ['$animate', function($animate) {
return {
restrict: 'A',
multiElement: true,
link: function(scope, element, attr) {
scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
// we're adding a temporary, animation-specific class for ng-hide since this way
// we can control when the element is actually displayed on screen without having
// to have a global/greedy CSS selector that breaks when other animations are run.
// Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
$animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
tempClasses: NG_HIDE_IN_PROGRESS_CLASS
});
});
}
};
}];
/**
* @ngdoc directive
* @name ngHide
*
* @description
* The `ngHide` directive shows or hides the given HTML element based on the expression
* provided to the `ngHide` attribute. The element is shown or hidden by removing or adding
* the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
* in AngularJS and sets the display style to none (using an !important flag).
* For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
*
* ```html
* <!-- when $scope.myValue is truthy (element is hidden) -->
* <div ng-hide="myValue" class="ng-hide"></div>
*
* <!-- when $scope.myValue is falsy (element is visible) -->
* <div ng-hide="myValue"></div>
* ```
*
* When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class
* attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed
* from the element causing the element not to appear hidden.
*
* ## Why is !important used?
*
* You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
* can be easily overridden by heavier selectors. For example, something as simple
* as changing the display style on a HTML list item would make hidden elements appear visible.
* This also becomes a bigger issue when dealing with CSS frameworks.
*
* By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
* specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
* styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
*
* ### Overriding `.ng-hide`
*
* By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
* the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
* class in CSS:
*
* ```css
* .ng-hide {
* /* this is just another form of hiding an element */
* display: block!important;
* position: absolute;
* top: -9999px;
* left: -9999px;
* }
* ```
*
* By default you don't need to override in CSS anything and the animations will work around the display style.
*
* ## A note about animations with `ngHide`
*
* Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
* is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`
* CSS class is added and removed for you instead of your own CSS class.
*
* ```css
* //
* //a working example can be found at the bottom of this page
* //
* .my-element.ng-hide-add, .my-element.ng-hide-remove {
* transition: 0.5s linear all;
* }
*
* .my-element.ng-hide-add { ... }
* .my-element.ng-hide-add.ng-hide-add-active { ... }
* .my-element.ng-hide-remove { ... }
* .my-element.ng-hide-remove.ng-hide-remove-active { ... }
* ```
*
* Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
* property to block during animation states--ngAnimate will handle the style toggling automatically for you.
*
* @animations
* removeClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden
* addClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a non truthy value and just before the contents are set to visible
*
* @element ANY
* @param {expression} ngHide If the {@link guide/expression expression} is truthy then
* the element is shown or hidden respectively.
*
* @example
<example module="ngAnimate" deps="angular-animate.js" animations="true">
<file name="index.html">
Click me: <input type="checkbox" ng-model="checked"><br/>
<div>
Show:
<div class="check-element animate-hide" ng-show="checked">
<span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
</div>
</div>
<div>
Hide:
<div class="check-element animate-hide" ng-hide="checked">
<span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
</div>
</div>
</file>
<file name="glyphicons.css">
@import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
</file>
<file name="animations.css">
.animate-hide {
-webkit-transition: all linear 0.5s;
transition: all linear 0.5s;
line-height: 20px;
opacity: 1;
padding: 10px;
border: 1px solid black;
background: white;
}
.animate-hide.ng-hide {
line-height: 0;
opacity: 0;
padding: 0 10px;
}
.check-element {
padding: 10px;
border: 1px solid black;
background: white;
}
</file>
<file name="protractor.js" type="protractor">
var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
it('should check ng-show / ng-hide', function() {
expect(thumbsUp.isDisplayed()).toBeFalsy();
expect(thumbsDown.isDisplayed()).toBeTruthy();
element(by.model('checked')).click();
expect(thumbsUp.isDisplayed()).toBeTruthy();
expect(thumbsDown.isDisplayed()).toBeFalsy();
});
</file>
</example>
*/
var ngHideDirective = ['$animate', function($animate) {
return {
restrict: 'A',
multiElement: true,
link: function(scope, element, attr) {
scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
// The comment inside of the ngShowDirective explains why we add and
// remove a temporary class for the show/hide animation
$animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
tempClasses: NG_HIDE_IN_PROGRESS_CLASS
});
});
}
};
}];
/**
* @ngdoc directive
* @name ngStyle
* @restrict AC
*
* @description
* The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
*
* @element ANY
* @param {expression} ngStyle
*
* {@link guide/expression Expression} which evals to an
* object whose keys are CSS style names and values are corresponding values for those CSS
* keys.
*
* Since some CSS style names are not valid keys for an object, they must be quoted.
* See the 'background-color' style in the example below.
*
* @example
<example>
<file name="index.html">
<input type="button" value="set color" ng-click="myStyle={color:'red'}">
<input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
<input type="button" value="clear" ng-click="myStyle={}">
<br/>
<span ng-style="myStyle">Sample Text</span>
<pre>myStyle={{myStyle}}</pre>
</file>
<file name="style.css">
span {
color: black;
}
</file>
<file name="protractor.js" type="protractor">
var colorSpan = element(by.css('span'));
it('should check ng-style', function() {
expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
element(by.css('input[value=\'set color\']')).click();
expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
element(by.css('input[value=clear]')).click();
expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
});
</file>
</example>
*/
var ngStyleDirective = ngDirective(function(scope, element, attr) {
scope.$watchCollection(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
if (oldStyles && (newStyles !== oldStyles)) {
forEach(oldStyles, function(val, style) { element.css(style, '');});
}
if (newStyles) element.css(newStyles);
});
});
/**
* @ngdoc directive
* @name ngSwitch
* @restrict EA
*
* @description
* The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
* Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
* as specified in the template.
*
* The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
* from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
* matches the value obtained from the evaluated expression. In other words, you define a container element
* (where you place the directive), place an expression on the **`on="..."` attribute**
* (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
* a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
* expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
* attribute is displayed.
*
* <div class="alert alert-info">
* Be aware that the attribute values to match against cannot be expressions. They are interpreted
* as literal string values to match against.
* For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
* value of the expression `$scope.someVal`.
* </div>
* @animations
* enter - happens after the ngSwitch contents change and the matched child element is placed inside the container
* leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM
*
* @usage
*
* ```
* <ANY ng-switch="expression">
* <ANY ng-switch-when="matchValue1">...</ANY>
* <ANY ng-switch-when="matchValue2">...</ANY>
* <ANY ng-switch-default>...</ANY>
* </ANY>
* ```
*
*
* @scope
* @priority 1200
* @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>.
* On child elements add:
*
* * `ngSwitchWhen`: the case statement to match against. If match then this
* case will be displayed. If the same match appears multiple times, all the
* elements will be displayed.
* * `ngSwitchDefault`: the default case when no other case match. If there
* are multiple default cases, all of them will be displayed when no other
* case match.
*
*
* @example
<example module="switchExample" deps="angular-animate.js" animations="true">
<file name="index.html">
<div ng-controller="ExampleController">
<select ng-model="selection" ng-options="item for item in items">
</select>
<tt>selection={{selection}}</tt>
<hr/>
<div class="animate-switch-container"
ng-switch on="selection">
<div class="animate-switch" ng-switch-when="settings">Settings Div</div>
<div class="animate-switch" ng-switch-when="home">Home Span</div>
<div class="animate-switch" ng-switch-default>default</div>
</div>
</div>
</file>
<file name="script.js">
angular.module('switchExample', ['ngAnimate'])
.controller('ExampleController', ['$scope', function($scope) {
$scope.items = ['settings', 'home', 'other'];
$scope.selection = $scope.items[0];
}]);
</file>
<file name="animations.css">
.animate-switch-container {
position:relative;
background:white;
border:1px solid black;
height:40px;
overflow:hidden;
}
.animate-switch {
padding:10px;
}
.animate-switch.ng-animate {
-webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
}
.animate-switch.ng-leave.ng-leave-active,
.animate-switch.ng-enter {
top:-50px;
}
.animate-switch.ng-leave,
.animate-switch.ng-enter.ng-enter-active {
top:0;
}
</file>
<file name="protractor.js" type="protractor">
var switchElem = element(by.css('[ng-switch]'));
var select = element(by.model('selection'));
it('should start in settings', function() {
expect(switchElem.getText()).toMatch(/Settings Div/);
});
it('should change to home', function() {
select.all(by.css('option')).get(1).click();
expect(switchElem.getText()).toMatch(/Home Span/);
});
it('should select default', function() {
select.all(by.css('option')).get(2).click();
expect(switchElem.getText()).toMatch(/default/);
});
</file>
</example>
*/
var ngSwitchDirective = ['$animate', function($animate) {
return {
restrict: 'EA',
require: 'ngSwitch',
// asks for $scope to fool the BC controller module
controller: ['$scope', function ngSwitchController() {
this.cases = {};
}],
link: function(scope, element, attr, ngSwitchController) {
var watchExpr = attr.ngSwitch || attr.on,
selectedTranscludes = [],
selectedElements = [],
previousLeaveAnimations = [],
selectedScopes = [];
var spliceFactory = function(array, index) {
return function() { array.splice(index, 1); };
};
scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
var i, ii;
for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) {
$animate.cancel(previousLeaveAnimations[i]);
}
previousLeaveAnimations.length = 0;
for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
var selected = getBlockNodes(selectedElements[i].clone);
selectedScopes[i].$destroy();
var promise = previousLeaveAnimations[i] = $animate.leave(selected);
promise.then(spliceFactory(previousLeaveAnimations, i));
}
selectedElements.length = 0;
selectedScopes.length = 0;
if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
forEach(selectedTranscludes, function(selectedTransclude) {
selectedTransclude.transclude(function(caseElement, selectedScope) {
selectedScopes.push(selectedScope);
var anchor = selectedTransclude.element;
caseElement[caseElement.length++] = document.createComment(' end ngSwitchWhen: ');
var block = { clone: caseElement };
selectedElements.push(block);
$animate.enter(caseElement, anchor.parent(), anchor);
});
});
}
});
}
};
}];
var ngSwitchWhenDirective = ngDirective({
transclude: 'element',
priority: 1200,
require: '^ngSwitch',
multiElement: true,
link: function(scope, element, attrs, ctrl, $transclude) {
ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });
}
});
var ngSwitchDefaultDirective = ngDirective({
transclude: 'element',
priority: 1200,
require: '^ngSwitch',
multiElement: true,
link: function(scope, element, attr, ctrl, $transclude) {
ctrl.cases['?'] = (ctrl.cases['?'] || []);
ctrl.cases['?'].push({ transclude: $transclude, element: element });
}
});
/**
* @ngdoc directive
* @name ngTransclude
* @restrict EAC
*
* @description
* Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
*
* Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted.
*
* @element ANY
*
* @example
<example module="transcludeExample">
<file name="index.html">
<script>
angular.module('transcludeExample', [])
.directive('pane', function(){
return {
restrict: 'E',
transclude: true,
scope: { title:'@' },
template: '<div style="border: 1px solid black;">' +
'<div style="background-color: gray">{{title}}</div>' +
'<ng-transclude></ng-transclude>' +
'</div>'
};
})
.controller('ExampleController', ['$scope', function($scope) {
$scope.title = 'Lorem Ipsum';
$scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
}]);
</script>
<div ng-controller="ExampleController">
<input ng-model="title"> <br/>
<textarea ng-model="text"></textarea> <br/>
<pane title="{{title}}">{{text}}</pane>
</div>
</file>
<file name="protractor.js" type="protractor">
it('should have transcluded', function() {
var titleElement = element(by.model('title'));
titleElement.clear();
titleElement.sendKeys('TITLE');
var textElement = element(by.model('text'));
textElement.clear();
textElement.sendKeys('TEXT');
expect(element(by.binding('title')).getText()).toEqual('TITLE');
expect(element(by.binding('text')).getText()).toEqual('TEXT');
});
</file>
</example>
*
*/
var ngTranscludeDirective = ngDirective({
restrict: 'EAC',
link: function($scope, $element, $attrs, controller, $transclude) {
if (!$transclude) {
throw minErr('ngTransclude')('orphan',
'Illegal use of ngTransclude directive in the template! ' +
'No parent directive that requires a transclusion found. ' +
'Element: {0}',
startingTag($element));
}
$transclude(function(clone) {
$element.empty();
$element.append(clone);
});
}
});
/**
* @ngdoc directive
* @name script
* @restrict E
*
* @description
* Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
* template can be used by {@link ng.directive:ngInclude `ngInclude`},
* {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
* `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
* assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
*
* @param {string} type Must be set to `'text/ng-template'`.
* @param {string} id Cache name of the template.
*
* @example
<example>
<file name="index.html">
<script type="text/ng-template" id="/tpl.html">
Content of the template.
</script>
<a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
<div id="tpl-content" ng-include src="currentTpl"></div>
</file>
<file name="protractor.js" type="protractor">
it('should load template defined inside script tag', function() {
element(by.css('#tpl-link')).click();
expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
});
</file>
</example>
*/
var scriptDirective = ['$templateCache', function($templateCache) {
return {
restrict: 'E',
terminal: true,
compile: function(element, attr) {
if (attr.type == 'text/ng-template') {
var templateUrl = attr.id,
text = element[0].text;
$templateCache.put(templateUrl, text);
}
}
};
}];
var ngOptionsMinErr = minErr('ngOptions');
/**
* @ngdoc directive
* @name select
* @restrict E
*
* @description
* HTML `SELECT` element with angular data-binding.
*
* # `ngOptions`
*
* The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
* elements for the `<select>` element using the array or object obtained by evaluating the
* `ngOptions` comprehension expression.
*
* In many cases, `ngRepeat` can be used on `<option>` elements instead of `ngOptions` to achieve a
* similar result. However, `ngOptions` provides some benefits such as reducing memory and
* increasing speed by not creating a new scope for each repeated instance, as well as providing
* more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
* comprehension expression. `ngOptions` should be used when the `<select>` model needs to be bound
* to a non-string value. This is because an option element can only be bound to string values at
* present.
*
* When an item in the `<select>` menu is selected, the array element or object property
* represented by the selected option will be bound to the model identified by the `ngModel`
* directive.
*
* Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
* be nested into the `<select>` element. This element will then represent the `null` or "not selected"
* option. See example below for demonstration.
*
* <div class="alert alert-warning">
* **Note:** `ngModel` compares by reference, not value. This is important when binding to an
* array of objects. See an example [in this jsfiddle](http://jsfiddle.net/qWzTb/).
* </div>
*
* ## `select` **`as`**
*
* Using `select` **`as`** will bind the result of the `select` expression to the model, but
* the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
* or property name (for object data sources) of the value within the collection. If a **`track by`** expression
* is used, the result of that expression will be set as the value of the `option` and `select` elements.
*
*
* ### `select` **`as`** and **`track by`**
*
* <div class="alert alert-warning">
* Do not use `select` **`as`** and **`track by`** in the same expression. They are not designed to work together.
* </div>
*
* Consider the following example:
*
* ```html
* <select ng-options="item.subItem as item.label for item in values track by item.id" ng-model="selected">
* ```
*
* ```js
* $scope.values = [{
* id: 1,
* label: 'aLabel',
* subItem: { name: 'aSubItem' }
* }, {
* id: 2,
* label: 'bLabel',
* subItem: { name: 'bSubItem' }
* }];
*
* $scope.selected = { name: 'aSubItem' };
* ```
*
* With the purpose of preserving the selection, the **`track by`** expression is always applied to the element
* of the data source (to `item` in this example). To calculate whether an element is selected, we do the
* following:
*
* 1. Apply **`track by`** to the elements in the array. In the example: `[1, 2]`
* 2. Apply **`track by`** to the already selected value in `ngModel`.
* In the example: this is not possible as **`track by`** refers to `item.id`, but the selected
* value from `ngModel` is `{name: 'aSubItem'}`, so the **`track by`** expression is applied to
* a wrong object, the selected element can't be found, `<select>` is always reset to the "not
* selected" option.
*
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required The control is considered valid only if value is entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {comprehension_expression=} ngOptions in one of the following forms:
*
* * for array data sources:
* * `label` **`for`** `value` **`in`** `array`
* * `select` **`as`** `label` **`for`** `value` **`in`** `array`
* * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
* * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
* * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
* (for including a filter with `track by`)
* * for object data sources:
* * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
* * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
* * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
* * `select` **`as`** `label` **`group by`** `group`
* **`for` `(`**`key`**`,`** `value`**`) in`** `object`
*
* Where:
*
* * `array` / `object`: an expression which evaluates to an array / object to iterate over.
* * `value`: local variable which will refer to each item in the `array` or each property value
* of `object` during iteration.
* * `key`: local variable which will refer to a property name in `object` during iteration.
* * `label`: The result of this expression will be the label for `<option>` element. The
* `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
* * `select`: The result of this expression will be bound to the model of the parent `<select>`
* element. If not specified, `select` expression will default to `value`.
* * `group`: The result of this expression will be used to group options using the `<optgroup>`
* DOM element.
* * `trackexpr`: Used when working with an array of objects. The result of this expression will be
* used to identify the objects in the array. The `trackexpr` will most likely refer to the
* `value` variable (e.g. `value.propertyName`). With this the selection is preserved
* even when the options are recreated (e.g. reloaded from the server).
*
* @example
<example module="selectExample">
<file name="index.html">
<script>
angular.module('selectExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.colors = [
{name:'black', shade:'dark'},
{name:'white', shade:'light'},
{name:'red', shade:'dark'},
{name:'blue', shade:'dark'},
{name:'yellow', shade:'light'}
];
$scope.myColor = $scope.colors[2]; // red
}]);
</script>
<div ng-controller="ExampleController">
<ul>
<li ng-repeat="color in colors">
Name: <input ng-model="color.name">
[<a href ng-click="colors.splice($index, 1)">X</a>]
</li>
<li>
[<a href ng-click="colors.push({})">add</a>]
</li>
</ul>
<hr/>
Color (null not allowed):
<select ng-model="myColor" ng-options="color.name for color in colors"></select><br>
Color (null allowed):
<span class="nullable">
<select ng-model="myColor" ng-options="color.name for color in colors">
<option value="">-- choose color --</option>
</select>
</span><br/>
Color grouped by shade:
<select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
</select><br/>
Select <a href ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</a>.<br>
<hr/>
Currently selected: {{ {selected_color:myColor} }}
<div style="border:solid 1px black; height:20px"
ng-style="{'background-color':myColor.name}">
</div>
</div>
</file>
<file name="protractor.js" type="protractor">
it('should check ng-options', function() {
expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
element.all(by.model('myColor')).first().click();
element.all(by.css('select[ng-model="myColor"] option')).first().click();
expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
element(by.css('.nullable select[ng-model="myColor"]')).click();
element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
});
</file>
</example>
*/
var ngOptionsDirective = valueFn({
restrict: 'A',
terminal: true
});
// jshint maxlen: false
var selectDirective = ['$compile', '$parse', function($compile, $parse) {
//000011111111110000000000022222222220000000000000000000003333333333000000000000004444444444444440000000005555555555555550000000666666666666666000000000000000777777777700000000000000000008888888888
var NG_OPTIONS_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/,
nullModelCtrl = {$setViewValue: noop};
// jshint maxlen: 100
return {
restrict: 'E',
require: ['select', '?ngModel'],
controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
var self = this,
optionsMap = {},
ngModelCtrl = nullModelCtrl,
nullOption,
unknownOption;
self.databound = $attrs.ngModel;
self.init = function(ngModelCtrl_, nullOption_, unknownOption_) {
ngModelCtrl = ngModelCtrl_;
nullOption = nullOption_;
unknownOption = unknownOption_;
};
self.addOption = function(value, element) {
assertNotHasOwnProperty(value, '"option value"');
optionsMap[value] = true;
if (ngModelCtrl.$viewValue == value) {
$element.val(value);
if (unknownOption.parent()) unknownOption.remove();
}
// Workaround for https://code.google.com/p/chromium/issues/detail?id=381459
// Adding an <option selected="selected"> element to a <select required="required"> should
// automatically select the new element
if (element && element[0].hasAttribute('selected')) {
element[0].selected = true;
}
};
self.removeOption = function(value) {
if (this.hasOption(value)) {
delete optionsMap[value];
if (ngModelCtrl.$viewValue === value) {
this.renderUnknownOption(value);
}
}
};
self.renderUnknownOption = function(val) {
var unknownVal = '? ' + hashKey(val) + ' ?';
unknownOption.val(unknownVal);
$element.prepend(unknownOption);
$element.val(unknownVal);
unknownOption.prop('selected', true); // needed for IE
};
self.hasOption = function(value) {
return optionsMap.hasOwnProperty(value);
};
$scope.$on('$destroy', function() {
// disable unknown option so that we don't do work when the whole select is being destroyed
self.renderUnknownOption = noop;
});
}],
link: function(scope, element, attr, ctrls) {
// if ngModel is not defined, we don't need to do anything
if (!ctrls[1]) return;
var selectCtrl = ctrls[0],
ngModelCtrl = ctrls[1],
multiple = attr.multiple,
optionsExp = attr.ngOptions,
nullOption = false, // if false, user will not be able to select it (used by ngOptions)
emptyOption,
renderScheduled = false,
// we can't just jqLite('<option>') since jqLite is not smart enough
// to create it in <select> and IE barfs otherwise.
optionTemplate = jqLite(document.createElement('option')),
optGroupTemplate =jqLite(document.createElement('optgroup')),
unknownOption = optionTemplate.clone();
// find "null" option
for (var i = 0, children = element.children(), ii = children.length; i < ii; i++) {
if (children[i].value === '') {
emptyOption = nullOption = children.eq(i);
break;
}
}
selectCtrl.init(ngModelCtrl, nullOption, unknownOption);
// required validator
if (multiple) {
ngModelCtrl.$isEmpty = function(value) {
return !value || value.length === 0;
};
}
if (optionsExp) setupAsOptions(scope, element, ngModelCtrl);
else if (multiple) setupAsMultiple(scope, element, ngModelCtrl);
else setupAsSingle(scope, element, ngModelCtrl, selectCtrl);
////////////////////////////
function setupAsSingle(scope, selectElement, ngModelCtrl, selectCtrl) {
ngModelCtrl.$render = function() {
var viewValue = ngModelCtrl.$viewValue;
if (selectCtrl.hasOption(viewValue)) {
if (unknownOption.parent()) unknownOption.remove();
selectElement.val(viewValue);
if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy
} else {
if (isUndefined(viewValue) && emptyOption) {
selectElement.val('');
} else {
selectCtrl.renderUnknownOption(viewValue);
}
}
};
selectElement.on('change', function() {
scope.$apply(function() {
if (unknownOption.parent()) unknownOption.remove();
ngModelCtrl.$setViewValue(selectElement.val());
});
});
}
function setupAsMultiple(scope, selectElement, ctrl) {
var lastView;
ctrl.$render = function() {
var items = new HashMap(ctrl.$viewValue);
forEach(selectElement.find('option'), function(option) {
option.selected = isDefined(items.get(option.value));
});
};
// we have to do it on each watch since ngModel watches reference, but
// we need to work of an array, so we need to see if anything was inserted/removed
scope.$watch(function selectMultipleWatch() {
if (!equals(lastView, ctrl.$viewValue)) {
lastView = shallowCopy(ctrl.$viewValue);
ctrl.$render();
}
});
selectElement.on('change', function() {
scope.$apply(function() {
var array = [];
forEach(selectElement.find('option'), function(option) {
if (option.selected) {
array.push(option.value);
}
});
ctrl.$setViewValue(array);
});
});
}
function setupAsOptions(scope, selectElement, ctrl) {
var match;
if (!(match = optionsExp.match(NG_OPTIONS_REGEXP))) {
throw ngOptionsMinErr('iexp',
"Expected expression in form of " +
"'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
" but got '{0}'. Element: {1}",
optionsExp, startingTag(selectElement));
}
var displayFn = $parse(match[2] || match[1]),
valueName = match[4] || match[6],
selectAs = / as /.test(match[0]) && match[1],
selectAsFn = selectAs ? $parse(selectAs) : null,
keyName = match[5],
groupByFn = $parse(match[3] || ''),
valueFn = $parse(match[2] ? match[1] : valueName),
valuesFn = $parse(match[7]),
track = match[8],
trackFn = track ? $parse(match[8]) : null,
trackKeysCache = {},
// This is an array of array of existing option groups in DOM.
// We try to reuse these if possible
// - optionGroupsCache[0] is the options with no option group
// - optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element
optionGroupsCache = [[{element: selectElement, label:''}]],
//re-usable object to represent option's locals
locals = {};
if (nullOption) {
// compile the element since there might be bindings in it
$compile(nullOption)(scope);
// remove the class, which is added automatically because we recompile the element and it
// becomes the compilation root
nullOption.removeClass('ng-scope');
// we need to remove it before calling selectElement.empty() because otherwise IE will
// remove the label from the element. wtf?
nullOption.remove();
}
// clear contents, we'll add what's needed based on the model
selectElement.empty();
selectElement.on('change', selectionChanged);
ctrl.$render = render;
scope.$watchCollection(valuesFn, scheduleRendering);
scope.$watchCollection(getLabels, scheduleRendering);
if (multiple) {
scope.$watchCollection(function() { return ctrl.$modelValue; }, scheduleRendering);
}
// ------------------------------------------------------------------ //
function callExpression(exprFn, key, value) {
locals[valueName] = value;
if (keyName) locals[keyName] = key;
return exprFn(scope, locals);
}
function selectionChanged() {
scope.$apply(function() {
var collection = valuesFn(scope) || [];
var viewValue;
if (multiple) {
viewValue = [];
forEach(selectElement.val(), function(selectedKey) {
selectedKey = trackFn ? trackKeysCache[selectedKey] : selectedKey;
viewValue.push(getViewValue(selectedKey, collection[selectedKey]));
});
} else {
var selectedKey = trackFn ? trackKeysCache[selectElement.val()] : selectElement.val();
viewValue = getViewValue(selectedKey, collection[selectedKey]);
}
ctrl.$setViewValue(viewValue);
render();
});
}
function getViewValue(key, value) {
if (key === '?') {
return undefined;
} else if (key === '') {
return null;
} else {
var viewValueFn = selectAsFn ? selectAsFn : valueFn;
return callExpression(viewValueFn, key, value);
}
}
function getLabels() {
var values = valuesFn(scope);
var toDisplay;
if (values && isArray(values)) {
toDisplay = new Array(values.length);
for (var i = 0, ii = values.length; i < ii; i++) {
toDisplay[i] = callExpression(displayFn, i, values[i]);
}
return toDisplay;
} else if (values) {
// TODO: Add a test for this case
toDisplay = {};
for (var prop in values) {
if (values.hasOwnProperty(prop)) {
toDisplay[prop] = callExpression(displayFn, prop, values[prop]);
}
}
}
return toDisplay;
}
function createIsSelectedFn(viewValue) {
var selectedSet;
if (multiple) {
if (trackFn && isArray(viewValue)) {
selectedSet = new HashMap([]);
for (var trackIndex = 0; trackIndex < viewValue.length; trackIndex++) {
// tracking by key
selectedSet.put(callExpression(trackFn, null, viewValue[trackIndex]), true);
}
} else {
selectedSet = new HashMap(viewValue);
}
} else if (trackFn) {
viewValue = callExpression(trackFn, null, viewValue);
}
return function isSelected(key, value) {
var compareValueFn;
if (trackFn) {
compareValueFn = trackFn;
} else if (selectAsFn) {
compareValueFn = selectAsFn;
} else {
compareValueFn = valueFn;
}
if (multiple) {
return isDefined(selectedSet.remove(callExpression(compareValueFn, key, value)));
} else {
return viewValue === callExpression(compareValueFn, key, value);
}
};
}
function scheduleRendering() {
if (!renderScheduled) {
scope.$$postDigest(render);
renderScheduled = true;
}
}
/**
* A new labelMap is created with each render.
* This function is called for each existing option with added=false,
* and each new option with added=true.
* - Labels that are passed to this method twice,
* (once with added=true and once with added=false) will end up with a value of 0, and
* will cause no change to happen to the corresponding option.
* - Labels that are passed to this method only once with added=false will end up with a
* value of -1 and will eventually be passed to selectCtrl.removeOption()
* - Labels that are passed to this method only once with added=true will end up with a
* value of 1 and will eventually be passed to selectCtrl.addOption()
*/
function updateLabelMap(labelMap, label, added) {
labelMap[label] = labelMap[label] || 0;
labelMap[label] += (added ? 1 : -1);
}
function render() {
renderScheduled = false;
// Temporary location for the option groups before we render them
var optionGroups = {'':[]},
optionGroupNames = [''],
optionGroupName,
optionGroup,
option,
existingParent, existingOptions, existingOption,
viewValue = ctrl.$viewValue,
values = valuesFn(scope) || [],
keys = keyName ? sortedKeys(values) : values,
key,
value,
groupLength, length,
groupIndex, index,
labelMap = {},
selected,
isSelected = createIsSelectedFn(viewValue),
anySelected = false,
lastElement,
element,
label,
optionId;
trackKeysCache = {};
// We now build up the list of options we need (we merge later)
for (index = 0; length = keys.length, index < length; index++) {
key = index;
if (keyName) {
key = keys[index];
if (key.charAt(0) === '$') continue;
}
value = values[key];
optionGroupName = callExpression(groupByFn, key, value) || '';
if (!(optionGroup = optionGroups[optionGroupName])) {
optionGroup = optionGroups[optionGroupName] = [];
optionGroupNames.push(optionGroupName);
}
selected = isSelected(key, value);
anySelected = anySelected || selected;
label = callExpression(displayFn, key, value); // what will be seen by the user
// doing displayFn(scope, locals) || '' overwrites zero values
label = isDefined(label) ? label : '';
optionId = trackFn ? trackFn(scope, locals) : (keyName ? keys[index] : index);
if (trackFn) {
trackKeysCache[optionId] = key;
}
optionGroup.push({
// either the index into array or key from object
id: optionId,
label: label,
selected: selected // determine if we should be selected
});
}
if (!multiple) {
if (nullOption || viewValue === null) {
// insert null option if we have a placeholder, or the model is null
optionGroups[''].unshift({id:'', label:'', selected:!anySelected});
} else if (!anySelected) {
// option could not be found, we have to insert the undefined item
optionGroups[''].unshift({id:'?', label:'', selected:true});
}
}
// Now we need to update the list of DOM nodes to match the optionGroups we computed above
for (groupIndex = 0, groupLength = optionGroupNames.length;
groupIndex < groupLength;
groupIndex++) {
// current option group name or '' if no group
optionGroupName = optionGroupNames[groupIndex];
// list of options for that group. (first item has the parent)
optionGroup = optionGroups[optionGroupName];
if (optionGroupsCache.length <= groupIndex) {
// we need to grow the optionGroups
existingParent = {
element: optGroupTemplate.clone().attr('label', optionGroupName),
label: optionGroup.label
};
existingOptions = [existingParent];
optionGroupsCache.push(existingOptions);
selectElement.append(existingParent.element);
} else {
existingOptions = optionGroupsCache[groupIndex];
existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element
// update the OPTGROUP label if not the same.
if (existingParent.label != optionGroupName) {
existingParent.element.attr('label', existingParent.label = optionGroupName);
}
}
lastElement = null; // start at the beginning
for (index = 0, length = optionGroup.length; index < length; index++) {
option = optionGroup[index];
if ((existingOption = existingOptions[index + 1])) {
// reuse elements
lastElement = existingOption.element;
if (existingOption.label !== option.label) {
updateLabelMap(labelMap, existingOption.label, false);
updateLabelMap(labelMap, option.label, true);
lastElement.text(existingOption.label = option.label);
lastElement.prop('label', existingOption.label);
}
if (existingOption.id !== option.id) {
lastElement.val(existingOption.id = option.id);
}
// lastElement.prop('selected') provided by jQuery has side-effects
if (lastElement[0].selected !== option.selected) {
lastElement.prop('selected', (existingOption.selected = option.selected));
if (msie) {
// See #7692
// The selected item wouldn't visually update on IE without this.
// Tested on Win7: IE9, IE10 and IE11. Future IEs should be tested as well
lastElement.prop('selected', existingOption.selected);
}
}
} else {
// grow elements
// if it's a null option
if (option.id === '' && nullOption) {
// put back the pre-compiled element
element = nullOption;
} else {
// jQuery(v1.4.2) Bug: We should be able to chain the method calls, but
// in this version of jQuery on some browser the .text() returns a string
// rather then the element.
(element = optionTemplate.clone())
.val(option.id)
.prop('selected', option.selected)
.attr('selected', option.selected)
.prop('label', option.label)
.text(option.label);
}
existingOptions.push(existingOption = {
element: element,
label: option.label,
id: option.id,
selected: option.selected
});
updateLabelMap(labelMap, option.label, true);
if (lastElement) {
lastElement.after(element);
} else {
existingParent.element.append(element);
}
lastElement = element;
}
}
// remove any excessive OPTIONs in a group
index++; // increment since the existingOptions[0] is parent element not OPTION
while (existingOptions.length > index) {
option = existingOptions.pop();
updateLabelMap(labelMap, option.label, false);
option.element.remove();
}
}
// remove any excessive OPTGROUPs from select
while (optionGroupsCache.length > groupIndex) {
// remove all the labels in the option group
optionGroup = optionGroupsCache.pop();
for (index = 1; index < optionGroup.length; ++index) {
updateLabelMap(labelMap, optionGroup[index].label, false);
}
optionGroup[0].element.remove();
}
forEach(labelMap, function(count, label) {
if (count > 0) {
selectCtrl.addOption(label);
} else if (count < 0) {
selectCtrl.removeOption(label);
}
});
}
}
}
};
}];
var optionDirective = ['$interpolate', function($interpolate) {
var nullSelectCtrl = {
addOption: noop,
removeOption: noop
};
return {
restrict: 'E',
priority: 100,
compile: function(element, attr) {
if (isUndefined(attr.value)) {
var interpolateFn = $interpolate(element.text(), true);
if (!interpolateFn) {
attr.$set('value', element.text());
}
}
return function(scope, element, attr) {
var selectCtrlName = '$selectController',
parent = element.parent(),
selectCtrl = parent.data(selectCtrlName) ||
parent.parent().data(selectCtrlName); // in case we are in optgroup
if (!selectCtrl || !selectCtrl.databound) {
selectCtrl = nullSelectCtrl;
}
if (interpolateFn) {
scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) {
attr.$set('value', newVal);
if (oldVal !== newVal) {
selectCtrl.removeOption(oldVal);
}
selectCtrl.addOption(newVal, element);
});
} else {
selectCtrl.addOption(attr.value, element);
}
element.on('$destroy', function() {
selectCtrl.removeOption(attr.value);
});
};
}
};
}];
var styleDirective = valueFn({
restrict: 'E',
terminal: false
});
var requiredDirective = function() {
return {
restrict: 'A',
require: '?ngModel',
link: function(scope, elm, attr, ctrl) {
if (!ctrl) return;
attr.required = true; // force truthy in case we are on non input element
ctrl.$validators.required = function(modelValue, viewValue) {
return !attr.required || !ctrl.$isEmpty(viewValue);
};
attr.$observe('required', function() {
ctrl.$validate();
});
}
};
};
var patternDirective = function() {
return {
restrict: 'A',
require: '?ngModel',
link: function(scope, elm, attr, ctrl) {
if (!ctrl) return;
var regexp, patternExp = attr.ngPattern || attr.pattern;
attr.$observe('pattern', function(regex) {
if (isString(regex) && regex.length > 0) {
regex = new RegExp('^' + regex + '$');
}
if (regex && !regex.test) {
throw minErr('ngPattern')('noregexp',
'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
regex, startingTag(elm));
}
regexp = regex || undefined;
ctrl.$validate();
});
ctrl.$validators.pattern = function(value) {
return ctrl.$isEmpty(value) || isUndefined(regexp) || regexp.test(value);
};
}
};
};
var maxlengthDirective = function() {
return {
restrict: 'A',
require: '?ngModel',
link: function(scope, elm, attr, ctrl) {
if (!ctrl) return;
var maxlength = -1;
attr.$observe('maxlength', function(value) {
var intVal = int(value);
maxlength = isNaN(intVal) ? -1 : intVal;
ctrl.$validate();
});
ctrl.$validators.maxlength = function(modelValue, viewValue) {
return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
};
}
};
};
var minlengthDirective = function() {
return {
restrict: 'A',
require: '?ngModel',
link: function(scope, elm, attr, ctrl) {
if (!ctrl) return;
var minlength = 0;
attr.$observe('minlength', function(value) {
minlength = int(value) || 0;
ctrl.$validate();
});
ctrl.$validators.minlength = function(modelValue, viewValue) {
return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
};
}
};
};
if (window.angular.bootstrap) {
//AngularJS is already loaded, so we can return here...
console.log('WARNING: Tried to load angular more than once.');
return;
}
//try to bind to jquery now so that one can write jqLite(document).ready()
//but we will rebind on bootstrap again.
bindJQuery();
publishExternalAPI(angular);
jqLite(document).ready(function() {
angularInit(document, bootstrap);
});
})(window, document);
!window.angular.$$csp() && window.angular.element(document).find('head').prepend('<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide:not(.ng-hide-animate){display:none !important;}ng\\:form{display:block;}</style>'); |
import COLORS from '../constants/colors';
import TrackedData from './tracked-data';
const DEFAULT_INTENSITY = 0;
const DEFAULT_COLOR = COLORS.WHITE;
export default class LightArray extends TrackedData {
constructor(stripLengths, defaultIntensity = DEFAULT_INTENSITY, defaultColor = DEFAULT_COLOR) {
const properties = {};
const stripIds = Object.keys(stripLengths);
for (let stripId of stripIds) {
const strip = {};
const panelIds = [];
for (let panelId = 0; panelId < stripLengths[stripId]; panelId++) {
panelId = '' + panelId;
strip[panelId] = new TrackedData({
intensity: defaultIntensity,
color: defaultColor,
active: false
});
panelIds.push(panelId);
}
properties[stripId] = new TrackedData({
maxIntensity: 100,
panels: new TrackedData(strip)
});
properties[stripId].panelIds = panelIds;
}
super(properties);
this.stripIds = stripIds;
this.defaultIntensity = defaultIntensity;
this.defaultColor = defaultColor;
}
/**
* Sets the max intensity for the given strip.
* If stripId is null, sets the max intensity for all strips
*/
setMaxIntensity(intensity, stripId = null, props) {
const stripsToModify = stripId === null ? this.stripIds : [stripId];
for (let targetStripId of stripsToModify) {
const strip = this.get(targetStripId);
strip.set("maxIntensity", intensity, props);
}
}
getMaxIntensity(stripId) {
return this.get(stripId).get("maxIntensity");
}
getPanel(stripId, panelId) {
return this.get(stripId).get("panels").get(panelId);
}
setToDefaultColor(stripId, panelId) {
return this.setColor(stripId, panelId, this.defaultColor);
}
/**
* If panelId is null, we'll set the color for all panels in the given strip.
*/
setColor(stripId, panelId, color, props) {
this._applyToOnePanelOrAll(stripId, panelId, (panel) => panel.set("color", color, props));
}
getColor(stripId, panelId) {
const panel = this.getPanel(stripId, panelId);
return panel.get("color");
}
getIntensity(stripId, panelId) {
const panel = this.getPanel(stripId, panelId);
return panel.get("intensity");
}
setToDefaultIntensity(stripId, panelId) {
return this.setIntensity(stripId, panelId, this.defaultIntensity);
}
/**
* If panelId is null, we'll set the color for all panels in the given strip.
*/
setIntensity(stripId, panelId, intensity, props) {
this._applyToOnePanelOrAll(stripId, panelId, (panel) => panel.set("intensity", intensity, props));
}
isActive(stripId, panelId) {
const panel = this.getPanel(stripId, panelId);
return panel.get("active");
}
setActive(stripId, panelId, active = true, props) {
const panel = this.getPanel(stripId, panelId);
panel.set("active", active, props);
}
deactivateAll(stripId = null) {
const targetStripIds = stripId === null ? this.stripIds : [stripId];
for (let targetStripId of targetStripIds) {
for (let panelId of this.get(targetStripId).panelIds) {
this.setActive(targetStripId, panelId, false);
}
}
}
_applyToOnePanelOrAll(stripId, panelId = null, panelFunc) {
const panels = this._getOnePanelOrAll(stripId, panelId);
panels.forEach(panelFunc);
}
_getOnePanelOrAll(stripId, panelId) {
if (panelId === null) {
// this code is necessary because there is no Object.values() function
// FIXME: ES2017 added Object.values(). Make sure we polyfill correctly before enabling that
const stripPanels = this.get(stripId).get("panels");
// Old code
// return [for (stripPanelId of stripPanels) stripPanels.get(stripPanelId)];
// FIXME: New code, untested
return Array.from(stripPanels).map((id) => stripPanels.get(id));
}
else {
return [this.getPanel(stripId, panelId)];
}
}
}
|
'use babel'
import IconsSection from './IconsSectionView'
import ColorSection from './ColorSectionView'
import LayoutSection from './LayoutSectionView'
import TypographySection from './TypographySectionView'
export {
IconsSection,
ColorSection,
LayoutSection,
TypographySection,
}
|
/* eslint-env node, jest */
jest.mock('cloudinary');
jest.mock('node-persist');
jest.mock('./render.js');
jest.mock('./fetch.js');
const lolex = require('lolex');
const Slack = require('../lib/slackMock.js');
const sunrise = require('./index.js');
let slack = null;
let clock = null;
describe('sunrise', () => {
beforeEach(async () => {
slack = new Slack();
clock = lolex.install();
process.env.CHANNEL_SANDBOX = slack.fakeChannel;
await sunrise(slack);
});
afterEach(() => {
if (clock !== null) {
clock.uninstall();
}
});
it('notify sunrise on sunrise', () => new Promise((resolve) => {
clock.setSystemTime(new Date('2019-03-21T06:00:00+0900'));
slack.on('chat.postMessage', ({text}) => {
if (!text.includes('wave')) {
expect(text).toContain('ahokusa');
resolve();
}
});
clock.tick(15 * 1000);
}));
it('notify sunset on sunset', () => new Promise((resolve) => {
clock.setSystemTime(new Date('2019-03-21T19:00:00+0900'));
slack.on('chat.postMessage', ({text}) => {
if (!text.includes('ahokusa')) {
expect(text).toContain('wave');
resolve();
}
});
clock.tick(15 * 1000);
}));
});
|
'use strict';
// Declare app level module which depends on views, and components
angular.module('myApp', [
'ngRoute',
'myApp.PatientsCtrl',
'myApp.DoctorsCtrl',
'myApp.WardsCtrl',
'myApp.NursesCtrl',
'myApp.version',
'ngMaterial'
]).
config(['$locationProvider', '$routeProvider', function($locationProvider, $routeProvider) {
$locationProvider.hashPrefix('!');
$routeProvider.otherwise({redirectTo: '/nurses'});
}]);
|
'use strict';
/**
* Module dependencies.
*/
var should = require('should'),
mongoose = require('mongoose'),
User = mongoose.model('User'),
Player = mongoose.model('Player');
/**
* Globals
*/
var user, player;
/**
* Unit tests
*/
describe('Player Model Unit Tests:', function() {
beforeEach(function(done) {
user = new User({
firstName: 'Full',
lastName: 'Name',
displayName: 'Full Name',
email: 'test@test.com',
username: 'username',
password: 'password'
});
user.save(function() {
player = new Player({
name: 'Player Name',
user: user
});
done();
});
});
describe('Method Save', function() {
it('should be able to save without problems', function(done) {
return player.save(function(err) {
should.not.exist(err);
done();
});
});
it('should be able to show an error when try to save without name', function(done) {
player.name = '';
return player.save(function(err) {
should.exist(err);
done();
});
});
});
afterEach(function(done) {
Player.remove().exec(function(){
User.remove().exec(function(){
done();
});
});
});
});
|
var Stats = { };
$(document).ready(function( ) {
Stats.loadCharts( );
});
Stats.dateForStat = function( stat ) {
var date = new Date( stat.created_at );
var timezoneOffsetInMilliseconds = date.getTimezoneOffset( ) * 60 * 1000;
var startOfLocalDay = new Date( date.getTime() + timezoneOffsetInMilliseconds );
return startOfLocalDay
}
Stats.loadCharts = function( ) {
var prefetched_stats;
try { prefetched_stats = STATS_JSON; }
catch( err ) { prefetched_stats = null; }
if( prefetched_stats ) {
Stats.loadChartsFromJSON( prefetched_stats );
} else {
Stats.loadAjaxCharts( );
}
};
Stats.loadAjaxCharts = function( ) {
$.getJSON("/stats.json?start_date=" + Stats.yearAgoDate( ), function( json ) {
Stats.loadChartsFromJSON( json );
});
};
Stats.loadChartsFromJSON = function( json ) {
Stats.loadObsSpark( json );
Stats.loadPercentIdSpark( json );
Stats.loadPercentCIDToGenusSpark( json );
Stats.loadActiveUsersSpark( json );
Stats.loadNewUsersSpark( json );
Stats.load7ObsUsersSpark( json );
Stats.loadObservations7Days( json );
Stats.loadPlatforms( json );
Stats.loadTTID( json );
Stats.loadUsers( json );
Stats.loadObservations( json );
Stats.loadCumulativeUsers( json );
Stats.loadCumulativePlatforms( json );
Stats.loadProjects( json );
Stats.loadRanks( json );
Stats.loadRanksPie( json );
};
Stats.loadObsSpark = function ( json ) {
google.setOnLoadCallback(Stats.sparkline({
element_id: "obsspark",
series: [
{ label: "Today" }
],
data: _.map( json, function( stat ) {
return [ Stats.dateForStat( stat ), stat.data.observations.today ]
})
}));
}
Stats.loadPercentIdSpark = function ( json ) {
google.setOnLoadCallback(Stats.sparkline({
element_id: "percentidspark",
series: [
{ label: "% ID" }
],
data: _.map( json, function( stat ) {
if (stat.data.identifier) {
return [ Stats.dateForStat( stat ), stat.data.identifier.percent_id]
} else {
return [ Stats.dateForStat( stat ), 0]
}
})
}));
}
Stats.loadPercentCIDToGenusSpark = function ( json ) {
google.setOnLoadCallback(Stats.sparkline({
element_id: "percentcidtogenusspark",
series: [
{ label: "% ID" }
],
data: _.map( json, function( stat ) {
if (stat.data.identifier) {
return [ Stats.dateForStat( stat ), stat.data.identifier.percent_cid_to_genus ]
} else {
return [ Stats.dateForStat( stat ), 0 ]
}
})
}));
}
Stats.loadActiveUsersSpark = function ( json ) {
google.setOnLoadCallback(Stats.sparkline({
element_id: "activeusersspark",
series: [
{ label: "% ID" }
],
data: _.map( json, function( stat ) {
return [ Stats.dateForStat( stat ), stat.data.users.active ]
})
}));
}
Stats.loadNewUsersSpark = function ( json ) {
google.setOnLoadCallback(Stats.sparkline({
element_id: "newusersspark",
series: [
{ label: "% ID" }
],
data: _.map( json, function( stat ) {
return [ Stats.dateForStat( stat ), stat.data.users.last_7_days ]
})
}));
}
Stats.load7ObsUsersSpark = function ( json ) {
google.setOnLoadCallback(Stats.sparkline({
element_id: "new7obsusersspark",
series: [
{ label: "% ID" }
],
data: _.map( json, function( stat ) {
return [ Stats.dateForStat( stat ), stat.data.users.recent_7_obs ]
})
}));
}
Stats.loadObservations = function( json ) {
google.setOnLoadCallback(Stats.simpleChart({
element_id: "observations",
series: [
{ label: I18n.t( "total" ) },
{ label: I18n.t( "research_grade" ) }
],
data: _.map( json, function( stat ) {
stat.data.platforms_cumulative = stat.data.platforms_cumulative || { };
return [
Stats.dateForStat( stat ),
stat.data.observations.count,
stat.data.observations.research_grade
];
})
}));
};
Stats.loadCumulativePlatforms = function( json ) {
google.setOnLoadCallback(Stats.simpleChart({
element_id: "cumulative-platforms",
chartOptions: { isStacked: true },
series: [
{ label: I18n.t( "website" ) },
{ label: I18n.t( "iphone" ) },
{ label: I18n.t( "android" ) },
{ label: I18n.t( "other" ) }
],
data: _.map( json, function( stat ) {
stat.data.platforms_cumulative = stat.data.platforms_cumulative || { };
return [
Stats.dateForStat( stat ),
stat.data.platforms_cumulative.web,
stat.data.platforms_cumulative.iphone,
stat.data.platforms_cumulative.android,
stat.data.platforms_cumulative.other
];
})
}));
};
Stats.loadObservations7Days = function( json ) {
google.setOnLoadCallback(Stats.simpleChart({
element_id: "obs_7",
chartType: google.visualization.AnnotationChart,
series: [
{ label: I18n.t( "obs" ) },
{ label: I18n.t( "obs_id_d" ) },
{ label: I18n.t( "obs_cid_d" ) },
{ label: I18n.t( "views.stats.index.obs_cid_d_to_genus" ) },
{ label: I18n.t( "views.stats.index.obs_1_day" ) }
],
data: _.map( json, function( stat ) {
return [
Stats.dateForStat( stat ),
stat.data.observations.last_7_days,
stat.data.observations.identified,
stat.data.observations.community_identified,
stat.data.observations.community_identified_to_genus,
stat.data.observations.today
];
})
}));
};
Stats.loadPlatforms = function( json ) {
google.setOnLoadCallback(Stats.simpleChart({
element_id: "platforms",
chartType: google.visualization.AnnotationChart,
series: [
{ label: I18n.t( "website" ) },
{ label: I18n.t( "iphone" ) },
{ label: I18n.t( "android" ) },
{ label: I18n.t( "other" ) }
],
data: _.map( json, function( stat ) {
stat.data.platforms = stat.data.platforms || { };
return [
Stats.dateForStat( stat ),
stat.data.platforms.web,
stat.data.platforms.iphone,
stat.data.platforms.android,
stat.data.platforms.other
];
})
}));
};
Stats.loadTTID = function( json ) {
var dodgerblue = d3.rgb('dodgerblue'),
ldodgerblue = d3.rgb(dodgerblue.r + 75, dodgerblue.g + 75, dodgerblue.b + 75),
pink = d3.rgb('deeppink'),
lpink = d3.rgb(pink.r + 100, pink.g + 100, pink.b + 100)
google.setOnLoadCallback(Stats.simpleChart({
element_id: "ttid",
chartType: google.visualization.AnnotationChart,
series: [
{ label: I18n.t( "views.stats.index.med_ttid" ) },
{ label: I18n.t( "views.stats.index.avg_ttid" ) },
{ label: I18n.t( "views.stats.index.med_ttcid" ) },
{ label: I18n.t( "views.stats.index.avg_ttcid" ) }
],
data: _.map( json, function( stat ) {
if (stat.data.identifier) {
return [
Stats.dateForStat( stat ),
stat.data.identifier.med_ttid / 60,
stat.data.identifier.avg_ttid / 60,
stat.data.identifier.med_ttcid / 60,
stat.data.identifier.avg_ttcid / 60
];
} else {
return [ Stats.dateForStat( stat ), null, null, null, null];
}
}),
chartOptions: {
scaleType: 'allfixed',
colors: [
dodgerblue.toString(),
ldodgerblue.toString(),
pink.toString(),
lpink.toString()
]
}
}));
};
Stats.loadProjects = function( json ) {
google.setOnLoadCallback(Stats.simpleChart({
element_id: "projects",
series: [ { label: I18n.t( "total" ) } ],
data: _.map( json, function( stat ) {
return [ Stats.dateForStat( stat ), stat.data.projects.count ]
})
}));
};
Stats.loadCumulativeUsers = function( json ) {
google.setOnLoadCallback(Stats.simpleChart({
element_id: "cumulative-users",
series: [
{ label: "Total" },
{ label: "Active" },
{ label: "Curators" },
{ label: "Admins" }
],
data: _.map( json, function( stat ) {
return [ Stats.dateForStat( stat ), stat.data.users.count, stat.data.users.active, stat.data.users.curators, stat.data.users.admins ];
})
}));
};
Stats.loadUsers = function( json ) {
google.setOnLoadCallback(Stats.simpleChart({
element_id: "users",
chartType: google.visualization.AnnotationChart,
series: [
{ label: I18n.t( "active" ) },
{ label: I18n.t( "new" ) },
{ label: I18n.t( "identifiers" ) },
{ label: I18n.t( "recent" ) },
{ label: I18n.t( "views.stats.index.recent_w_7_obs" ) },
{ label: I18n.t( "views.stats.index.recent_w_0_obs" ) },
],
data: _.map( json, function( stat ) {
return [
Stats.dateForStat( stat ),
stat.data.users.active,
stat.data.users.today,
stat.data.users.identifiers,
stat.data.users.last_7_days,
stat.data.users.recent_7_obs,
stat.data.users.recent_0_obs
];
})
}));
};
Stats.loadRanks = function( json ) {
var ranks = _.keys( json[0].data.taxa.count_by_rank ).reverse( );
google.setOnLoadCallback(Stats.simpleChart({
element_id: "ranks",
series: _.map( ranks, function( rank ) {
return { label: I18n.t( "ranks." + rank, { defaultValue: rank } ) }
}),
data: _.map( json, function( stat ) {
var values = _.map( ranks, function( rank ) {
return _.detect(stat.data.taxa.count_by_rank, function(v, k) { return k === rank });
});
values.unshift( Stats.dateForStat( stat ) );
return values;
}),
chartOptions: { isStacked: true }
}));
};
Stats.loadRanksPie = function( json ) {
google.setOnLoadCallback(Stats.simpleChart({
element_id: "ranks_pie",
data: _.map( json[0].data.taxa.count_by_rank, function( value, rank ) {
return [ I18n.t( "ranks." + rank, { defaultValue: rank } ), parseInt( value ) ];
}),
chartType: google.visualization.PieChart
}));
};
Stats.yearAgoDate = function( ) {
var date = new Date( );
return ( date.getFullYear( ) - 4 ) + "-" +
(date.getMonth( ) + 1) + "-" + date.getDate( );
};
Stats.monthAgoDate = function( ) {
var date = new Date( );
return date.getFullYear( ) + "-" + date.getMonth( ) + "-" + date.getDate( );
};
Stats.simpleChart = function( options ) {
options.chartType = options.chartType || google.visualization.AreaChart;
var chartOptions = options.chartOptions || { };
var data = new google.visualization.DataTable( );
if( options.chartType === google.visualization.AreaChart ) {
data.addColumn( 'date', 'Date' );
chartOptions.vAxis = { minValue: 0 };
chartOptions.height = 300;
chartOptions.chartArea = { height: "80%" };
chartOptions.explorer = {
axis: "horizontal",
keepInBounds: false,
zoomDelta: 1.05
};
} else if( options.chartType === google.visualization.PieChart ) {
data.addColumn( 'string', 'Key' );
data.addColumn( 'number', 'Value' );
} else if (options.chartType = google.visualization.AnnotationChart) {
data.addColumn( 'date', 'Date' );
chartOptions.min = 0
chartOptions.zoomStartTime = new Date(Stats.monthAgoDate())
}
_.each( options.series, function( s ) {
data.addColumn( 'number', s.label );
});
data.addRows( options.data );
var chart = new options.chartType(
document.getElementById( options.element_id ));
chart.draw( data, chartOptions );
};
Stats.sparkline = function( options ) {
var element = options.element_id,
series = options.series,
data = options.data,
graph = d3.select("#"+element).append("svg:svg").attr("width", "100%").attr("height", "100%"),
numDays = 100;
data = _.map( data.slice(0, numDays).reverse(), function( stat ) {
return stat[1] || 0
})
var x = d3.scale.linear().domain([0, data.length]).range([0, $('#'+element).width()]);
var y = d3.scale.linear().domain([0, _.max(data)]).range([$('#'+element).height(), 0]);
var line = d3.svg.line()
.x(function(d,i) {
return x(i);
})
.y(function(d) {
return y(d);
});
graph.append("svg:path").attr("d", line(data));
};
|
//-- copyright
// OpenProject is a project management system.
// Copyright (C) 2012-2013 the OpenProject Foundation (OPF)
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License version 3.
//
// OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
// Copyright (C) 2006-2013 Jean-Philippe Lang
// Copyright (C) 2010-2013 the ChiliProject Team
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
// See doc/COPYRIGHT.rdoc for more details.
//++
/* redMine - project management software
Copyright (C) 2006-2008 Jean-Philippe Lang */
var observingContextMenuClick;
ContextMenu = Class.create();
ContextMenu.prototype = {
initialize: function (url) {
this.url = url;
this.createMenu();
if (!observingContextMenuClick) {
Event.observe(document, 'click', this.Click.bindAsEventListener(this));
Event.observe(document, 'contextmenu', this.RightClick.bindAsEventListener(this));
observingContextMenuClick = true;
}
this.unselectAll();
this.lastSelected = null;
},
RightClick: function(e) {
this.hideMenu();
// do not show the context menu on links
if (Event.element(e).tagName == 'A') { return; }
var tr = Event.findElement(e, 'tr');
if (tr == document || tr == undefined || !tr.hasClassName('hascontextmenu')) { return; }
Event.stop(e);
if (!this.isSelected(tr)) {
this.unselectAll();
this.addSelection(tr, e);
this.lastSelected = tr;
}
this.showMenu(e);
},
Click: function(e) {
this.hideMenu();
if (Event.element(e).tagName == 'A') { return; }
if (!Event.isRightClick(e) || (navigator.appVersion.match(/\bMSIE\b/))) {
var tr = Event.findElement(e, 'tr');
if (tr!=null && tr!=document && tr.hasClassName('hascontextmenu')) {
// a row was clicked, check if the click was on checkbox
var box = Event.findElement(e, 'input');
if (box!=document && box!=undefined) {
// a checkbox may be clicked
if (box.checked) {
tr.addClassName('context-menu-selection');
} else {
tr.removeClassName('context-menu-selection');
}
} else {
if (e.ctrlKey || e.metaKey) {
this.toggleSelection(tr, e);
} else if (e.shiftKey) {
if (this.lastSelected != null) {
var toggling = false;
var rows = $$('.hascontextmenu');
for (i=0; i<rows.length; i++) {
if (toggling || rows[i]==tr) {
this.addSelection(rows[i], e);
}
if (rows[i]==tr || rows[i]==this.lastSelected) {
toggling = !toggling;
}
}
} else {
this.addSelection(tr, e);
}
} else {
this.unselectAll();
this.addSelection(tr, e);
}
this.lastSelected = tr;
}
} else {
// click is outside the rows
var t = Event.findElement(e, 'a');
if (t == document || t == undefined) {
this.unselectAll();
} else {
if (Element.hasClassName(t, 'disabled') || Element.hasClassName(t, 'submenu')) {
Event.stop(e);
}
}
}
}
},
createMenu: function() {
if (!$('context-menu')) {
var menu = document.createElement("div");
menu.setAttribute("id", "context-menu");
menu.setAttribute("style", "display:none;");
document.getElementById("content").appendChild(menu);
}
},
showMenu: function(e) {
var mouse_x = Event.pointerX(e);
var mouse_y = Event.pointerY(e);
var render_x = mouse_x;
var render_y = mouse_y - $('top-menu').getHeight();
var dims;
var menu_width;
var menu_height;
var window_width;
var window_height;
var max_width;
var max_height;
$('context-menu').style['left'] = (render_x + 'px');
$('context-menu').style['top'] = (render_y + 'px');
Element.update('context-menu', '');
// some IE-versions only know the srcElement
var target = e.target ? e.target : e.srcElement;
new Ajax.Updater({success:'context-menu'}, this.url,
{asynchronous:true,
method: 'get',
evalScripts:true,
parameters: jQuery(target).closest("form").serialize(),
onComplete:function(request){
dims = $('context-menu').getDimensions();
menu_width = dims.width;
menu_height = dims.height;
max_width = render_x + 2*menu_width;
max_height = render_y + menu_height;
var ws = window_size();
window_width = ws.width;
window_height = ws.height;
/* display the menu above and/or to the left of the click if needed */
if (max_width > window_width) {
render_x -= menu_width;
$('context-menu').addClassName('reverse-x');
} else {
$('context-menu').removeClassName('reverse-x');
}
if (max_height > window_height) {
render_y -= menu_height;
$('context-menu').addClassName('reverse-y');
} else {
$('context-menu').removeClassName('reverse-y');
}
if (render_x <= 0) render_x = 1;
if (render_y <= 0) render_y = 1;
$('context-menu').style['left'] = (render_x + 'px');
$('context-menu').style['top'] = (render_y + 'px');
Effect.Appear('context-menu', {duration: 0.20});
if (window.parseStylesheets) { window.parseStylesheets(); } // IE
}})
},
hideMenu: function() {
Element.hide('context-menu');
},
addSelection: function(tr, e) {
tr.addClassName('context-menu-selection');
this.checkSelectionBox(tr, true);
this.clearDocumentSelection(e);
},
toggleSelection: function(tr,e) {
if (this.isSelected(tr)) {
this.removeSelection(tr);
} else {
this.addSelection(tr, e);
}
},
removeSelection: function(tr) {
tr.removeClassName('context-menu-selection');
this.checkSelectionBox(tr, false);
},
unselectAll: function() {
var rows = $$('.hascontextmenu');
for (i=0; i<rows.length; i++) {
this.removeSelection(rows[i]);
}
},
checkSelectionBox: function(tr, checked) {
var inputs = Element.getElementsBySelector(tr, 'input');
if (inputs.length > 0) { inputs[0].checked = checked; }
},
isSelected: function(tr) {
return Element.hasClassName(tr, 'context-menu-selection');
},
clearDocumentSelection: function(e) {
if (document.selection) {
if (document.selection.type == "Text" && e.shiftKey) {
document.selection.empty(); // IE
}
} else {
window.getSelection().removeAllRanges();
}
}
}
function toggleIssuesSelection(el) {
var boxes = el.getElementsBySelector('input[type=checkbox]');
var all_checked = true;
for (i = 0; i < boxes.length; i++) { if (boxes[i].checked == false) { all_checked = false; } }
for (i = 0; i < boxes.length; i++) {
if (all_checked) {
boxes[i].checked = false;
boxes[i].up('tr').removeClassName('context-menu-selection');
} else if (boxes[i].checked == false) {
boxes[i].checked = true;
boxes[i].up('tr').addClassName('context-menu-selection');
}
}
}
function window_size() {
var w;
var h;
if (window.innerWidth) {
w = window.innerWidth;
h = window.innerHeight;
} else if (document.documentElement) {
w = document.documentElement.clientWidth;
h = document.documentElement.clientHeight;
} else {
w = document.body.clientWidth;
h = document.body.clientHeight;
}
return {width: w, height: h};
}
|
"use strict";
const path = require("path");
const chokidar = require("chokidar");
const fs = require("graceful-fs");
const webpack = require("webpack");
const Server = require("../../lib/Server");
const config = require("../fixtures/watch-files-config/webpack.config");
const runBrowser = require("../helpers/run-browser");
const port = require("../ports-map")["watch-files-option"];
const watchDir = path.resolve(
__dirname,
"../fixtures/watch-files-config/public"
);
describe("watchFiles option", () => {
describe("should work with string and path to file", () => {
const file = path.join(watchDir, "assets/example.txt");
let compiler;
let server;
let page;
let browser;
let pageErrors;
let consoleMessages;
beforeEach(async () => {
compiler = webpack(config);
server = new Server(
{
watchFiles: file,
port,
},
compiler
);
await server.start();
({ page, browser } = await runBrowser());
pageErrors = [];
consoleMessages = [];
});
afterEach(async () => {
await browser.close();
await server.stop();
fs.truncateSync(file);
});
it("should reload when file content is changed", async () => {
page
.on("console", (message) => {
consoleMessages.push(message);
})
.on("pageerror", (error) => {
pageErrors.push(error);
});
const response = await page.goto(`http://127.0.0.1:${port}/`, {
waitUntil: "networkidle0",
});
expect(response.status()).toMatchSnapshot("response status");
expect(consoleMessages.map((message) => message.text())).toMatchSnapshot(
"console messages"
);
expect(pageErrors).toMatchSnapshot("page errors");
// change file content
fs.writeFileSync(file, "Kurosaki Ichigo", "utf8");
await new Promise((resolve) => {
server.staticWatchers[0].on("change", async (changedPath) => {
// page reload
await page.waitForNavigation({ waitUntil: "networkidle0" });
expect(changedPath).toBe(file);
resolve();
});
});
});
});
describe("should work with string and path to directory", () => {
const file = path.join(watchDir, "assets/example.txt");
let compiler;
let server;
let page;
let browser;
let pageErrors;
let consoleMessages;
beforeEach(async () => {
compiler = webpack(config);
server = new Server(
{
watchFiles: watchDir,
port,
},
compiler
);
await server.start();
({ page, browser } = await runBrowser());
pageErrors = [];
consoleMessages = [];
});
afterEach(async () => {
await browser.close();
await server.stop();
fs.truncateSync(file);
});
it("should reload when file content is changed", async () => {
page
.on("console", (message) => {
consoleMessages.push(message);
})
.on("pageerror", (error) => {
pageErrors.push(error);
});
const response = await page.goto(`http://127.0.0.1:${port}/`, {
waitUntil: "networkidle0",
});
expect(response.status()).toMatchSnapshot("response status");
expect(consoleMessages.map((message) => message.text())).toMatchSnapshot(
"console messages"
);
expect(pageErrors).toMatchSnapshot("page errors");
// change file content
fs.writeFileSync(file, "Kurosaki Ichigo", "utf8");
await new Promise((resolve) => {
server.staticWatchers[0].on("change", async (changedPath) => {
// page reload
await page.waitForNavigation({ waitUntil: "networkidle0" });
expect(changedPath).toBe(file);
resolve();
});
});
});
});
describe("should work with string and glob", () => {
const file = path.join(watchDir, "assets/example.txt");
let compiler;
let server;
let page;
let browser;
let pageErrors;
let consoleMessages;
beforeEach(async () => {
compiler = webpack(config);
server = new Server(
{
watchFiles: `${watchDir}/**/*`,
port,
},
compiler
);
await server.start();
({ page, browser } = await runBrowser());
pageErrors = [];
consoleMessages = [];
});
afterEach(async () => {
await browser.close();
await server.stop();
fs.truncateSync(file);
});
it("should reload when file content is changed", async () => {
page
.on("console", (message) => {
consoleMessages.push(message);
})
.on("pageerror", (error) => {
pageErrors.push(error);
});
const response = await page.goto(`http://127.0.0.1:${port}/`, {
waitUntil: "networkidle0",
});
expect(response.status()).toMatchSnapshot("response status");
expect(consoleMessages.map((message) => message.text())).toMatchSnapshot(
"console messages"
);
expect(pageErrors).toMatchSnapshot("page errors");
// change file content
fs.writeFileSync(file, "Kurosaki Ichigo", "utf8");
await new Promise((resolve) => {
server.staticWatchers[0].on("change", async (changedPath) => {
// page reload
await page.waitForNavigation({ waitUntil: "networkidle0" });
expect(changedPath).toBe(file);
resolve();
});
});
});
});
describe("should not crash if file doesn't exist", () => {
const nonExistFile = path.join(watchDir, "assets/non-exist.txt");
let compiler;
let server;
let page;
let browser;
let pageErrors;
let consoleMessages;
beforeEach(async () => {
try {
fs.unlinkSync(nonExistFile);
} catch (error) {
// ignore
}
compiler = webpack(config);
server = new Server(
{
watchFiles: nonExistFile,
port,
},
compiler
);
await server.start();
({ page, browser } = await runBrowser());
pageErrors = [];
consoleMessages = [];
});
afterEach(async () => {
await browser.close();
await server.stop();
});
it("should reload when file content is changed", async () => {
page
.on("console", (message) => {
consoleMessages.push(message);
})
.on("pageerror", (error) => {
pageErrors.push(error);
});
const response = await page.goto(`http://127.0.0.1:${port}/`, {
waitUntil: "networkidle0",
});
expect(response.status()).toMatchSnapshot("response status");
expect(consoleMessages.map((message) => message.text())).toMatchSnapshot(
"console messages"
);
expect(pageErrors).toMatchSnapshot("page errors");
await new Promise((resolve) => {
server.staticWatchers[0].on("change", async (changedPath) => {
// page reload
await page.waitForNavigation({ waitUntil: "networkidle0" });
expect(changedPath).toBe(nonExistFile);
resolve();
});
// create file content
setTimeout(() => {
fs.writeFileSync(nonExistFile, "Kurosaki Ichigo", "utf8");
// change file content
setTimeout(() => {
fs.writeFileSync(nonExistFile, "Kurosaki Ichigo", "utf8");
}, 1000);
}, 1000);
});
});
});
describe("should work with object with single path", () => {
const file = path.join(watchDir, "assets/example.txt");
let compiler;
let server;
let page;
let browser;
let pageErrors;
let consoleMessages;
beforeEach(async () => {
compiler = webpack(config);
server = new Server(
{
watchFiles: { paths: file },
port,
},
compiler
);
await server.start();
({ page, browser } = await runBrowser());
pageErrors = [];
consoleMessages = [];
});
afterEach(async () => {
await browser.close();
await server.stop();
fs.truncateSync(file);
});
it("should reload when file content is changed", async () => {
page
.on("console", (message) => {
consoleMessages.push(message);
})
.on("pageerror", (error) => {
pageErrors.push(error);
});
const response = await page.goto(`http://127.0.0.1:${port}/`, {
waitUntil: "networkidle0",
});
expect(response.status()).toMatchSnapshot("response status");
expect(consoleMessages.map((message) => message.text())).toMatchSnapshot(
"console messages"
);
expect(pageErrors).toMatchSnapshot("page errors");
// change file content
fs.writeFileSync(file, "Kurosaki Ichigo", "utf8");
await new Promise((resolve) => {
server.staticWatchers[0].on("change", async (changedPath) => {
// page reload
await page.waitForNavigation({ waitUntil: "networkidle0" });
expect(changedPath).toBe(file);
resolve();
});
});
});
});
describe("should work with object with multiple paths", () => {
const file = path.join(watchDir, "assets/example.txt");
const other = path.join(watchDir, "assets/other.txt");
let compiler;
let server;
let page;
let browser;
let pageErrors;
let consoleMessages;
beforeEach(async () => {
compiler = webpack(config);
server = new Server(
{
watchFiles: { paths: [file, other] },
port,
},
compiler
);
await server.start();
({ page, browser } = await runBrowser());
pageErrors = [];
consoleMessages = [];
});
afterEach(async () => {
await browser.close();
await server.stop();
fs.truncateSync(file);
fs.truncateSync(other);
});
it("should reload when file content is changed", async () => {
page
.on("console", (message) => {
consoleMessages.push(message);
})
.on("pageerror", (error) => {
pageErrors.push(error);
});
const response = await page.goto(`http://127.0.0.1:${port}/`, {
waitUntil: "networkidle0",
});
expect(response.status()).toMatchSnapshot("response status");
expect(consoleMessages.map((message) => message.text())).toMatchSnapshot(
"console messages"
);
expect(pageErrors).toMatchSnapshot("page errors");
// change file content
fs.writeFileSync(file, "foo", "utf8");
fs.writeFileSync(other, "bar", "utf8");
await new Promise((resolve) => {
const expected = [file, other];
let changed = 0;
server.staticWatchers[0].on("change", async (changedPath) => {
// page reload
await page.waitForNavigation({ waitUntil: "networkidle0" });
expect(expected.includes(changedPath)).toBeTruthy();
changed += 1;
if (changed === 2) {
resolve();
}
});
});
});
});
describe("should work with array config", () => {
const file = path.join(watchDir, "assets/example.txt");
const other = path.join(watchDir, "assets/other.txt");
let compiler;
let server;
let page;
let browser;
let pageErrors;
let consoleMessages;
beforeEach(async () => {
compiler = webpack(config);
server = new Server(
{
watchFiles: [{ paths: [file] }, other],
port,
},
compiler
);
await server.start();
({ page, browser } = await runBrowser());
pageErrors = [];
consoleMessages = [];
});
afterEach(async () => {
await browser.close();
await server.stop();
fs.truncateSync(file);
fs.truncateSync(other);
});
it("should reload when file content is changed", async () => {
page
.on("console", (message) => {
consoleMessages.push(message);
})
.on("pageerror", (error) => {
pageErrors.push(error);
});
const response = await page.goto(`http://127.0.0.1:${port}/`, {
waitUntil: "networkidle0",
});
expect(response.status()).toMatchSnapshot("response status");
expect(consoleMessages.map((message) => message.text())).toMatchSnapshot(
"console messages"
);
expect(pageErrors).toMatchSnapshot("page errors");
// change file content
fs.writeFileSync(file, "foo", "utf8");
fs.writeFileSync(other, "bar", "utf8");
await new Promise((resolve) => {
let changed = 0;
server.staticWatchers[0].on("change", async (changedPath) => {
// page reload
await page.waitForNavigation({ waitUntil: "networkidle0" });
expect(changedPath).toBe(file);
changed += 1;
if (changed === 2) {
resolve();
}
});
server.staticWatchers[1].on("change", async (changedPath) => {
// page reload
await page.waitForNavigation({ waitUntil: "networkidle0" });
expect(changedPath).toBe(other);
changed += 1;
if (changed === 2) {
resolve();
}
});
});
});
});
describe("should work with options", () => {
const file = path.join(watchDir, "assets/example.txt");
const chokidarMock = jest.spyOn(chokidar, "watch");
const optionCases = [
{
poll: true,
},
{
poll: 200,
},
{
usePolling: true,
},
{
usePolling: true,
poll: 200,
},
{
usePolling: false,
},
{
usePolling: false,
poll: 200,
},
{
usePolling: false,
poll: true,
},
{
interval: 400,
poll: 200,
},
{
usePolling: true,
interval: 200,
poll: 400,
},
{
usePolling: false,
interval: 200,
poll: 400,
},
];
optionCases.forEach((optionCase) => {
describe(JSON.stringify(optionCase), () => {
let compiler;
let server;
let page;
let browser;
let pageErrors;
let consoleMessages;
beforeEach(async () => {
chokidarMock.mockClear();
compiler = webpack(config);
server = new Server(
{
watchFiles: {
paths: file,
options: optionCase,
},
port,
},
compiler
);
await server.start();
({ page, browser } = await runBrowser());
pageErrors = [];
consoleMessages = [];
});
afterEach(async () => {
await server.stop();
await browser.close();
fs.truncateSync(file);
});
it("should reload when file content is changed", async () => {
page
.on("console", (message) => {
consoleMessages.push(message);
})
.on("pageerror", (error) => {
pageErrors.push(error);
});
const response = await page.goto(`http://127.0.0.1:${port}/`, {
waitUntil: "networkidle0",
});
// should pass correct options to chokidar config
expect(chokidarMock.mock.calls[0][1]).toMatchSnapshot();
expect(response.status()).toMatchSnapshot("response status");
expect(
consoleMessages.map((message) => message.text())
).toMatchSnapshot("console messages");
expect(pageErrors).toMatchSnapshot("page errors");
// change file content
fs.writeFileSync(file, "Kurosaki Ichigo", "utf8");
await new Promise((resolve) => {
server.staticWatchers[0].on("change", async (changedPath) => {
// page reload
await page.waitForNavigation({ waitUntil: "networkidle0" });
expect(changedPath).toBe(file);
resolve();
});
});
});
});
});
});
});
|
import arrayToID from '../../../utils/func/arrayToID';
import unique from '../../../utils/func/unique';
import constants from '../constants';
const initialState = [];
/**
* List of the feed timeline events
*
* **Actions listened**:
*
* * `FETCH_FEED_TIMELINE`
* * `FETCH_TIMELINE_EVENT`
* * `CLEAR_TIMELINE_FEED`
*
* @alias module:Timelines.feed
* @category reducers
*
* @example
* // get reducer
* BetaSeries.getReducer('timelines', 'feed').timelinesFeed;
*
* // state example
* [ 3215, 2576, 9234, ...] // Event Ids
*
* @param {Object} state
* @param {Object} action
*
* @returns {Object}
*/
export default function timelineFeedReducer(state = initialState, action) {
switch (action.type) {
case constants.CLEAR_TIMELINE_FEED: {
return initialState;
}
case constants.FETCH_FEED_TIMELINE: {
if (action.payload.events.length === 0) {
return state;
}
const events = action.payload.events;
const page = action.payload.page || 1;
return unique([
...(page > 1 ? [] : arrayToID(events)),
...state,
...(page === 1 ? [] : arrayToID(events))
]);
}
default:
return state;
}
}
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const datatype_1 = require("../datatype");
// TODO: Support full 64-bit integer range using https://tc39.github.io/proposal-integer/
const MAX_SAFE_INTEGER = Math.pow(2, 53) - 1;
const MIN_SAFE_INTEGER = -(Math.pow(2, 53) - 1);
class IntType extends datatype_1.ScalarType {
tag() {
return "i";
}
decode(str) {
if (!/^-?\d+$/.test(str)) {
throw new Error(`invalid signed int: '${str}'`);
}
let result = parseInt(str);
if (result > MAX_SAFE_INTEGER || result < MIN_SAFE_INTEGER) {
throw new RangeError(`value not in safe integer range: ${result}`);
}
return result;
}
}
exports.IntType = IntType;
class UintType extends datatype_1.ScalarType {
tag() {
return "u";
}
decode(str) {
if (!/^-?\d+$/.test(str)) {
throw new Error(`invalid unsigned int: '${str}'`);
}
if (str[0] == "-") {
throw new RangeError(`value is less than zero: ${str}`);
}
let result = parseInt(str);
if (result > MAX_SAFE_INTEGER) {
throw new RangeError(`value not in safe integer range: ${str}`);
}
return result;
}
}
exports.UintType = UintType;
|
const path = require('path')
const appEnv = process.env.APP_ENV || process.env.NODE_ENV || 'development'
let publicPaths = {
development: '/',
ghpages: '/brocessing.men/',
preprod: '/',
production: '/'
}
module.exports = {
// Used by the devServer and base href
public: publicPaths[appEnv] || publicPaths.development,
// Used by the module bundler
root: path.join(__dirname, '..'),
src: path.join(__dirname, '..', 'src'),
build: path.join(__dirname, '..', 'build'),
static: path.join(__dirname, '..', 'static'),
// Node-Resolve aliases
components: path.join(__dirname, '..', 'src', 'components'),
utils: path.join(__dirname, '..', 'src', 'utils'),
// Generating page from content and layouts
layouts: path.join(__dirname, '..', 'src', 'layouts'),
partials: path.join(__dirname, '..', 'src', 'layouts')
}
|
{
"type": "FeatureCollection",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
"features": [
{ "type": "Feature", "properties": { "Unnamed: 0": 0, "Incident Number": 150310032, "Date": "01\/31\/2015", "Time": "09:10 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.110096, -87.937946 ], "Address": "5122 N 21ST ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 6, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.937946061683618, 43.110095655943113 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 1, "Incident Number": 150310059, "Date": "01\/31\/2015", "Time": "12:37 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.109713, -87.963654 ], "Address": "5067 N 41ST ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 2, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.963654135610625, 43.109713268105523 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 2, "Incident Number": 150300044, "Date": "01\/30\/2015", "Time": "09:01 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.105257, -87.942868 ], "Address": "4835 N 24TH PL", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 6, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.942868084828632, 43.105256947544575 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 3, "Incident Number": 150300111, "Date": "01\/30\/2015", "Time": "07:33 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.108461, -87.948691 ], "Address": "5003 N TEUTONIA AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 6, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.948691389837677, 43.108461230913534 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 4, "Incident Number": 150310007, "Date": "01\/30\/2015", "Time": "11:42 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.104450, -87.931429 ], "Address": "4803 N GREEN BAY AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 6, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.931428959041725, 43.104450306068159 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 5, "Incident Number": 150290077, "Date": "01\/29\/2015", "Time": "01:03 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.110058, -87.963805 ], "Address": "5101 N 41ST ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 2, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.963804562900094, 43.110058191499846 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 6, "Incident Number": 150290079, "Date": "01\/29\/2015", "Time": "01:09 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.104580, -87.946696 ], "Address": "4801 N TEUTONIA AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 6, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.946696069964361, 43.104579620989313 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 7, "Incident Number": 150280037, "Date": "01\/28\/2015", "Time": "09:50 AM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.125923, -87.956053 ], "Address": "5966 N 35TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 4, "g_clusterK9": 4, "e_clusterK10": 2, "g_clusterK10": 2 }, "geometry": { "type": "Point", "coordinates": [ -87.956052962694685, 43.125922653160181 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 8, "Incident Number": 150280090, "Date": "01\/28\/2015", "Time": "06:36 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.102287, -87.935400 ], "Address": "4685 N 19TH PL", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 6, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.935400117577231, 43.102287 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 9, "Incident Number": 150280094, "Date": "01\/28\/2015", "Time": "06:53 PM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.117902, -87.950606 ], "Address": "5541 N TEUTONIA AV #3", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 2, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.950606182063041, 43.11790184860515 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 10, "Incident Number": 150280136, "Date": "01\/28\/2015", "Time": "07:51 PM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.098901, -87.941102 ], "Address": "2316 W RUBY AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 6, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.941101919095161, 43.09890052596792 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 11, "Incident Number": 150270104, "Date": "01\/27\/2015", "Time": "11:54 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.105399, -87.978886 ], "Address": "4828 N 53RD ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 3, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 1, "g_clusterK7": 0, "e_clusterK8": 6, "g_clusterK8": 6, "e_clusterK9": 4, "g_clusterK9": 4, "e_clusterK10": 2, "g_clusterK10": 2 }, "geometry": { "type": "Point", "coordinates": [ -87.978886184950312, 43.105398537884469 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 12, "Incident Number": 150260098, "Date": "01\/26\/2015", "Time": "03:41 PM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.114827, -87.950240 ], "Address": "5335 N TEUTONIA AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 2, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.950239891655357, 43.114827080760605 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 13, "Incident Number": 150250026, "Date": "01\/25\/2015", "Time": "05:08 AM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.112608, -87.950069 ], "Address": "5233 N TEUTONIA AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 6, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.950069493796249, 43.112607736886133 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 14, "Incident Number": 150250053, "Date": "01\/25\/2015", "Time": "11:22 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.111017, -87.934463 ], "Address": "5144 N 19TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 6, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.934463404639772, 43.111017052455423 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 15, "Incident Number": 150250072, "Date": "01\/25\/2015", "Time": "02:06 PM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.114897, -87.933997 ], "Address": "5385 N GREEN BAY AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 6, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.93399747326869, 43.114897405191641 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 16, "Incident Number": 150250073, "Date": "01\/25\/2015", "Time": "01:13 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.106076, -87.956484 ], "Address": "4858 N MOTHER DANIELS WA", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 2, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.956484352992405, 43.106075580904843 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 17, "Incident Number": 150240013, "Date": "01\/24\/2015", "Time": "01:50 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.104699, -87.946732 ], "Address": "4811 N TEUTONIA AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 6, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.946731745397571, 43.104698684719182 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 18, "Incident Number": 150250004, "Date": "01\/24\/2015", "Time": "11:55 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.107624, -87.937985 ], "Address": "4950 N 21ST ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 6, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.937985328034102, 43.10762430391253 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 19, "Incident Number": 150230117, "Date": "01\/23\/2015", "Time": "07:48 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.106185, -87.962721 ], "Address": "4873 N 40TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 2, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.962721132003949, 43.106184586733235 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 20, "Incident Number": 150220010, "Date": "01\/22\/2015", "Time": "03:59 AM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.091847, -87.941884 ], "Address": "4112 N 24TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 6, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.941883904639781, 43.091846800998326 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 21, "Incident Number": 150210042, "Date": "01\/21\/2015", "Time": "07:48 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.106959, -87.959018 ], "Address": "4921 N 37TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 2, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.959017632003949, 43.106958586733214 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 22, "Incident Number": 150210057, "Date": "01\/21\/2015", "Time": "11:28 AM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.127677, -87.959788 ], "Address": "6043 N 38TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 2, "e_clusterK5": 3, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 4, "g_clusterK9": 4, "e_clusterK10": 2, "g_clusterK10": 2 }, "geometry": { "type": "Point", "coordinates": [ -87.959788106468721, 43.127677341104516 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 23, "Incident Number": 150210068, "Date": "01\/21\/2015", "Time": "12:15 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.106633, -87.952812 ], "Address": "4920 N 32ND ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 6, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.952812393531275, 43.10663332944776 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 24, "Incident Number": 150200019, "Date": "01\/20\/2015", "Time": "08:47 AM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.118118, -87.957472 ], "Address": "5530 N 36TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 2, "g_clusterK10": 2 }, "geometry": { "type": "Point", "coordinates": [ -87.957472360782688, 43.118117884817366 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 25, "Incident Number": 150200083, "Date": "01\/20\/2015", "Time": "03:41 PM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.120403, -87.966244 ], "Address": "5650 N 43RD ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 3, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 4, "g_clusterK9": 4, "e_clusterK10": 2, "g_clusterK10": 2 }, "geometry": { "type": "Point", "coordinates": [ -87.9662439190665, 43.120402910352595 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 26, "Incident Number": 150180085, "Date": "01\/18\/2015", "Time": "02:46 PM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.129809, -87.958395 ], "Address": "6140 N 37TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 2, "e_clusterK5": 3, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 4, "g_clusterK9": 4, "e_clusterK10": 2, "g_clusterK10": 2 }, "geometry": { "type": "Point", "coordinates": [ -87.95839486078269, 43.129808800998347 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 27, "Incident Number": 150170089, "Date": "01\/17\/2015", "Time": "05:47 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.109577, -87.966568 ], "Address": "5075 N SHERMAN BL", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 4, "g_clusterK9": 3, "e_clusterK10": 2, "g_clusterK10": 2 }, "geometry": { "type": "Point", "coordinates": [ -87.966568164895818, 43.109576528449423 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 28, "Incident Number": 150160028, "Date": "01\/16\/2015", "Time": "07:59 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.105022, -87.935285 ], "Address": "4828 N 19TH PL", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 6, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.935284893531275, 43.105022465722215 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 29, "Incident Number": 150160032, "Date": "01\/16\/2015", "Time": "09:12 AM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.142949, -87.958924 ], "Address": "6921 N SUSSEX ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 3, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 4, "g_clusterK9": 4, "e_clusterK10": 2, "g_clusterK10": 2 }, "geometry": { "type": "Point", "coordinates": [ -87.958924490160911, 43.142948613364979 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 30, "Incident Number": 150160082, "Date": "01\/16\/2015", "Time": "03:03 PM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.148747, -87.963820 ], "Address": "4154 W GOOD HOPE RD", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 3, "g_clusterK5": 0, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 0, "g_clusterK7": 2, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 4, "g_clusterK9": 4, "e_clusterK10": 2, "g_clusterK10": 2 }, "geometry": { "type": "Point", "coordinates": [ -87.963820499874856, 43.148746641641189 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 31, "Incident Number": 150150034, "Date": "01\/15\/2015", "Time": "09:32 AM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.091028, -87.933124 ], "Address": "4064 N 18TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 6, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.933124437388358, 43.091027717179315 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 32, "Incident Number": 150140016, "Date": "01\/14\/2015", "Time": "04:39 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.105652, -87.945316 ], "Address": "4852 N 26TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 6, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.945315911853129, 43.105651910352577 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 33, "Incident Number": 150120047, "Date": "01\/12\/2015", "Time": "10:17 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.111859, -87.956091 ], "Address": "3427 W VILLARD AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 2, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.956091167638064, 43.111859481245453 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 34, "Incident Number": 150120069, "Date": "01\/12\/2015", "Time": "12:13 PM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.133118, -87.973704 ], "Address": "4811 W WOOLWORTH AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 3, "g_clusterK5": 3, "e_clusterK6": 3, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 6, "g_clusterK8": 6, "e_clusterK9": 4, "g_clusterK9": 4, "e_clusterK10": 2, "g_clusterK10": 2 }, "geometry": { "type": "Point", "coordinates": [ -87.973704, 43.133117546165693 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 35, "Incident Number": 150100039, "Date": "01\/10\/2015", "Time": "12:27 PM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.090903, -87.925820 ], "Address": "4067 N 12TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 6, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.925820073720146, 43.090903424923539 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 36, "Incident Number": 150080032, "Date": "01\/08\/2015", "Time": "12:43 PM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.091442, -87.929426 ], "Address": "4100 N 15TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 2, "e_clusterK6": 5, "g_clusterK6": 4, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 6, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.929426411853129, 43.091441633360262 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 37, "Incident Number": 150080077, "Date": "01\/08\/2015", "Time": "08:17 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.109856, -87.939075 ], "Address": "5080 N 22ND ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 6, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.939075128331964, 43.109855709091981 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 38, "Incident Number": 150060098, "Date": "01\/06\/2015", "Time": "01:38 PM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.094493, -87.946889 ], "Address": "4275 N 27TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 6, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.946889135899085, 43.094492863725549 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 39, "Incident Number": 150040049, "Date": "01\/04\/2015", "Time": "12:29 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.104719, -87.965099 ], "Address": "4200 W HAMPTON AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 2, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.965098923589267, 43.104718877742819 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 40, "Incident Number": 150030036, "Date": "01\/03\/2015", "Time": "07:39 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.105113, -87.958993 ], "Address": "4820 N 37TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 2, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.958993360782685, 43.105112884817373 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 41, "Incident Number": 150030061, "Date": "01\/03\/2015", "Time": "01:39 PM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.111994, -87.962533 ], "Address": "4000 W VILLARD AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 2, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.962533099085221, 43.111994433841303 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 42, "Incident Number": 150010066, "Date": "01\/01\/2015", "Time": "09:39 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.106369, -87.959803 ], "Address": "3723 W STARK ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 2, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.959803332361929, 43.106368506780676 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 43, "Incident Number": 150300034, "Date": "01\/30\/2015", "Time": "07:27 AM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.043552, -87.970974 ], "Address": "1062 N 46TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 1, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 0, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 7, "g_clusterK10": 7 }, "geometry": { "type": "Point", "coordinates": [ -87.970973896849486, 43.043552413266781 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 44, "Incident Number": 150290010, "Date": "01\/29\/2015", "Time": "01:06 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.075411, -87.983119 ], "Address": "5600 W BURLEIGH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.983119071232991, 43.075410874951203 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 45, "Incident Number": 150290054, "Date": "01\/29\/2015", "Time": "10:14 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.068105, -87.976225 ], "Address": "2705 N 50TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.976225444286811, 43.068105266635918 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 46, "Incident Number": 150290087, "Date": "01\/29\/2015", "Time": "02:32 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.071902, -87.979772 ], "Address": "2909 N 53RD ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.979771632003946, 43.071902444630382 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 47, "Incident Number": 150280053, "Date": "01\/28\/2015", "Time": "12:05 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.071417, -87.984202 ], "Address": "2874 N 57TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.984202360782689, 43.07141716763806 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 48, "Incident Number": 150280015, "Date": "01\/27\/2015", "Time": "10:04 PM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.039975, -87.983534 ], "Address": "835 N HAWLEY RD", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 1, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 0, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 7, "g_clusterK10": 7 }, "geometry": { "type": "Point", "coordinates": [ -87.9835339812944, 43.039974658920968 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 49, "Incident Number": 150210096, "Date": "01\/21\/2015", "Time": "03:13 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.071498, -87.982099 ], "Address": "2877 N 55TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.982099106468723, 43.071497612268445 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 50, "Incident Number": 150200111, "Date": "01\/20\/2015", "Time": "05:05 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.086727, -87.994659 ], "Address": "3819 N 66TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 3, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 6, "g_clusterK8": 6, "e_clusterK9": 6, "g_clusterK9": 6, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.994659124790587, 43.086727089647411 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 51, "Incident Number": 150190072, "Date": "01\/19\/2015", "Time": "01:45 PM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.067996, -87.984324 ], "Address": "5631 W CENTER ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.984324, 43.067996488458817 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 52, "Incident Number": 150190101, "Date": "01\/19\/2015", "Time": "04:12 PM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.034148, -87.960104 ], "Address": "316 N 37TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 4, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 7, "g_clusterK10": 7 }, "geometry": { "type": "Point", "coordinates": [ -87.960103970136956, 43.034147717179309 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 53, "Incident Number": 150160099, "Date": "01\/16\/2015", "Time": "11:58 AM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.033638, -87.957855 ], "Address": "3505 W MT VERNON AV", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 4, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 7, "g_clusterK10": 7 }, "geometry": { "type": "Point", "coordinates": [ -87.957855436464939, 43.033637824738186 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 54, "Incident Number": 150140031, "Date": "01\/14\/2015", "Time": "08:33 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.088994, -87.999462 ], "Address": "3959 N 70TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 0, "e_clusterK5": 3, "g_clusterK5": 3, "e_clusterK6": 3, "g_clusterK6": 5, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 6, "g_clusterK8": 6, "e_clusterK9": 6, "g_clusterK9": 6, "e_clusterK10": 0, "g_clusterK10": 0 }, "geometry": { "type": "Point", "coordinates": [ -87.999461599255355, 43.088994335276141 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 55, "Incident Number": 150070039, "Date": "01\/07\/2015", "Time": "11:26 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.081889, -87.987278 ], "Address": "3435 N 60TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 3, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 1, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 6, "g_clusterK9": 8, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.987278107403199, 43.081888573662681 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 56, "Incident Number": 150060125, "Date": "01\/06\/2015", "Time": "09:49 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.080826, -87.996636 ], "Address": "6780 W APPLETON AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 3, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 6, "g_clusterK8": 5, "e_clusterK9": 6, "g_clusterK9": 6, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.996636218247147, 43.080826335853033 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 57, "Incident Number": 150050071, "Date": "01\/05\/2015", "Time": "03:22 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.078753, -87.979660 ], "Address": "3275 N 53RD ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.979660106468728, 43.078753341104516 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 58, "Incident Number": 150020089, "Date": "01\/02\/2015", "Time": "02:54 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.076394, -87.978531 ], "Address": "3151 N 52ND ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.978530606468723, 43.076393696087479 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 59, "Incident Number": 150010125, "Date": "01\/01\/2015", "Time": "04:58 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.073474, -87.976181 ], "Address": "5000 W CHAMBERS ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.976181259074494, 43.073474483841586 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 60, "Incident Number": 150310029, "Date": "01\/31\/2015", "Time": "04:32 AM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.003042, -87.958394 ], "Address": "3510 W LINCOLN AV", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 8, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.958393585348247, 43.003042478792615 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 61, "Incident Number": 150290014, "Date": "01\/29\/2015", "Time": "12:25 AM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.004194, -87.959015 ], "Address": "2222 S 36TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 8, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.959014970136948, 43.004194187344922 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 62, "Incident Number": 150290025, "Date": "01\/29\/2015", "Time": "03:56 AM", "Police District": 6.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 42.974047, -88.017861 ], "Address": "3869 S 84TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 1, "g_clusterK6": 1, "e_clusterK7": 4, "g_clusterK7": 4, "e_clusterK8": 3, "g_clusterK8": 3, "e_clusterK9": 0, "g_clusterK9": 0, "e_clusterK10": 8, "g_clusterK10": 3 }, "geometry": { "type": "Point", "coordinates": [ -88.017860501009608, 42.974047257285491 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 63, "Incident Number": 150290060, "Date": "01\/29\/2015", "Time": "11:20 AM", "Police District": 6.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 42.975375, -87.953682 ], "Address": "3828 S MINER ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 1, "g_clusterK6": 1, "e_clusterK7": 4, "g_clusterK7": 4, "e_clusterK8": 3, "g_clusterK8": 3, "e_clusterK9": 0, "g_clusterK9": 0, "e_clusterK10": 3, "g_clusterK10": 3 }, "geometry": { "type": "Point", "coordinates": [ -87.953682271537744, 42.975375387417365 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 65, "Incident Number": 150250124, "Date": "01\/25\/2015", "Time": "09:00 PM", "Police District": 6.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 42.984891, -87.948438 ], "Address": "3355 S 27TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 1, "g_clusterK6": 1, "e_clusterK7": 4, "g_clusterK7": 4, "e_clusterK8": 3, "g_clusterK8": 3, "e_clusterK9": 0, "g_clusterK9": 0, "e_clusterK10": 3, "g_clusterK10": 3 }, "geometry": { "type": "Point", "coordinates": [ -87.948437518897848, 42.984890912488318 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 66, "Incident Number": 150190023, "Date": "01\/19\/2015", "Time": "05:57 AM", "Police District": 6.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 42.983400, -87.942248 ], "Address": "3365 S 22ND ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 1, "g_clusterK6": 1, "e_clusterK7": 4, "g_clusterK7": 4, "e_clusterK8": 3, "g_clusterK8": 3, "e_clusterK9": 0, "g_clusterK9": 0, "e_clusterK10": 3, "g_clusterK10": 3 }, "geometry": { "type": "Point", "coordinates": [ -87.942247848648591, 42.98340034864858 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 67, "Incident Number": 150190041, "Date": "01\/19\/2015", "Time": "08:52 AM", "Police District": 6.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 42.984024, -87.943718 ], "Address": "2324 W SUNBURY CT", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 1, "g_clusterK6": 1, "e_clusterK7": 4, "g_clusterK7": 4, "e_clusterK8": 3, "g_clusterK8": 3, "e_clusterK9": 0, "g_clusterK9": 0, "e_clusterK10": 3, "g_clusterK10": 3 }, "geometry": { "type": "Point", "coordinates": [ -87.943718321172227, 42.984024112170893 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 68, "Incident Number": 150160097, "Date": "01\/16\/2015", "Time": "04:50 PM", "Police District": 6.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 42.988412, -87.959750 ], "Address": "3615 W OKLAHOMA AV", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 1, "g_clusterK6": 1, "e_clusterK7": 4, "g_clusterK7": 4, "e_clusterK8": 3, "g_clusterK8": 3, "e_clusterK9": 0, "g_clusterK9": 0, "e_clusterK10": 8, "g_clusterK10": 3 }, "geometry": { "type": "Point", "coordinates": [ -87.959749971550579, 42.988412495672186 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 69, "Incident Number": 150080076, "Date": "01\/08\/2015", "Time": "06:10 PM", "Police District": 6.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 42.968106, -87.978290 ], "Address": "4207 S 51ST ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 1, "g_clusterK6": 1, "e_clusterK7": 4, "g_clusterK7": 4, "e_clusterK8": 3, "g_clusterK8": 3, "e_clusterK9": 0, "g_clusterK9": 0, "e_clusterK10": 3, "g_clusterK10": 3 }, "geometry": { "type": "Point", "coordinates": [ -87.9782895337582, 42.968106199001681 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 70, "Incident Number": 150020136, "Date": "01\/02\/2015", "Time": "08:02 PM", "Police District": 6.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 42.982902, -87.943456 ], "Address": "3413 S 23RD ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 1, "g_clusterK6": 1, "e_clusterK7": 4, "g_clusterK7": 4, "e_clusterK8": 3, "g_clusterK8": 3, "e_clusterK9": 0, "g_clusterK9": 0, "e_clusterK10": 3, "g_clusterK10": 3 }, "geometry": { "type": "Point", "coordinates": [ -87.943455507874177, 42.982901733033337 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 71, "Incident Number": 150310042, "Date": "01\/31\/2015", "Time": "10:19 AM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.019878, -87.926685 ], "Address": "1110 S 12TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.926684651715803, 43.019877786519608 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 72, "Incident Number": 150310044, "Date": "01\/31\/2015", "Time": "11:03 AM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.022216, -87.932322 ], "Address": "1558 W WALKER ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.932322167638063, 43.022216460470737 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 73, "Incident Number": 150290092, "Date": "01\/29\/2015", "Time": "02:59 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.015124, -87.924042 ], "Address": "1535 S 10TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.92404153707642, 43.015123676380625 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 74, "Incident Number": 150280041, "Date": "01\/28\/2015", "Time": "10:51 AM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.014447, -87.930760 ], "Address": "1569 S 15TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.93076001543632, 43.014447366639729 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 75, "Incident Number": 150280064, "Date": "01\/28\/2015", "Time": "12:23 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.024322, -87.931363 ], "Address": "1500 W PIERCE ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.931363256012745, 43.024321817346674 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 76, "Incident Number": 150280135, "Date": "01\/28\/2015", "Time": "08:33 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.014076, -87.934219 ], "Address": "1700 W LAPHAM ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.934218581961559, 43.014076052065654 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 77, "Incident Number": 150290007, "Date": "01\/28\/2015", "Time": "11:30 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.010066, -87.925618 ], "Address": "1901 S 11TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.925618008222969, 43.010065760199666 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 78, "Incident Number": 150260042, "Date": "01\/26\/2015", "Time": "10:21 AM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.012286, -87.911613 ], "Address": "117 W MITCHELL ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.911612664723876, 43.012285513994044 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 79, "Incident Number": 150250058, "Date": "01\/25\/2015", "Time": "11:17 AM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.008947, -87.923314 ], "Address": "922 W WINDLAKE AV", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.923314098822672, 43.008947265624016 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 80, "Incident Number": 150250079, "Date": "01\/25\/2015", "Time": "03:05 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.021412, -87.909833 ], "Address": "934 S BARCLAY ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.909832955710229, 43.021411994171615 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 81, "Incident Number": 150250103, "Date": "01\/25\/2015", "Time": "06:12 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.018040, -87.928600 ], "Address": "1319 W MADISON ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.928600332361938, 43.018039521207392 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 82, "Incident Number": 150240089, "Date": "01\/24\/2015", "Time": "01:17 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.009395, -87.932113 ], "Address": "1932 S 15TH PL", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.932112561169333, 43.009395485429053 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 83, "Incident Number": 150240150, "Date": "01\/24\/2015", "Time": "08:24 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.012238, -87.934155 ], "Address": "1700 S 17TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.934154899106119, 43.012238404726098 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 84, "Incident Number": 150230100, "Date": "01\/23\/2015", "Time": "05:10 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.017982, -87.918554 ], "Address": "617 W MADISON ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.918553820529183, 43.017981522595058 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 85, "Incident Number": 150230147, "Date": "01\/23\/2015", "Time": "10:54 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.014729, -87.936984 ], "Address": "1585 S UNION ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.936984252620377, 43.014728530543721 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 86, "Incident Number": 150220110, "Date": "01\/22\/2015", "Time": "10:05 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.014701, -87.936870 ], "Address": "1560 S UNION ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.936869851491863, 43.014701211754954 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 87, "Incident Number": 150210084, "Date": "01\/21\/2015", "Time": "01:48 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.008227, -87.933153 ], "Address": "2000 S 16TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.933153470136943, 43.008227298084137 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 88, "Incident Number": 150200037, "Date": "01\/20\/2015", "Time": "10:07 AM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.011105, -87.927054 ], "Address": "1200 W MAPLE ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.927054146480131, 43.011105146480133 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 89, "Incident Number": 150200070, "Date": "01\/20\/2015", "Time": "01:52 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.012215, -87.929857 ], "Address": "1425 W MITCHELL ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.929856876165573, 43.01221538867361 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 90, "Incident Number": 150170058, "Date": "01\/17\/2015", "Time": "12:49 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.004461, -87.933276 ], "Address": "2208 S 16TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.933275944601718, 43.004461201771633 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 91, "Incident Number": 150160030, "Date": "01\/16\/2015", "Time": "08:22 AM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.008262, -87.931555 ], "Address": "1523 W ROGERS ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.931555267388504, 43.008262033119429 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 92, "Incident Number": 150160037, "Date": "01\/16\/2015", "Time": "06:48 AM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.022106, -87.938014 ], "Address": "822 S 20TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 8, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.93801444460172, 43.022105832361945 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 93, "Incident Number": 150150035, "Date": "01\/15\/2015", "Time": "09:49 AM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.008158, -87.928289 ], "Address": "2003 S 13TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.928289018754555, 43.008157844018712 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 94, "Incident Number": 150150045, "Date": "01\/15\/2015", "Time": "11:02 AM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.018956, -87.935569 ], "Address": "1201 S 18TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.935568566506774, 43.018956167638066 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 95, "Incident Number": 150140084, "Date": "01\/14\/2015", "Time": "04:05 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.017642, -87.925304 ], "Address": "1312 S 11TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.925303915171369, 43.017642 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 96, "Incident Number": 150140089, "Date": "01\/14\/2015", "Time": "04:52 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.001405, -87.923595 ], "Address": "2366 S 9TH PL", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.923595470136945, 43.001405077990654 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 97, "Incident Number": 150130019, "Date": "01\/13\/2015", "Time": "08:18 AM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.021131, -87.931652 ], "Address": "1541 W MINERAL ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.9316515, 43.021130502885526 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 98, "Incident Number": 150130027, "Date": "01\/13\/2015", "Time": "09:19 AM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.023349, -87.938079 ], "Address": "737 S 20TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 8, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.938079110363859, 43.023348502914189 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 99, "Incident Number": 150130031, "Date": "01\/13\/2015", "Time": "09:46 AM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.019478, -87.931888 ], "Address": "1129 S 15TH PL", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.931888065929854, 43.019478 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 100, "Incident Number": 150130078, "Date": "01\/13\/2015", "Time": "03:08 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.019243, -87.934255 ], "Address": "1138 S 17TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.934254974032086, 43.019242994171634 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 101, "Incident Number": 150090059, "Date": "01\/09\/2015", "Time": "03:03 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.021647, -87.936756 ], "Address": "908 S 19TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.936756415171359, 43.021646832361938 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 102, "Incident Number": 150090066, "Date": "01\/09\/2015", "Time": "04:51 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.019133, -87.922581 ], "Address": "900 W SCOTT ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.922581156660044, 43.019133156660061 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 103, "Incident Number": 150090103, "Date": "01\/09\/2015", "Time": "09:33 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.018587, -87.931815 ], "Address": "1218 S 15TH PL", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.931814937388353, 43.018587 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 104, "Incident Number": 150060014, "Date": "01\/06\/2015", "Time": "06:52 AM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.020092, -87.927192 ], "Address": "1211 W WASHINGTON ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.927192, 43.020092474032097 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 105, "Incident Number": 150060021, "Date": "01\/06\/2015", "Time": "09:43 AM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.016979, -87.919828 ], "Address": "1403 S 7TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.919827575123918, 43.016978648177663 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 106, "Incident Number": 150060043, "Date": "01\/06\/2015", "Time": "01:22 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.022051, -87.922532 ], "Address": "903 S 9TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.922531548184921, 43.022050742714526 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 107, "Incident Number": 150060062, "Date": "01\/06\/2015", "Time": "03:27 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.010064, -87.922798 ], "Address": "1901 S 9TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.922797566506773, 43.010064450458771 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 108, "Incident Number": 150040054, "Date": "01\/04\/2015", "Time": "01:44 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.018695, -87.939413 ], "Address": "1214 S 21ST ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 8, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.939413426279856, 43.018695 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 109, "Incident Number": 150040071, "Date": "01\/04\/2015", "Time": "04:53 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.021774, -87.935552 ], "Address": "905 S 18TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.935551562611636, 43.021773586733218 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 110, "Incident Number": 150040074, "Date": "01\/04\/2015", "Time": "05:08 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.001281, -87.928870 ], "Address": "1310 W HAYES AV", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.928870080904844, 43.001281486005979 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 111, "Incident Number": 150030040, "Date": "01\/03\/2015", "Time": "09:36 AM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.008363, -87.926002 ], "Address": "1120 W ROGERS ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.92600245659122, 43.008362692089577 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 112, "Incident Number": 150030045, "Date": "01\/03\/2015", "Time": "10:57 AM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.019036, -87.930243 ], "Address": "1429 W SCOTT ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.930243, 43.019035513994027 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 113, "Incident Number": 150030060, "Date": "01\/03\/2015", "Time": "01:34 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.020071, -87.914879 ], "Address": "323 W WASHINGTON ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.914879413266775, 43.020071488458825 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 114, "Incident Number": 150020065, "Date": "01\/02\/2015", "Time": "11:56 AM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.021121, -87.933942 ], "Address": "1629 W MINERAL ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.933941580904843, 43.021121481245466 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 115, "Incident Number": 150020175, "Date": "01\/02\/2015", "Time": "11:33 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.013902, -87.933151 ], "Address": "1605 W LAPHAM ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.933150947510612, 43.013901800597523 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 116, "Incident Number": 150010138, "Date": "01\/01\/2015", "Time": "07:25 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.019036, -87.928344 ], "Address": "1309 W SCOTT ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.928344083819027, 43.019035513994027 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 117, "Incident Number": 150010148, "Date": "01\/01\/2015", "Time": "08:44 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.011653, -87.918526 ], "Address": "1724 S 6TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.918525962346664, 43.011652903139229 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 118, "Incident Number": 150300047, "Date": "01\/30\/2015", "Time": "09:41 AM", "Police District": 6.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 42.981140, -87.938402 ], "Address": "1935 W MORGAN AV", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 1, "g_clusterK6": 1, "e_clusterK7": 4, "g_clusterK7": 4, "e_clusterK8": 3, "g_clusterK8": 3, "e_clusterK9": 0, "g_clusterK9": 0, "e_clusterK10": 3, "g_clusterK10": 3 }, "geometry": { "type": "Point", "coordinates": [ -87.938401835276125, 42.981139521207389 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 119, "Incident Number": 150280143, "Date": "01\/28\/2015", "Time": "10:10 PM", "Police District": 6.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 42.930186, -87.890186 ], "Address": "1500 E COLLEGE AV", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 1, "g_clusterK6": 1, "e_clusterK7": 4, "g_clusterK7": 4, "e_clusterK8": 3, "g_clusterK8": 3, "e_clusterK9": 2, "g_clusterK9": 2, "e_clusterK10": 3, "g_clusterK10": 3 }, "geometry": { "type": "Point", "coordinates": [ -87.890185504001266, 42.930186044104346 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 120, "Incident Number": 150260128, "Date": "01\/26\/2015", "Time": "08:07 PM", "Police District": 6.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 42.959472, -87.939656 ], "Address": "2020 W LAYTON AV", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 1, "g_clusterK6": 1, "e_clusterK7": 4, "g_clusterK7": 4, "e_clusterK8": 3, "g_clusterK8": 3, "e_clusterK9": 0, "g_clusterK9": 0, "e_clusterK10": 3, "g_clusterK10": 3 }, "geometry": { "type": "Point", "coordinates": [ -87.939655573194003, 42.959472081106867 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 121, "Incident Number": 150240060, "Date": "01\/24\/2015", "Time": "10:00 AM", "Police District": 6.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 42.983937, -87.934904 ], "Address": "3332 S 17TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 1, "g_clusterK6": 1, "e_clusterK7": 4, "g_clusterK7": 4, "e_clusterK8": 3, "g_clusterK8": 3, "e_clusterK9": 0, "g_clusterK9": 2, "e_clusterK10": 3, "g_clusterK10": 3 }, "geometry": { "type": "Point", "coordinates": [ -87.934904404639781, 42.983936664723871 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 122, "Incident Number": 150240074, "Date": "01\/24\/2015", "Time": "10:48 AM", "Police District": 6.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 42.973964, -87.941273 ], "Address": "2126 W HOWARD AV", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 1, "g_clusterK6": 1, "e_clusterK7": 4, "g_clusterK7": 4, "e_clusterK8": 3, "g_clusterK8": 3, "e_clusterK9": 0, "g_clusterK9": 0, "e_clusterK10": 3, "g_clusterK10": 3 }, "geometry": { "type": "Point", "coordinates": [ -87.94127322300767, 42.973964453257395 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 123, "Incident Number": 150220030, "Date": "01\/22\/2015", "Time": "10:50 AM", "Police District": 6.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 42.959498, -87.942480 ], "Address": "2240 W LAYTON AV", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 1, "g_clusterK6": 1, "e_clusterK7": 4, "g_clusterK7": 4, "e_clusterK8": 3, "g_clusterK8": 3, "e_clusterK9": 0, "g_clusterK9": 0, "e_clusterK10": 3, "g_clusterK10": 3 }, "geometry": { "type": "Point", "coordinates": [ -87.942480278221197, 42.959497908734186 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 124, "Incident Number": 150210087, "Date": "01\/21\/2015", "Time": "01:18 PM", "Police District": 6.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 42.959474, -87.940488 ], "Address": "2120 W LAYTON AV #211", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 1, "g_clusterK6": 1, "e_clusterK7": 4, "g_clusterK7": 4, "e_clusterK8": 3, "g_clusterK8": 3, "e_clusterK9": 0, "g_clusterK9": 0, "e_clusterK10": 3, "g_clusterK10": 3 }, "geometry": { "type": "Point", "coordinates": [ -87.940487725013114, 42.95947426636922 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 125, "Incident Number": 150200050, "Date": "01\/20\/2015", "Time": "11:27 AM", "Police District": 6.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 42.960384, -87.911129 ], "Address": "4601 S 1ST ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 1, "g_clusterK6": 1, "e_clusterK7": 4, "g_clusterK7": 4, "e_clusterK8": 3, "g_clusterK8": 3, "e_clusterK9": 2, "g_clusterK9": 2, "e_clusterK10": 3, "g_clusterK10": 3 }, "geometry": { "type": "Point", "coordinates": [ -87.911129063765472, 42.960384 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 126, "Incident Number": 150190034, "Date": "01\/19\/2015", "Time": "09:14 AM", "Police District": 6.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 42.973077, -87.939441 ], "Address": "2012 W VAN BECK WA", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 1, "g_clusterK6": 1, "e_clusterK7": 4, "g_clusterK7": 4, "e_clusterK8": 3, "g_clusterK8": 3, "e_clusterK9": 0, "g_clusterK9": 0, "e_clusterK10": 3, "g_clusterK10": 3 }, "geometry": { "type": "Point", "coordinates": [ -87.939441052455422, 42.97307650375091 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 127, "Incident Number": 150190068, "Date": "01\/19\/2015", "Time": "01:15 PM", "Police District": 6.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 42.959498, -87.942480 ], "Address": "2240 W LAYTON AV", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 1, "g_clusterK6": 1, "e_clusterK7": 4, "g_clusterK7": 4, "e_clusterK8": 3, "g_clusterK8": 3, "e_clusterK9": 0, "g_clusterK9": 0, "e_clusterK10": 3, "g_clusterK10": 3 }, "geometry": { "type": "Point", "coordinates": [ -87.942480278221197, 42.959497908734186 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 128, "Incident Number": 150190080, "Date": "01\/19\/2015", "Time": "11:28 AM", "Police District": 6.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 42.960515, -87.938831 ], "Address": "4610 S 20TH ST #2", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 1, "g_clusterK6": 1, "e_clusterK7": 4, "g_clusterK7": 4, "e_clusterK8": 3, "g_clusterK8": 3, "e_clusterK9": 0, "g_clusterK9": 0, "e_clusterK10": 3, "g_clusterK10": 3 }, "geometry": { "type": "Point", "coordinates": [ -87.938830815588034, 42.960514736438434 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 129, "Incident Number": 150190141, "Date": "01\/19\/2015", "Time": "06:46 PM", "Police District": 6.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 42.973111, -87.912009 ], "Address": "3927 S 1ST PL", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 1, "g_clusterK6": 1, "e_clusterK7": 4, "g_clusterK7": 4, "e_clusterK8": 3, "g_clusterK8": 3, "e_clusterK9": 2, "g_clusterK9": 2, "e_clusterK10": 3, "g_clusterK10": 3 }, "geometry": { "type": "Point", "coordinates": [ -87.912008515436327, 42.973110586733213 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 130, "Incident Number": 150180118, "Date": "01\/18\/2015", "Time": "08:36 PM", "Police District": 6.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 42.959473, -87.940383 ], "Address": "2110 W LAYTON AV", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 1, "g_clusterK6": 1, "e_clusterK7": 4, "g_clusterK7": 4, "e_clusterK8": 3, "g_clusterK8": 3, "e_clusterK9": 0, "g_clusterK9": 0, "e_clusterK10": 3, "g_clusterK10": 3 }, "geometry": { "type": "Point", "coordinates": [ -87.940383352951031, 42.959473469635924 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 131, "Incident Number": 150150092, "Date": "01\/15\/2015", "Time": "04:38 PM", "Police District": 6.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 42.959279, -87.908953 ], "Address": "110 E LAYTON AV", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 1, "g_clusterK6": 1, "e_clusterK7": 4, "g_clusterK7": 4, "e_clusterK8": 3, "g_clusterK8": 3, "e_clusterK9": 2, "g_clusterK9": 2, "e_clusterK10": 3, "g_clusterK10": 3 }, "geometry": { "type": "Point", "coordinates": [ -87.908953416180964, 42.959279460470761 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 132, "Incident Number": 150130018, "Date": "01\/13\/2015", "Time": "07:46 AM", "Police District": 6.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 42.928811, -87.939705 ], "Address": "2000 W SALEM ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 1, "g_clusterK6": 1, "e_clusterK7": 4, "g_clusterK7": 4, "e_clusterK8": 3, "g_clusterK8": 3, "e_clusterK9": 0, "g_clusterK9": 0, "e_clusterK10": 3, "g_clusterK10": 3 }, "geometry": { "type": "Point", "coordinates": [ -87.939705477287248, 42.928810769773278 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 133, "Incident Number": 150110045, "Date": "01\/11\/2015", "Time": "12:16 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.001991, -87.937066 ], "Address": "2342 S 19TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.937065919066498, 43.00199138773155 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 134, "Incident Number": 150090048, "Date": "01\/09\/2015", "Time": "01:16 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.003485, -87.934479 ], "Address": "2255 S 17TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.934479048184912, 43.003485282820691 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 135, "Incident Number": 150020064, "Date": "01\/02\/2015", "Time": "12:11 PM", "Police District": 6.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 42.970276, -87.948345 ], "Address": "4100 S 27TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 1, "g_clusterK6": 1, "e_clusterK7": 4, "g_clusterK7": 4, "e_clusterK8": 3, "g_clusterK8": 3, "e_clusterK9": 0, "g_clusterK9": 0, "e_clusterK10": 3, "g_clusterK10": 3 }, "geometry": { "type": "Point", "coordinates": [ -87.948345459462075, 42.970275555369625 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 136, "Incident Number": 150290099, "Date": "01\/29\/2015", "Time": "03:43 PM", "Police District": 6.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 42.993595, -87.925374 ], "Address": "1005 W MONTANA ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 2, "g_clusterK9": 2, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.925374, 42.993595477927236 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 137, "Incident Number": 150290165, "Date": "01\/29\/2015", "Time": "10:57 PM", "Police District": 6.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 42.987266, -87.926312 ], "Address": "3140 S 11TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 1, "g_clusterK6": 1, "e_clusterK7": 4, "g_clusterK7": 4, "e_clusterK8": 3, "g_clusterK8": 3, "e_clusterK9": 2, "g_clusterK9": 2, "e_clusterK10": 3, "g_clusterK10": 3 }, "geometry": { "type": "Point", "coordinates": [ -87.926312495672164, 42.987265742714527 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 138, "Incident Number": 150230041, "Date": "01\/23\/2015", "Time": "10:50 AM", "Police District": 6.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 42.991074, -87.922568 ], "Address": "2946 S 9TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 1, "e_clusterK7": 4, "g_clusterK7": 4, "e_clusterK8": 3, "g_clusterK8": 3, "e_clusterK9": 2, "g_clusterK9": 2, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.922567996166578, 42.991073664344043 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 139, "Incident Number": 150170035, "Date": "01\/17\/2015", "Time": "08:31 AM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.002105, -87.916988 ], "Address": "2323 S 5TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 2, "g_clusterK9": 2, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.916987569824997, 43.00210507660568 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 140, "Incident Number": 150160103, "Date": "01\/16\/2015", "Time": "05:11 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.007091, -87.907624 ], "Address": "2023 S KINNICKINNIC AV", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 2, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.907623890962853, 43.007091246436772 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 141, "Incident Number": 150140022, "Date": "01\/14\/2015", "Time": "05:43 AM", "Police District": 6.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 42.982757, -87.921546 ], "Address": "3402 S 8TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 1, "g_clusterK6": 1, "e_clusterK7": 4, "g_clusterK7": 4, "e_clusterK8": 3, "g_clusterK8": 3, "e_clusterK9": 2, "g_clusterK9": 2, "e_clusterK10": 3, "g_clusterK10": 3 }, "geometry": { "type": "Point", "coordinates": [ -87.921545937388359, 42.9827574970858 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 142, "Incident Number": 150120013, "Date": "01\/12\/2015", "Time": "02:42 AM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 42.994881, -87.928688 ], "Address": "2727 S 13TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 2, "g_clusterK9": 2, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.928688085405568, 42.994880863725541 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 143, "Incident Number": 150080013, "Date": "01\/08\/2015", "Time": "07:18 AM", "Police District": 6.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 42.992973, -87.882246 ], "Address": "2869 S SUPERIOR ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 2, "g_clusterK9": 2, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.882245815309474, 42.992972551186021 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 144, "Incident Number": 150050091, "Date": "01\/05\/2015", "Time": "04:31 PM", "Police District": 6.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.002415, -87.904788 ], "Address": "2317 S HOWELL AV", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 2, "g_clusterK9": 2, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.904788069824988, 43.002414586733238 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 145, "Incident Number": 150030099, "Date": "01\/03\/2015", "Time": "07:04 PM", "Police District": 6.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 42.986357, -87.925124 ], "Address": "3202 S 10TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 1, "g_clusterK6": 1, "e_clusterK7": 4, "g_clusterK7": 4, "e_clusterK8": 3, "g_clusterK8": 3, "e_clusterK9": 2, "g_clusterK9": 2, "e_clusterK10": 3, "g_clusterK10": 3 }, "geometry": { "type": "Point", "coordinates": [ -87.925124411853133, 42.98635724562871 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 146, "Incident Number": 150290153, "Date": "01\/29\/2015", "Time": "09:44 PM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.067686, -87.925923 ], "Address": "1100 W CENTER ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.925923, 43.067686493219334 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 147, "Incident Number": 150290166, "Date": "01\/29\/2015", "Time": "11:38 PM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.060076, -87.926856 ], "Address": "2242 N 12TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.926855875209412, 43.060076413266785 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 148, "Incident Number": 150280059, "Date": "01\/28\/2015", "Time": "12:49 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.068475, -87.964550 ], "Address": "2723 N 41ST ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.964550080933492, 43.06847500582839 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 149, "Incident Number": 150280079, "Date": "01\/28\/2015", "Time": "03:08 PM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.061431, -87.947386 ], "Address": "2342 N 27TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 1, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 7, "g_clusterK10": 7 }, "geometry": { "type": "Point", "coordinates": [ -87.947385852441883, 43.06143072509493 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 150, "Incident Number": 150280095, "Date": "01\/28\/2015", "Time": "05:44 PM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.067924, -87.972701 ], "Address": "4711 W CENTER ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.972700667638065, 43.0679244884588 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 151, "Incident Number": 150270012, "Date": "01\/27\/2015", "Time": "02:29 AM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.060548, -87.956673 ], "Address": "3421 W NORTH AV", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 1, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 7, "g_clusterK10": 7 }, "geometry": { "type": "Point", "coordinates": [ -87.956672760139639, 43.060547790558545 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 152, "Incident Number": 150270070, "Date": "01\/27\/2015", "Time": "11:39 AM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.065144, -87.927641 ], "Address": "2551 N 13TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.927640624790584, 43.065144167638067 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 153, "Incident Number": 150260044, "Date": "01\/26\/2015", "Time": "01:13 AM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.060561, -87.952793 ], "Address": "2351 N 31ST ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 1, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 7, "g_clusterK10": 7 }, "geometry": { "type": "Point", "coordinates": [ -87.952792836361866, 43.060561161669341 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 154, "Incident Number": 150250126, "Date": "01\/25\/2015", "Time": "09:26 PM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.060546, -87.946492 ], "Address": "2601 W NORTH AV", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 1, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 7, "g_clusterK10": 7 }, "geometry": { "type": "Point", "coordinates": [ -87.946491860811349, 43.060546499567309 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 155, "Incident Number": 150240087, "Date": "01\/24\/2015", "Time": "01:14 PM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.060076, -87.926856 ], "Address": "2242 N 12TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.926855875209412, 43.060076413266785 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 156, "Incident Number": 150230019, "Date": "01\/23\/2015", "Time": "03:15 AM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.058700, -87.959904 ], "Address": "2154 N 37TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 1, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 7, "g_clusterK10": 7 }, "geometry": { "type": "Point", "coordinates": [ -87.959904393531275, 43.058699580904857 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 157, "Incident Number": 150220007, "Date": "01\/22\/2015", "Time": "01:56 AM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.060704, -87.963513 ], "Address": "4000 W NORTH AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 7, "g_clusterK10": 7 }, "geometry": { "type": "Point", "coordinates": [ -87.963513209441473, 43.060704209441482 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 158, "Incident Number": 150220109, "Date": "01\/22\/2015", "Time": "05:04 PM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.069735, -87.937511 ], "Address": "2801 N 20TH ST", "e_clusterK2": 0, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 4, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 7, "g_clusterK10": 7 }, "geometry": { "type": "Point", "coordinates": [ -87.937510555398276, 43.069734618096845 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 159, "Incident Number": 150220118, "Date": "01\/22\/2015", "Time": "11:14 PM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.066782, -87.976218 ], "Address": "2629 N 50TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.976218124790577, 43.066782335276116 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 160, "Incident Number": 150210056, "Date": "01\/21\/2015", "Time": "10:20 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.067936, -87.956603 ], "Address": "3414 W CENTER ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 7, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.956603497085808, 43.067935507646062 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 161, "Incident Number": 150210075, "Date": "01\/21\/2015", "Time": "11:32 AM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.056476, -87.958584 ], "Address": "3530 W BROWN ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 1, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 7, "g_clusterK10": 7 }, "geometry": { "type": "Point", "coordinates": [ -87.958583580904843, 43.056476474897458 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 162, "Incident Number": 150190115, "Date": "01\/19\/2015", "Time": "05:16 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.069068, -87.955171 ], "Address": "2757 N 33RD ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 7, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.955170609786947, 43.069068 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 163, "Incident Number": 150180043, "Date": "01\/18\/2015", "Time": "07:22 AM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.056370, -87.949593 ], "Address": "2825 W BROWN ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 1, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 0, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 7, "g_clusterK10": 7 }, "geometry": { "type": "Point", "coordinates": [ -87.949593167638056, 43.056369525102532 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 164, "Incident Number": 150180058, "Date": "01\/18\/2015", "Time": "11:09 AM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.060238, -87.936780 ], "Address": "1937 W MONROE ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 8, "g_clusterK9": 1, "e_clusterK10": 7, "g_clusterK10": 7 }, "geometry": { "type": "Point", "coordinates": [ -87.93678038248008, 43.060238027180013 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 165, "Incident Number": 150180076, "Date": "01\/18\/2015", "Time": "02:07 PM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.062967, -87.968871 ], "Address": "2425 N 44TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.968871077038358, 43.062966586733239 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 166, "Incident Number": 150170062, "Date": "01\/17\/2015", "Time": "01:11 PM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.061425, -87.971244 ], "Address": "2334 N 46TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.971244477350297, 43.061425155981311 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 167, "Incident Number": 150170106, "Date": "01\/17\/2015", "Time": "08:07 PM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.052454, -87.947613 ], "Address": "1646 N 27TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 1, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 0, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 7, "g_clusterK10": 7 }, "geometry": { "type": "Point", "coordinates": [ -87.947613400744643, 43.052453884817368 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 168, "Incident Number": 150160056, "Date": "01\/16\/2015", "Time": "12:19 PM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.065785, -87.923191 ], "Address": "912 W CLARKE ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.923191332361938, 43.065785460470757 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 169, "Incident Number": 150140009, "Date": "01\/14\/2015", "Time": "01:23 AM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.062011, -87.975606 ], "Address": "4950 W LISBON AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.975605818269841, 43.062011033889078 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 170, "Incident Number": 150130110, "Date": "01\/13\/2015", "Time": "06:53 PM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.067940, -87.975233 ], "Address": "4915 W CENTER ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.975233276992313, 43.067940477350319 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 171, "Incident Number": 150120101, "Date": "01\/12\/2015", "Time": "05:13 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.069213, -87.958611 ], "Address": "2765 N 36TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 7, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.958611077038356, 43.06921283819031 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 172, "Incident Number": 150110089, "Date": "01\/11\/2015", "Time": "07:05 PM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.067115, -87.956279 ], "Address": "2649 N 34TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 7, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.956279080933498, 43.067115 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 173, "Incident Number": 150080079, "Date": "01\/08\/2015", "Time": "09:16 PM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.067602, -87.922944 ], "Address": "905 W CENTER ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.922944167638065, 43.067601546742623 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 174, "Incident Number": 150060120, "Date": "01\/06\/2015", "Time": "08:25 PM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.067654, -87.928864 ], "Address": "1341 W CENTER ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.928863868024706, 43.0676544884588 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 175, "Incident Number": 150050070, "Date": "01\/05\/2015", "Time": "03:19 PM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.053473, -87.946670 ], "Address": "2632 W LISBON AV", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 1, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 0, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 7, "g_clusterK10": 7 }, "geometry": { "type": "Point", "coordinates": [ -87.946669665649253, 43.053473488501787 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 176, "Incident Number": 150040031, "Date": "01\/04\/2015", "Time": "06:09 AM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.065013, -87.960985 ], "Address": "2542 N 38TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 7, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.960984858284348, 43.065012767402919 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 177, "Incident Number": 150040038, "Date": "01\/04\/2015", "Time": "09:23 AM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.067205, -87.964492 ], "Address": "2650 N 41ST ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.964492360782685, 43.067205 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 178, "Incident Number": 150040072, "Date": "01\/04\/2015", "Time": "03:02 PM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.059564, -87.962266 ], "Address": "2212 N 39TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 1, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 7, "g_clusterK10": 7 }, "geometry": { "type": "Point", "coordinates": [ -87.962265919066496, 43.059564 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 179, "Incident Number": 150040087, "Date": "01\/04\/2015", "Time": "06:59 PM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.058673, -87.925562 ], "Address": "2139 N 11TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.925561562611634, 43.058673251457094 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 180, "Incident Number": 150030052, "Date": "01\/03\/2015", "Time": "12:15 PM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.066495, -87.958660 ], "Address": "2617 N 36TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 7, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.958659580933499, 43.066494586733228 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 181, "Incident Number": 150020052, "Date": "01\/02\/2015", "Time": "11:28 AM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.062011, -87.975606 ], "Address": "4950 W LISBON AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.975605818269841, 43.062011033889078 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 182, "Incident Number": 150020157, "Date": "01\/02\/2015", "Time": "09:02 PM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.060561, -87.948161 ], "Address": "2727 W NORTH AV", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 1, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 7, "g_clusterK10": 7 }, "geometry": { "type": "Point", "coordinates": [ -87.948161025535228, 43.060560520630474 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 183, "Incident Number": 150310127, "Date": "01\/31\/2015", "Time": "10:30 PM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.115361, -87.987376 ], "Address": "5370 N 61ST ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 3, "g_clusterK5": 3, "e_clusterK6": 3, "g_clusterK6": 5, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 6, "g_clusterK8": 6, "e_clusterK9": 4, "g_clusterK9": 4, "e_clusterK10": 2, "g_clusterK10": 2 }, "geometry": { "type": "Point", "coordinates": [ -87.987376375209408, 43.115361212880138 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 184, "Incident Number": 150300038, "Date": "01\/30\/2015", "Time": "08:09 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.103640, -87.990323 ], "Address": "6225 W SPENCER PL", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 0, "e_clusterK5": 3, "g_clusterK5": 3, "e_clusterK6": 3, "g_clusterK6": 5, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 6, "g_clusterK8": 6, "e_clusterK9": 4, "g_clusterK9": 6, "e_clusterK10": 2, "g_clusterK10": 2 }, "geometry": { "type": "Point", "coordinates": [ -87.990323111316158, 43.103640322494194 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 185, "Incident Number": 150290053, "Date": "01\/29\/2015", "Time": "10:04 AM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.121826, -88.005875 ], "Address": "5712 N 76TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 3, "g_clusterK5": 0, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 6, "g_clusterK8": 6, "e_clusterK9": 4, "g_clusterK9": 4, "e_clusterK10": 0, "g_clusterK10": 2 }, "geometry": { "type": "Point", "coordinates": [ -88.005874816925612, 43.12182558090484 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 186, "Incident Number": 150290055, "Date": "01\/29\/2015", "Time": "10:20 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.103668, -87.988627 ], "Address": "6131 W LINCOLN CREEK DR", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 0, "e_clusterK5": 3, "g_clusterK5": 3, "e_clusterK6": 3, "g_clusterK6": 5, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 6, "g_clusterK8": 6, "e_clusterK9": 4, "g_clusterK9": 4, "e_clusterK10": 2, "g_clusterK10": 2 }, "geometry": { "type": "Point", "coordinates": [ -87.98862670027107, 43.103668014138279 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 187, "Incident Number": 150290108, "Date": "01\/29\/2015", "Time": "05:24 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.108480, -87.990001 ], "Address": "5001 N 63RD ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 0, "e_clusterK5": 3, "g_clusterK5": 3, "e_clusterK6": 3, "g_clusterK6": 5, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 6, "g_clusterK8": 6, "e_clusterK9": 4, "g_clusterK9": 4, "e_clusterK10": 2, "g_clusterK10": 2 }, "geometry": { "type": "Point", "coordinates": [ -87.990001106468725, 43.108479586733239 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 188, "Incident Number": 150290114, "Date": "01\/29\/2015", "Time": "05:43 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.090042, -87.999791 ], "Address": "7000 W CAPITOL DR", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 0, "e_clusterK5": 3, "g_clusterK5": 3, "e_clusterK6": 3, "g_clusterK6": 5, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 6, "g_clusterK8": 6, "e_clusterK9": 6, "g_clusterK9": 6, "e_clusterK10": 0, "g_clusterK10": 0 }, "geometry": { "type": "Point", "coordinates": [ -87.999790667638067, 43.090041518754568 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 189, "Incident Number": 150280030, "Date": "01\/28\/2015", "Time": "09:02 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.100126, -88.005700 ], "Address": "4545 N 75TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 0, "e_clusterK5": 3, "g_clusterK5": 3, "e_clusterK6": 3, "g_clusterK6": 5, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 6, "g_clusterK8": 6, "e_clusterK9": 6, "g_clusterK9": 6, "e_clusterK10": 0, "g_clusterK10": 0 }, "geometry": { "type": "Point", "coordinates": [ -88.005699657539182, 43.100126413266793 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 190, "Incident Number": 150260161, "Date": "01\/26\/2015", "Time": "12:20 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.097235, -88.001200 ], "Address": "7114 W CONGRESS ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 0, "e_clusterK5": 3, "g_clusterK5": 3, "e_clusterK6": 3, "g_clusterK6": 5, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 6, "g_clusterK8": 6, "e_clusterK9": 6, "g_clusterK9": 6, "e_clusterK10": 0, "g_clusterK10": 0 }, "geometry": { "type": "Point", "coordinates": [ -88.001199723007673, 43.097234529863066 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 191, "Incident Number": 150240002, "Date": "01\/24\/2015", "Time": "12:01 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.111290, -88.007872 ], "Address": "7701 W KATHRYN AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 3, "g_clusterK5": 3, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 6, "g_clusterK8": 6, "e_clusterK9": 6, "g_clusterK9": 6, "e_clusterK10": 0, "g_clusterK10": 0 }, "geometry": { "type": "Point", "coordinates": [ -88.0078725, 43.111289536211039 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 192, "Incident Number": 150220023, "Date": "01\/22\/2015", "Time": "10:08 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.105045, -88.002351 ], "Address": "7208 W HAMPTON AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 3, "g_clusterK5": 3, "e_clusterK6": 3, "g_clusterK6": 5, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 6, "g_clusterK8": 6, "e_clusterK9": 6, "g_clusterK9": 6, "e_clusterK10": 0, "g_clusterK10": 0 }, "geometry": { "type": "Point", "coordinates": [ -88.002350580904846, 43.105044518754546 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 193, "Incident Number": 150220094, "Date": "01\/22\/2015", "Time": "08:03 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.099220, -87.996269 ], "Address": "6750 W RUBY AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 0, "e_clusterK5": 3, "g_clusterK5": 3, "e_clusterK6": 3, "g_clusterK6": 5, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 6, "g_clusterK8": 6, "e_clusterK9": 6, "g_clusterK9": 6, "e_clusterK10": 0, "g_clusterK10": 0 }, "geometry": { "type": "Point", "coordinates": [ -87.996268796944833, 43.099219835289389 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 194, "Incident Number": 150200108, "Date": "01\/20\/2015", "Time": "05:39 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.096284, -87.990602 ], "Address": "4336 N 63RD ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 3, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 6, "g_clusterK8": 6, "e_clusterK9": 6, "g_clusterK9": 6, "e_clusterK10": 1, "g_clusterK10": 2 }, "geometry": { "type": "Point", "coordinates": [ -87.990602335247459, 43.09628366472387 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 195, "Incident Number": 150190031, "Date": "01\/19\/2015", "Time": "07:48 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.105878, -88.001914 ], "Address": "4838 N 72ND ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 3, "g_clusterK5": 3, "e_clusterK6": 3, "g_clusterK6": 5, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 6, "g_clusterK8": 6, "e_clusterK9": 6, "g_clusterK9": 6, "e_clusterK10": 0, "g_clusterK10": 0 }, "geometry": { "type": "Point", "coordinates": [ -88.001914360782692, 43.105878167638053 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 196, "Incident Number": 150190043, "Date": "01\/19\/2015", "Time": "10:06 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.104865, -87.989210 ], "Address": "6212 W HAMPTON AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 0, "e_clusterK5": 3, "g_clusterK5": 3, "e_clusterK6": 3, "g_clusterK6": 5, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 6, "g_clusterK8": 6, "e_clusterK9": 4, "g_clusterK9": 4, "e_clusterK10": 2, "g_clusterK10": 2 }, "geometry": { "type": "Point", "coordinates": [ -87.989209826533553, 43.104865493219343 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 197, "Incident Number": 150180077, "Date": "01\/18\/2015", "Time": "01:45 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.111592, -87.997286 ], "Address": "5176 N 69TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 3, "g_clusterK5": 3, "e_clusterK6": 3, "g_clusterK6": 5, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 6, "g_clusterK8": 6, "e_clusterK9": 4, "g_clusterK9": 4, "e_clusterK10": 0, "g_clusterK10": 2 }, "geometry": { "type": "Point", "coordinates": [ -87.997286411853125, 43.111592161809682 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 198, "Incident Number": 150170017, "Date": "01\/17\/2015", "Time": "02:25 AM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.120395, -87.991111 ], "Address": "5639 N 64TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 3, "g_clusterK5": 3, "e_clusterK6": 3, "g_clusterK6": 5, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 6, "g_clusterK8": 6, "e_clusterK9": 4, "g_clusterK9": 4, "e_clusterK10": 2, "g_clusterK10": 2 }, "geometry": { "type": "Point", "coordinates": [ -87.991110657539181, 43.120395 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 199, "Incident Number": 150170123, "Date": "01\/17\/2015", "Time": "10:19 PM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.124796, -87.998405 ], "Address": "5876 N 70TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 3, "g_clusterK5": 0, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 6, "g_clusterK8": 6, "e_clusterK9": 4, "g_clusterK9": 4, "e_clusterK10": 2, "g_clusterK10": 2 }, "geometry": { "type": "Point", "coordinates": [ -87.998405335247469, 43.12479583236194 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 200, "Incident Number": 150130034, "Date": "01\/13\/2015", "Time": "09:59 AM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.132324, -88.013952 ], "Address": "8228 W BENDER AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 0, "g_clusterK5": 0, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 2, "g_clusterK7": 2, "e_clusterK8": 7, "g_clusterK8": 7, "e_clusterK9": 5, "g_clusterK9": 4, "e_clusterK10": 5, "g_clusterK10": 5 }, "geometry": { "type": "Point", "coordinates": [ -88.013952, 43.132323518754568 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 201, "Incident Number": 150090092, "Date": "01\/09\/2015", "Time": "08:03 PM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.117393, -87.991118 ], "Address": "5453 N 64TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 3, "g_clusterK5": 3, "e_clusterK6": 3, "g_clusterK6": 5, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 6, "g_clusterK8": 6, "e_clusterK9": 4, "g_clusterK9": 4, "e_clusterK10": 2, "g_clusterK10": 2 }, "geometry": { "type": "Point", "coordinates": [ -87.991117847301837, 43.11739276646481 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 202, "Incident Number": 150070083, "Date": "01\/07\/2015", "Time": "05:46 PM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.120585, -88.028348 ], "Address": "5649 N 93RD ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 0, "g_clusterK5": 0, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 2, "g_clusterK7": 1, "e_clusterK8": 7, "g_clusterK8": 7, "e_clusterK9": 5, "g_clusterK9": 6, "e_clusterK10": 0, "g_clusterK10": 0 }, "geometry": { "type": "Point", "coordinates": [ -88.02834815753917, 43.120584838190325 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 203, "Incident Number": 143420007, "Date": "01\/06\/2015", "Time": "03:53 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.095151, -87.988140 ], "Address": "4273 N 61ST ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 3, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 6, "g_clusterK8": 6, "e_clusterK9": 6, "g_clusterK9": 6, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.988139599255362, 43.095150754371275 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 204, "Incident Number": 150040036, "Date": "01\/04\/2015", "Time": "08:11 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.093466, -87.985053 ], "Address": "5825 W HOPE AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 3, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 6, "g_clusterK8": 6, "e_clusterK9": 6, "g_clusterK9": 6, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.985053251457089, 43.093465513994033 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 205, "Incident Number": 150030038, "Date": "01\/03\/2015", "Time": "09:13 AM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.116885, -88.015293 ], "Address": "5440 N 83RD ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 3, "g_clusterK5": 0, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 7, "g_clusterK8": 7, "e_clusterK9": 6, "g_clusterK9": 6, "e_clusterK10": 0, "g_clusterK10": 0 }, "geometry": { "type": "Point", "coordinates": [ -88.015292860782694, 43.116885 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 206, "Incident Number": 150030070, "Date": "01\/03\/2015", "Time": "02:29 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.090134, -87.984393 ], "Address": "5700 W CAPITOL DR", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 3, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 6, "g_clusterK8": 6, "e_clusterK9": 6, "g_clusterK9": 3, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.984392972630985, 43.090134401484285 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 207, "Incident Number": 150030074, "Date": "01\/03\/2015", "Time": "03:04 PM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.121520, -88.000049 ], "Address": "7139 W THURSTON AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 3, "g_clusterK5": 0, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 6, "g_clusterK8": 6, "e_clusterK9": 4, "g_clusterK9": 4, "e_clusterK10": 0, "g_clusterK10": 2 }, "geometry": { "type": "Point", "coordinates": [ -88.000049044116878, 43.121520168734584 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 208, "Incident Number": 150030077, "Date": "01\/03\/2015", "Time": "03:49 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.094048, -87.979842 ], "Address": "5323 W LEON TR", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 3, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 1, "g_clusterK7": 0, "e_clusterK8": 6, "g_clusterK8": 6, "e_clusterK9": 4, "g_clusterK9": 3, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.979842192221, 43.094048187604713 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 209, "Incident Number": 150030094, "Date": "01\/03\/2015", "Time": "05:53 PM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.120472, -88.022803 ], "Address": "8825 W THURSTON AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 0, "g_clusterK5": 0, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 2, "g_clusterK7": 1, "e_clusterK8": 7, "g_clusterK8": 7, "e_clusterK9": 5, "g_clusterK9": 6, "e_clusterK10": 0, "g_clusterK10": 0 }, "geometry": { "type": "Point", "coordinates": [ -88.022803164723868, 43.12047248124545 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 210, "Incident Number": 150300035, "Date": "01\/30\/2015", "Time": "07:24 AM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.068429, -87.904119 ], "Address": "2741 N BOOTH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.904118606468728, 43.068429335276136 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 211, "Incident Number": 150300050, "Date": "01\/30\/2015", "Time": "10:04 AM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.073832, -87.896372 ], "Address": "1238 E CHAMBERS ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.896372300803449, 43.073831662242924 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 212, "Incident Number": 150300081, "Date": "01\/30\/2015", "Time": "12:40 PM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.063515, -87.901682 ], "Address": "2469 N FRATNEY ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.901681639217301, 43.063514832361932 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 213, "Incident Number": 150290048, "Date": "01\/29\/2015", "Time": "07:54 AM", "Police District": 1.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.077665, -87.890932 ], "Address": "1514 E HARTFORD AV", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.890931974464777, 43.077664507646055 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 214, "Incident Number": 150290051, "Date": "01\/29\/2015", "Time": "09:39 AM", "Police District": 1.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.061453, -87.885573 ], "Address": "2400 N MURRAY AV", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.885572959028451, 43.061452826533554 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 215, "Incident Number": 150280154, "Date": "01\/28\/2015", "Time": "10:22 PM", "Police District": 1.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.048185, -87.904252 ], "Address": "600 E OGDEN AV", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.904251974464771, 43.048184529863072 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 216, "Incident Number": 150270039, "Date": "01\/27\/2015", "Time": "08:51 AM", "Police District": 1.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.053454, -87.896804 ], "Address": "1724 N FRANKLIN PL", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.896803881845855, 43.053453502914181 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 217, "Incident Number": 150260061, "Date": "01\/26\/2015", "Time": "12:08 PM", "Police District": 1.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.071026, -87.878893 ], "Address": "2506 E LOCUST ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.87889333236194, 43.071026489324204 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 218, "Incident Number": 150250093, "Date": "01\/25\/2015", "Time": "05:12 PM", "Police District": 1.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.064875, -87.878834 ], "Address": "2513 E WEBSTER PL", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.878834025535227, 43.064875499567322 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 219, "Incident Number": 150240070, "Date": "01\/24\/2015", "Time": "11:17 AM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.071523, -87.902739 ], "Address": "2918 N PIERCE ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.902739138566943, 43.071522743649687 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 220, "Incident Number": 150250082, "Date": "01\/24\/2015", "Time": "03:24 PM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.064064, -87.901605 ], "Address": "2500 N FRATNEY ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.901605357464476, 43.064064 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 221, "Incident Number": 150210069, "Date": "01\/21\/2015", "Time": "12:24 PM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.066009, -87.902889 ], "Address": "2617 N PIERCE ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.902888551503139, 43.066008754371296 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 222, "Incident Number": 150190026, "Date": "01\/19\/2015", "Time": "06:46 AM", "Police District": 1.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.060096, -87.886800 ], "Address": "1901 E NORTH AV", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.8868, 43.060095546742616 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 223, "Incident Number": 150180111, "Date": "01\/18\/2015", "Time": "06:50 PM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.060210, -87.898342 ], "Address": "1030 E NORTH AV", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.898342248542903, 43.060209504327837 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 224, "Incident Number": 150130128, "Date": "01\/13\/2015", "Time": "09:46 PM", "Police District": 1.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.058135, -87.885670 ], "Address": "2150 N PROSPECT AV", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.885670225604756, 43.05813511876066 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 225, "Incident Number": 150120126, "Date": "01\/12\/2015", "Time": "07:47 PM", "Police District": 1.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.071524, -87.887952 ], "Address": "2921 N OAKLAND AV", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.887951599255359, 43.07152402553524 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 226, "Incident Number": 150110073, "Date": "01\/11\/2015", "Time": "05:48 PM", "Police District": 1.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.054511, -87.900682 ], "Address": "908 E HAMILTON ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.900682320769178, 43.054511043085199 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 227, "Incident Number": 150090021, "Date": "01\/09\/2015", "Time": "07:03 AM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.068401, -87.901555 ], "Address": "2740 N FRATNEY ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.901554926279857, 43.06840141326677 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 228, "Incident Number": 150090028, "Date": "01\/09\/2015", "Time": "09:25 AM", "Police District": 1.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.053780, -87.895506 ], "Address": "1711 N PULASKI ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.895505545934554, 43.053779620030063 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 229, "Incident Number": 150070064, "Date": "01\/07\/2015", "Time": "02:20 PM", "Police District": 1.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.046131, -87.907263 ], "Address": "1228 N MILWAUKEE ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.907262651983572, 43.046131045859219 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 230, "Incident Number": 150030037, "Date": "01\/03\/2015", "Time": "08:32 AM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.070796, -87.899179 ], "Address": "2869 N WEIL ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.899178580933494, 43.070796167638065 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 231, "Incident Number": 150020017, "Date": "01\/02\/2015", "Time": "03:55 AM", "Police District": 1.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.049445, -87.897866 ], "Address": "1115 E LYON ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.897865584367281, 43.049445130157608 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 232, "Incident Number": 150270076, "Date": "01\/27\/2015", "Time": "01:24 PM", "Police District": 1.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.036101, -87.917502 ], "Address": "500 N 5TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 1, "g_clusterK9": 7, "e_clusterK10": 9, "g_clusterK10": 9 }, "geometry": { "type": "Point", "coordinates": [ -87.91750182493621, 43.036101444105341 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 233, "Incident Number": 150270084, "Date": "01\/27\/2015", "Time": "01:55 PM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.041686, -87.951033 ], "Address": "2900 W KILBOURN AV", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 3, "g_clusterK4": 1, "e_clusterK5": 1, "g_clusterK5": 4, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 8, "g_clusterK9": 7, "e_clusterK10": 7, "g_clusterK10": 7 }, "geometry": { "type": "Point", "coordinates": [ -87.951032832361932, 43.041686489324185 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 234, "Incident Number": 150260069, "Date": "01\/26\/2015", "Time": "01:18 PM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.036139, -87.953513 ], "Address": "3123 W CLYBOURN ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 1, "e_clusterK4": 3, "g_clusterK4": 1, "e_clusterK5": 1, "g_clusterK5": 4, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 7, "g_clusterK10": 7 }, "geometry": { "type": "Point", "coordinates": [ -87.9535125, 43.036139495672167 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 235, "Incident Number": 150240147, "Date": "01\/24\/2015", "Time": "07:59 PM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.041605, -87.934914 ], "Address": "1719 W KILBOURN AV", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 7, "g_clusterK10": 7 }, "geometry": { "type": "Point", "coordinates": [ -87.934914, 43.041604506780679 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 236, "Incident Number": 150200032, "Date": "01\/20\/2015", "Time": "09:42 AM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.049862, -87.956414 ], "Address": "1450 N 34TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 1, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 0, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 7, "g_clusterK10": 7 }, "geometry": { "type": "Point", "coordinates": [ -87.956414404639773, 43.049861748542895 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 237, "Incident Number": 150200076, "Date": "01\/20\/2015", "Time": "12:06 PM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.038804, -87.955501 ], "Address": "3300 W WISCONSIN AV", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 3, "g_clusterK4": 1, "e_clusterK5": 1, "g_clusterK5": 4, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 5, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 7, "g_clusterK10": 7 }, "geometry": { "type": "Point", "coordinates": [ -87.955501248542902, 43.038804497114469 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 238, "Incident Number": 150190166, "Date": "01\/19\/2015", "Time": "09:43 PM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.044297, -87.927205 ], "Address": "1201 W HIGHLAND AV", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 7 }, "geometry": { "type": "Point", "coordinates": [ -87.927205387333601, 43.04429692187832 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 239, "Incident Number": 150150020, "Date": "01\/15\/2015", "Time": "06:32 AM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.049492, -87.951223 ], "Address": "1436 N 30TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 1, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 0, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 7, "g_clusterK10": 7 }, "geometry": { "type": "Point", "coordinates": [ -87.951222919066495, 43.049492497085822 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 240, "Incident Number": 150150122, "Date": "01\/15\/2015", "Time": "08:13 PM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.040729, -87.939411 ], "Address": "819 N 21ST ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 7, "g_clusterK10": 7 }, "geometry": { "type": "Point", "coordinates": [ -87.939410964365891, 43.040728927837733 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 241, "Incident Number": 150140044, "Date": "01\/14\/2015", "Time": "10:08 AM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.046815, -87.957619 ], "Address": "1254 N 35TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 1, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 0, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 7, "g_clusterK10": 7 }, "geometry": { "type": "Point", "coordinates": [ -87.957619025948276, 43.046815295506718 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 242, "Incident Number": 150140060, "Date": "01\/14\/2015", "Time": "12:54 PM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.047218, -87.952824 ], "Address": "3115 W MC KINLEY BL", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 1, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 0, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 7, "g_clusterK10": 7 }, "geometry": { "type": "Point", "coordinates": [ -87.952824, 43.047217542847477 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 243, "Incident Number": 150130036, "Date": "01\/13\/2015", "Time": "10:07 AM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.043815, -87.942898 ], "Address": "1025 N 24TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 4, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 5, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 7, "g_clusterK10": 7 }, "geometry": { "type": "Point", "coordinates": [ -87.942898113682077, 43.04381508964741 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 244, "Incident Number": 150130038, "Date": "01\/13\/2015", "Time": "09:11 AM", "Police District": 1.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.044832, -87.902134 ], "Address": "1040 N CASS ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.902134101131281, 43.044832068555586 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 245, "Incident Number": 150060070, "Date": "01\/06\/2015", "Time": "04:36 PM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.038786, -87.938784 ], "Address": "2040 W WISCONSIN AV", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 3, "g_clusterK4": 1, "e_clusterK5": 1, "g_clusterK5": 2, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 7, "g_clusterK10": 7 }, "geometry": { "type": "Point", "coordinates": [ -87.938784, 43.038785519908387 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 246, "Incident Number": 150030086, "Date": "01\/03\/2015", "Time": "05:26 PM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.046496, -87.945235 ], "Address": "1226 N 25TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 4, "e_clusterK6": 0, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 7, "g_clusterK10": 7 }, "geometry": { "type": "Point", "coordinates": [ -87.94523545181508, 43.04649613627447 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 247, "Incident Number": 150010058, "Date": "01\/01\/2015", "Time": "08:35 AM", "Police District": 1.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.044464, -87.914400 ], "Address": "1110 N OLD WORLD THIRD ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.914400269366695, 43.044463590365083 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 248, "Incident Number": 150300089, "Date": "01\/30\/2015", "Time": "04:48 PM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.109613, -88.043361 ], "Address": "5057 N 105TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 0, "g_clusterK5": 0, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 2, "g_clusterK7": 1, "e_clusterK8": 7, "g_clusterK8": 7, "e_clusterK9": 6, "g_clusterK9": 6, "e_clusterK10": 0, "g_clusterK10": 0 }, "geometry": { "type": "Point", "coordinates": [ -88.043361153644028, 43.109613 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 249, "Incident Number": 150300130, "Date": "01\/30\/2015", "Time": "09:45 PM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.121785, -88.038400 ], "Address": "10111 W APPLETON AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 0, "g_clusterK5": 0, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 2, "g_clusterK7": 1, "e_clusterK8": 7, "g_clusterK8": 7, "e_clusterK9": 5, "g_clusterK9": 6, "e_clusterK10": 0, "g_clusterK10": 0 }, "geometry": { "type": "Point", "coordinates": [ -88.038399574701089, 43.121784502048818 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 251, "Incident Number": 150290057, "Date": "01\/29\/2015", "Time": "10:30 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.087224, -88.032942 ], "Address": "9700 W LISBON AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 3, "g_clusterK5": 3, "e_clusterK6": 3, "g_clusterK6": 5, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 7, "g_clusterK8": 7, "e_clusterK9": 6, "g_clusterK9": 6, "e_clusterK10": 0, "g_clusterK10": 0 }, "geometry": { "type": "Point", "coordinates": [ -88.032942058687837, 43.087224403571931 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 252, "Incident Number": 150270043, "Date": "01\/27\/2015", "Time": "09:07 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.091884, -88.017551 ], "Address": "4101 N 84TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 0, "e_clusterK5": 3, "g_clusterK5": 3, "e_clusterK6": 3, "g_clusterK6": 5, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 7, "g_clusterK8": 7, "e_clusterK9": 6, "g_clusterK9": 6, "e_clusterK10": 0, "g_clusterK10": 0 }, "geometry": { "type": "Point", "coordinates": [ -88.017551143112456, 43.091883838190313 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 253, "Incident Number": 150260033, "Date": "01\/26\/2015", "Time": "09:37 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.068736, -88.035148 ], "Address": "2751 N 98TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 0, "e_clusterK5": 3, "g_clusterK5": 4, "e_clusterK6": 3, "g_clusterK6": 0, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 7, "g_clusterK8": 7, "e_clusterK9": 6, "g_clusterK9": 6, "e_clusterK10": 0, "g_clusterK10": 0 }, "geometry": { "type": "Point", "coordinates": [ -88.035148092042007, 43.068735670552257 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 254, "Incident Number": 150260038, "Date": "01\/26\/2015", "Time": "09:36 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.072569, -88.025061 ], "Address": "2951 N 90TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 0, "e_clusterK5": 3, "g_clusterK5": 4, "e_clusterK6": 3, "g_clusterK6": 0, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 7, "g_clusterK8": 7, "e_clusterK9": 6, "g_clusterK9": 6, "e_clusterK10": 0, "g_clusterK10": 0 }, "geometry": { "type": "Point", "coordinates": [ -88.025060606468728, 43.072568748542921 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 255, "Incident Number": 150250032, "Date": "01\/25\/2015", "Time": "07:02 AM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.132438, -88.030642 ], "Address": "9510 W FOND DU LAC AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 0, "g_clusterK5": 0, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 2, "g_clusterK7": 2, "e_clusterK8": 7, "g_clusterK8": 7, "e_clusterK9": 5, "g_clusterK9": 5, "e_clusterK10": 5, "g_clusterK10": 5 }, "geometry": { "type": "Point", "coordinates": [ -88.030642183421094, 43.132437867360878 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 256, "Incident Number": 150230023, "Date": "01\/23\/2015", "Time": "06:36 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.091323, -88.012561 ], "Address": "7954 W FIEBRANTZ AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 0, "e_clusterK5": 3, "g_clusterK5": 3, "e_clusterK6": 3, "g_clusterK6": 5, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 7, "g_clusterK8": 6, "e_clusterK9": 6, "g_clusterK9": 6, "e_clusterK10": 0, "g_clusterK10": 0 }, "geometry": { "type": "Point", "coordinates": [ -88.012561449737618, 43.091322568699823 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 257, "Incident Number": 150230055, "Date": "01\/23\/2015", "Time": "01:20 PM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.114410, -88.055557 ], "Address": "5326 N LOVERS LANE RD", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 0, "g_clusterK5": 0, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 2, "g_clusterK7": 1, "e_clusterK8": 7, "g_clusterK8": 7, "e_clusterK9": 5, "g_clusterK9": 6, "e_clusterK10": 0, "g_clusterK10": 0 }, "geometry": { "type": "Point", "coordinates": [ -88.055557137736088, 43.114410196490084 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 258, "Incident Number": 150220039, "Date": "01\/22\/2015", "Time": "11:28 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.090889, -88.040685 ], "Address": "10173 W GRANTOSA DR", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 3, "g_clusterK5": 0, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 7, "g_clusterK8": 7, "e_clusterK9": 6, "g_clusterK9": 6, "e_clusterK10": 0, "g_clusterK10": 0 }, "geometry": { "type": "Point", "coordinates": [ -88.040684936955671, 43.090888780426127 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 259, "Incident Number": 150220077, "Date": "01\/22\/2015", "Time": "06:00 PM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.106527, -88.040879 ], "Address": "4877 N 103RD ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 0, "g_clusterK5": 0, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 2, "g_clusterK7": 1, "e_clusterK8": 7, "g_clusterK8": 7, "e_clusterK9": 6, "g_clusterK9": 6, "e_clusterK10": 0, "g_clusterK10": 0 }, "geometry": { "type": "Point", "coordinates": [ -88.040878624790579, 43.106527058283802 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 260, "Incident Number": 150210055, "Date": "01\/21\/2015", "Time": "09:56 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.081505, -88.029940 ], "Address": "3445 N 94TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 0, "e_clusterK5": 3, "g_clusterK5": 3, "e_clusterK6": 3, "g_clusterK6": 0, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 7, "g_clusterK8": 7, "e_clusterK9": 6, "g_clusterK9": 6, "e_clusterK10": 0, "g_clusterK10": 0 }, "geometry": { "type": "Point", "coordinates": [ -88.029939580933501, 43.081505413266768 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 261, "Incident Number": 150210128, "Date": "01\/21\/2015", "Time": "08:08 PM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.126287, -88.025800 ], "Address": "6001 N 91ST ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 0, "g_clusterK5": 0, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 2, "g_clusterK7": 1, "e_clusterK8": 7, "g_clusterK8": 7, "e_clusterK9": 5, "g_clusterK9": 6, "e_clusterK10": 0, "g_clusterK10": 0 }, "geometry": { "type": "Point", "coordinates": [ -88.025800107188928, 43.126287191788315 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 262, "Incident Number": 150190038, "Date": "01\/19\/2015", "Time": "09:51 AM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.127405, -88.051221 ], "Address": "11125 W LANGLADE ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 0, "g_clusterK5": 0, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 2, "g_clusterK7": 2, "e_clusterK8": 7, "g_clusterK8": 7, "e_clusterK9": 5, "g_clusterK9": 5, "e_clusterK10": 0, "g_clusterK10": 0 }, "geometry": { "type": "Point", "coordinates": [ -88.051221465866433, 43.127404513994037 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 263, "Incident Number": 150190156, "Date": "01\/19\/2015", "Time": "08:44 PM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.139021, -88.039231 ], "Address": "10213 W FOND DU LAC AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 0, "g_clusterK5": 0, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 2, "g_clusterK7": 2, "e_clusterK8": 7, "g_clusterK8": 7, "e_clusterK9": 5, "g_clusterK9": 5, "e_clusterK10": 5, "g_clusterK10": 5 }, "geometry": { "type": "Point", "coordinates": [ -88.039230964686467, 43.139020871577358 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 264, "Incident Number": 150180012, "Date": "01\/18\/2015", "Time": "01:46 AM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.112889, -88.055571 ], "Address": "5238 N LOVERS LANE RD", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 0, "g_clusterK5": 0, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 2, "g_clusterK7": 1, "e_clusterK8": 7, "g_clusterK8": 7, "e_clusterK9": 5, "g_clusterK9": 6, "e_clusterK10": 0, "g_clusterK10": 0 }, "geometry": { "type": "Point", "coordinates": [ -88.055570569765763, 43.112888559560581 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 265, "Incident Number": 150160045, "Date": "01\/16\/2015", "Time": "10:49 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.080957, -88.007458 ], "Address": "3415 N 76TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 0, "e_clusterK5": 3, "g_clusterK5": 4, "e_clusterK6": 3, "g_clusterK6": 0, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 6, "g_clusterK8": 6, "e_clusterK9": 6, "g_clusterK9": 6, "e_clusterK10": 0, "g_clusterK10": 0 }, "geometry": { "type": "Point", "coordinates": [ -88.007457580933504, 43.080957251457107 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 266, "Incident Number": 150130017, "Date": "01\/13\/2015", "Time": "07:06 AM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.137263, -88.039361 ], "Address": "6594 N BOURBON ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 0, "g_clusterK5": 0, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 2, "g_clusterK7": 2, "e_clusterK8": 7, "g_clusterK8": 7, "e_clusterK9": 5, "g_clusterK9": 5, "e_clusterK10": 5, "g_clusterK10": 5 }, "geometry": { "type": "Point", "coordinates": [ -88.039361060621076, 43.137263381037798 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 267, "Incident Number": 150070062, "Date": "01\/07\/2015", "Time": "02:53 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.104864, -88.019643 ], "Address": "8537 W HAMPTON AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 3, "g_clusterK5": 0, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 7, "g_clusterK8": 7, "e_clusterK9": 6, "g_clusterK9": 6, "e_clusterK10": 0, "g_clusterK10": 0 }, "geometry": { "type": "Point", "coordinates": [ -88.019642734167647, 43.104863734167644 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 268, "Incident Number": 150060017, "Date": "01\/06\/2015", "Time": "07:21 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.108390, -88.022240 ], "Address": "8805 W POTOMAC AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 3, "g_clusterK5": 0, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 7, "g_clusterK8": 7, "e_clusterK9": 6, "g_clusterK9": 6, "e_clusterK10": 0, "g_clusterK10": 0 }, "geometry": { "type": "Point", "coordinates": [ -88.022239746205628, 43.108390373564646 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 269, "Incident Number": 150060046, "Date": "01\/06\/2015", "Time": "02:00 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.078085, -88.025036 ], "Address": "3266 N 90TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 0, "e_clusterK5": 3, "g_clusterK5": 4, "e_clusterK6": 3, "g_clusterK6": 0, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 7, "g_clusterK8": 7, "e_clusterK9": 6, "g_clusterK9": 6, "e_clusterK10": 0, "g_clusterK10": 0 }, "geometry": { "type": "Point", "coordinates": [ -88.025036419066495, 43.07808519317328 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 270, "Incident Number": 150030017, "Date": "01\/03\/2015", "Time": "02:37 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.089837, -88.027863 ], "Address": "9200 W CAPITOL DR", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 3, "g_clusterK5": 3, "e_clusterK6": 3, "g_clusterK6": 5, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 7, "g_clusterK8": 7, "e_clusterK9": 6, "g_clusterK9": 6, "e_clusterK10": 0, "g_clusterK10": 0 }, "geometry": { "type": "Point", "coordinates": [ -88.027863246497944, 43.089837246497964 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 271, "Incident Number": 150020158, "Date": "01\/02\/2015", "Time": "09:54 PM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.136145, -88.042696 ], "Address": "6483 N 105TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 0, "g_clusterK5": 0, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 2, "g_clusterK7": 2, "e_clusterK8": 7, "g_clusterK8": 7, "e_clusterK9": 5, "g_clusterK9": 5, "e_clusterK10": 5, "g_clusterK10": 5 }, "geometry": { "type": "Point", "coordinates": [ -88.042695587598587, 43.136144884817355 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 272, "Incident Number": 150020130, "Date": "01\/01\/2015", "Time": "07:40 PM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.117352, -88.054176 ], "Address": "11400 W SILVER SPRING DR", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 0, "g_clusterK5": 0, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 2, "g_clusterK7": 1, "e_clusterK8": 7, "g_clusterK8": 7, "e_clusterK9": 5, "g_clusterK9": 6, "e_clusterK10": 0, "g_clusterK10": 0 }, "geometry": { "type": "Point", "coordinates": [ -88.054176231894473, 43.117352391078434 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 273, "Incident Number": 150310086, "Date": "01\/31\/2015", "Time": "05:04 PM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.048402, -87.920345 ], "Address": "711 W VLIET ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.920344756699109, 43.048401808891157 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 274, "Incident Number": 150300032, "Date": "01\/30\/2015", "Time": "07:00 AM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.071155, -87.907361 ], "Address": "306 E LOCUST ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.907361223007683, 43.071155474897459 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 275, "Incident Number": 150290029, "Date": "01\/29\/2015", "Time": "05:57 AM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.054594, -87.918416 ], "Address": "1840 N 6TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.918415886317916, 43.054594292804033 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 276, "Incident Number": 150290045, "Date": "01\/29\/2015", "Time": "08:49 AM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.059016, -87.908953 ], "Address": "221 E GARFIELD AV", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.9089535, 43.059016499567306 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 277, "Incident Number": 150280100, "Date": "01\/28\/2015", "Time": "05:34 PM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.074369, -87.923872 ], "Address": "3054 N 10TH ST", "e_clusterK2": 0, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.923872375209413, 43.074368832361927 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 278, "Incident Number": 150280109, "Date": "01\/28\/2015", "Time": "06:07 PM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.058980, -87.910534 ], "Address": "139 E GARFIELD AV", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.910534306221862, 43.058980030523216 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 279, "Incident Number": 150270038, "Date": "01\/27\/2015", "Time": "07:27 AM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.056811, -87.908349 ], "Address": "2019 N HUBBARD ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.908348606468721, 43.056810502914203 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 280, "Incident Number": 150250062, "Date": "01\/25\/2015", "Time": "01:15 PM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.084563, -87.942346 ], "Address": "2407 W NASH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 6, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.942345718010202, 43.084562812894951 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 281, "Incident Number": 150250110, "Date": "01\/25\/2015", "Time": "07:05 PM", "Police District": 1.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.052485, -87.915382 ], "Address": "325 W WALNUT ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.915381836661098, 43.052484556697273 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 282, "Incident Number": 150240007, "Date": "01\/24\/2015", "Time": "12:59 AM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.085916, -87.939523 ], "Address": "3760 N 22ND ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 6, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.939523353569328, 43.08591622009348 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 283, "Incident Number": 150240085, "Date": "01\/24\/2015", "Time": "09:54 AM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.088805, -87.929485 ], "Address": "3954 N 15TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 6, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.929484849674182, 43.088805052455427 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 284, "Incident Number": 150240168, "Date": "01\/24\/2015", "Time": "09:47 PM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.068321, -87.909578 ], "Address": "2745 N PALMER ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.90957795347974, 43.068320689827601 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 285, "Incident Number": 150230066, "Date": "01\/23\/2015", "Time": "02:18 PM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.055218, -87.918698 ], "Address": "1901 N 6TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.918697610363864, 43.055217670552253 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 286, "Incident Number": 150230131, "Date": "01\/23\/2015", "Time": "08:31 PM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.058811, -87.915558 ], "Address": "2180 N 4TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.915558056111138, 43.058810629766626 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 287, "Incident Number": 150210073, "Date": "01\/21\/2015", "Time": "12:52 PM", "Police District": 1.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.050658, -87.914867 ], "Address": "308 W COURT ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.914867233517612, 43.050657736930738 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 288, "Incident Number": 150190024, "Date": "01\/19\/2015", "Time": "05:35 AM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.056478, -87.909111 ], "Address": "216 E BROWN ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.909111, 43.056477533181287 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 289, "Incident Number": 150180001, "Date": "01\/18\/2015", "Time": "12:04 AM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.087410, -87.927151 ], "Address": "3837 N 13TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 4, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 6, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.927151099255354, 43.087410115182649 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 290, "Incident Number": 150180025, "Date": "01\/18\/2015", "Time": "03:19 AM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.072927, -87.908962 ], "Address": "215 E CHAMBERS ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.908961860811345, 43.07292653952927 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 291, "Incident Number": 150180061, "Date": "01\/18\/2015", "Time": "10:08 AM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.066026, -87.912580 ], "Address": "2611 N 2ND ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.912580077615274, 43.066026167638057 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 292, "Incident Number": 150170126, "Date": "01\/17\/2015", "Time": "10:32 PM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.081794, -87.937250 ], "Address": "3429 N 20TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 0, "g_clusterK7": 5, "e_clusterK8": 2, "g_clusterK8": 5, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 6, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.937250073720136, 43.081794115182646 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 293, "Incident Number": 150160046, "Date": "01\/16\/2015", "Time": "10:50 AM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.073676, -87.905212 ], "Address": "3032 N HOLTON ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.905212367996043, 43.073675664723879 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 294, "Incident Number": 150160059, "Date": "01\/16\/2015", "Time": "12:35 PM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.059206, -87.896862 ], "Address": "1100 E GARFIELD AV", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.896861664723872, 43.059205529286132 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 295, "Incident Number": 150130014, "Date": "01\/13\/2015", "Time": "07:21 AM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.055423, -87.912728 ], "Address": "1909 N 2ND ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.9127276031505, 43.055423360811346 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 296, "Incident Number": 150090067, "Date": "01\/09\/2015", "Time": "05:06 PM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.075927, -87.928710 ], "Address": "3143 N 14TH ST", "e_clusterK2": 0, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 6, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.928710132003943, 43.075926838190327 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 297, "Incident Number": 150090096, "Date": "01\/09\/2015", "Time": "07:38 PM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.087752, -87.943496 ], "Address": "3874 N 24TH PL", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 6, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.943495879104546, 43.087752136274474 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 298, "Incident Number": 150070030, "Date": "01\/07\/2015", "Time": "02:18 AM", "Police District": 1.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.049869, -87.916830 ], "Address": "424 W CHERRY ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.916830113653418, 43.049869476051299 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 299, "Incident Number": 150070038, "Date": "01\/07\/2015", "Time": "11:13 AM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.078527, -87.932232 ], "Address": "3270 N 17TH ST", "e_clusterK2": 0, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 4, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 3, "g_clusterK9": 1, "e_clusterK10": 6, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.932232379104548, 43.078527220093491 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 300, "Incident Number": 150060034, "Date": "01\/06\/2015", "Time": "11:56 AM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.089222, -87.910055 ], "Address": "117 E CAPITOL DR", "e_clusterK2": 0, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.910054637803668, 43.089222491777036 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 301, "Incident Number": 150060073, "Date": "01\/06\/2015", "Time": "05:00 PM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.080221, -87.908454 ], "Address": "227 E TOWNSEND ST", "e_clusterK2": 0, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.908453528449414, 43.08022149567217 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 302, "Incident Number": 150050059, "Date": "01\/05\/2015", "Time": "02:26 PM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.084036, -87.913068 ], "Address": "3703 N 2ND LA", "e_clusterK2": 0, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.913067635322165, 43.084035670552254 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 303, "Incident Number": 150020040, "Date": "01\/02\/2015", "Time": "09:46 AM", "Police District": 1.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.047540, -87.915814 ], "Address": "1300 N 4TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 1, "g_clusterK4": 1, "e_clusterK5": 2, "g_clusterK5": 2, "e_clusterK6": 4, "g_clusterK6": 4, "e_clusterK7": 6, "g_clusterK7": 6, "e_clusterK8": 4, "g_clusterK8": 4, "e_clusterK9": 1, "g_clusterK9": 1, "e_clusterK10": 4, "g_clusterK10": 4 }, "geometry": { "type": "Point", "coordinates": [ -87.915813933493226, 43.047539748542903 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 304, "Incident Number": 150310022, "Date": "01\/31\/2015", "Time": "05:49 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.104581, -87.974950 ], "Address": "4925 W HAMPTON AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 3, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 6, "g_clusterK8": 6, "e_clusterK9": 4, "g_clusterK9": 3, "e_clusterK10": 2, "g_clusterK10": 2 }, "geometry": { "type": "Point", "coordinates": [ -87.9749505, 43.104580535634135 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 305, "Incident Number": 150310031, "Date": "01\/31\/2015", "Time": "08:56 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.099549, -87.980792 ], "Address": "5401 W LINCOLN CREEK DR", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 3, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 1, "g_clusterK7": 0, "e_clusterK8": 6, "g_clusterK8": 6, "e_clusterK9": 4, "g_clusterK9": 3, "e_clusterK10": 2, "g_clusterK10": 2 }, "geometry": { "type": "Point", "coordinates": [ -87.980791835276122, 43.099548539529245 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 306, "Incident Number": 150290017, "Date": "01\/29\/2015", "Time": "01:55 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.083792, -87.975842 ], "Address": "3612 N 50TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.975842419066495, 43.083791884817373 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 307, "Incident Number": 150290082, "Date": "01\/29\/2015", "Time": "01:31 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.100808, -87.960444 ], "Address": "3800 W GLENDALE AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 2, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.96044426046717, 43.100808260467176 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 308, "Incident Number": 150290126, "Date": "01\/29\/2015", "Time": "07:00 PM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.077263, -87.947196 ], "Address": "3210 N 27TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 6, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.94719630549298, 43.077262839107959 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 309, "Incident Number": 150270063, "Date": "01\/27\/2015", "Time": "12:26 PM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.077084, -87.951022 ], "Address": "3000 W AUER AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 6, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.951021827695371, 43.077083624219114 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 310, "Incident Number": 150270081, "Date": "01\/27\/2015", "Time": "01:41 PM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.079089, -87.944890 ], "Address": "2500 W CONCORDIA AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 3, "g_clusterK9": 8, "e_clusterK10": 6, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.944890080904841, 43.079089493219335 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 311, "Incident Number": 150260079, "Date": "01\/26\/2015", "Time": "03:42 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.083459, -87.959680 ], "Address": "3611 N 37TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.959680106468724, 43.083459335276132 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 312, "Incident Number": 150260151, "Date": "01\/26\/2015", "Time": "09:52 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.071354, -87.973572 ], "Address": "2874 N 48TH ST #LWR", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.973572386317912, 43.071353968636402 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 313, "Incident Number": 150260160, "Date": "01\/26\/2015", "Time": "11:37 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.068961, -87.972420 ], "Address": "2745 N 47TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.972420124790574, 43.068960838190321 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 314, "Incident Number": 150240042, "Date": "01\/24\/2015", "Time": "05:28 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.073766, -87.962055 ], "Address": "3020 N 39TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.962055415171363, 43.073765664723879 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 315, "Incident Number": 150240121, "Date": "01\/24\/2015", "Time": "05:02 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.086853, -87.960819 ], "Address": "3839 N 38TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 5, "g_clusterK7": 0, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.960819124790575, 43.086852754371279 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 316, "Incident Number": 150230031, "Date": "01\/23\/2015", "Time": "08:42 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.079697, -87.975959 ], "Address": "3327 N 50TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.975959095360224, 43.079697335276137 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 317, "Incident Number": 150230032, "Date": "01\/23\/2015", "Time": "08:42 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.079697, -87.975959 ], "Address": "3327 N 50TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.975959095360224, 43.079697335276137 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 318, "Incident Number": 150210080, "Date": "01\/22\/2015", "Time": "11:50 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.072029, -87.968685 ], "Address": "2920 N 44TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.968685386317915, 43.072028968636403 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 319, "Incident Number": 150220051, "Date": "01\/22\/2015", "Time": "12:52 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.077223, -87.963186 ], "Address": "3210 N 40TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.963185889636136, 43.077222639188648 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 320, "Incident Number": 150230004, "Date": "01\/22\/2015", "Time": "12:48 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.082757, -87.964233 ], "Address": "3508 N 41ST ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.964232853569328, 43.082756580904856 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 321, "Incident Number": 150210062, "Date": "01\/21\/2015", "Time": "11:45 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.084548, -87.980909 ], "Address": "3701 N 54TH BL", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.980908617577228, 43.084547696087469 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 322, "Incident Number": 150210097, "Date": "01\/21\/2015", "Time": "04:04 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.073839, -87.969832 ], "Address": "3016 N 45TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.969832367996048, 43.073838555369605 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 323, "Incident Number": 150200088, "Date": "01\/20\/2015", "Time": "04:11 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.078249, -87.970946 ], "Address": "3256 N 46TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.970946419066493, 43.078248639188644 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 324, "Incident Number": 150200097, "Date": "01\/20\/2015", "Time": "04:41 PM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.066053, -87.967618 ], "Address": "2525 N SHERMAN BL", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.967618125367494, 43.06605286372556 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 325, "Incident Number": 150190048, "Date": "01\/19\/2015", "Time": "10:48 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.104623, -87.958962 ], "Address": "3635 W HAMPTON AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 2, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.958962419095158, 43.104622528420762 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 326, "Incident Number": 150190049, "Date": "01\/19\/2015", "Time": "10:52 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.104623, -87.958962 ], "Address": "3635 W HAMPTON AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 2, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.958962419095158, 43.104622528420762 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 327, "Incident Number": 150190124, "Date": "01\/19\/2015", "Time": "05:59 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.100074, -87.963939 ], "Address": "4551 N 41ST ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 2, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.963938599255357, 43.100073838190326 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 328, "Incident Number": 150180046, "Date": "01\/18\/2015", "Time": "08:25 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.096122, -87.965012 ], "Address": "4339 N 42ND ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 2, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.96501163200395, 43.096122167638072 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 329, "Incident Number": 150180138, "Date": "01\/18\/2015", "Time": "10:49 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.099022, -87.965575 ], "Address": "4224 W RUBY AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 2, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.965574854063036, 43.099022083921433 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 330, "Incident Number": 150150094, "Date": "01\/15\/2015", "Time": "04:34 PM", "Police District": 3.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.066053, -87.967618 ], "Address": "2525 N SHERMAN BL", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.967618125367494, 43.06605286372556 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 331, "Incident Number": 150140035, "Date": "01\/14\/2015", "Time": "10:03 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.089941, -87.966932 ], "Address": "4000 N SHERMAN BL", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 5, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.966931533996956, 43.089941217310624 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 332, "Incident Number": 150130033, "Date": "01\/13\/2015", "Time": "09:55 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.074477, -87.964373 ], "Address": "3050 N 41ST ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.964373411853131, 43.074477 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 333, "Incident Number": 150120025, "Date": "01\/12\/2015", "Time": "07:56 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.072784, -87.960883 ], "Address": "2956 N 38TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.96088344460172, 43.07278399417163 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 334, "Incident Number": 150120036, "Date": "01\/12\/2015", "Time": "09:52 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.073945, -87.958485 ], "Address": "3024 N 36TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.95848486078269, 43.073945413266784 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 335, "Incident Number": 150120050, "Date": "01\/12\/2015", "Time": "11:29 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.073252, -87.971032 ], "Address": "2978 N 46TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.971032437388359, 43.073252245628709 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 336, "Incident Number": 150110019, "Date": "01\/11\/2015", "Time": "06:46 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.102241, -87.977873 ], "Address": "4670 N 52ND ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 3, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 1, "g_clusterK7": 0, "e_clusterK8": 6, "g_clusterK8": 6, "e_clusterK9": 4, "g_clusterK9": 3, "e_clusterK10": 2, "g_clusterK10": 2 }, "geometry": { "type": "Point", "coordinates": [ -87.977873411853125, 43.102241245628704 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 337, "Incident Number": 150100042, "Date": "01\/10\/2015", "Time": "01:32 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.093856, -87.966871 ], "Address": "4222 N SHERMAN BL", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 1, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.966871395330074, 43.093856196673663 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 338, "Incident Number": 150080016, "Date": "01\/08\/2015", "Time": "09:38 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.093206, -87.957018 ], "Address": "4175 N 35TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 6, "g_clusterK10": 6 }, "geometry": { "type": "Point", "coordinates": [ -87.957018117577221, 43.09320645045878 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 339, "Incident Number": 150060041, "Date": "01\/06\/2015", "Time": "12:32 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.087519, -87.958411 ], "Address": "3871 N 36TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 0, "g_clusterK7": 0, "e_clusterK8": 2, "g_clusterK8": 2, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.958411106468716, 43.087518586733239 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 340, "Incident Number": 150030010, "Date": "01\/03\/2015", "Time": "01:47 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.088897, -87.970221 ], "Address": "4508 W MELVINA ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 5, "g_clusterK7": 0, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 3, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.970220580904837, 43.088897460470754 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 341, "Incident Number": 150030029, "Date": "01\/03\/2015", "Time": "05:07 AM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.084836, -87.958451 ], "Address": "3719 N 36TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 3, "g_clusterK9": 3, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.958450632003945, 43.084836167638059 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 342, "Incident Number": 150030078, "Date": "01\/03\/2015", "Time": "02:44 PM", "Police District": 7.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.088325, -87.976108 ], "Address": "5009 W MEDFORD AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 0, "g_clusterK4": 0, "e_clusterK5": 4, "g_clusterK5": 3, "e_clusterK6": 5, "g_clusterK6": 5, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 3, "e_clusterK10": 1, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.976108371371595, 43.088324972791348 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 343, "Incident Number": 150020029, "Date": "01\/02\/2015", "Time": "08:27 AM", "Police District": 5.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.071532, -87.941229 ], "Address": "2300 W LOCUST ST", "e_clusterK2": 0, "g_clusterK2": 1, "e_clusterK3": 1, "g_clusterK3": 1, "e_clusterK4": 0, "g_clusterK4": 1, "e_clusterK5": 4, "g_clusterK5": 4, "e_clusterK6": 5, "g_clusterK6": 0, "e_clusterK7": 5, "g_clusterK7": 5, "e_clusterK8": 5, "g_clusterK8": 5, "e_clusterK9": 8, "g_clusterK9": 8, "e_clusterK10": 7, "g_clusterK10": 1 }, "geometry": { "type": "Point", "coordinates": [ -87.941228630985421, 43.071531807212466 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 344, "Incident Number": 150290038, "Date": "01\/29\/2015", "Time": "08:13 AM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.024160, -87.943032 ], "Address": "2325 W PIERCE ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 8, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.943031832361939, 43.02416049567217 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 345, "Incident Number": 150290134, "Date": "01\/29\/2015", "Time": "07:46 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.006704, -87.947055 ], "Address": "2619 W BECHER ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 8, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.947054612268445, 43.006704477350311 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 346, "Incident Number": 150280129, "Date": "01\/28\/2015", "Time": "07:56 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.011152, -87.959091 ], "Address": "3603 W MAPLE ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 8, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.959091357897165, 43.011152488458805 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 347, "Incident Number": 150270028, "Date": "01\/27\/2015", "Time": "08:14 AM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.004214, -87.940935 ], "Address": "2224 S 22ND ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 8, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.940934922961631, 43.004213748542895 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 348, "Incident Number": 150270033, "Date": "01\/27\/2015", "Time": "08:30 AM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.006868, -87.952833 ], "Address": "2074 S 31ST ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 8, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.952832944601724, 43.006867826533551 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 349, "Incident Number": 150270037, "Date": "01\/27\/2015", "Time": "08:41 AM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.014545, -87.943593 ], "Address": "1566 S 24TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 8, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.943592951815077, 43.01454524562871 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 350, "Incident Number": 150270087, "Date": "01\/27\/2015", "Time": "02:19 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.015546, -87.943650 ], "Address": "1515 S 24TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 8, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.943649529863052, 43.015545754371288 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 351, "Incident Number": 150260028, "Date": "01\/26\/2015", "Time": "07:38 AM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.022506, -87.939498 ], "Address": "817 S 21ST ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 8, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.939498348263797, 43.022505920142471 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 352, "Incident Number": 150260117, "Date": "01\/26\/2015", "Time": "07:14 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.012437, -87.944743 ], "Address": "2439 W MITCHELL ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 8, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.944742586733213, 43.012437477350304 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 353, "Incident Number": 150250029, "Date": "01\/25\/2015", "Time": "05:38 AM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.026138, -87.947858 ], "Address": "555 S LAYTON BL", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 8, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.947858125944421, 43.026138 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 354, "Incident Number": 150240106, "Date": "01\/24\/2015", "Time": "03:14 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.023348, -87.952598 ], "Address": "715 S 31ST ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 8, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.95259758425172, 43.023348 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 355, "Incident Number": 150250001, "Date": "01\/24\/2015", "Time": "11:24 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.025112, -87.949023 ], "Address": "624 S 28TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 8, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.949022937388349, 43.025112 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 356, "Incident Number": 150230018, "Date": "01\/23\/2015", "Time": "01:32 AM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.006995, -87.941997 ], "Address": "2076 S MUSKEGO AV", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 8, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.941997188881331, 43.006995026983041 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 357, "Incident Number": 150230042, "Date": "01\/23\/2015", "Time": "10:57 AM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.021013, -87.939949 ], "Address": "2135 W MINERAL ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 8, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.939949264797718, 43.021013297419785 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 358, "Incident Number": 150200068, "Date": "01\/20\/2015", "Time": "01:40 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.023824, -87.952964 ], "Address": "3110 W PIERCE ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 8, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.95296433250617, 43.023824431617307 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 359, "Incident Number": 150200167, "Date": "01\/20\/2015", "Time": "11:08 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.018848, -87.939488 ], "Address": "1205 S 21ST ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 8, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.939488109786936, 43.018848 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 360, "Incident Number": 150180038, "Date": "01\/18\/2015", "Time": "05:35 AM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.003664, -87.950424 ], "Address": "2270 S 29TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 8, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.950423953196747, 43.003663566300929 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 361, "Incident Number": 150180047, "Date": "01\/18\/2015", "Time": "08:49 AM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.000623, -87.952936 ], "Address": "2424 S 31ST ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 8, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.952936466241795, 43.000623 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 362, "Incident Number": 150160140, "Date": "01\/16\/2015", "Time": "09:03 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.023467, -87.943609 ], "Address": "729 S 24TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 8, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.943609070401905, 43.02346694892956 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 363, "Incident Number": 150140012, "Date": "01\/14\/2015", "Time": "03:19 AM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 42.996168, -87.950524 ], "Address": "2670 S 29TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 1, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 8, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.95052390463978, 42.996167664723885 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 364, "Incident Number": 150140042, "Date": "01\/14\/2015", "Time": "10:44 AM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.014246, -87.942355 ], "Address": "2300 W LAPHAM ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 8, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.942354684122421, 43.014245609936459 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 365, "Incident Number": 150120149, "Date": "01\/12\/2015", "Time": "10:07 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.021793, -87.955396 ], "Address": "3300 W NATIONAL AV", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 8, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.955395511656761, 43.021793460470754 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 366, "Incident Number": 150080045, "Date": "01\/08\/2015", "Time": "04:18 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.014095, -87.949664 ], "Address": "2819 W LAPHAM ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 8, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.949663774078132, 43.014094535634136 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 367, "Incident Number": 150070015, "Date": "01\/07\/2015", "Time": "08:49 AM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.019053, -87.944260 ], "Address": "2416 W SCOTT ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 8, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.9442605, 43.019052504327838 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 368, "Incident Number": 150070047, "Date": "01\/07\/2015", "Time": "12:21 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.009064, -87.942264 ], "Address": "1954 S 23RD ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 2, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 8, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.942264415171365, 43.009064245628707 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 369, "Incident Number": 150060061, "Date": "01\/06\/2015", "Time": "03:09 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.022636, -87.941103 ], "Address": "2200 W NATIONAL AV", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 8, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.941103008742573, 43.022635500432685 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 370, "Incident Number": 150060067, "Date": "01\/06\/2015", "Time": "03:49 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.003556, -87.949226 ], "Address": "2260 S 28TH ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 8, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.949226411853132, 43.003556276992327 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 371, "Incident Number": 150050016, "Date": "01\/05\/2015", "Time": "03:10 AM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.012457, -87.945944 ], "Address": "2525 W MITCHELL ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 8, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.945943835276125, 43.012457488458807 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 372, "Incident Number": 150030051, "Date": "01\/03\/2015", "Time": "12:04 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.003174, -87.949791 ], "Address": "2814 W LINCOLN AV", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 8, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.949791419095163, 43.003173518754558 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 373, "Incident Number": 150020035, "Date": "01\/02\/2015", "Time": "09:04 AM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.023456, -87.952600 ], "Address": "711 S 31ST ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 8, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.952599617000317, 43.023456 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 374, "Incident Number": 150010151, "Date": "01\/01\/2015", "Time": "09:11 PM", "Police District": 2.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.017709, -87.953800 ], "Address": "3139 W MADISON ST", "e_clusterK2": 0, "g_clusterK2": 0, "e_clusterK3": 2, "g_clusterK3": 2, "e_clusterK4": 3, "g_clusterK4": 3, "e_clusterK5": 1, "g_clusterK5": 1, "e_clusterK6": 0, "g_clusterK6": 2, "e_clusterK7": 3, "g_clusterK7": 3, "e_clusterK8": 0, "g_clusterK8": 0, "e_clusterK9": 7, "g_clusterK9": 7, "e_clusterK10": 8, "g_clusterK10": 8 }, "geometry": { "type": "Point", "coordinates": [ -87.953800164723873, 43.017708532315893 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 375, "Incident Number": 150280127, "Date": "01\/28\/2015", "Time": "07:29 PM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.177660, -88.012287 ], "Address": "8247 W BROWN DEER RD", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 0, "g_clusterK5": 0, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 2, "g_clusterK7": 2, "e_clusterK8": 1, "g_clusterK8": 1, "e_clusterK9": 5, "g_clusterK9": 5, "e_clusterK10": 5, "g_clusterK10": 5 }, "geometry": { "type": "Point", "coordinates": [ -88.012286734444274, 43.177660061822003 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 376, "Incident Number": 150280138, "Date": "01\/28\/2015", "Time": "03:27 PM", "Police District": 4.0, "Offense 1": "THEFT FROM BUILDING", "Offense 2": "MOTOR VEHICLE THEFT", "Location": [ 43.122517, -87.984801 ], "Address": "5730 W CARMEN AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 3, "g_clusterK5": 3, "e_clusterK6": 3, "g_clusterK6": 5, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 6, "g_clusterK8": 6, "e_clusterK9": 4, "g_clusterK9": 4, "e_clusterK10": 2, "g_clusterK10": 2 }, "geometry": { "type": "Point", "coordinates": [ -87.9848012514571, 43.122516504327841 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 377, "Incident Number": 150270025, "Date": "01\/27\/2015", "Time": "07:23 AM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.157744, -88.039001 ], "Address": "10040 W FOUNTAIN AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 0, "g_clusterK5": 0, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 2, "g_clusterK7": 2, "e_clusterK8": 1, "g_clusterK8": 1, "e_clusterK9": 5, "g_clusterK9": 5, "e_clusterK10": 5, "g_clusterK10": 5 }, "geometry": { "type": "Point", "coordinates": [ -88.039001442902645, 43.157743515243141 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 378, "Incident Number": 150270027, "Date": "01\/27\/2015", "Time": "08:13 AM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.122459, -87.985152 ], "Address": "5801 W CARMEN AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 3, "g_clusterK5": 3, "e_clusterK6": 3, "g_clusterK6": 5, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 6, "g_clusterK8": 6, "e_clusterK9": 4, "g_clusterK9": 4, "e_clusterK10": 2, "g_clusterK10": 2 }, "geometry": { "type": "Point", "coordinates": [ -87.985151832361936, 43.122458536211035 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 379, "Incident Number": 150260024, "Date": "01\/26\/2015", "Time": "08:03 AM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.180776, -88.015690 ], "Address": "8973 N 85TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 0, "g_clusterK5": 0, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 2, "g_clusterK7": 2, "e_clusterK8": 1, "g_clusterK8": 1, "e_clusterK9": 5, "g_clusterK9": 5, "e_clusterK10": 5, "g_clusterK10": 5 }, "geometry": { "type": "Point", "coordinates": [ -88.015690149099342, 43.180776490510681 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 380, "Incident Number": 150230027, "Date": "01\/23\/2015", "Time": "07:43 AM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.169914, -88.032163 ], "Address": "9621 W DARNEL AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 0, "g_clusterK5": 0, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 2, "g_clusterK7": 2, "e_clusterK8": 1, "g_clusterK8": 1, "e_clusterK9": 5, "g_clusterK9": 5, "e_clusterK10": 5, "g_clusterK10": 5 }, "geometry": { "type": "Point", "coordinates": [ -88.0321635, 43.169914499567327 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 381, "Incident Number": 150220066, "Date": "01\/22\/2015", "Time": "02:48 PM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.177890, -88.024709 ], "Address": "9108 W BROWN DEER RD", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 0, "g_clusterK5": 0, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 2, "g_clusterK7": 2, "e_clusterK8": 1, "g_clusterK8": 1, "e_clusterK9": 5, "g_clusterK9": 5, "e_clusterK10": 5, "g_clusterK10": 5 }, "geometry": { "type": "Point", "coordinates": [ -88.02470948576881, 43.177889873876822 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 382, "Incident Number": 150180112, "Date": "01\/18\/2015", "Time": "06:19 PM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.184135, -88.014834 ], "Address": "8405 W NORTHRIDGE CT", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 0, "g_clusterK5": 0, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 2, "g_clusterK7": 2, "e_clusterK8": 1, "g_clusterK8": 1, "e_clusterK9": 5, "g_clusterK9": 5, "e_clusterK10": 5, "g_clusterK10": 5 }, "geometry": { "type": "Point", "coordinates": [ -88.014834186335293, 43.184135191759658 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 383, "Incident Number": 150170045, "Date": "01\/17\/2015", "Time": "09:35 AM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.135357, -88.015243 ], "Address": "8311 W BRENTWOOD AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 0, "g_clusterK5": 0, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 2, "g_clusterK7": 2, "e_clusterK8": 7, "g_clusterK8": 7, "e_clusterK9": 5, "g_clusterK9": 5, "e_clusterK10": 5, "g_clusterK10": 5 }, "geometry": { "type": "Point", "coordinates": [ -88.015242593946581, 43.135357485140588 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 384, "Incident Number": 150150150, "Date": "01\/15\/2015", "Time": "11:58 PM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.177600, -88.023951 ], "Address": "9025 W BROWN DEER RD", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 0, "g_clusterK5": 0, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 2, "g_clusterK7": 2, "e_clusterK8": 1, "g_clusterK8": 1, "e_clusterK9": 5, "g_clusterK9": 5, "e_clusterK10": 5, "g_clusterK10": 5 }, "geometry": { "type": "Point", "coordinates": [ -88.023950748542902, 43.177599546742613 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 385, "Incident Number": 150140117, "Date": "01\/14\/2015", "Time": "06:56 PM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.142238, -87.985563 ], "Address": "6840 N 60TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 3, "g_clusterK5": 0, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 1, "g_clusterK7": 2, "e_clusterK8": 6, "g_clusterK8": 6, "e_clusterK9": 4, "g_clusterK9": 4, "e_clusterK10": 2, "g_clusterK10": 2 }, "geometry": { "type": "Point", "coordinates": [ -87.985562875209411, 43.142237633360281 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 386, "Incident Number": 150100053, "Date": "01\/10\/2015", "Time": "03:31 PM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.132454, -87.986035 ], "Address": "6300 N 60TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 3, "g_clusterK5": 0, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 1, "g_clusterK7": 2, "e_clusterK8": 6, "g_clusterK8": 6, "e_clusterK9": 4, "g_clusterK9": 4, "e_clusterK10": 2, "g_clusterK10": 2 }, "geometry": { "type": "Point", "coordinates": [ -87.986035152852409, 43.132454343543877 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 387, "Incident Number": 150060122, "Date": "01\/06\/2015", "Time": "09:21 PM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.162867, -88.004861 ], "Address": "7965 N 76TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 0, "g_clusterK5": 0, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 2, "g_clusterK7": 2, "e_clusterK8": 1, "g_clusterK8": 1, "e_clusterK9": 5, "g_clusterK9": 5, "e_clusterK10": 5, "g_clusterK10": 5 }, "geometry": { "type": "Point", "coordinates": [ -88.004860581510414, 43.162866785734906 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 388, "Incident Number": 150040066, "Date": "01\/04\/2015", "Time": "03:01 PM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.137513, -87.979453 ], "Address": "6582 N 54TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 3, "g_clusterK5": 0, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 1, "g_clusterK7": 2, "e_clusterK8": 6, "g_clusterK8": 6, "e_clusterK9": 4, "g_clusterK9": 4, "e_clusterK10": 2, "g_clusterK10": 2 }, "geometry": { "type": "Point", "coordinates": [ -87.979453367996044, 43.137512884817369 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 389, "Incident Number": 150040095, "Date": "01\/04\/2015", "Time": "08:03 PM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.141739, -87.985659 ], "Address": "6815 N 60TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 3, "g_clusterK5": 0, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 1, "g_clusterK7": 2, "e_clusterK8": 6, "g_clusterK8": 6, "e_clusterK9": 4, "g_clusterK9": 4, "e_clusterK10": 2, "g_clusterK10": 2 }, "geometry": { "type": "Point", "coordinates": [ -87.985658603727416, 43.141739384961582 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 390, "Incident Number": 150020078, "Date": "01\/03\/2015", "Time": "02:22 AM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.148556, -88.002734 ], "Address": "7401 W GOOD HOPE RD", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 0, "g_clusterK5": 0, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 2, "g_clusterK7": 2, "e_clusterK8": 1, "g_clusterK8": 1, "e_clusterK9": 5, "g_clusterK9": 5, "e_clusterK10": 5, "g_clusterK10": 5 }, "geometry": { "type": "Point", "coordinates": [ -88.002733546771267, 43.148556471147486 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 391, "Incident Number": 150020038, "Date": "01\/02\/2015", "Time": "10:06 AM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.170205, -88.039882 ], "Address": "10313 W DEAN RD", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 0, "g_clusterK5": 0, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 2, "g_clusterK7": 2, "e_clusterK8": 1, "g_clusterK8": 1, "e_clusterK9": 5, "g_clusterK9": 5, "e_clusterK10": 5, "g_clusterK10": 5 }, "geometry": { "type": "Point", "coordinates": [ -88.03988163918865, 43.170204532315907 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 392, "Incident Number": 150020162, "Date": "01\/02\/2015", "Time": "10:07 PM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.148517, -87.998700 ], "Address": "7101 W GOOD HOPE RD", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 0, "g_clusterK5": 0, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 2, "g_clusterK7": 2, "e_clusterK8": 1, "g_clusterK8": 1, "e_clusterK9": 5, "g_clusterK9": 5, "e_clusterK10": 5, "g_clusterK10": 5 }, "geometry": { "type": "Point", "coordinates": [ -87.998700201974117, 43.148517472158048 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 393, "Incident Number": 150010071, "Date": "01\/01\/2015", "Time": "09:58 AM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.183985, -88.002775 ], "Address": "9084 N 75TH ST", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 0, "g_clusterK5": 0, "e_clusterK6": 3, "g_clusterK6": 3, "e_clusterK7": 2, "g_clusterK7": 2, "e_clusterK8": 1, "g_clusterK8": 1, "e_clusterK9": 5, "g_clusterK9": 5, "e_clusterK10": 5, "g_clusterK10": 5 }, "geometry": { "type": "Point", "coordinates": [ -88.002775153367239, 43.183985212188865 ] } },
{ "type": "Feature", "properties": { "Unnamed: 0": 394, "Incident Number": 150010082, "Date": "01\/01\/2015", "Time": "11:43 AM", "Police District": 4.0, "Offense 1": "MOTOR VEHICLE THEFT", "Location": [ 43.121203, -87.990763 ], "Address": "6337 W THURSTON AV", "e_clusterK2": 1, "g_clusterK2": 1, "e_clusterK3": 0, "g_clusterK3": 0, "e_clusterK4": 2, "g_clusterK4": 2, "e_clusterK5": 3, "g_clusterK5": 3, "e_clusterK6": 3, "g_clusterK6": 5, "e_clusterK7": 1, "g_clusterK7": 1, "e_clusterK8": 6, "g_clusterK8": 6, "e_clusterK9": 4, "g_clusterK9": 4, "e_clusterK10": 2, "g_clusterK10": 2 }, "geometry": { "type": "Point", "coordinates": [ -87.990762944630376, 43.121202539529257 ] } }
]
}
|
(function () {
'use strict';
angular
.module('virtualRepeatDeferredLoadingDemo', ['ngMaterial'])
.controller('AppCtrl', function ($timeout) {
// In this example, we set up our model using a class.
// Using a plain object works too. All that matters
// is that we implement getItemAtIndex and getLength.
var DynamicItems = function () {
/**
* @type {!Object<?Array>} Data pages, keyed by page number (0-index).
*/
this.loadedPages = {};
/** @type {number} Total number of items. */
this.numItems = 0;
/** @const {number} Number of items to fetch per request. */
this.PAGE_SIZE = 50;
this.fetchNumItems_();
};
// Required.
DynamicItems.prototype.getItemAtIndex = function (index) {
var pageNumber = Math.floor(index / this.PAGE_SIZE);
var page = this.loadedPages[pageNumber];
if (page) {
return page[index % this.PAGE_SIZE];
} else if (page !== null) {
this.fetchPage_(pageNumber);
}
};
// Required.
DynamicItems.prototype.getLength = function () {
return this.numItems;
};
DynamicItems.prototype.fetchPage_ = function (pageNumber) {
// Set the page to null so we know it is already being fetched.
this.loadedPages[pageNumber] = null;
// For demo purposes, we simulate loading more items with a timed
// promise. In real code, this function would likely contain an
// $http request.
$timeout(angular.noop, 300).then(angular.bind(this, function () {
this.loadedPages[pageNumber] = [];
var pageOffset = pageNumber * this.PAGE_SIZE;
for (var i = pageOffset; i < pageOffset + this.PAGE_SIZE; i++) {
this.loadedPages[pageNumber].push(i);
}
}));
};
DynamicItems.prototype.fetchNumItems_ = function () {
// For demo purposes, we simulate loading the item count with a timed
// promise. In real code, this function would likely contain an
// $http request.
$timeout(angular.noop, 300).then(angular.bind(this, function () {
this.numItems = 50000;
}));
};
this.dynamicItems = new DynamicItems();
});
})();
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.