code
stringlengths
2
1.05M
(function () { var tabfocus = (function () { 'use strict'; var global = tinymce.util.Tools.resolve('tinymce.PluginManager'); var global$1 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils'); var global$2 = tinymce.util.Tools.resolve('tinymce.EditorManager'); var global$3 = tinymce.util.Tools.resolve('tinymce.Env'); var global$4 = tinymce.util.Tools.resolve('tinymce.util.Delay'); var global$5 = tinymce.util.Tools.resolve('tinymce.util.Tools'); var global$6 = tinymce.util.Tools.resolve('tinymce.util.VK'); var getTabFocusElements = function (editor) { return editor.getParam('tabfocus_elements', ':prev,:next'); }; var getTabFocus = function (editor) { return editor.getParam('tab_focus', getTabFocusElements(editor)); }; var $_h0mnpk8jgqkx0rw = { getTabFocus: getTabFocus }; var DOM = global$1.DOM; var tabCancel = function (e) { if (e.keyCode === global$6.TAB && !e.ctrlKey && !e.altKey && !e.metaKey) { e.preventDefault(); } }; var setup = function (editor) { function tabHandler(e) { var x, el, v, i; if (e.keyCode !== global$6.TAB || e.ctrlKey || e.altKey || e.metaKey || e.isDefaultPrevented()) { return; } function find(direction) { el = DOM.select(':input:enabled,*[tabindex]:not(iframe)'); function canSelectRecursive(e) { return e.nodeName === 'BODY' || e.type !== 'hidden' && e.style.display !== 'none' && e.style.visibility !== 'hidden' && canSelectRecursive(e.parentNode); } function canSelect(el) { return /INPUT|TEXTAREA|BUTTON/.test(el.tagName) && global$2.get(e.id) && el.tabIndex !== -1 && canSelectRecursive(el); } global$5.each(el, function (e, i) { if (e.id === editor.id) { x = i; return false; } }); if (direction > 0) { for (i = x + 1; i < el.length; i++) { if (canSelect(el[i])) { return el[i]; } } } else { for (i = x - 1; i >= 0; i--) { if (canSelect(el[i])) { return el[i]; } } } return null; } v = global$5.explode($_h0mnpk8jgqkx0rw.getTabFocus(editor)); if (v.length === 1) { v[1] = v[0]; v[0] = ':prev'; } if (e.shiftKey) { if (v[0] === ':prev') { el = find(-1); } else { el = DOM.get(v[0]); } } else { if (v[1] === ':next') { el = find(1); } else { el = DOM.get(v[1]); } } if (el) { var focusEditor = global$2.get(el.id || el.name); if (el.id && focusEditor) { focusEditor.focus(); } else { global$4.setTimeout(function () { if (!global$3.webkit) { window.focus(); } el.focus(); }, 10); } e.preventDefault(); } } editor.on('init', function () { if (editor.inline) { DOM.setAttrib(editor.getBody(), 'tabIndex', null); } editor.on('keyup', tabCancel); if (global$3.gecko) { editor.on('keypress keydown', tabHandler); } else { editor.on('keydown', tabHandler); } }); }; var $_24hm9ck1jgqkx0rq = { setup: setup }; global.add('tabfocus', function (editor) { $_24hm9ck1jgqkx0rq.setup(editor); }); function Plugin () { } return Plugin; }()); })();
// https://github.com/openstreetmap/potlatch2/blob/master/net/systemeD/halcyon/connection/actions/DeleteNodeAction.as iD.actions.DeleteNode = function(nodeId) { var action = function(graph) { var node = graph.entity(nodeId); graph.parentWays(node) .forEach(function(parent) { parent = parent.removeNode(nodeId); graph = graph.replace(parent); if (parent.isDegenerate()) { graph = iD.actions.DeleteWay(parent.id)(graph); } }); graph.parentRelations(node) .forEach(function(parent) { parent = parent.removeMembersWithID(nodeId); graph = graph.replace(parent); if (parent.isDegenerate()) { graph = iD.actions.DeleteRelation(parent.id)(graph); } }); return graph.remove(node); }; action.disabled = function() { return false; }; return action; };
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const denodeify = require("denodeify"); const SilentError = require('silent-error'); const PortFinder = require('portfinder'); const getPort = denodeify(PortFinder.getPort); function checkPort(port, host, basePort = 49152) { PortFinder.basePort = basePort; return getPort({ port, host }) .then(foundPort => { // If the port isn't available and we weren't looking for any port, throw error. if (port !== foundPort && port !== 0) { throw new SilentError(`Port ${port} is already in use. Use '--port' to specify a different port.`); } // Otherwise, our found port is good. return foundPort; }); } exports.checkPort = checkPort; //# sourceMappingURL=/users/hans/sources/angular-cli/utilities/check-port.js.map
/** * $Id: editor_plugin_src.js 129 2006-10-23 09:45:17Z spocke $ * * @author Moxiecode * @copyright Copyright © 2004-2006, Moxiecode Systems AB, All rights reserved. */ /* Import plugin specific language pack */ if (!tinyMCE.settings['contextmenu_skip_plugin_css']) { tinyMCE.loadCSS(tinyMCE.baseURL + "/plugins/contextmenu/css/contextmenu.css"); } var TinyMCE_ContextMenuPlugin = { // Private fields _contextMenu : null, getInfo : function() { return { longname : 'Context menus', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://tinymce.moxiecode.com/tinymce/docs/plugin_contextmenu.html', version : tinyMCE.majorVersion + "." + tinyMCE.minorVersion }; }, initInstance : function(inst) { // Is not working on MSIE 5.0 or Opera no contextmenu event if (tinyMCE.isMSIE5_0 && tinyMCE.isOpera) return; TinyMCE_ContextMenuPlugin._contextMenu = new TinyMCE_ContextMenu({ commandhandler : "TinyMCE_ContextMenuPlugin._commandHandler", spacer_image : tinyMCE.baseURL + "/plugins/contextmenu/images/spacer.gif" }); // Add hide event handles tinyMCE.addEvent(inst.getDoc(), "click", TinyMCE_ContextMenuPlugin._hideContextMenu); tinyMCE.addEvent(inst.getDoc(), "keypress", TinyMCE_ContextMenuPlugin._hideContextMenu); tinyMCE.addEvent(inst.getDoc(), "keydown", TinyMCE_ContextMenuPlugin._hideContextMenu); tinyMCE.addEvent(document, "click", TinyMCE_ContextMenuPlugin._hideContextMenu); tinyMCE.addEvent(document, "keypress", TinyMCE_ContextMenuPlugin._hideContextMenu); tinyMCE.addEvent(document, "keydown", TinyMCE_ContextMenuPlugin._hideContextMenu); // Attach contextmenu event if (tinyMCE.isGecko) { tinyMCE.addEvent(inst.getDoc(), "contextmenu", function(e) {TinyMCE_ContextMenuPlugin._showContextMenu(tinyMCE.isMSIE ? inst.contentWindow.event : e, inst);}); } else tinyMCE.addEvent(inst.getDoc(), "contextmenu", TinyMCE_ContextMenuPlugin._onContextMenu); }, // Private plugin internal methods _onContextMenu : function(e) { var elm = tinyMCE.isMSIE ? e.srcElement : e.target; var targetInst, body; // Find instance if ((body = tinyMCE.getParentElement(elm, "body")) != null) { for (var n in tinyMCE.instances) { var inst = tinyMCE.instances[n]; if (!tinyMCE.isInstance(inst)) continue; if (body == inst.getBody()) { targetInst = inst; break; } } return TinyMCE_ContextMenuPlugin._showContextMenu(tinyMCE.isMSIE ? targetInst.contentWindow.event : e, targetInst); } }, _showContextMenu : function(e, inst) { function getAttrib(elm, name) { return elm.getAttribute(name) ? elm.getAttribute(name) : ""; } var x, y, elm, contextMenu; var pos = tinyMCE.getAbsPosition(inst.iframeElement); x = tinyMCE.isMSIE ? e.screenX : pos.absLeft + (e.pageX - inst.getBody().scrollLeft); y = tinyMCE.isMSIE ? e.screenY : pos.absTop + (e.pageY - inst.getBody().scrollTop); elm = tinyMCE.isMSIE ? e.srcElement : e.target; contextMenu = this._contextMenu; contextMenu.inst = inst; // Mozilla needs some time window.setTimeout(function () { var theme = tinyMCE.getParam("theme"); contextMenu.clearAll(); var sel = inst.selection.getSelectedText().length != 0 || elm.nodeName == "IMG"; // Default items contextMenu.addItem(tinyMCE.baseURL + "/themes/" + theme + "/images/cut.gif", "$lang_cut_desc", "Cut", "", !sel); contextMenu.addItem(tinyMCE.baseURL + "/themes/" + theme + "/images/copy.gif", "$lang_copy_desc", "Copy", "", !sel); contextMenu.addItem(tinyMCE.baseURL + "/themes/" + theme + "/images/paste.gif", "$lang_paste_desc", "Paste", "", false); if (sel || (elm ? (elm.nodeName == 'A') || (elm.nodeName == 'IMG') : false)) { contextMenu.addSeparator(); contextMenu.addItem(tinyMCE.baseURL + "/themes/advanced/images/link.gif", "$lang_link_desc", inst.hasPlugin("advlink") ? "mceAdvLink" : "mceLink"); contextMenu.addItem(tinyMCE.baseURL + "/themes/advanced/images/unlink.gif", "$lang_unlink_desc", "unlink", "", (elm ? (elm.nodeName != 'A') && (elm.nodeName != 'IMG') : true)); } // Get element elm = tinyMCE.getParentElement(elm, "img,table,td" + (inst.hasPlugin("advhr") ? ',hr' : '')); if (elm) { switch (elm.nodeName) { case "IMG": contextMenu.addSeparator(); // If flash if (tinyMCE.hasPlugin('flash') && tinyMCE.getAttrib(elm, 'class').indexOf('mceItemFlash') != -1) contextMenu.addItem(tinyMCE.baseURL + "/plugins/flash/images/flash.gif", "$lang_flash_props", "mceFlash"); else if (tinyMCE.hasPlugin('media') && /mceItem(Flash|ShockWave|WindowsMedia|QuickTime|RealMedia)/.test(tinyMCE.getAttrib(elm, 'class'))) contextMenu.addItem(tinyMCE.baseURL + "/plugins/flash/images/flash.gif", "$lang_media_title", "mceMedia"); else contextMenu.addItem(tinyMCE.baseURL + "/themes/" + theme + "/images/image.gif", "$lang_image_props_desc", inst.hasPlugin("advimage") ? "mceAdvImage" : "mceImage"); break; case "HR": contextMenu.addSeparator(); contextMenu.addItem(tinyMCE.baseURL + "/plugins/advhr/images/advhr.gif", "$lang_insert_advhr_desc", "mceAdvancedHr"); break; case "TABLE": case "TD": // Is table plugin loaded if (inst.hasPlugin("table")) { var colspan = (elm.nodeName == "TABLE") ? "" : getAttrib(elm, "colspan"); var rowspan = (elm.nodeName == "TABLE") ? "" : getAttrib(elm, "rowspan"); colspan = colspan == "" ? "1" : colspan; rowspan = rowspan == "" ? "1" : rowspan; contextMenu.addSeparator(); contextMenu.addItem(tinyMCE.baseURL + "/themes/" + theme + "/images/cut.gif", "$lang_table_cut_row_desc", "mceTableCutRow"); contextMenu.addItem(tinyMCE.baseURL + "/themes/" + theme + "/images/copy.gif", "$lang_table_copy_row_desc", "mceTableCopyRow"); contextMenu.addItem(tinyMCE.baseURL + "/themes/" + theme + "/images/paste.gif", "$lang_table_paste_row_before_desc", "mceTablePasteRowBefore", "", inst.tableRowClipboard == null); contextMenu.addItem(tinyMCE.baseURL + "/themes/" + theme + "/images/paste.gif", "$lang_table_paste_row_after_desc", "mceTablePasteRowAfter", "", inst.tableRowClipboard == null); /* contextMenu.addItem(tinyMCE.baseURL + "/themes/" + theme + "/images/justifyleft.gif", "$lang_justifyleft_desc", "JustifyLeft", "", false); contextMenu.addItem(tinyMCE.baseURL + "/themes/" + theme + "/images/justifycenter.gif", "$lang_justifycenter_desc", "JustifyCenter", "", false); contextMenu.addItem(tinyMCE.baseURL + "/themes/" + theme + "/images/justifyright.gif", "$lang_justifyright_desc", "JustifyRight", "", false); contextMenu.addItem(tinyMCE.baseURL + "/themes/" + theme + "/images/justifyfull.gif", "$lang_justifyfull_desc", "JustifyFull", "", false);*/ contextMenu.addSeparator(); contextMenu.addItem(tinyMCE.baseURL + "/plugins/table/images/table.gif", "$lang_table_desc", "mceInsertTable", "insert"); contextMenu.addItem(tinyMCE.baseURL + "/plugins/table/images/table.gif", "$lang_table_props_desc", "mceInsertTable"); contextMenu.addItem(tinyMCE.baseURL + "/plugins/table/images/table_cell_props.gif", "$lang_table_cell_desc", "mceTableCellProps"); contextMenu.addItem(tinyMCE.baseURL + "/plugins/table/images/table_delete.gif", "$lang_table_del", "mceTableDelete"); contextMenu.addSeparator(); contextMenu.addItem(tinyMCE.baseURL + "/plugins/table/images/table_row_props.gif", "$lang_table_row_desc", "mceTableRowProps"); contextMenu.addItem(tinyMCE.baseURL + "/plugins/table/images/table_insert_row_before.gif", "$lang_table_row_before_desc", "mceTableInsertRowBefore"); contextMenu.addItem(tinyMCE.baseURL + "/plugins/table/images/table_insert_row_after.gif", "$lang_table_row_after_desc", "mceTableInsertRowAfter"); contextMenu.addItem(tinyMCE.baseURL + "/plugins/table/images/table_delete_row.gif", "$lang_table_delete_row_desc", "mceTableDeleteRow"); contextMenu.addSeparator(); contextMenu.addItem(tinyMCE.baseURL + "/plugins/table/images/table_insert_col_before.gif", "$lang_table_col_before_desc", "mceTableInsertColBefore"); contextMenu.addItem(tinyMCE.baseURL + "/plugins/table/images/table_insert_col_after.gif", "$lang_table_col_after_desc", "mceTableInsertColAfter"); contextMenu.addItem(tinyMCE.baseURL + "/plugins/table/images/table_delete_col.gif", "$lang_table_delete_col_desc", "mceTableDeleteCol"); contextMenu.addSeparator(); contextMenu.addItem(tinyMCE.baseURL + "/plugins/table/images/table_split_cells.gif", "$lang_table_split_cells_desc", "mceTableSplitCells", "", (colspan == "1" && rowspan == "1")); contextMenu.addItem(tinyMCE.baseURL + "/plugins/table/images/table_merge_cells.gif", "$lang_table_merge_cells_desc", "mceTableMergeCells", "", false); } break; } } else { // Add table specific if (inst.hasPlugin("table")) { contextMenu.addSeparator(); contextMenu.addItem(tinyMCE.baseURL + "/plugins/table/images/table.gif", "$lang_table_desc", "mceInsertTable", "insert"); } } contextMenu.show(x, y); }, 10); // Cancel default handeling tinyMCE.cancelEvent(e); return false; }, _hideContextMenu : function() { if (TinyMCE_ContextMenuPlugin._contextMenu) TinyMCE_ContextMenuPlugin._contextMenu.hide(); }, _commandHandler : function(command, value) { var cm = TinyMCE_ContextMenuPlugin._contextMenu; cm.hide(); // UI must be true on these var ui = false; if (command == "mceInsertTable" || command == "mceTableCellProps" || command == "mceTableRowProps" || command == "mceTableMergeCells") ui = true; if (command == "Paste") value = null; if (tinyMCE.getParam("dialog_type") == "modal" && tinyMCE.isMSIE) { // Cell properties will generate access denied error is this isn't done?! window.setTimeout(function() { cm.inst.execCommand(command, ui, value); }, 100); } else cm.inst.execCommand(command, ui, value); } }; tinyMCE.addPlugin("contextmenu", TinyMCE_ContextMenuPlugin); // Context menu class function TinyMCE_ContextMenu(settings) { var doc, self = this; // Default value function function defParam(key, def_val) { settings[key] = typeof(settings[key]) != "undefined" ? settings[key] : def_val; } this.isMSIE = (navigator.appName == "Microsoft Internet Explorer"); // Setup contextmenu div this.contextMenuDiv = document.createElement("div"); this.contextMenuDiv.className = "contextMenu"; this.contextMenuDiv.setAttribute("class", "contextMenu"); this.contextMenuDiv.style.display = "none"; this.contextMenuDiv.style.position = 'absolute'; this.contextMenuDiv.style.zindex = 1000; this.contextMenuDiv.style.left = '0'; this.contextMenuDiv.style.top = '0'; this.contextMenuDiv.unselectable = "on"; document.body.appendChild(this.contextMenuDiv); // Setup default values defParam("commandhandler", ""); defParam("spacer_image", "images/spacer.gif"); this.items = new Array(); this.settings = settings; this.html = ""; // IE Popup if (tinyMCE.isMSIE && !tinyMCE.isMSIE5_0 && !tinyMCE.isOpera) { this.pop = window.createPopup(); doc = this.pop.document; doc.open(); doc.write('<html><head><link href="' + tinyMCE.baseURL + '/plugins/contextmenu/css/contextmenu.css" rel="stylesheet" type="text/css" /></head><body unselectable="yes" class="contextMenuIEPopup"></body></html>'); doc.close(); } }; TinyMCE_ContextMenu.prototype = { clearAll : function() { this.html = ""; this.contextMenuDiv.innerHTML = ""; }, addSeparator : function() { this.html += '<tr class="contextMenuItem"><td class="contextMenuIcon"><img src="' + this.settings['spacer_image'] + '" width="20" height="1" class="contextMenuImage" /></td><td><img class="contextMenuSeparator" width="1" height="1" src="' + this.settings['spacer_image'] + '" /></td></tr>'; }, addItem : function(icon, title, command, value, disabled) { if (title.charAt(0) == '$') title = tinyMCE.getLang(title.substring(1)); var onMouseDown = ''; var html = ''; if (tinyMCE.isMSIE && !tinyMCE.isMSIE5_0) onMouseDown = 'contextMenu.execCommand(\'' + command + '\', \'' + value + '\');return false;'; else onMouseDown = this.settings['commandhandler'] + '(\'' + command + '\', \'' + value + '\');return false;'; if (icon == "") icon = this.settings['spacer_image']; if (!disabled) html += '<tr class="contextMenuItem">'; else html += '<tr class="contextMenuItemDisabled">'; html += '<td class="contextMenuIcon"><img src="' + icon + '" width="20" height="20" class="contextMenuImage" /></td>'; html += '<td><div class="contextMenuText">'; html += '<a href="javascript:void(0);" onclick="' + onMouseDown + '" onmousedown="return false;">&#160;'; // Add text html += title; html += '&#160;</a>'; html += '</div></td>'; html += '</tr>'; // Add to main this.html += html; }, show : function(x, y) { var vp, width, height, yo; if (this.html == "") return; var html = ''; html += '<a href="#"></a><table border="0" cellpadding="0" cellspacing="0">'; html += this.html; html += '</table>'; this.contextMenuDiv.innerHTML = html; // Get dimensions this.contextMenuDiv.style.display = "block"; width = this.contextMenuDiv.offsetWidth; height = this.contextMenuDiv.offsetHeight; this.contextMenuDiv.style.display = "none"; if (tinyMCE.isMSIE && !tinyMCE.isMSIE5_0 && !tinyMCE.isOpera) { // Setup popup and show this.pop.document.body.innerHTML = '<div class="contextMenu">' + html + "</div>"; this.pop.document.tinyMCE = tinyMCE; this.pop.document.contextMenu = this; this.pop.show(x, y, width, height); } else { vp = this.getViewPort(); yo = tinyMCE.isMSIE5_0 ? document.body.scrollTop : self.pageYOffset; this.contextMenuDiv.style.left = (x > vp.left + vp.width - width ? vp.left + vp.width - width : x) + 'px'; this.contextMenuDiv.style.top = (y > vp.top + vp.height - height ? vp.top + vp.height - height : y) + 'px'; this.contextMenuDiv.style.display = "block"; } }, getViewPort : function() { return { left : self.pageXOffset || self.document.documentElement.scrollLeft || self.document.body.scrollLeft, top: self.pageYOffset || self.document.documentElement.scrollTop || self.document.body.scrollTop, width : document.documentElement.offsetWidth || document.body.offsetWidth, height : self.innerHeight || document.documentElement.clientHeight || document.body.clientHeight }; }, hide : function() { if (tinyMCE.isMSIE && !tinyMCE.isMSIE5_0 && !tinyMCE.isOpera) this.pop.hide(); else this.contextMenuDiv.style.display = "none"; }, execCommand : function(command, value) { eval(this.settings['commandhandler'] + "(command, value);"); } };
/* * * * License: www.highcharts.com/license * * */ 'use strict'; import H from '../parts/Globals.js'; import '../parts/Utilities.js'; var isArray = H.isArray, seriesType = H.seriesType; function populateAverage(points, xVal, yVal, i, period) { var mmY = yVal[i - 1][3] - yVal[i - period - 1][3], mmX = xVal[i - 1]; points.shift(); // remove point until range < period return [mmX, mmY]; } /** * The Momentum series type. * * @private * @class * @name Highcharts.seriesTypes.momentum * * @augments Highcharts.Series */ seriesType('momentum', 'sma', /** * Momentum. This series requires `linkedTo` option to be set. * * @sample stock/indicators/momentum * Momentum indicator * * @extends plotOptions.sma * @since 6.0.0 * @product highstock * @optionparent plotOptions.momentum */ { params: { period: 14 } }, /** * @lends Highcharts.Series# */ { nameBase: 'Momentum', getValues: function (series, params) { var period = params.period, xVal = series.xData, yVal = series.yData, yValLen = yVal ? yVal.length : 0, xValue = xVal[0], yValue = yVal[0], MM = [], xData = [], yData = [], index, i, points, MMPoint; if (xVal.length <= period) { return false; } // Switch index for OHLC / Candlestick / Arearange if (isArray(yVal[0])) { yValue = yVal[0][3]; } else { return false; } // Starting point points = [ [xValue, yValue] ]; // Calculate value one-by-one for each period in visible data for (i = (period + 1); i < yValLen; i++) { MMPoint = populateAverage(points, xVal, yVal, i, period, index); MM.push(MMPoint); xData.push(MMPoint[0]); yData.push(MMPoint[1]); } MMPoint = populateAverage(points, xVal, yVal, i, period, index); MM.push(MMPoint); xData.push(MMPoint[0]); yData.push(MMPoint[1]); return { values: MM, xData: xData, yData: yData }; } } ); /** * A `Momentum` series. If the [type](#series.momentum.type) option is not * specified, it is inherited from [chart.type](#chart.type). * * @extends series,plotOptions.momentum * @since 6.0.0 * @excluding dataParser, dataURL * @product highstock * @apioption series.momentum */
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); var _exportNames = { iconButtonClasses: true }; Object.defineProperty(exports, "default", { enumerable: true, get: function () { return _IconButton.default; } }); Object.defineProperty(exports, "iconButtonClasses", { enumerable: true, get: function () { return _iconButtonClasses.default; } }); var _IconButton = _interopRequireDefault(require("./IconButton")); var _iconButtonClasses = _interopRequireWildcard(require("./iconButtonClasses")); Object.keys(_iconButtonClasses).forEach(function (key) { if (key === "default" || key === "__esModule") return; if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; if (key in exports && exports[key] === _iconButtonClasses[key]) return; Object.defineProperty(exports, key, { enumerable: true, get: function () { return _iconButtonClasses[key]; } }); }); function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; /** * @class * Initializes a new instance of the ErrorModel class. * @constructor * @member {number} [code] * * @member {string} [message] * */ function ErrorModel() { } /** * Defines the metadata of ErrorModel * * @returns {object} metadata of ErrorModel * */ ErrorModel.prototype.mapper = function () { return { required: false, serializedName: 'Error', type: { name: 'Composite', className: 'ErrorModel', modelProperties: { code: { required: false, serializedName: 'code', type: { name: 'Number' } }, message: { required: false, serializedName: 'message', type: { name: 'String' } } } } }; }; module.exports = ErrorModel;
import Ember from 'ember'; import EmberSelectizeComponent from 'ember-cli-selectize/components/ember-selectize'; export default EmberSelectizeComponent.extend({ /** * Event callback that is triggered when user creates a tag * - modified to pass the caret position to the action */ _create(input, callback) { var caret = this._selectize.caretPos; // Delete user entered text this._selectize.setTextboxValue(''); // Send create action // allow the observers and computed properties to run first Ember.run.schedule('actions', this, function () { this.sendAction('create-item', input, caret); }); // We cancel the creation here, so it's up to you to include the created element // in the content and selection property callback(null); } });
import fooBarBaz from 'my-app/utils/foo/bar-baz'; import { module, test } from 'qunit'; module('Unit | Utility | foo/bar-baz'); // Replace this with your real tests. test('it works', function(assert) { let result = fooBarBaz(); assert.ok(result); });
'use strict'; require('../common'); const assert = require('assert'); const net = require('net'); const dgram = require('dgram'); assert.ok((new net.Server()).ref() instanceof net.Server); assert.ok((new net.Server()).unref() instanceof net.Server); assert.ok((new net.Socket()).ref() instanceof net.Socket); assert.ok((new net.Socket()).unref() instanceof net.Socket); assert.ok((new dgram.Socket('udp4')).ref() instanceof dgram.Socket); assert.ok((new dgram.Socket('udp6')).unref() instanceof dgram.Socket);
'use strict'; var blacklist = [ 'freelist', 'sys' ]; module.exports = Object.keys(process.binding('natives')).filter(function (el) { return !/^_|^internal|\//.test(el) && blacklist.indexOf(el) === -1; }).sort();
/*************************************************************************************************** PopupWindow - The ultimate popup/dialog/modal jQuery plugin Author : Gaspare Sganga Version : 1.0.3 License : MIT Documentation : http://gasparesganga.com/labs/jquery-popup-window/ ***************************************************************************************************/ (function($, undefined){ // Default Settings var _defaults = { title : "Popup Window", modal : true, autoOpen : true, animationTime : 300, customClass : "", buttons : { close : true, maximize : true, collapse : true, minimize : true }, buttonsPosition : "right", buttonsTexts : { close : "Close", maximize : "Maximize", unmaximize : "Restore", minimize : "Minimize", unminimize : "Show", collapse : "Collapse", uncollapse : "Expand" }, draggable : true, dragOpacity : 0.6, resizable : true, resizeOpacity : 0.6, statusBar : true, top : "auto", left : "auto", height : 200, width : 400, maxHeight : undefined, maxWidth : undefined, minHeight : 100, minWidth : 200, collapsedWidth : undefined, keepInViewport : true, mouseMoveEvents : true }; // Required CSS var _css = { container : { "box-sizing" : "border-box", "position" : "fixed", "top" : "0", "bottom" : "0", "right" : "0", "left" : "0", "display" : "flex", "justify-content" : "flex-start", "align-content" : "flex-start", "pointer-events" : "none" }, overlay : { "box-sizing" : "border-box", "position" : "fixed", "top" : "0", "left" : "0", "width" : "100%", "height" : "100%" }, minplaceholder : { "box-sizing" : "border-box", "background" : "transparent", "border" : "none" }, popupwindow : { "box-sizing" : "border-box", "display" : "flex", "flex-flow" : "column nowrap", "position" : "absolute", "padding" : "0", "pointer-events" : "auto" }, titlebar : { "box-sizing" : "border-box", "flex" : "0 0 auto", "display" : "flex", "align-items" : "center" }, titlebar_text : { "box-sizing" : "border-box", "flex" : "1 1 auto", "overflow" : "hidden", "text-overflow" : "ellipsis", "white-space" : "nowrap" }, titlebar_button : { "box-sizing" : "border-box", "flex" : "0 0 auto", "display" : "flex" }, content : { "flex" : "1 1 auto", "overflow" : "auto" }, statusbar : { "box-sizing" : "border-box", "flex" : "0 0 auto", "display" : "flex", "align-items" : "flex-end" }, statusbar_content : { "box-sizing" : "border-box", "flex" : "1 1 auto", "overflow" : "hidden", "text-align" : "left", "text-overflow" : "ellipsis", "white-space" : "nowrap" }, statusbar_handle : { "box-sizing" : "border-box", "display" : "flex" }, statusbar_handle_resizable : { "cursor" : "se-resize" }, resizer_top : { "position" : "absolute", "left" : "0", "right" : "0", "cursor" : "n-resize" }, resizer_bottom : { "position" : "absolute", "left" : "0", "right" : "0", "cursor" : "s-resize" }, resizer_left : { "position" : "absolute", "top" : "0", "bottom" : "0", "cursor" : "e-resize" }, resizer_right : { "position" : "absolute", "top" : "0", "bottom" : "0", "cursor" : "w-resize" }, resizer_topleft : { "position" : "absolute", "cursor" : "nw-resize" }, resizer_topright : { "position" : "absolute", "cursor" : "ne-resize" }, resizer_bottomleft : { "position" : "absolute", "cursor" : "ne-resize" }, resizer_bottomright : { "position" : "absolute", "cursor" : "nw-resize" } }; // Icons var _icons = { close : '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 10 10" height="100%" width="100%"><g><line y2="0" x2="10" y1="10" x1="0"/><line y2="10" x2="10" y1="0" x1="0"/></g></svg>', collapse : '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 10 10" height="100%" width="100%"><g fill="none"><polyline points="1,7 9,7 5,2 1,7 9,7"/></g></svg>', uncollapse : '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 10 10" height="100%" width="100%"><g fill="none"><polyline points="1,3 9,3 5,8 1,3 9,3"/></g></svg>', maximize : '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 10 10" height="100%" width="100%"><g fill="none"><rect x="1" y="1" height="8" width="8"/></g></svg>', unmaximize : '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 10 10" height="100%" width="100%"><g fill="none"><rect x="1" y="3" height="6" width="6"/><line y1="3" x1="3" y2="1" x2="3"/><line y1="1" x1="2.5" y2="1" x2="9.5"/><line y1="1" x1="9" y2="7" x2="9"/><line y1="7" x1="9.5" y2="7" x2="7"/></g></svg>', minimize : '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 10 10" height="100%" width="100%"><g><line y1="6" x1="8" y2="6" x2="2"/></g></svg>', resizeHandle : '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 10 10" height="100%" width="100%"><g><line y2="0" x2="10" y1="10" x1="0"/><line y2="2" x2="12" y1="12" x1="2"/><line y2="4" x2="14" y1="14" x1="4"/></g></svg>' }; // Constants var _constants = { resizersWidth : 4, secondaryAnimationTimeFactor : 3 }; // Main Container var _mainContainer; // Minimized Area var _minimizedArea = { position : "bottom left", direction : "horizontal" }; // ************************************************** // METHODS // ************************************************** $.PopupWindowSetup = function(options){ $.extend(true, _defaults, options); }; $.PopupWindowMinimizedArea = function(options){ if (options === undefined) return $.extend({}, _minimizedArea); if (options.position) _minimizedArea.position = ((options.position.toLowerCase().indexOf("b") >= 0) ? "bottom" : "top") + " " + ((options.position.toLowerCase().indexOf("l") >= 0) ? "left" : "right"); if (options.direction) _minimizedArea.direction = (options.direction.toLowerCase().indexOf("h") >= 0) ? "horizontal" : "vertical"; _SetMinimizedArea(); }; $.fn.PopupWindow = function(opt1, opt2){ if (typeof opt1 == "string") { switch (opt1.toLowerCase()) { case "init": return this.each(function(){ _Init($(this), opt2); }); case "open": return this.each(function(){ _Open($(this).closest(".popupwindow")); }); case "close": return this.each(function(){ _Close($(this).closest(".popupwindow")); }); case "maximize": return this.each(function(){ _Maximize($(this).closest(".popupwindow")); }); case "unmaximize": return this.each(function(){ _Unmaximize($(this).closest(".popupwindow")); }); case "collapse": return this.each(function(){ _Collapse($(this).closest(".popupwindow")); }); case "uncollapse": return this.each(function(){ _Uncollapse($(this).closest(".popupwindow")); }); case "minimize": return this.each(function(){ _Minimize($(this).closest(".popupwindow")); }); case "unminimize": return this.each(function(){ _Unminimize($(this).closest(".popupwindow")); }); case "getposition": if (!this[0]) return undefined; return _GetCurrentPosition($(this[0]).closest(".popupwindow")); case "setposition": return this.each(function(){ _ChangePosition($(this).closest(".popupwindow"), $.extend({}, opt2, { check : true, event : true }), true); }); case "getsize": if (!this[0]) return undefined; return _GetCurrentSize($(this[0]).closest(".popupwindow")); case "setsize": return this.each(function(){ _ChangeSize($(this).closest(".popupwindow"), $.extend({}, opt2, { checkSize : true, checkPosition : true, event : true }), true); }); case "getstate": if (!this[0]) return undefined; return _GetState($(this[0]).closest(".popupwindow")); case "setstate": return this.each(function(){ _SetState($(this).closest(".popupwindow"), opt2); }); case "settitle": return this.each(function(){ _SetTitle($(this).closest(".popupwindow"), opt2); }); case "statusbar": return this.each(function(){ _StatusBar($(this).closest(".popupwindow"), opt2); }); case "destroy": return this.each(function(){ _Destroy($(this).closest(".popupwindow")); }); } } else { return this.each(function(){ _Init($(this), opt1); }); } }; // ************************************************** // FUNCTIONS // ************************************************** function _Init(originalTarget, options){ if (originalTarget.closest(".popupwindow").length) { _Warning("jQuery PopupWindow is already initialized on this element"); return; } var settings = $.extend(true, {}, _defaults, options); settings.animationTime = parseInt(settings.animationTime, 10); settings.height = parseInt(settings.height, 10); settings.width = parseInt(settings.width, 10); settings.maxHeight = parseInt(settings.maxHeight, 10) || 0; settings.maxWidth = parseInt(settings.maxWidth, 10) || 0; settings.minHeight = parseInt(settings.minHeight, 10) || 0; settings.minWidth = parseInt(settings.minWidth, 10) || 0; // Overlay var overlay = $("<div>", { class : "popupwindow_overlay" }) .css(_css.overlay) .appendTo(_mainContainer); if (settings.modal) overlay.css("pointer-events", "auto"); // Minimized Placeholder var minPlaceholder = $("<div>", { class : "popupwindow_minplaceholder" }) .css(_css.minplaceholder) .hide() .appendTo(_mainContainer); // Popup Window var position = { left : (settings.left == "auto") ? ((overlay.width() - settings.width) / 2) : parseInt(settings.left, 10), top : (settings.top == "auto") ? ((overlay.height() - settings.height) / 2) : parseInt(settings.top, 10) }; var popupWindow = $("<div>", { class : "popupwindow", css : { height : settings.height, left : position.left, top : position.top, width : settings.width } }) .css(_css.popupwindow) .addClass(settings.customClass) .data({ originalTarget : originalTarget, originalParent : originalTarget.parent(), overlay : overlay, minPlaceholder : minPlaceholder, settings : settings, opened : false, collapsed : false, minimized : false, maximized : false, currentPosition : position, currentSize : { height : settings.height, width : settings.width }, savedPosition : undefined, savedSize : undefined }) .on("mousedown", ".popupwindow_titlebar_draggable", _Titlebar_MouseDown) .appendTo(overlay); // Titlebar var leftToRight = (settings.buttonsPosition.toLowerCase().indexOf("l") < 0); var titlebar = $("<div>", { class : "popupwindow_titlebar" }) .css(_css.titlebar) .appendTo(popupWindow); if (settings.draggable) titlebar.addClass("popupwindow_titlebar_draggable"); // Text $("<div>", { class : "popupwindow_titlebar_text", text : settings.title }) .css(_css.titlebar_text) .css("order", leftToRight ? 1 : 5) .appendTo(titlebar); // Buttons if (settings.buttons.close) { $("<div>", { class : "popupwindow_titlebar_button popupwindow_titlebar_button_close" }) .css(_css.titlebar_button) .css("order", leftToRight ? 5 : 1) .attr("title", settings.buttonsTexts.close) .on("click", _ButtonClose_Click) .append(_icons.close) .appendTo(titlebar); } if (settings.buttons.maximize) { $("<div>", { class : "popupwindow_titlebar_button popupwindow_titlebar_button_maximize" }) .css(_css.titlebar_button) .css("order", leftToRight ? 4 : 2) .attr("title", settings.buttonsTexts.maximize) .on("click", _ButtonMax_Click) .append(_icons.maximize) .appendTo(titlebar); } if (settings.buttons.collapse) { $("<div>", { class : "popupwindow_titlebar_button popupwindow_titlebar_button_collapse" }) .css(_css.titlebar_button) .css("order", leftToRight ? 3 : 3) .attr("title", settings.buttonsTexts.collapse) .on("click", _ButtonCollapse_Click) .append(_icons.collapse) .appendTo(titlebar); } if (settings.buttons.minimize) { $("<div>", { class : "popupwindow_titlebar_button popupwindow_titlebar_button_minimize" }) .css(_css.titlebar_button) .css("order", leftToRight ? 2 : 4) .attr("title", settings.buttonsTexts.minimize) .on("click", _ButtonMin_Click) .append(_icons.minimize) .appendTo(titlebar); } // Content var content = $("<div>", { class : "popupwindow_content" }) .css(_css.content) .appendTo(popupWindow); originalTarget.show().appendTo(content); // StatusBar if (settings.statusBar) { var statusBar = $("<div>", { class : "popupwindow_statusbar" }) .css(_css.statusbar) .appendTo(popupWindow); $("<div>", { class : "popupwindow_statusbar_content" }) .css(_css.statusbar_content) .appendTo(statusBar); var resizeHandle = $("<div>", { class : "popupwindow_statusbar_handle" }) .css(_css.statusbar_handle) .appendTo(statusBar); if (settings.resizable) { resizeHandle .css(_css.statusbar_handle_resizable) .append(_icons.resizeHandle) .on("mousedown", null, { dimension : "both", directionX : "right", directionY : "bottom" }, _Resizer_MouseDown); } } // Resizing if (settings.resizable) { var bordersWidth = _GetBordersWidth(popupWindow); // Top $("<div>", { class : "popupwindow_resizer popupwindow_resizer_top", css : { top : 0 - bordersWidth.top - (_constants.resizersWidth / 2), height : bordersWidth.top + _constants.resizersWidth } }) .css(_css.resizer_top) .on("mousedown", null, { dimension : "height", directionY : "top" }, _Resizer_MouseDown) .appendTo(popupWindow); // Bottom $("<div>", { class : "popupwindow_resizer popupwindow_resizer_bottom", css : { bottom : 0 - bordersWidth.bottom - (_constants.resizersWidth / 2), height : bordersWidth.bottom + _constants.resizersWidth } }) .css(_css.resizer_bottom) .on("mousedown", null, { dimension : "height", directionY : "bottom", }, _Resizer_MouseDown) .appendTo(popupWindow); // Left $("<div>", { class : "popupwindow_resizer popupwindow_resizer_left", css : { left : 0 - bordersWidth.left - (_constants.resizersWidth / 2), width : bordersWidth.left + _constants.resizersWidth } }) .css(_css.resizer_left) .on("mousedown", null, { dimension : "width", directionX : "left" }, _Resizer_MouseDown) .appendTo(popupWindow); // Right $("<div>", { class : "popupwindow_resizer popupwindow_resizer_right", css : { right : 0 - bordersWidth.right - (_constants.resizersWidth / 2), width : bordersWidth.right + _constants.resizersWidth } }) .css(_css.resizer_right) .on("mousedown", null, { dimension : "width", directionX : "right", }, _Resizer_MouseDown) .appendTo(popupWindow); // Top Left $("<div>", { class : "popupwindow_resizer popupwindow_resizer_topleft", css : { top : 0 - bordersWidth.top - (_constants.resizersWidth / 2), left : 0 - bordersWidth.left - (_constants.resizersWidth / 2), width : bordersWidth.left + _constants.resizersWidth, height : bordersWidth.top + _constants.resizersWidth } }) .css(_css.resizer_topleft) .on("mousedown", null, { dimension : "both", directionX : "left", directionY : "top" }, _Resizer_MouseDown) .appendTo(popupWindow); // Top Right $("<div>", { class : "popupwindow_resizer popupwindow_resizer_topright", css : { top : 0 - bordersWidth.top - (_constants.resizersWidth / 2), right : 0 - bordersWidth.right - (_constants.resizersWidth / 2), width : bordersWidth.right + _constants.resizersWidth, height : bordersWidth.top + _constants.resizersWidth } }) .css(_css.resizer_topright) .on("mousedown", null, { dimension : "both", directionX : "right", directionY : "top" }, _Resizer_MouseDown) .appendTo(popupWindow); // Bottom Left $("<div>", { class : "popupwindow_resizer popupwindow_resizer_bottomleft", css : { bottom : 0 - bordersWidth.bottom - (_constants.resizersWidth / 2), left : 0 - bordersWidth.left - (_constants.resizersWidth / 2), width : bordersWidth.left + _constants.resizersWidth, height : bordersWidth.bottom + _constants.resizersWidth } }) .css(_css.resizer_bottomleft) .on("mousedown", null, { dimension : "both", directionX : "left", directionY : "bottom" }, _Resizer_MouseDown) .appendTo(popupWindow); // Bottom Right $("<div>", { class : "popupwindow_resizer popupwindow_resizer_bottomright", css : { bottom : 0 - bordersWidth.bottom - (_constants.resizersWidth / 2), right : 0 - bordersWidth.right - (_constants.resizersWidth / 2), width : bordersWidth.right + _constants.resizersWidth, height : bordersWidth.bottom + _constants.resizersWidth } }) .css(_css.resizer_bottomright) .on("mousedown", null, { dimension : "both", directionX : "right", directionY : "bottom" }, _Resizer_MouseDown) .appendTo(popupWindow); } // Final Settings if (!settings.modal) overlay.width(0).height(0); overlay.hide(); if (settings.autoOpen) _Open(popupWindow); } function _Open(popupWindow){ if (!_CheckPopupWindow(popupWindow) || popupWindow.data("opened")) return; popupWindow.data("overlay").show(); popupWindow.data("opened", true); _TriggerEvent(popupWindow, "open"); _Uncollapse(popupWindow); _Unminimize(popupWindow) } function _Close(popupWindow){ if (!_CheckPopupWindow(popupWindow) || !popupWindow.data("opened")) return; if (popupWindow.data("minimized")) _Unminimize(popupWindow); popupWindow.data("overlay").hide(); popupWindow.data("opened", false); _TriggerEvent(popupWindow, "close"); } function _Maximize(popupWindow){ if (!_CheckPopupWindow(popupWindow) || !popupWindow.data("opened") || popupWindow.data("maximized") || popupWindow.data("collapsed") || popupWindow.data("minimized")) return; var settings = popupWindow.data("settings"); popupWindow.find(".popupwindow_titlebar_button_maximize") .empty() .append(_icons.unmaximize) .attr("title", settings.buttonsTexts.unmaximize); popupWindow.find(".popupwindow_statusbar_handle *, .popupwindow_resizer, .popupwindow_titlebar_button_collapse").hide(); if (settings.draggable) popupWindow.find(".popupwindow_titlebar").removeClass("popupwindow_titlebar_draggable"); if (!settings.modal) popupWindow.data("overlay").css("background-color", "transparent").width("100%").height("100%"); _SaveCurrentPosition(popupWindow); _SaveCurrentSize(popupWindow); var defPosition = _ChangePosition(popupWindow, { top : 0, left : 0 }); var defSize = _ChangeSize(popupWindow, { width : "100%", height : "100%" }); return $.when(defPosition, defSize).then(function(){ popupWindow.data("maximized", true); _TriggerEvent(popupWindow, "maximize"); }); } function _Unmaximize(popupWindow){ if (!_CheckPopupWindow(popupWindow) || !popupWindow.data("opened") || !popupWindow.data("maximized")) return; var settings = popupWindow.data("settings"); var defPosition = _RestoreSavedPosition(popupWindow); var defSize = _RestoreSavedSize(popupWindow); popupWindow.find(".popupwindow_titlebar_button_maximize") .empty() .append(_icons.maximize) .attr("title", settings.buttonsTexts.maximize); popupWindow.find(".popupwindow_statusbar_handle *, .popupwindow_resizer, .popupwindow_titlebar_button_collapse").show(); if (settings.draggable) popupWindow.find(".popupwindow_titlebar").addClass("popupwindow_titlebar_draggable"); if (!settings.modal) popupWindow.data("overlay").width(0).height(0).css("background-color", ""); return $.when(defPosition, defSize).then(function(){ popupWindow.data("maximized", false); _TriggerEvent(popupWindow, "unmaximize"); }); } function _Collapse(popupWindow){ if (!_CheckPopupWindow(popupWindow) || !popupWindow.data("opened") || popupWindow.data("maximized") || popupWindow.data("collapsed") || popupWindow.data("minimized")) return; var settings = popupWindow.data("settings"); popupWindow.find(".popupwindow_titlebar_button_collapse") .empty() .append(_icons.uncollapse) .attr("title", settings.buttonsTexts.uncollapse); popupWindow.find(".popupwindow_content, .popupwindow_statusbar, .popupwindow_resizer, .popupwindow_titlebar_button_maximize, .popupwindow_titlebar_button_minimize").hide(); _SaveCurrentSize(popupWindow); var defSize = _ChangeSize(popupWindow, { width : settings.collapsedWidth, height : _GetBordersWidth(popupWindow, "top") + _GetBordersWidth(popupWindow, "bottom") + popupWindow.find(".popupwindow_titlebar").outerHeight() }); return $.when(defSize).then(function(){ popupWindow.data("collapsed", true); _TriggerEvent(popupWindow, "collapse"); }); } function _Uncollapse(popupWindow){ if (!_CheckPopupWindow(popupWindow) || !popupWindow.data("opened") || !popupWindow.data("collapsed")) return; var settings = popupWindow.data("settings"); var defSize = _RestoreSavedSize(popupWindow); popupWindow.find(".popupwindow_titlebar_button_collapse") .empty() .append(_icons.collapse) .attr("title", settings.buttonsTexts.collapse); popupWindow.find(".popupwindow_content, .popupwindow_statusbar, .popupwindow_resizer, .popupwindow_titlebar_button_maximize, .popupwindow_titlebar_button_minimize").show(); return $.when(defSize).then(function(){ popupWindow.data("collapsed", false); _TriggerEvent(popupWindow, "uncollapse"); }); } function _Minimize(popupWindow){ if (!_CheckPopupWindow(popupWindow) || !popupWindow.data("opened") || popupWindow.data("collapsed") || popupWindow.data("minimized")) return; var defRet = $.Deferred(); var settings = popupWindow.data("settings"); var defUnmaximize; if (popupWindow.data("maximized")) { var savedAnimationTime = settings.animationTime; settings.animationTime = settings.animationTime / _constants.secondaryAnimationTimeFactor; defUnmaximize = _Unmaximize(popupWindow); settings.animationTime = savedAnimationTime; } else { _SaveCurrentPosition(popupWindow); _SaveCurrentSize(popupWindow); defUnmaximize = $.Deferred().resolve(); } $.when(defUnmaximize).then(function(){ popupWindow.addClass("popupwindow_minimized").width(""); popupWindow.find(".popupwindow_titlebar_button_minimize").attr("title", settings.buttonsTexts.unminimize); popupWindow.find(".popupwindow_content, .popupwindow_statusbar, .popupwindow_resizer, .popupwindow_titlebar_button_maximize, .popupwindow_titlebar_button_collapse").hide(); if (settings.draggable) popupWindow.find(".popupwindow_titlebar").removeClass("popupwindow_titlebar_draggable"); var minPlaceholder = popupWindow.data("minPlaceholder"); var minimizedSize = { width : popupWindow.outerWidth(), height : _GetBordersWidth(popupWindow, "top") + _GetBordersWidth(popupWindow, "bottom") + popupWindow.find(".popupwindow_titlebar").outerHeight() }; minPlaceholder .outerWidth(minimizedSize.width) .outerHeight(minimizedSize.height) .show(); var minPlaceholderAnimation = {}; var newPosition = minPlaceholder.position(); if (_minimizedArea.direction == "horizontal") { minPlaceholderAnimation.width = minimizedSize.width; minPlaceholder.width(0); } else { minPlaceholderAnimation.height = minimizedSize.height; minPlaceholder.height(0); } var defPosition = _ChangePosition(popupWindow, newPosition); var defSize = _ChangeSize(popupWindow, { height : minimizedSize.height }); minPlaceholder.animate(minPlaceholderAnimation, { duration : settings.animationTime, queue : false, complete : function(){ $(this).hide(); popupWindow.css({ position : "relative", top : "", left : "" }).insertAfter(popupWindow.data("overlay")); } }); $.when(defPosition, defSize).then(function(){ popupWindow.data("minimized", true); _TriggerEvent(popupWindow, "minimize"); defRet.resolve(); }); }); return defRet.promise(); } function _Unminimize(popupWindow){ if (!_CheckPopupWindow(popupWindow) || !popupWindow.data("opened") || !popupWindow.data("minimized")) return; var settings = popupWindow.data("settings"); var minPlaceholder = popupWindow.data("minPlaceholder"); popupWindow.removeClass("popupwindow_minimized"); popupWindow.find(".popupwindow_titlebar_button_minimize").attr("title", settings.buttonsTexts.minimize); popupWindow.find(".popupwindow_content, .popupwindow_statusbar, .popupwindow_resizer, .popupwindow_titlebar_button_maximize, .popupwindow_titlebar_button_collapse").show(); if (settings.draggable) popupWindow.find(".popupwindow_titlebar").addClass("popupwindow_titlebar_draggable"); minPlaceholder.show().insertAfter(popupWindow.data("overlay")); var minimizedSize = { width : minPlaceholder.outerWidth(), height : minPlaceholder.outerHeight() }; var minPlaceholderAnimation = {}; var newPosition = minPlaceholder.position(); if (_minimizedArea.direction == "horizontal") { minPlaceholderAnimation.width = 0; minPlaceholder.width(minimizedSize.width); } else { minPlaceholderAnimation.height = 0; minPlaceholder.height(minimizedSize.height); } popupWindow.css({ position : "absolute", top : newPosition.top, left : newPosition.left, width : minimizedSize.width }).appendTo(popupWindow.data("overlay")); var defPosition = _RestoreSavedPosition(popupWindow); var defSize = _RestoreSavedSize(popupWindow); minPlaceholder.animate(minPlaceholderAnimation, { duration : settings.animationTime, queue : false, complete : function(){ $(this).hide(); } }); return $.when(defPosition, defSize).then(function(){ popupWindow.data("minimized", false); _TriggerEvent(popupWindow, "unminimize"); }); } function _Destroy(popupWindow){ if (!_CheckPopupWindow(popupWindow)) return; var originalTarget = popupWindow.data("originalTarget"); originalTarget.appendTo(popupWindow.data("originalParent")); if (popupWindow.data("minimized")) { popupWindow.remove(); } else { popupWindow.data("overlay").remove(); } originalTarget.trigger("destroy.popupwindow"); } function _GetCurrentPosition(popupWindow){ if (!_CheckPopupWindow(popupWindow)) return undefined; return $.extend({}, popupWindow.data("currentPosition")); } function _SetCurrentPosition(popupWindow, position){ $.extend(popupWindow.data("currentPosition"), position); } function _SaveCurrentPosition(popupWindow){ popupWindow.data("savedPosition", _GetCurrentPosition(popupWindow)); } function _RestoreSavedPosition(popupWindow){ return _ChangePosition(popupWindow, popupWindow.data("savedPosition")); } function _ChangePosition(popupWindow, params){ if (!_CheckPopupWindow(popupWindow)) return; var defRet = $.Deferred(); var settings = popupWindow.data("settings"); var animationTime = (params.animationTime !== undefined) ? parseInt(params.animationTime) : settings.animationTime; var newPosition = { top : params.top, left : params.left }; if (params.check) { if (!popupWindow.data("opened") || popupWindow.data("maximized") || popupWindow.data("minimized")) return; if (settings.keepInViewport) { var size = _GetCurrentSize(popupWindow); var $window = $(window); if (newPosition.top > $window.height() - size.height) newPosition.top = $window.height() - size.height; if (newPosition.left > $window.width() - size.width) newPosition.left = $window.width() - size.width; if (newPosition.top < 0) newPosition.top = 0; if (newPosition.left < 0) newPosition.left = 0; } } var currentPosition = _GetCurrentPosition(popupWindow); if (currentPosition.top != newPosition.top || currentPosition.left != newPosition.left) { popupWindow.animate(newPosition, { duration : animationTime, queue : false, complete : function(){ _SetCurrentPosition(popupWindow, newPosition); if (params.event) _TriggerEvent(popupWindow, "move"); defRet.resolve(); } }); } else { defRet.resolve(); } return defRet.promise(); } function _CheckPosition(popupWindow){ _ChangePosition(popupWindow, $.extend({ animationTime : popupWindow.data("settings").animationTime / _constants.secondaryAnimationTimeFactor, check : true, event : true }, _GetCurrentPosition(popupWindow))); } function _GetCurrentSize(popupWindow){ if (!_CheckPopupWindow(popupWindow)) return undefined; return $.extend({}, popupWindow.data("currentSize")); } function _SetCurrentSize(popupWindow, size){ $.extend(popupWindow.data("currentSize"), size); } function _SaveCurrentSize(popupWindow){ popupWindow.data("savedSize", _GetCurrentSize(popupWindow)); } function _RestoreSavedSize(popupWindow){ return _ChangeSize(popupWindow, $.extend({ checkPosition : true, checkSize : false, event : false }, popupWindow.data("savedSize"))); } function _ChangeSize(popupWindow, params){ if (!_CheckPopupWindow(popupWindow)) return; var defRet = $.Deferred(); var settings = popupWindow.data("settings"); var animationTime = (params.animationTime !== undefined) ? parseInt(params.animationTime) : settings.animationTime; var newSize = { width : params.width, height : params.height }; if (params.checkSize) { if (!popupWindow.data("opened") || popupWindow.data("maximized") || popupWindow.data("minimized")) return; if (settings.maxWidth && newSize.width > settings.maxWidth) newSize.width = settings.maxWidth; if (settings.minWidth && newSize.width < settings.minWidth) newSize.width = settings.minWidth; if (settings.maxHeight && newSize.height > settings.maxHeight) newSize.height = settings.maxHeight; if (settings.minHeight && newSize.height < settings.minHeight) newSize.height = settings.minHeight; if (popupWindow.data("collapsed")) { popupWindow.data("savedSize", $.extend({}, newSize)); delete newSize.height; } } var currentSize = _GetCurrentSize(popupWindow); if (currentSize.width != newSize.width || currentSize.height != newSize.height) { popupWindow.animate(newSize, { duration : animationTime, queue : false, complete : function(){ _SetCurrentSize(popupWindow, newSize); if (params.event) _TriggerEvent(popupWindow, "resize"); if (params.checkPosition) _CheckPosition(popupWindow); defRet.resolve(); } }); } else { defRet.resolve(); } return defRet.promise(); } function _CheckSize(popupWindow){ _ChangeSize(popupWindow, $.extend({ animationTime : popupWindow.data("settings").animationTime / _constants.secondaryAnimationTimeFactor, checkPosition : false, checkSize : true, event : true }, _GetCurrentSize(popupWindow))); } function _GetState(popupWindow){ if (!popupWindow.length) return undefined; if (!popupWindow.data("opened")) return "closed"; if (popupWindow.data("minimized")) return "minimized"; if (popupWindow.data("collapsed")) return "collapsed"; if (popupWindow.data("maximized")) return "maximized"; return "normal"; } function _SetState(popupWindow, state){ if (!_CheckPopupWindow(popupWindow)) return; switch (state.toLowerCase()) { case "normal": if (!popupWindow.data("opened")) _Open(popupWindow); if (popupWindow.data("minimized")) _Unminimize(popupWindow); if (popupWindow.data("collapsed")) _Uncollapse(popupWindow); if (popupWindow.data("maximized")) _Unmaximize(popupWindow); break; case "closed": _Close(popupWindow); break; case "maximized": _Maximize(popupWindow); break; case "unmaximized": _Unmaximize(popupWindow); break; case "collapsed": _Collapse(popupWindow); break; case "uncollapsed": _Uncollapse(popupWindow); break; case "minimized": _Minimize(popupWindow); break; case "unminimized": _Unminimize(popupWindow); break; } } function _SetTitle(popupWindow, title){ if (!_CheckPopupWindow(popupWindow)) return; popupWindow.data("settings").title = title; popupWindow.find(".popupwindow_titlebar_text").text(title); } function _StatusBar(popupWindow, content){ if (!_CheckPopupWindow(popupWindow)) return; popupWindow.find(".popupwindow_statusbar_content").html(content); } function _GetBordersWidth(popupWindow, border){ if (border !== undefined) return parseInt(popupWindow.css("border-"+border+"-width"), 10); return { top : parseInt(popupWindow.css("border-top-width"), 10), bottom : parseInt(popupWindow.css("border-bottom-width"), 10), left : parseInt(popupWindow.css("border-left-width"), 10), right : parseInt(popupWindow.css("border-right-width"), 10) }; } function _AddDocumentMouseEventHandlers(eventData){ eventData.popupWindow.fadeTo(0, eventData.opacity); if (!eventData.popupWindow.data("settings").mouseMoveEvents) eventData.popupWindow.data("tempSavedData", { position : _GetCurrentPosition(eventData.popupWindow), size : _GetCurrentSize(eventData.popupWindow) }); $(document) .on("mousemove", eventData, _Document_MouseMove) .on("mouseup", eventData, _Document_MouseUp); } function _TriggerEvent(popupWindow, eventName){ var eventData; if (eventName == "move") eventData = _GetCurrentPosition(popupWindow); if (eventName == "resize") eventData = _GetCurrentSize(popupWindow); popupWindow.data("originalTarget").trigger(eventName + ".popupwindow", eventData); } function _SetMinimizedArea(){ var flex = {}; if (_minimizedArea.direction == "horizontal") { flex["flex-direction"] = (_minimizedArea.position.indexOf("left") >= 0) ? "row" : "row-reverse"; flex["flex-wrap"] = (_minimizedArea.position.indexOf("top") >= 0) ? "wrap" : "wrap-reverse"; } else { flex["flex-direction"] = (_minimizedArea.position.indexOf("top") >= 0) ? "column" : "column-reverse"; flex["flex-wrap"] = (_minimizedArea.position.indexOf("left") >= 0) ? "wrap" : "wrap-reverse"; } _mainContainer.css(flex); } function _CheckPopupWindow(popupWindow){ if (popupWindow.length) return true; _Warning("jQuery PopupWindow is not initialized on this element"); return false; } function _Warning(message){ message = "jQuery PopupWindow Warning: " + message; if (window.console.warn) { console.warn(message); } else if (window.console.log) { console.log(message); } } // ************************************************** // EVENT HANDLERS // ************************************************** function _ButtonClose_Click(event){ _Close($(event.currentTarget).closest(".popupwindow")); } function _ButtonMax_Click(event){ var popupWindow = $(event.currentTarget).closest(".popupwindow"); if (!popupWindow.data("maximized")) { _Maximize(popupWindow); } else { _Unmaximize(popupWindow); } } function _ButtonCollapse_Click(event){ var popupWindow = $(event.currentTarget).closest(".popupwindow"); if (!popupWindow.data("collapsed")) { _Collapse(popupWindow); } else { _Uncollapse(popupWindow); } } function _ButtonMin_Click(event){ var popupWindow = $(event.currentTarget).closest(".popupwindow"); if (!popupWindow.data("minimized")) { _Minimize(popupWindow); } else { _Unminimize(popupWindow); } } function _Titlebar_MouseDown(event){ if (event.target !== event.currentTarget && !$(event.target).hasClass("popupwindow_titlebar_text")) return false; var popupWindow = $(event.currentTarget).closest(".popupwindow"); var currentPosition = _GetCurrentPosition(popupWindow); var settings = popupWindow.data("settings"); if (!settings.modal) popupWindow.data("overlay").css("background-color", "transparent").width("100%").height("100%"); _AddDocumentMouseEventHandlers({ popupWindow : popupWindow, action : "drag", opacity : settings.dragOpacity, compensationX : event.pageX - currentPosition.left, compensationY : event.pageY - currentPosition.top }); event.preventDefault(); } function _Resizer_MouseDown(event){ var popupWindow = $(event.currentTarget).closest(".popupwindow"); var currentPosition = _GetCurrentPosition(popupWindow); var currentSize = _GetCurrentSize(popupWindow); _AddDocumentMouseEventHandlers({ popupWindow : popupWindow, action : "resize", dimension : event.data.dimension, directionX : event.data.directionX, directionY : event.data.directionY, opacity : popupWindow.data("settings").resizeOpacity, startX : event.pageX + ((event.data.directionX == "left") ? currentSize.width : -currentSize.width), startY : event.pageY + ((event.data.directionY == "top" ) ? currentSize.height : -currentSize.height), compensationX : event.pageX - currentPosition.left, compensationY : event.pageY - currentPosition.top }); event.preventDefault(); } function _Document_MouseMove(event){ var popupWindow = event.data.popupWindow; var settings = popupWindow.data("settings"); var currentPosition = _GetCurrentPosition(popupWindow); var currentSize = _GetCurrentSize(popupWindow); var newPosition = {}; var newSize = {}; switch (event.data.action) { case "drag": newPosition.top = event.pageY - event.data.compensationY; newPosition.left = event.pageX - event.data.compensationX; if (settings.keepInViewport) { var size = _GetCurrentSize(popupWindow); var $window = $(window); if (newPosition.top < 0) newPosition.top = 0; if (newPosition.left < 0) newPosition.left = 0; if (newPosition.top > $window.height() - size.height) newPosition.top = $window.height() - size.height; if (newPosition.left > $window.width() - size.width) newPosition.left = $window.width() - size.width; } break; case "resize": if (event.data.dimension != "height" && event.pageX > 0) { var newWidth = (event.data.directionX == "left") ? event.data.startX - event.pageX : event.pageX - event.data.startX; if (newWidth >= settings.minWidth && (!settings.maxWidth || newWidth <= settings.maxWidth)) { newSize.width = newWidth; if (event.data.directionX == "left") newPosition.left = event.pageX - event.data.compensationX; } } if (event.data.dimension != "width" && event.pageY > 0) { var newHeight = (event.data.directionY == "top") ? event.data.startY - event.pageY : event.pageY - event.data.startY; if (newHeight >= settings.minHeight && (!settings.maxHeight || newHeight <= settings.maxHeight)) { newSize.height = newHeight; if (event.data.directionY == "top") newPosition.top = event.pageY - event.data.compensationY; } } break; } if ((newPosition.top !== undefined && newPosition.top != currentPosition.top) || (newPosition.left !== undefined && newPosition.left != currentPosition.left)) { popupWindow.css(newPosition); _SetCurrentPosition(popupWindow, newPosition); if (settings.mouseMoveEvents) _TriggerEvent(popupWindow, "move"); } if ((newSize.width !== undefined && newSize.width != currentSize.width) || (newSize.height !== undefined && newSize.height != currentSize.height)) { popupWindow.outerWidth(newSize.width).outerHeight(newSize.height); _SetCurrentSize(popupWindow, newSize); if (settings.mouseMoveEvents) _TriggerEvent(popupWindow, "resize"); } } function _Document_MouseUp(event){ var popupWindow = event.data.popupWindow; var settings = popupWindow.data("settings"); popupWindow.fadeTo(0, 1); $(document) .off("mousemove", _Document_MouseMove) .off("mouseup", _Document_MouseUp); if (!settings.modal) popupWindow.data("overlay").width(0).height(0).css("background-color", ""); if (!settings.mouseMoveEvents) { var currentPosition = _GetCurrentPosition(popupWindow); var currentSize = _GetCurrentSize(popupWindow); var savedData = popupWindow.data("tempSavedData"); if (savedData.position.top != currentPosition.top || savedData.position.left != currentPosition.left) _TriggerEvent(popupWindow, "move"); if (savedData.size.width != currentSize.width || savedData.size.height != currentSize.height) _TriggerEvent(popupWindow, "resize"); popupWindow.removeData("tempSavedData"); } } $(function(){ _mainContainer = $("<div>", { class : "popupwindow_container" }) .css(_css.container) .appendTo("body"); _SetMinimizedArea(); $(window).on("resize", function(){ $(document).find(".popupwindow").each(function(){ var popupWindow = $(this); if (popupWindow.data("settings").keepInViewport) _CheckPosition(popupWindow); }); }); }); }(jQuery));
var request = require('../support/http') , app = require('../../examples/mvc'); describe('mvc', function(){ describe('GET /', function(){ it('should redirect to /users', function(done){ request(app) .get('/') .end(function(err, res){ res.should.have.status(302); res.headers.location.should.include('/users'); done(); }) }) }) describe('GET /users', function(){ it('should display a list of users', function(done){ request(app) .get('/users') .end(function(err, res){ res.text.should.include('<h1>Users</h1>'); res.text.should.include('>TJ<'); res.text.should.include('>Guillermo<'); res.text.should.include('>Nathan<'); done(); }) }) }) describe('GET /user/:id', function(){ describe('when present', function(){ it('should display the user', function(done){ request(app) .get('/user/0') .end(function(err, res){ res.text.should.include('<h1>TJ <a href="/user/0/edit">edit'); done(); }) }) it('should display the users pets', function(done){ request(app) .get('/user/0') .end(function(err, res){ res.text.should.include('/pet/0">Tobi'); res.text.should.include('/pet/1">Loki'); res.text.should.include('/pet/2">Jane'); done(); }) }) }) describe('when not present', function(){ it('should 404', function(done){ request(app) .get('/user/123') .expect(404, done); }) }) }) describe('GET /user/:id/edit', function(){ it('should display the edit form', function(done){ request(app) .get('/user/1/edit') .end(function(err, res){ res.text.should.include('<h1>Guillermo</h1>'); res.text.should.include('value="put"'); done(); }) }) }) describe('PUT /user/:id', function(){ it('should update the user', function(done){ request(app) .put('/user/1') .send({ user: { name: 'Tobo' }}) .end(function(err, res){ request(app) .get('/user/1/edit') .end(function(err, res){ res.text.should.include('<h1>Tobo</h1>'); done(); }) }) }) }) })
SVG.ViewBox = function(element) { var x, y, width, height , wm = 1 /* width multiplier */ , hm = 1 /* height multiplier */ , box = element.bbox() , view = (element.attr('viewBox') || '').match(/-?[\d\.]+/g) , we = element , he = element /* get dimensions of current node */ width = new SVG.Number(element.width()) height = new SVG.Number(element.height()) /* find nearest non-percentual dimensions */ while (width.unit == '%') { wm *= width.value width = new SVG.Number(we instanceof SVG.Doc ? we.parent().offsetWidth : we.parent().width()) we = we.parent() } while (height.unit == '%') { hm *= height.value height = new SVG.Number(he instanceof SVG.Doc ? he.parent().offsetHeight : he.parent().height()) he = he.parent() } /* ensure defaults */ this.x = box.x this.y = box.y this.width = width * wm this.height = height * hm this.zoom = 1 if (view) { /* get width and height from viewbox */ x = parseFloat(view[0]) y = parseFloat(view[1]) width = parseFloat(view[2]) height = parseFloat(view[3]) /* calculate zoom accoring to viewbox */ this.zoom = ((this.width / this.height) > (width / height)) ? this.height / height : this.width / width /* calculate real pixel dimensions on parent SVG.Doc element */ this.x = x this.y = y this.width = width this.height = height } } // SVG.extend(SVG.ViewBox, { // Parse viewbox to string toString: function() { return this.x + ' ' + this.y + ' ' + this.width + ' ' + this.height } })
/* Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'clipboard', 'vi', { copy: 'Sao chép', copyError: 'Các thiết lập bảo mật của trình duyệt không cho phép trình biên tập tự động thực thi lệnh sao chép. Hãy sử dụng bàn phím cho lệnh này (Ctrl/Cmd+C).', cut: 'Cắt', cutError: 'Các thiết lập bảo mật của trình duyệt không cho phép trình biên tập tự động thực thi lệnh cắt. Hãy sử dụng bàn phím cho lệnh này (Ctrl/Cmd+X).', paste: 'Dán', pasteArea: 'Khu vực dán', pasteMsg: 'Hãy dán nội dung vào trong khung bên dưới, sử dụng tổ hợp phím (<STRONG>Ctrl/Cmd+V</STRONG>) và nhấn vào nút <STRONG>Đồng ý</STRONG>.', securityMsg: 'Do thiết lập bảo mật của trình duyệt nên trình biên tập không thể truy cập trực tiếp vào nội dung đã sao chép. Bạn cần phải dán lại nội dung vào cửa sổ này.', title: 'Dán' } );
!function() { var d3 = { version: "3.5.5" }; var d3_arraySlice = [].slice, d3_array = function(list) { return d3_arraySlice.call(list); }; var d3_document = this.document; function d3_documentElement(node) { return node && (node.ownerDocument || node.document || node).documentElement; } function d3_window(node) { return node && (node.ownerDocument && node.ownerDocument.defaultView || node.document && node || node.defaultView); } if (d3_document) { try { d3_array(d3_document.documentElement.childNodes)[0].nodeType; } catch (e) { d3_array = function(list) { var i = list.length, array = new Array(i); while (i--) array[i] = list[i]; return array; }; } } if (!Date.now) Date.now = function() { return +new Date(); }; if (d3_document) { try { d3_document.createElement("DIV").style.setProperty("opacity", 0, ""); } catch (error) { var d3_element_prototype = this.Element.prototype, d3_element_setAttribute = d3_element_prototype.setAttribute, d3_element_setAttributeNS = d3_element_prototype.setAttributeNS, d3_style_prototype = this.CSSStyleDeclaration.prototype, d3_style_setProperty = d3_style_prototype.setProperty; d3_element_prototype.setAttribute = function(name, value) { d3_element_setAttribute.call(this, name, value + ""); }; d3_element_prototype.setAttributeNS = function(space, local, value) { d3_element_setAttributeNS.call(this, space, local, value + ""); }; d3_style_prototype.setProperty = function(name, value, priority) { d3_style_setProperty.call(this, name, value + "", priority); }; } } d3.ascending = d3_ascending; function d3_ascending(a, b) { return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN; } d3.descending = function(a, b) { return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN; }; d3.min = function(array, f) { var i = -1, n = array.length, a, b; if (arguments.length === 1) { while (++i < n) if ((b = array[i]) != null && b >= b) { a = b; break; } while (++i < n) if ((b = array[i]) != null && a > b) a = b; } else { while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) { a = b; break; } while (++i < n) if ((b = f.call(array, array[i], i)) != null && a > b) a = b; } return a; }; d3.max = function(array, f) { var i = -1, n = array.length, a, b; if (arguments.length === 1) { while (++i < n) if ((b = array[i]) != null && b >= b) { a = b; break; } while (++i < n) if ((b = array[i]) != null && b > a) a = b; } else { while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) { a = b; break; } while (++i < n) if ((b = f.call(array, array[i], i)) != null && b > a) a = b; } return a; }; d3.extent = function(array, f) { var i = -1, n = array.length, a, b, c; if (arguments.length === 1) { while (++i < n) if ((b = array[i]) != null && b >= b) { a = c = b; break; } while (++i < n) if ((b = array[i]) != null) { if (a > b) a = b; if (c < b) c = b; } } else { while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) { a = c = b; break; } while (++i < n) if ((b = f.call(array, array[i], i)) != null) { if (a > b) a = b; if (c < b) c = b; } } return [ a, c ]; }; function d3_number(x) { return x === null ? NaN : +x; } function d3_numeric(x) { return !isNaN(x); } d3.sum = function(array, f) { var s = 0, n = array.length, a, i = -1; if (arguments.length === 1) { while (++i < n) if (d3_numeric(a = +array[i])) s += a; } else { while (++i < n) if (d3_numeric(a = +f.call(array, array[i], i))) s += a; } return s; }; d3.mean = function(array, f) { var s = 0, n = array.length, a, i = -1, j = n; if (arguments.length === 1) { while (++i < n) if (d3_numeric(a = d3_number(array[i]))) s += a; else --j; } else { while (++i < n) if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) s += a; else --j; } if (j) return s / j; }; d3.quantile = function(values, p) { var H = (values.length - 1) * p + 1, h = Math.floor(H), v = +values[h - 1], e = H - h; return e ? v + e * (values[h] - v) : v; }; d3.median = function(array, f) { var numbers = [], n = array.length, a, i = -1; if (arguments.length === 1) { while (++i < n) if (d3_numeric(a = d3_number(array[i]))) numbers.push(a); } else { while (++i < n) if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) numbers.push(a); } if (numbers.length) return d3.quantile(numbers.sort(d3_ascending), .5); }; d3.variance = function(array, f) { var n = array.length, m = 0, a, d, s = 0, i = -1, j = 0; if (arguments.length === 1) { while (++i < n) { if (d3_numeric(a = d3_number(array[i]))) { d = a - m; m += d / ++j; s += d * (a - m); } } } else { while (++i < n) { if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) { d = a - m; m += d / ++j; s += d * (a - m); } } } if (j > 1) return s / (j - 1); }; d3.deviation = function() { var v = d3.variance.apply(this, arguments); return v ? Math.sqrt(v) : v; }; function d3_bisector(compare) { return { left: function(a, x, lo, hi) { if (arguments.length < 3) lo = 0; if (arguments.length < 4) hi = a.length; while (lo < hi) { var mid = lo + hi >>> 1; if (compare(a[mid], x) < 0) lo = mid + 1; else hi = mid; } return lo; }, right: function(a, x, lo, hi) { if (arguments.length < 3) lo = 0; if (arguments.length < 4) hi = a.length; while (lo < hi) { var mid = lo + hi >>> 1; if (compare(a[mid], x) > 0) hi = mid; else lo = mid + 1; } return lo; } }; } var d3_bisect = d3_bisector(d3_ascending); d3.bisectLeft = d3_bisect.left; d3.bisect = d3.bisectRight = d3_bisect.right; d3.bisector = function(f) { return d3_bisector(f.length === 1 ? function(d, x) { return d3_ascending(f(d), x); } : f); }; d3.shuffle = function(array, i0, i1) { if ((m = arguments.length) < 3) { i1 = array.length; if (m < 2) i0 = 0; } var m = i1 - i0, t, i; while (m) { i = Math.random() * m-- | 0; t = array[m + i0], array[m + i0] = array[i + i0], array[i + i0] = t; } return array; }; d3.permute = function(array, indexes) { var i = indexes.length, permutes = new Array(i); while (i--) permutes[i] = array[indexes[i]]; return permutes; }; d3.pairs = function(array) { var i = 0, n = array.length - 1, p0, p1 = array[0], pairs = new Array(n < 0 ? 0 : n); while (i < n) pairs[i] = [ p0 = p1, p1 = array[++i] ]; return pairs; }; d3.zip = function() { if (!(n = arguments.length)) return []; for (var i = -1, m = d3.min(arguments, d3_zipLength), zips = new Array(m); ++i < m; ) { for (var j = -1, n, zip = zips[i] = new Array(n); ++j < n; ) { zip[j] = arguments[j][i]; } } return zips; }; function d3_zipLength(d) { return d.length; } d3.transpose = function(matrix) { return d3.zip.apply(d3, matrix); }; d3.keys = function(map) { var keys = []; for (var key in map) keys.push(key); return keys; }; d3.values = function(map) { var values = []; for (var key in map) values.push(map[key]); return values; }; d3.entries = function(map) { var entries = []; for (var key in map) entries.push({ key: key, value: map[key] }); return entries; }; d3.merge = function(arrays) { var n = arrays.length, m, i = -1, j = 0, merged, array; while (++i < n) j += arrays[i].length; merged = new Array(j); while (--n >= 0) { array = arrays[n]; m = array.length; while (--m >= 0) { merged[--j] = array[m]; } } return merged; }; var abs = Math.abs; d3.range = function(start, stop, step) { if (arguments.length < 3) { step = 1; if (arguments.length < 2) { stop = start; start = 0; } } if ((stop - start) / step === Infinity) throw new Error("infinite range"); var range = [], k = d3_range_integerScale(abs(step)), i = -1, j; start *= k, stop *= k, step *= k; if (step < 0) while ((j = start + step * ++i) > stop) range.push(j / k); else while ((j = start + step * ++i) < stop) range.push(j / k); return range; }; function d3_range_integerScale(x) { var k = 1; while (x * k % 1) k *= 10; return k; } function d3_class(ctor, properties) { for (var key in properties) { Object.defineProperty(ctor.prototype, key, { value: properties[key], enumerable: false }); } } d3.map = function(object, f) { var map = new d3_Map(); if (object instanceof d3_Map) { object.forEach(function(key, value) { map.set(key, value); }); } else if (Array.isArray(object)) { var i = -1, n = object.length, o; if (arguments.length === 1) while (++i < n) map.set(i, object[i]); else while (++i < n) map.set(f.call(object, o = object[i], i), o); } else { for (var key in object) map.set(key, object[key]); } return map; }; function d3_Map() { this._ = Object.create(null); } var d3_map_proto = "__proto__", d3_map_zero = "\x00"; d3_class(d3_Map, { has: d3_map_has, get: function(key) { return this._[d3_map_escape(key)]; }, set: function(key, value) { return this._[d3_map_escape(key)] = value; }, remove: d3_map_remove, keys: d3_map_keys, values: function() { var values = []; for (var key in this._) values.push(this._[key]); return values; }, entries: function() { var entries = []; for (var key in this._) entries.push({ key: d3_map_unescape(key), value: this._[key] }); return entries; }, size: d3_map_size, empty: d3_map_empty, forEach: function(f) { for (var key in this._) f.call(this, d3_map_unescape(key), this._[key]); } }); function d3_map_escape(key) { return (key += "") === d3_map_proto || key[0] === d3_map_zero ? d3_map_zero + key : key; } function d3_map_unescape(key) { return (key += "")[0] === d3_map_zero ? key.slice(1) : key; } function d3_map_has(key) { return d3_map_escape(key) in this._; } function d3_map_remove(key) { return (key = d3_map_escape(key)) in this._ && delete this._[key]; } function d3_map_keys() { var keys = []; for (var key in this._) keys.push(d3_map_unescape(key)); return keys; } function d3_map_size() { var size = 0; for (var key in this._) ++size; return size; } function d3_map_empty() { for (var key in this._) return false; return true; } d3.nest = function() { var nest = {}, keys = [], sortKeys = [], sortValues, rollup; function map(mapType, array, depth) { if (depth >= keys.length) return rollup ? rollup.call(nest, array) : sortValues ? array.sort(sortValues) : array; var i = -1, n = array.length, key = keys[depth++], keyValue, object, setter, valuesByKey = new d3_Map(), values; while (++i < n) { if (values = valuesByKey.get(keyValue = key(object = array[i]))) { values.push(object); } else { valuesByKey.set(keyValue, [ object ]); } } if (mapType) { object = mapType(); setter = function(keyValue, values) { object.set(keyValue, map(mapType, values, depth)); }; } else { object = {}; setter = function(keyValue, values) { object[keyValue] = map(mapType, values, depth); }; } valuesByKey.forEach(setter); return object; } function entries(map, depth) { if (depth >= keys.length) return map; var array = [], sortKey = sortKeys[depth++]; map.forEach(function(key, keyMap) { array.push({ key: key, values: entries(keyMap, depth) }); }); return sortKey ? array.sort(function(a, b) { return sortKey(a.key, b.key); }) : array; } nest.map = function(array, mapType) { return map(mapType, array, 0); }; nest.entries = function(array) { return entries(map(d3.map, array, 0), 0); }; nest.key = function(d) { keys.push(d); return nest; }; nest.sortKeys = function(order) { sortKeys[keys.length - 1] = order; return nest; }; nest.sortValues = function(order) { sortValues = order; return nest; }; nest.rollup = function(f) { rollup = f; return nest; }; return nest; }; d3.set = function(array) { var set = new d3_Set(); if (array) for (var i = 0, n = array.length; i < n; ++i) set.add(array[i]); return set; }; function d3_Set() { this._ = Object.create(null); } d3_class(d3_Set, { has: d3_map_has, add: function(key) { this._[d3_map_escape(key += "")] = true; return key; }, remove: d3_map_remove, values: d3_map_keys, size: d3_map_size, empty: d3_map_empty, forEach: function(f) { for (var key in this._) f.call(this, d3_map_unescape(key)); } }); d3.behavior = {}; function d3_identity(d) { return d; } d3.rebind = function(target, source) { var i = 1, n = arguments.length, method; while (++i < n) target[method = arguments[i]] = d3_rebind(target, source, source[method]); return target; }; function d3_rebind(target, source, method) { return function() { var value = method.apply(source, arguments); return value === source ? target : value; }; } function d3_vendorSymbol(object, name) { if (name in object) return name; name = name.charAt(0).toUpperCase() + name.slice(1); for (var i = 0, n = d3_vendorPrefixes.length; i < n; ++i) { var prefixName = d3_vendorPrefixes[i] + name; if (prefixName in object) return prefixName; } } var d3_vendorPrefixes = [ "webkit", "ms", "moz", "Moz", "o", "O" ]; function d3_noop() {} d3.dispatch = function() { var dispatch = new d3_dispatch(), i = -1, n = arguments.length; while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch); return dispatch; }; function d3_dispatch() {} d3_dispatch.prototype.on = function(type, listener) { var i = type.indexOf("."), name = ""; if (i >= 0) { name = type.slice(i + 1); type = type.slice(0, i); } if (type) return arguments.length < 2 ? this[type].on(name) : this[type].on(name, listener); if (arguments.length === 2) { if (listener == null) for (type in this) { if (this.hasOwnProperty(type)) this[type].on(name, null); } return this; } }; function d3_dispatch_event(dispatch) { var listeners = [], listenerByName = new d3_Map(); function event() { var z = listeners, i = -1, n = z.length, l; while (++i < n) if (l = z[i].on) l.apply(this, arguments); return dispatch; } event.on = function(name, listener) { var l = listenerByName.get(name), i; if (arguments.length < 2) return l && l.on; if (l) { l.on = null; listeners = listeners.slice(0, i = listeners.indexOf(l)).concat(listeners.slice(i + 1)); listenerByName.remove(name); } if (listener) listeners.push(listenerByName.set(name, { on: listener })); return dispatch; }; return event; } d3.event = null; function d3_eventPreventDefault() { d3.event.preventDefault(); } function d3_eventSource() { var e = d3.event, s; while (s = e.sourceEvent) e = s; return e; } function d3_eventDispatch(target) { var dispatch = new d3_dispatch(), i = 0, n = arguments.length; while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch); dispatch.of = function(thiz, argumentz) { return function(e1) { try { var e0 = e1.sourceEvent = d3.event; e1.target = target; d3.event = e1; dispatch[e1.type].apply(thiz, argumentz); } finally { d3.event = e0; } }; }; return dispatch; } d3.requote = function(s) { return s.replace(d3_requote_re, "\\$&"); }; var d3_requote_re = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g; var d3_subclass = {}.__proto__ ? function(object, prototype) { object.__proto__ = prototype; } : function(object, prototype) { for (var property in prototype) object[property] = prototype[property]; }; function d3_selection(groups) { d3_subclass(groups, d3_selectionPrototype); return groups; } var d3_select = function(s, n) { return n.querySelector(s); }, d3_selectAll = function(s, n) { return n.querySelectorAll(s); }, d3_selectMatches = function(n, s) { var d3_selectMatcher = n.matches || n[d3_vendorSymbol(n, "matchesSelector")]; d3_selectMatches = function(n, s) { return d3_selectMatcher.call(n, s); }; return d3_selectMatches(n, s); }; if (typeof Sizzle === "function") { d3_select = function(s, n) { return Sizzle(s, n)[0] || null; }; d3_selectAll = Sizzle; d3_selectMatches = Sizzle.matchesSelector; } d3.selection = function() { return d3.select(d3_document.documentElement); }; var d3_selectionPrototype = d3.selection.prototype = []; d3_selectionPrototype.select = function(selector) { var subgroups = [], subgroup, subnode, group, node; selector = d3_selection_selector(selector); for (var j = -1, m = this.length; ++j < m; ) { subgroups.push(subgroup = []); subgroup.parentNode = (group = this[j]).parentNode; for (var i = -1, n = group.length; ++i < n; ) { if (node = group[i]) { subgroup.push(subnode = selector.call(node, node.__data__, i, j)); if (subnode && "__data__" in node) subnode.__data__ = node.__data__; } else { subgroup.push(null); } } } return d3_selection(subgroups); }; function d3_selection_selector(selector) { return typeof selector === "function" ? selector : function() { return d3_select(selector, this); }; } d3_selectionPrototype.selectAll = function(selector) { var subgroups = [], subgroup, node; selector = d3_selection_selectorAll(selector); for (var j = -1, m = this.length; ++j < m; ) { for (var group = this[j], i = -1, n = group.length; ++i < n; ) { if (node = group[i]) { subgroups.push(subgroup = d3_array(selector.call(node, node.__data__, i, j))); subgroup.parentNode = node; } } } return d3_selection(subgroups); }; function d3_selection_selectorAll(selector) { return typeof selector === "function" ? selector : function() { return d3_selectAll(selector, this); }; } var d3_nsPrefix = { svg: "http://www.w3.org/2000/svg", xhtml: "http://www.w3.org/1999/xhtml", xlink: "http://www.w3.org/1999/xlink", xml: "http://www.w3.org/XML/1998/namespace", xmlns: "http://www.w3.org/2000/xmlns/" }; d3.ns = { prefix: d3_nsPrefix, qualify: function(name) { var i = name.indexOf(":"), prefix = name; if (i >= 0) { prefix = name.slice(0, i); name = name.slice(i + 1); } return d3_nsPrefix.hasOwnProperty(prefix) ? { space: d3_nsPrefix[prefix], local: name } : name; } }; d3_selectionPrototype.attr = function(name, value) { if (arguments.length < 2) { if (typeof name === "string") { var node = this.node(); name = d3.ns.qualify(name); return name.local ? node.getAttributeNS(name.space, name.local) : node.getAttribute(name); } for (value in name) this.each(d3_selection_attr(value, name[value])); return this; } return this.each(d3_selection_attr(name, value)); }; function d3_selection_attr(name, value) { name = d3.ns.qualify(name); function attrNull() { this.removeAttribute(name); } function attrNullNS() { this.removeAttributeNS(name.space, name.local); } function attrConstant() { this.setAttribute(name, value); } function attrConstantNS() { this.setAttributeNS(name.space, name.local, value); } function attrFunction() { var x = value.apply(this, arguments); if (x == null) this.removeAttribute(name); else this.setAttribute(name, x); } function attrFunctionNS() { var x = value.apply(this, arguments); if (x == null) this.removeAttributeNS(name.space, name.local); else this.setAttributeNS(name.space, name.local, x); } return value == null ? name.local ? attrNullNS : attrNull : typeof value === "function" ? name.local ? attrFunctionNS : attrFunction : name.local ? attrConstantNS : attrConstant; } function d3_collapse(s) { return s.trim().replace(/\s+/g, " "); } d3_selectionPrototype.classed = function(name, value) { if (arguments.length < 2) { if (typeof name === "string") { var node = this.node(), n = (name = d3_selection_classes(name)).length, i = -1; if (value = node.classList) { while (++i < n) if (!value.contains(name[i])) return false; } else { value = node.getAttribute("class"); while (++i < n) if (!d3_selection_classedRe(name[i]).test(value)) return false; } return true; } for (value in name) this.each(d3_selection_classed(value, name[value])); return this; } return this.each(d3_selection_classed(name, value)); }; function d3_selection_classedRe(name) { return new RegExp("(?:^|\\s+)" + d3.requote(name) + "(?:\\s+|$)", "g"); } function d3_selection_classes(name) { return (name + "").trim().split(/^|\s+/); } function d3_selection_classed(name, value) { name = d3_selection_classes(name).map(d3_selection_classedName); var n = name.length; function classedConstant() { var i = -1; while (++i < n) name[i](this, value); } function classedFunction() { var i = -1, x = value.apply(this, arguments); while (++i < n) name[i](this, x); } return typeof value === "function" ? classedFunction : classedConstant; } function d3_selection_classedName(name) { var re = d3_selection_classedRe(name); return function(node, value) { if (c = node.classList) return value ? c.add(name) : c.remove(name); var c = node.getAttribute("class") || ""; if (value) { re.lastIndex = 0; if (!re.test(c)) node.setAttribute("class", d3_collapse(c + " " + name)); } else { node.setAttribute("class", d3_collapse(c.replace(re, " "))); } }; } d3_selectionPrototype.style = function(name, value, priority) { var n = arguments.length; if (n < 3) { if (typeof name !== "string") { if (n < 2) value = ""; for (priority in name) this.each(d3_selection_style(priority, name[priority], value)); return this; } if (n < 2) { var node = this.node(); return d3_window(node).getComputedStyle(node, null).getPropertyValue(name); } priority = ""; } return this.each(d3_selection_style(name, value, priority)); }; function d3_selection_style(name, value, priority) { function styleNull() { this.style.removeProperty(name); } function styleConstant() { this.style.setProperty(name, value, priority); } function styleFunction() { var x = value.apply(this, arguments); if (x == null) this.style.removeProperty(name); else this.style.setProperty(name, x, priority); } return value == null ? styleNull : typeof value === "function" ? styleFunction : styleConstant; } d3_selectionPrototype.property = function(name, value) { if (arguments.length < 2) { if (typeof name === "string") return this.node()[name]; for (value in name) this.each(d3_selection_property(value, name[value])); return this; } return this.each(d3_selection_property(name, value)); }; function d3_selection_property(name, value) { function propertyNull() { delete this[name]; } function propertyConstant() { this[name] = value; } function propertyFunction() { var x = value.apply(this, arguments); if (x == null) delete this[name]; else this[name] = x; } return value == null ? propertyNull : typeof value === "function" ? propertyFunction : propertyConstant; } d3_selectionPrototype.text = function(value) { return arguments.length ? this.each(typeof value === "function" ? function() { var v = value.apply(this, arguments); this.textContent = v == null ? "" : v; } : value == null ? function() { this.textContent = ""; } : function() { this.textContent = value; }) : this.node().textContent; }; d3_selectionPrototype.html = function(value) { return arguments.length ? this.each(typeof value === "function" ? function() { var v = value.apply(this, arguments); this.innerHTML = v == null ? "" : v; } : value == null ? function() { this.innerHTML = ""; } : function() { this.innerHTML = value; }) : this.node().innerHTML; }; d3_selectionPrototype.append = function(name) { name = d3_selection_creator(name); return this.select(function() { return this.appendChild(name.apply(this, arguments)); }); }; function d3_selection_creator(name) { function create() { var document = this.ownerDocument, namespace = this.namespaceURI; return namespace ? document.createElementNS(namespace, name) : document.createElement(name); } function createNS() { return this.ownerDocument.createElementNS(name.space, name.local); } return typeof name === "function" ? name : (name = d3.ns.qualify(name)).local ? createNS : create; } d3_selectionPrototype.insert = function(name, before) { name = d3_selection_creator(name); before = d3_selection_selector(before); return this.select(function() { return this.insertBefore(name.apply(this, arguments), before.apply(this, arguments) || null); }); }; d3_selectionPrototype.remove = function() { return this.each(d3_selectionRemove); }; function d3_selectionRemove() { var parent = this.parentNode; if (parent) parent.removeChild(this); } d3_selectionPrototype.data = function(value, key) { var i = -1, n = this.length, group, node; if (!arguments.length) { value = new Array(n = (group = this[0]).length); while (++i < n) { if (node = group[i]) { value[i] = node.__data__; } } return value; } function bind(group, groupData) { var i, n = group.length, m = groupData.length, n0 = Math.min(n, m), updateNodes = new Array(m), enterNodes = new Array(m), exitNodes = new Array(n), node, nodeData; if (key) { var nodeByKeyValue = new d3_Map(), keyValues = new Array(n), keyValue; for (i = -1; ++i < n; ) { if (nodeByKeyValue.has(keyValue = key.call(node = group[i], node.__data__, i))) { exitNodes[i] = node; } else { nodeByKeyValue.set(keyValue, node); } keyValues[i] = keyValue; } for (i = -1; ++i < m; ) { if (!(node = nodeByKeyValue.get(keyValue = key.call(groupData, nodeData = groupData[i], i)))) { enterNodes[i] = d3_selection_dataNode(nodeData); } else if (node !== true) { updateNodes[i] = node; node.__data__ = nodeData; } nodeByKeyValue.set(keyValue, true); } for (i = -1; ++i < n; ) { if (nodeByKeyValue.get(keyValues[i]) !== true) { exitNodes[i] = group[i]; } } } else { for (i = -1; ++i < n0; ) { node = group[i]; nodeData = groupData[i]; if (node) { node.__data__ = nodeData; updateNodes[i] = node; } else { enterNodes[i] = d3_selection_dataNode(nodeData); } } for (;i < m; ++i) { enterNodes[i] = d3_selection_dataNode(groupData[i]); } for (;i < n; ++i) { exitNodes[i] = group[i]; } } enterNodes.update = updateNodes; enterNodes.parentNode = updateNodes.parentNode = exitNodes.parentNode = group.parentNode; enter.push(enterNodes); update.push(updateNodes); exit.push(exitNodes); } var enter = d3_selection_enter([]), update = d3_selection([]), exit = d3_selection([]); if (typeof value === "function") { while (++i < n) { bind(group = this[i], value.call(group, group.parentNode.__data__, i)); } } else { while (++i < n) { bind(group = this[i], value); } } update.enter = function() { return enter; }; update.exit = function() { return exit; }; return update; }; function d3_selection_dataNode(data) { return { __data__: data }; } d3_selectionPrototype.datum = function(value) { return arguments.length ? this.property("__data__", value) : this.property("__data__"); }; d3_selectionPrototype.filter = function(filter) { var subgroups = [], subgroup, group, node; if (typeof filter !== "function") filter = d3_selection_filter(filter); for (var j = 0, m = this.length; j < m; j++) { subgroups.push(subgroup = []); subgroup.parentNode = (group = this[j]).parentNode; for (var i = 0, n = group.length; i < n; i++) { if ((node = group[i]) && filter.call(node, node.__data__, i, j)) { subgroup.push(node); } } } return d3_selection(subgroups); }; function d3_selection_filter(selector) { return function() { return d3_selectMatches(this, selector); }; } d3_selectionPrototype.order = function() { for (var j = -1, m = this.length; ++j < m; ) { for (var group = this[j], i = group.length - 1, next = group[i], node; --i >= 0; ) { if (node = group[i]) { if (next && next !== node.nextSibling) next.parentNode.insertBefore(node, next); next = node; } } } return this; }; d3_selectionPrototype.sort = function(comparator) { comparator = d3_selection_sortComparator.apply(this, arguments); for (var j = -1, m = this.length; ++j < m; ) this[j].sort(comparator); return this.order(); }; function d3_selection_sortComparator(comparator) { if (!arguments.length) comparator = d3_ascending; return function(a, b) { return a && b ? comparator(a.__data__, b.__data__) : !a - !b; }; } d3_selectionPrototype.each = function(callback) { return d3_selection_each(this, function(node, i, j) { callback.call(node, node.__data__, i, j); }); }; function d3_selection_each(groups, callback) { for (var j = 0, m = groups.length; j < m; j++) { for (var group = groups[j], i = 0, n = group.length, node; i < n; i++) { if (node = group[i]) callback(node, i, j); } } return groups; } d3_selectionPrototype.call = function(callback) { var args = d3_array(arguments); callback.apply(args[0] = this, args); return this; }; d3_selectionPrototype.empty = function() { return !this.node(); }; d3_selectionPrototype.node = function() { for (var j = 0, m = this.length; j < m; j++) { for (var group = this[j], i = 0, n = group.length; i < n; i++) { var node = group[i]; if (node) return node; } } return null; }; d3_selectionPrototype.size = function() { var n = 0; d3_selection_each(this, function() { ++n; }); return n; }; function d3_selection_enter(selection) { d3_subclass(selection, d3_selection_enterPrototype); return selection; } var d3_selection_enterPrototype = []; d3.selection.enter = d3_selection_enter; d3.selection.enter.prototype = d3_selection_enterPrototype; d3_selection_enterPrototype.append = d3_selectionPrototype.append; d3_selection_enterPrototype.empty = d3_selectionPrototype.empty; d3_selection_enterPrototype.node = d3_selectionPrototype.node; d3_selection_enterPrototype.call = d3_selectionPrototype.call; d3_selection_enterPrototype.size = d3_selectionPrototype.size; d3_selection_enterPrototype.select = function(selector) { var subgroups = [], subgroup, subnode, upgroup, group, node; for (var j = -1, m = this.length; ++j < m; ) { upgroup = (group = this[j]).update; subgroups.push(subgroup = []); subgroup.parentNode = group.parentNode; for (var i = -1, n = group.length; ++i < n; ) { if (node = group[i]) { subgroup.push(upgroup[i] = subnode = selector.call(group.parentNode, node.__data__, i, j)); subnode.__data__ = node.__data__; } else { subgroup.push(null); } } } return d3_selection(subgroups); }; d3_selection_enterPrototype.insert = function(name, before) { if (arguments.length < 2) before = d3_selection_enterInsertBefore(this); return d3_selectionPrototype.insert.call(this, name, before); }; function d3_selection_enterInsertBefore(enter) { var i0, j0; return function(d, i, j) { var group = enter[j].update, n = group.length, node; if (j != j0) j0 = j, i0 = 0; if (i >= i0) i0 = i + 1; while (!(node = group[i0]) && ++i0 < n) ; return node; }; } d3.select = function(node) { var group; if (typeof node === "string") { group = [ d3_select(node, d3_document) ]; group.parentNode = d3_document.documentElement; } else { group = [ node ]; group.parentNode = d3_documentElement(node); } return d3_selection([ group ]); }; d3.selectAll = function(nodes) { var group; if (typeof nodes === "string") { group = d3_array(d3_selectAll(nodes, d3_document)); group.parentNode = d3_document.documentElement; } else { group = nodes; group.parentNode = null; } return d3_selection([ group ]); }; d3_selectionPrototype.on = function(type, listener, capture) { var n = arguments.length; if (n < 3) { if (typeof type !== "string") { if (n < 2) listener = false; for (capture in type) this.each(d3_selection_on(capture, type[capture], listener)); return this; } if (n < 2) return (n = this.node()["__on" + type]) && n._; capture = false; } return this.each(d3_selection_on(type, listener, capture)); }; function d3_selection_on(type, listener, capture) { var name = "__on" + type, i = type.indexOf("."), wrap = d3_selection_onListener; if (i > 0) type = type.slice(0, i); var filter = d3_selection_onFilters.get(type); if (filter) type = filter, wrap = d3_selection_onFilter; function onRemove() { var l = this[name]; if (l) { this.removeEventListener(type, l, l.$); delete this[name]; } } function onAdd() { var l = wrap(listener, d3_array(arguments)); onRemove.call(this); this.addEventListener(type, this[name] = l, l.$ = capture); l._ = listener; } function removeAll() { var re = new RegExp("^__on([^.]+)" + d3.requote(type) + "$"), match; for (var name in this) { if (match = name.match(re)) { var l = this[name]; this.removeEventListener(match[1], l, l.$); delete this[name]; } } } return i ? listener ? onAdd : onRemove : listener ? d3_noop : removeAll; } var d3_selection_onFilters = d3.map({ mouseenter: "mouseover", mouseleave: "mouseout" }); if (d3_document) { d3_selection_onFilters.forEach(function(k) { if ("on" + k in d3_document) d3_selection_onFilters.remove(k); }); } function d3_selection_onListener(listener, argumentz) { return function(e) { var o = d3.event; d3.event = e; argumentz[0] = this.__data__; try { listener.apply(this, argumentz); } finally { d3.event = o; } }; } function d3_selection_onFilter(listener, argumentz) { var l = d3_selection_onListener(listener, argumentz); return function(e) { var target = this, related = e.relatedTarget; if (!related || related !== target && !(related.compareDocumentPosition(target) & 8)) { l.call(target, e); } }; } var d3_event_dragSelect, d3_event_dragId = 0; function d3_event_dragSuppress(node) { var name = ".dragsuppress-" + ++d3_event_dragId, click = "click" + name, w = d3.select(d3_window(node)).on("touchmove" + name, d3_eventPreventDefault).on("dragstart" + name, d3_eventPreventDefault).on("selectstart" + name, d3_eventPreventDefault); if (d3_event_dragSelect == null) { d3_event_dragSelect = "onselectstart" in node ? false : d3_vendorSymbol(node.style, "userSelect"); } if (d3_event_dragSelect) { var style = d3_documentElement(node).style, select = style[d3_event_dragSelect]; style[d3_event_dragSelect] = "none"; } return function(suppressClick) { w.on(name, null); if (d3_event_dragSelect) style[d3_event_dragSelect] = select; if (suppressClick) { var off = function() { w.on(click, null); }; w.on(click, function() { d3_eventPreventDefault(); off(); }, true); setTimeout(off, 0); } }; } d3.mouse = function(container) { return d3_mousePoint(container, d3_eventSource()); }; var d3_mouse_bug44083 = this.navigator && /WebKit/.test(this.navigator.userAgent) ? -1 : 0; function d3_mousePoint(container, e) { if (e.changedTouches) e = e.changedTouches[0]; var svg = container.ownerSVGElement || container; if (svg.createSVGPoint) { var point = svg.createSVGPoint(); if (d3_mouse_bug44083 < 0) { var window = d3_window(container); if (window.scrollX || window.scrollY) { svg = d3.select("body").append("svg").style({ position: "absolute", top: 0, left: 0, margin: 0, padding: 0, border: "none" }, "important"); var ctm = svg[0][0].getScreenCTM(); d3_mouse_bug44083 = !(ctm.f || ctm.e); svg.remove(); } } if (d3_mouse_bug44083) point.x = e.pageX, point.y = e.pageY; else point.x = e.clientX, point.y = e.clientY; point = point.matrixTransform(container.getScreenCTM().inverse()); return [ point.x, point.y ]; } var rect = container.getBoundingClientRect(); return [ e.clientX - rect.left - container.clientLeft, e.clientY - rect.top - container.clientTop ]; } d3.touch = function(container, touches, identifier) { if (arguments.length < 3) identifier = touches, touches = d3_eventSource().changedTouches; if (touches) for (var i = 0, n = touches.length, touch; i < n; ++i) { if ((touch = touches[i]).identifier === identifier) { return d3_mousePoint(container, touch); } } }; d3.behavior.drag = function() { var event = d3_eventDispatch(drag, "drag", "dragstart", "dragend"), origin = null, mousedown = dragstart(d3_noop, d3.mouse, d3_window, "mousemove", "mouseup"), touchstart = dragstart(d3_behavior_dragTouchId, d3.touch, d3_identity, "touchmove", "touchend"); function drag() { this.on("mousedown.drag", mousedown).on("touchstart.drag", touchstart); } function dragstart(id, position, subject, move, end) { return function() { var that = this, target = d3.event.target, parent = that.parentNode, dispatch = event.of(that, arguments), dragged = 0, dragId = id(), dragName = ".drag" + (dragId == null ? "" : "-" + dragId), dragOffset, dragSubject = d3.select(subject(target)).on(move + dragName, moved).on(end + dragName, ended), dragRestore = d3_event_dragSuppress(target), position0 = position(parent, dragId); if (origin) { dragOffset = origin.apply(that, arguments); dragOffset = [ dragOffset.x - position0[0], dragOffset.y - position0[1] ]; } else { dragOffset = [ 0, 0 ]; } dispatch({ type: "dragstart" }); function moved() { var position1 = position(parent, dragId), dx, dy; if (!position1) return; dx = position1[0] - position0[0]; dy = position1[1] - position0[1]; dragged |= dx | dy; position0 = position1; dispatch({ type: "drag", x: position1[0] + dragOffset[0], y: position1[1] + dragOffset[1], dx: dx, dy: dy }); } function ended() { if (!position(parent, dragId)) return; dragSubject.on(move + dragName, null).on(end + dragName, null); dragRestore(dragged && d3.event.target === target); dispatch({ type: "dragend" }); } }; } drag.origin = function(x) { if (!arguments.length) return origin; origin = x; return drag; }; return d3.rebind(drag, event, "on"); }; function d3_behavior_dragTouchId() { return d3.event.changedTouches[0].identifier; } d3.touches = function(container, touches) { if (arguments.length < 2) touches = d3_eventSource().touches; return touches ? d3_array(touches).map(function(touch) { var point = d3_mousePoint(container, touch); point.identifier = touch.identifier; return point; }) : []; }; var ε = 1e-6, ε2 = ε * ε, π = Math.PI, τ = 2 * π, τε = τ - ε, halfπ = π / 2, d3_radians = π / 180, d3_degrees = 180 / π; function d3_sgn(x) { return x > 0 ? 1 : x < 0 ? -1 : 0; } function d3_cross2d(a, b, c) { return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]); } function d3_acos(x) { return x > 1 ? 0 : x < -1 ? π : Math.acos(x); } function d3_asin(x) { return x > 1 ? halfπ : x < -1 ? -halfπ : Math.asin(x); } function d3_sinh(x) { return ((x = Math.exp(x)) - 1 / x) / 2; } function d3_cosh(x) { return ((x = Math.exp(x)) + 1 / x) / 2; } function d3_tanh(x) { return ((x = Math.exp(2 * x)) - 1) / (x + 1); } function d3_haversin(x) { return (x = Math.sin(x / 2)) * x; } var ρ = Math.SQRT2, ρ2 = 2, ρ4 = 4; d3.interpolateZoom = function(p0, p1) { var ux0 = p0[0], uy0 = p0[1], w0 = p0[2], ux1 = p1[0], uy1 = p1[1], w1 = p1[2]; var dx = ux1 - ux0, dy = uy1 - uy0, d2 = dx * dx + dy * dy, d1 = Math.sqrt(d2), b0 = (w1 * w1 - w0 * w0 + ρ4 * d2) / (2 * w0 * ρ2 * d1), b1 = (w1 * w1 - w0 * w0 - ρ4 * d2) / (2 * w1 * ρ2 * d1), r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0), r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1), dr = r1 - r0, S = (dr || Math.log(w1 / w0)) / ρ; function interpolate(t) { var s = t * S; if (dr) { var coshr0 = d3_cosh(r0), u = w0 / (ρ2 * d1) * (coshr0 * d3_tanh(ρ * s + r0) - d3_sinh(r0)); return [ ux0 + u * dx, uy0 + u * dy, w0 * coshr0 / d3_cosh(ρ * s + r0) ]; } return [ ux0 + t * dx, uy0 + t * dy, w0 * Math.exp(ρ * s) ]; } interpolate.duration = S * 1e3; return interpolate; }; d3.behavior.zoom = function() { var view = { x: 0, y: 0, k: 1 }, translate0, center0, center, size = [ 960, 500 ], scaleExtent = d3_behavior_zoomInfinity, duration = 250, zooming = 0, mousedown = "mousedown.zoom", mousemove = "mousemove.zoom", mouseup = "mouseup.zoom", mousewheelTimer, touchstart = "touchstart.zoom", touchtime, event = d3_eventDispatch(zoom, "zoomstart", "zoom", "zoomend"), x0, x1, y0, y1; if (!d3_behavior_zoomWheel) { d3_behavior_zoomWheel = "onwheel" in d3_document ? (d3_behavior_zoomDelta = function() { return -d3.event.deltaY * (d3.event.deltaMode ? 120 : 1); }, "wheel") : "onmousewheel" in d3_document ? (d3_behavior_zoomDelta = function() { return d3.event.wheelDelta; }, "mousewheel") : (d3_behavior_zoomDelta = function() { return -d3.event.detail; }, "MozMousePixelScroll"); } function zoom(g) { g.on(mousedown, mousedowned).on(d3_behavior_zoomWheel + ".zoom", mousewheeled).on("dblclick.zoom", dblclicked).on(touchstart, touchstarted); } zoom.event = function(g) { g.each(function() { var dispatch = event.of(this, arguments), view1 = view; if (d3_transitionInheritId) { d3.select(this).transition().each("start.zoom", function() { view = this.__chart__ || { x: 0, y: 0, k: 1 }; zoomstarted(dispatch); }).tween("zoom:zoom", function() { var dx = size[0], dy = size[1], cx = center0 ? center0[0] : dx / 2, cy = center0 ? center0[1] : dy / 2, i = d3.interpolateZoom([ (cx - view.x) / view.k, (cy - view.y) / view.k, dx / view.k ], [ (cx - view1.x) / view1.k, (cy - view1.y) / view1.k, dx / view1.k ]); return function(t) { var l = i(t), k = dx / l[2]; this.__chart__ = view = { x: cx - l[0] * k, y: cy - l[1] * k, k: k }; zoomed(dispatch); }; }).each("interrupt.zoom", function() { zoomended(dispatch); }).each("end.zoom", function() { zoomended(dispatch); }); } else { this.__chart__ = view; zoomstarted(dispatch); zoomed(dispatch); zoomended(dispatch); } }); }; zoom.translate = function(_) { if (!arguments.length) return [ view.x, view.y ]; view = { x: +_[0], y: +_[1], k: view.k }; rescale(); return zoom; }; zoom.scale = function(_) { if (!arguments.length) return view.k; view = { x: view.x, y: view.y, k: +_ }; rescale(); return zoom; }; zoom.scaleExtent = function(_) { if (!arguments.length) return scaleExtent; scaleExtent = _ == null ? d3_behavior_zoomInfinity : [ +_[0], +_[1] ]; return zoom; }; zoom.center = function(_) { if (!arguments.length) return center; center = _ && [ +_[0], +_[1] ]; return zoom; }; zoom.size = function(_) { if (!arguments.length) return size; size = _ && [ +_[0], +_[1] ]; return zoom; }; zoom.duration = function(_) { if (!arguments.length) return duration; duration = +_; return zoom; }; zoom.x = function(z) { if (!arguments.length) return x1; x1 = z; x0 = z.copy(); view = { x: 0, y: 0, k: 1 }; return zoom; }; zoom.y = function(z) { if (!arguments.length) return y1; y1 = z; y0 = z.copy(); view = { x: 0, y: 0, k: 1 }; return zoom; }; function location(p) { return [ (p[0] - view.x) / view.k, (p[1] - view.y) / view.k ]; } function point(l) { return [ l[0] * view.k + view.x, l[1] * view.k + view.y ]; } function scaleTo(s) { view.k = Math.max(scaleExtent[0], Math.min(scaleExtent[1], s)); } function translateTo(p, l) { l = point(l); view.x += p[0] - l[0]; view.y += p[1] - l[1]; } function zoomTo(that, p, l, k) { that.__chart__ = { x: view.x, y: view.y, k: view.k }; scaleTo(Math.pow(2, k)); translateTo(center0 = p, l); that = d3.select(that); if (duration > 0) that = that.transition().duration(duration); that.call(zoom.event); } function rescale() { if (x1) x1.domain(x0.range().map(function(x) { return (x - view.x) / view.k; }).map(x0.invert)); if (y1) y1.domain(y0.range().map(function(y) { return (y - view.y) / view.k; }).map(y0.invert)); } function zoomstarted(dispatch) { if (!zooming++) dispatch({ type: "zoomstart" }); } function zoomed(dispatch) { rescale(); dispatch({ type: "zoom", scale: view.k, translate: [ view.x, view.y ] }); } function zoomended(dispatch) { if (!--zooming) dispatch({ type: "zoomend" }); center0 = null; } function mousedowned() { var that = this, target = d3.event.target, dispatch = event.of(that, arguments), dragged = 0, subject = d3.select(d3_window(that)).on(mousemove, moved).on(mouseup, ended), location0 = location(d3.mouse(that)), dragRestore = d3_event_dragSuppress(that); d3_selection_interrupt.call(that); zoomstarted(dispatch); function moved() { dragged = 1; translateTo(d3.mouse(that), location0); zoomed(dispatch); } function ended() { subject.on(mousemove, null).on(mouseup, null); dragRestore(dragged && d3.event.target === target); zoomended(dispatch); } } function touchstarted() { var that = this, dispatch = event.of(that, arguments), locations0 = {}, distance0 = 0, scale0, zoomName = ".zoom-" + d3.event.changedTouches[0].identifier, touchmove = "touchmove" + zoomName, touchend = "touchend" + zoomName, targets = [], subject = d3.select(that), dragRestore = d3_event_dragSuppress(that); started(); zoomstarted(dispatch); subject.on(mousedown, null).on(touchstart, started); function relocate() { var touches = d3.touches(that); scale0 = view.k; touches.forEach(function(t) { if (t.identifier in locations0) locations0[t.identifier] = location(t); }); return touches; } function started() { var target = d3.event.target; d3.select(target).on(touchmove, moved).on(touchend, ended); targets.push(target); var changed = d3.event.changedTouches; for (var i = 0, n = changed.length; i < n; ++i) { locations0[changed[i].identifier] = null; } var touches = relocate(), now = Date.now(); if (touches.length === 1) { if (now - touchtime < 500) { var p = touches[0]; zoomTo(that, p, locations0[p.identifier], Math.floor(Math.log(view.k) / Math.LN2) + 1); d3_eventPreventDefault(); } touchtime = now; } else if (touches.length > 1) { var p = touches[0], q = touches[1], dx = p[0] - q[0], dy = p[1] - q[1]; distance0 = dx * dx + dy * dy; } } function moved() { var touches = d3.touches(that), p0, l0, p1, l1; d3_selection_interrupt.call(that); for (var i = 0, n = touches.length; i < n; ++i, l1 = null) { p1 = touches[i]; if (l1 = locations0[p1.identifier]) { if (l0) break; p0 = p1, l0 = l1; } } if (l1) { var distance1 = (distance1 = p1[0] - p0[0]) * distance1 + (distance1 = p1[1] - p0[1]) * distance1, scale1 = distance0 && Math.sqrt(distance1 / distance0); p0 = [ (p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2 ]; l0 = [ (l0[0] + l1[0]) / 2, (l0[1] + l1[1]) / 2 ]; scaleTo(scale1 * scale0); } touchtime = null; translateTo(p0, l0); zoomed(dispatch); } function ended() { if (d3.event.touches.length) { var changed = d3.event.changedTouches; for (var i = 0, n = changed.length; i < n; ++i) { delete locations0[changed[i].identifier]; } for (var identifier in locations0) { return void relocate(); } } d3.selectAll(targets).on(zoomName, null); subject.on(mousedown, mousedowned).on(touchstart, touchstarted); dragRestore(); zoomended(dispatch); } } function mousewheeled() { var dispatch = event.of(this, arguments); if (mousewheelTimer) clearTimeout(mousewheelTimer); else translate0 = location(center0 = center || d3.mouse(this)), d3_selection_interrupt.call(this), zoomstarted(dispatch); mousewheelTimer = setTimeout(function() { mousewheelTimer = null; zoomended(dispatch); }, 50); d3_eventPreventDefault(); scaleTo(Math.pow(2, d3_behavior_zoomDelta() * .002) * view.k); translateTo(center0, translate0); zoomed(dispatch); } function dblclicked() { var p = d3.mouse(this), k = Math.log(view.k) / Math.LN2; zoomTo(this, p, location(p), d3.event.shiftKey ? Math.ceil(k) - 1 : Math.floor(k) + 1); } return d3.rebind(zoom, event, "on"); }; var d3_behavior_zoomInfinity = [ 0, Infinity ], d3_behavior_zoomDelta, d3_behavior_zoomWheel; d3.color = d3_color; function d3_color() {} d3_color.prototype.toString = function() { return this.rgb() + ""; }; d3.hsl = d3_hsl; function d3_hsl(h, s, l) { return this instanceof d3_hsl ? void (this.h = +h, this.s = +s, this.l = +l) : arguments.length < 2 ? h instanceof d3_hsl ? new d3_hsl(h.h, h.s, h.l) : d3_rgb_parse("" + h, d3_rgb_hsl, d3_hsl) : new d3_hsl(h, s, l); } var d3_hslPrototype = d3_hsl.prototype = new d3_color(); d3_hslPrototype.brighter = function(k) { k = Math.pow(.7, arguments.length ? k : 1); return new d3_hsl(this.h, this.s, this.l / k); }; d3_hslPrototype.darker = function(k) { k = Math.pow(.7, arguments.length ? k : 1); return new d3_hsl(this.h, this.s, k * this.l); }; d3_hslPrototype.rgb = function() { return d3_hsl_rgb(this.h, this.s, this.l); }; function d3_hsl_rgb(h, s, l) { var m1, m2; h = isNaN(h) ? 0 : (h %= 360) < 0 ? h + 360 : h; s = isNaN(s) ? 0 : s < 0 ? 0 : s > 1 ? 1 : s; l = l < 0 ? 0 : l > 1 ? 1 : l; m2 = l <= .5 ? l * (1 + s) : l + s - l * s; m1 = 2 * l - m2; function v(h) { if (h > 360) h -= 360; else if (h < 0) h += 360; if (h < 60) return m1 + (m2 - m1) * h / 60; if (h < 180) return m2; if (h < 240) return m1 + (m2 - m1) * (240 - h) / 60; return m1; } function vv(h) { return Math.round(v(h) * 255); } return new d3_rgb(vv(h + 120), vv(h), vv(h - 120)); } d3.hcl = d3_hcl; function d3_hcl(h, c, l) { return this instanceof d3_hcl ? void (this.h = +h, this.c = +c, this.l = +l) : arguments.length < 2 ? h instanceof d3_hcl ? new d3_hcl(h.h, h.c, h.l) : h instanceof d3_lab ? d3_lab_hcl(h.l, h.a, h.b) : d3_lab_hcl((h = d3_rgb_lab((h = d3.rgb(h)).r, h.g, h.b)).l, h.a, h.b) : new d3_hcl(h, c, l); } var d3_hclPrototype = d3_hcl.prototype = new d3_color(); d3_hclPrototype.brighter = function(k) { return new d3_hcl(this.h, this.c, Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1))); }; d3_hclPrototype.darker = function(k) { return new d3_hcl(this.h, this.c, Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1))); }; d3_hclPrototype.rgb = function() { return d3_hcl_lab(this.h, this.c, this.l).rgb(); }; function d3_hcl_lab(h, c, l) { if (isNaN(h)) h = 0; if (isNaN(c)) c = 0; return new d3_lab(l, Math.cos(h *= d3_radians) * c, Math.sin(h) * c); } d3.lab = d3_lab; function d3_lab(l, a, b) { return this instanceof d3_lab ? void (this.l = +l, this.a = +a, this.b = +b) : arguments.length < 2 ? l instanceof d3_lab ? new d3_lab(l.l, l.a, l.b) : l instanceof d3_hcl ? d3_hcl_lab(l.h, l.c, l.l) : d3_rgb_lab((l = d3_rgb(l)).r, l.g, l.b) : new d3_lab(l, a, b); } var d3_lab_K = 18; var d3_lab_X = .95047, d3_lab_Y = 1, d3_lab_Z = 1.08883; var d3_labPrototype = d3_lab.prototype = new d3_color(); d3_labPrototype.brighter = function(k) { return new d3_lab(Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1)), this.a, this.b); }; d3_labPrototype.darker = function(k) { return new d3_lab(Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1)), this.a, this.b); }; d3_labPrototype.rgb = function() { return d3_lab_rgb(this.l, this.a, this.b); }; function d3_lab_rgb(l, a, b) { var y = (l + 16) / 116, x = y + a / 500, z = y - b / 200; x = d3_lab_xyz(x) * d3_lab_X; y = d3_lab_xyz(y) * d3_lab_Y; z = d3_lab_xyz(z) * d3_lab_Z; return new d3_rgb(d3_xyz_rgb(3.2404542 * x - 1.5371385 * y - .4985314 * z), d3_xyz_rgb(-.969266 * x + 1.8760108 * y + .041556 * z), d3_xyz_rgb(.0556434 * x - .2040259 * y + 1.0572252 * z)); } function d3_lab_hcl(l, a, b) { return l > 0 ? new d3_hcl(Math.atan2(b, a) * d3_degrees, Math.sqrt(a * a + b * b), l) : new d3_hcl(NaN, NaN, l); } function d3_lab_xyz(x) { return x > .206893034 ? x * x * x : (x - 4 / 29) / 7.787037; } function d3_xyz_lab(x) { return x > .008856 ? Math.pow(x, 1 / 3) : 7.787037 * x + 4 / 29; } function d3_xyz_rgb(r) { return Math.round(255 * (r <= .00304 ? 12.92 * r : 1.055 * Math.pow(r, 1 / 2.4) - .055)); } d3.rgb = d3_rgb; function d3_rgb(r, g, b) { return this instanceof d3_rgb ? void (this.r = ~~r, this.g = ~~g, this.b = ~~b) : arguments.length < 2 ? r instanceof d3_rgb ? new d3_rgb(r.r, r.g, r.b) : d3_rgb_parse("" + r, d3_rgb, d3_hsl_rgb) : new d3_rgb(r, g, b); } function d3_rgbNumber(value) { return new d3_rgb(value >> 16, value >> 8 & 255, value & 255); } function d3_rgbString(value) { return d3_rgbNumber(value) + ""; } var d3_rgbPrototype = d3_rgb.prototype = new d3_color(); d3_rgbPrototype.brighter = function(k) { k = Math.pow(.7, arguments.length ? k : 1); var r = this.r, g = this.g, b = this.b, i = 30; if (!r && !g && !b) return new d3_rgb(i, i, i); if (r && r < i) r = i; if (g && g < i) g = i; if (b && b < i) b = i; return new d3_rgb(Math.min(255, r / k), Math.min(255, g / k), Math.min(255, b / k)); }; d3_rgbPrototype.darker = function(k) { k = Math.pow(.7, arguments.length ? k : 1); return new d3_rgb(k * this.r, k * this.g, k * this.b); }; d3_rgbPrototype.hsl = function() { return d3_rgb_hsl(this.r, this.g, this.b); }; d3_rgbPrototype.toString = function() { return "#" + d3_rgb_hex(this.r) + d3_rgb_hex(this.g) + d3_rgb_hex(this.b); }; function d3_rgb_hex(v) { return v < 16 ? "0" + Math.max(0, v).toString(16) : Math.min(255, v).toString(16); } function d3_rgb_parse(format, rgb, hsl) { var r = 0, g = 0, b = 0, m1, m2, color; m1 = /([a-z]+)\((.*)\)/i.exec(format); if (m1) { m2 = m1[2].split(","); switch (m1[1]) { case "hsl": { return hsl(parseFloat(m2[0]), parseFloat(m2[1]) / 100, parseFloat(m2[2]) / 100); } case "rgb": { return rgb(d3_rgb_parseNumber(m2[0]), d3_rgb_parseNumber(m2[1]), d3_rgb_parseNumber(m2[2])); } } } if (color = d3_rgb_names.get(format.toLowerCase())) { return rgb(color.r, color.g, color.b); } if (format != null && format.charAt(0) === "#" && !isNaN(color = parseInt(format.slice(1), 16))) { if (format.length === 4) { r = (color & 3840) >> 4; r = r >> 4 | r; g = color & 240; g = g >> 4 | g; b = color & 15; b = b << 4 | b; } else if (format.length === 7) { r = (color & 16711680) >> 16; g = (color & 65280) >> 8; b = color & 255; } } return rgb(r, g, b); } function d3_rgb_hsl(r, g, b) { var min = Math.min(r /= 255, g /= 255, b /= 255), max = Math.max(r, g, b), d = max - min, h, s, l = (max + min) / 2; if (d) { s = l < .5 ? d / (max + min) : d / (2 - max - min); if (r == max) h = (g - b) / d + (g < b ? 6 : 0); else if (g == max) h = (b - r) / d + 2; else h = (r - g) / d + 4; h *= 60; } else { h = NaN; s = l > 0 && l < 1 ? 0 : h; } return new d3_hsl(h, s, l); } function d3_rgb_lab(r, g, b) { r = d3_rgb_xyz(r); g = d3_rgb_xyz(g); b = d3_rgb_xyz(b); var x = d3_xyz_lab((.4124564 * r + .3575761 * g + .1804375 * b) / d3_lab_X), y = d3_xyz_lab((.2126729 * r + .7151522 * g + .072175 * b) / d3_lab_Y), z = d3_xyz_lab((.0193339 * r + .119192 * g + .9503041 * b) / d3_lab_Z); return d3_lab(116 * y - 16, 500 * (x - y), 200 * (y - z)); } function d3_rgb_xyz(r) { return (r /= 255) <= .04045 ? r / 12.92 : Math.pow((r + .055) / 1.055, 2.4); } function d3_rgb_parseNumber(c) { var f = parseFloat(c); return c.charAt(c.length - 1) === "%" ? Math.round(f * 2.55) : f; } var d3_rgb_names = d3.map({ aliceblue: 15792383, antiquewhite: 16444375, aqua: 65535, aquamarine: 8388564, azure: 15794175, beige: 16119260, bisque: 16770244, black: 0, blanchedalmond: 16772045, blue: 255, blueviolet: 9055202, brown: 10824234, burlywood: 14596231, cadetblue: 6266528, chartreuse: 8388352, chocolate: 13789470, coral: 16744272, cornflowerblue: 6591981, cornsilk: 16775388, crimson: 14423100, cyan: 65535, darkblue: 139, darkcyan: 35723, darkgoldenrod: 12092939, darkgray: 11119017, darkgreen: 25600, darkgrey: 11119017, darkkhaki: 12433259, darkmagenta: 9109643, darkolivegreen: 5597999, darkorange: 16747520, darkorchid: 10040012, darkred: 9109504, darksalmon: 15308410, darkseagreen: 9419919, darkslateblue: 4734347, darkslategray: 3100495, darkslategrey: 3100495, darkturquoise: 52945, darkviolet: 9699539, deeppink: 16716947, deepskyblue: 49151, dimgray: 6908265, dimgrey: 6908265, dodgerblue: 2003199, firebrick: 11674146, floralwhite: 16775920, forestgreen: 2263842, fuchsia: 16711935, gainsboro: 14474460, ghostwhite: 16316671, gold: 16766720, goldenrod: 14329120, gray: 8421504, green: 32768, greenyellow: 11403055, grey: 8421504, honeydew: 15794160, hotpink: 16738740, indianred: 13458524, indigo: 4915330, ivory: 16777200, khaki: 15787660, lavender: 15132410, lavenderblush: 16773365, lawngreen: 8190976, lemonchiffon: 16775885, lightblue: 11393254, lightcoral: 15761536, lightcyan: 14745599, lightgoldenrodyellow: 16448210, lightgray: 13882323, lightgreen: 9498256, lightgrey: 13882323, lightpink: 16758465, lightsalmon: 16752762, lightseagreen: 2142890, lightskyblue: 8900346, lightslategray: 7833753, lightslategrey: 7833753, lightsteelblue: 11584734, lightyellow: 16777184, lime: 65280, limegreen: 3329330, linen: 16445670, magenta: 16711935, maroon: 8388608, mediumaquamarine: 6737322, mediumblue: 205, mediumorchid: 12211667, mediumpurple: 9662683, mediumseagreen: 3978097, mediumslateblue: 8087790, mediumspringgreen: 64154, mediumturquoise: 4772300, mediumvioletred: 13047173, midnightblue: 1644912, mintcream: 16121850, mistyrose: 16770273, moccasin: 16770229, navajowhite: 16768685, navy: 128, oldlace: 16643558, olive: 8421376, olivedrab: 7048739, orange: 16753920, orangered: 16729344, orchid: 14315734, palegoldenrod: 15657130, palegreen: 10025880, paleturquoise: 11529966, palevioletred: 14381203, papayawhip: 16773077, peachpuff: 16767673, peru: 13468991, pink: 16761035, plum: 14524637, powderblue: 11591910, purple: 8388736, rebeccapurple: 6697881, red: 16711680, rosybrown: 12357519, royalblue: 4286945, saddlebrown: 9127187, salmon: 16416882, sandybrown: 16032864, seagreen: 3050327, seashell: 16774638, sienna: 10506797, silver: 12632256, skyblue: 8900331, slateblue: 6970061, slategray: 7372944, slategrey: 7372944, snow: 16775930, springgreen: 65407, steelblue: 4620980, tan: 13808780, teal: 32896, thistle: 14204888, tomato: 16737095, turquoise: 4251856, violet: 15631086, wheat: 16113331, white: 16777215, whitesmoke: 16119285, yellow: 16776960, yellowgreen: 10145074 }); d3_rgb_names.forEach(function(key, value) { d3_rgb_names.set(key, d3_rgbNumber(value)); }); function d3_functor(v) { return typeof v === "function" ? v : function() { return v; }; } d3.functor = d3_functor; d3.xhr = d3_xhrType(d3_identity); function d3_xhrType(response) { return function(url, mimeType, callback) { if (arguments.length === 2 && typeof mimeType === "function") callback = mimeType, mimeType = null; return d3_xhr(url, mimeType, response, callback); }; } function d3_xhr(url, mimeType, response, callback) { var xhr = {}, dispatch = d3.dispatch("beforesend", "progress", "load", "error"), headers = {}, request = new XMLHttpRequest(), responseType = null; if (this.XDomainRequest && !("withCredentials" in request) && /^(http(s)?:)?\/\//.test(url)) request = new XDomainRequest(); "onload" in request ? request.onload = request.onerror = respond : request.onreadystatechange = function() { request.readyState > 3 && respond(); }; function respond() { var status = request.status, result; if (!status && d3_xhrHasResponse(request) || status >= 200 && status < 300 || status === 304) { try { result = response.call(xhr, request); } catch (e) { dispatch.error.call(xhr, e); return; } dispatch.load.call(xhr, result); } else { dispatch.error.call(xhr, request); } } request.onprogress = function(event) { var o = d3.event; d3.event = event; try { dispatch.progress.call(xhr, request); } finally { d3.event = o; } }; xhr.header = function(name, value) { name = (name + "").toLowerCase(); if (arguments.length < 2) return headers[name]; if (value == null) delete headers[name]; else headers[name] = value + ""; return xhr; }; xhr.mimeType = function(value) { if (!arguments.length) return mimeType; mimeType = value == null ? null : value + ""; return xhr; }; xhr.responseType = function(value) { if (!arguments.length) return responseType; responseType = value; return xhr; }; xhr.response = function(value) { response = value; return xhr; }; [ "get", "post" ].forEach(function(method) { xhr[method] = function() { return xhr.send.apply(xhr, [ method ].concat(d3_array(arguments))); }; }); xhr.send = function(method, data, callback) { if (arguments.length === 2 && typeof data === "function") callback = data, data = null; request.open(method, url, true); if (mimeType != null && !("accept" in headers)) headers["accept"] = mimeType + ",*/*"; if (request.setRequestHeader) for (var name in headers) request.setRequestHeader(name, headers[name]); if (mimeType != null && request.overrideMimeType) request.overrideMimeType(mimeType); if (responseType != null) request.responseType = responseType; if (callback != null) xhr.on("error", callback).on("load", function(request) { callback(null, request); }); dispatch.beforesend.call(xhr, request); request.send(data == null ? null : data); return xhr; }; xhr.abort = function() { request.abort(); return xhr; }; d3.rebind(xhr, dispatch, "on"); return callback == null ? xhr : xhr.get(d3_xhr_fixCallback(callback)); } function d3_xhr_fixCallback(callback) { return callback.length === 1 ? function(error, request) { callback(error == null ? request : null); } : callback; } function d3_xhrHasResponse(request) { var type = request.responseType; return type && type !== "text" ? request.response : request.responseText; } d3.dsv = function(delimiter, mimeType) { var reFormat = new RegExp('["' + delimiter + "\n]"), delimiterCode = delimiter.charCodeAt(0); function dsv(url, row, callback) { if (arguments.length < 3) callback = row, row = null; var xhr = d3_xhr(url, mimeType, row == null ? response : typedResponse(row), callback); xhr.row = function(_) { return arguments.length ? xhr.response((row = _) == null ? response : typedResponse(_)) : row; }; return xhr; } function response(request) { return dsv.parse(request.responseText); } function typedResponse(f) { return function(request) { return dsv.parse(request.responseText, f); }; } dsv.parse = function(text, f) { var o; return dsv.parseRows(text, function(row, i) { if (o) return o(row, i - 1); var a = new Function("d", "return {" + row.map(function(name, i) { return JSON.stringify(name) + ": d[" + i + "]"; }).join(",") + "}"); o = f ? function(row, i) { return f(a(row), i); } : a; }); }; dsv.parseRows = function(text, f) { var EOL = {}, EOF = {}, rows = [], N = text.length, I = 0, n = 0, t, eol; function token() { if (I >= N) return EOF; if (eol) return eol = false, EOL; var j = I; if (text.charCodeAt(j) === 34) { var i = j; while (i++ < N) { if (text.charCodeAt(i) === 34) { if (text.charCodeAt(i + 1) !== 34) break; ++i; } } I = i + 2; var c = text.charCodeAt(i + 1); if (c === 13) { eol = true; if (text.charCodeAt(i + 2) === 10) ++I; } else if (c === 10) { eol = true; } return text.slice(j + 1, i).replace(/""/g, '"'); } while (I < N) { var c = text.charCodeAt(I++), k = 1; if (c === 10) eol = true; else if (c === 13) { eol = true; if (text.charCodeAt(I) === 10) ++I, ++k; } else if (c !== delimiterCode) continue; return text.slice(j, I - k); } return text.slice(j); } while ((t = token()) !== EOF) { var a = []; while (t !== EOL && t !== EOF) { a.push(t); t = token(); } if (f && (a = f(a, n++)) == null) continue; rows.push(a); } return rows; }; dsv.format = function(rows) { if (Array.isArray(rows[0])) return dsv.formatRows(rows); var fieldSet = new d3_Set(), fields = []; rows.forEach(function(row) { for (var field in row) { if (!fieldSet.has(field)) { fields.push(fieldSet.add(field)); } } }); return [ fields.map(formatValue).join(delimiter) ].concat(rows.map(function(row) { return fields.map(function(field) { return formatValue(row[field]); }).join(delimiter); })).join("\n"); }; dsv.formatRows = function(rows) { return rows.map(formatRow).join("\n"); }; function formatRow(row) { return row.map(formatValue).join(delimiter); } function formatValue(text) { return reFormat.test(text) ? '"' + text.replace(/\"/g, '""') + '"' : text; } return dsv; }; d3.csv = d3.dsv(",", "text/csv"); d3.tsv = d3.dsv(" ", "text/tab-separated-values"); var d3_timer_queueHead, d3_timer_queueTail, d3_timer_interval, d3_timer_timeout, d3_timer_active, d3_timer_frame = this[d3_vendorSymbol(this, "requestAnimationFrame")] || function(callback) { setTimeout(callback, 17); }; d3.timer = function(callback, delay, then) { var n = arguments.length; if (n < 2) delay = 0; if (n < 3) then = Date.now(); var time = then + delay, timer = { c: callback, t: time, f: false, n: null }; if (d3_timer_queueTail) d3_timer_queueTail.n = timer; else d3_timer_queueHead = timer; d3_timer_queueTail = timer; if (!d3_timer_interval) { d3_timer_timeout = clearTimeout(d3_timer_timeout); d3_timer_interval = 1; d3_timer_frame(d3_timer_step); } }; function d3_timer_step() { var now = d3_timer_mark(), delay = d3_timer_sweep() - now; if (delay > 24) { if (isFinite(delay)) { clearTimeout(d3_timer_timeout); d3_timer_timeout = setTimeout(d3_timer_step, delay); } d3_timer_interval = 0; } else { d3_timer_interval = 1; d3_timer_frame(d3_timer_step); } } d3.timer.flush = function() { d3_timer_mark(); d3_timer_sweep(); }; function d3_timer_mark() { var now = Date.now(); d3_timer_active = d3_timer_queueHead; while (d3_timer_active) { if (now >= d3_timer_active.t) d3_timer_active.f = d3_timer_active.c(now - d3_timer_active.t); d3_timer_active = d3_timer_active.n; } return now; } function d3_timer_sweep() { var t0, t1 = d3_timer_queueHead, time = Infinity; while (t1) { if (t1.f) { t1 = t0 ? t0.n = t1.n : d3_timer_queueHead = t1.n; } else { if (t1.t < time) time = t1.t; t1 = (t0 = t1).n; } } d3_timer_queueTail = t0; return time; } function d3_format_precision(x, p) { return p - (x ? Math.ceil(Math.log(x) / Math.LN10) : 1); } d3.round = function(x, n) { return n ? Math.round(x * (n = Math.pow(10, n))) / n : Math.round(x); }; var d3_formatPrefixes = [ "y", "z", "a", "f", "p", "n", "µ", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y" ].map(d3_formatPrefix); d3.formatPrefix = function(value, precision) { var i = 0; if (value) { if (value < 0) value *= -1; if (precision) value = d3.round(value, d3_format_precision(value, precision)); i = 1 + Math.floor(1e-12 + Math.log(value) / Math.LN10); i = Math.max(-24, Math.min(24, Math.floor((i - 1) / 3) * 3)); } return d3_formatPrefixes[8 + i / 3]; }; function d3_formatPrefix(d, i) { var k = Math.pow(10, abs(8 - i) * 3); return { scale: i > 8 ? function(d) { return d / k; } : function(d) { return d * k; }, symbol: d }; } function d3_locale_numberFormat(locale) { var locale_decimal = locale.decimal, locale_thousands = locale.thousands, locale_grouping = locale.grouping, locale_currency = locale.currency, formatGroup = locale_grouping && locale_thousands ? function(value, width) { var i = value.length, t = [], j = 0, g = locale_grouping[0], length = 0; while (i > 0 && g > 0) { if (length + g + 1 > width) g = Math.max(1, width - length); t.push(value.substring(i -= g, i + g)); if ((length += g + 1) > width) break; g = locale_grouping[j = (j + 1) % locale_grouping.length]; } return t.reverse().join(locale_thousands); } : d3_identity; return function(specifier) { var match = d3_format_re.exec(specifier), fill = match[1] || " ", align = match[2] || ">", sign = match[3] || "-", symbol = match[4] || "", zfill = match[5], width = +match[6], comma = match[7], precision = match[8], type = match[9], scale = 1, prefix = "", suffix = "", integer = false, exponent = true; if (precision) precision = +precision.substring(1); if (zfill || fill === "0" && align === "=") { zfill = fill = "0"; align = "="; } switch (type) { case "n": comma = true; type = "g"; break; case "%": scale = 100; suffix = "%"; type = "f"; break; case "p": scale = 100; suffix = "%"; type = "r"; break; case "b": case "o": case "x": case "X": if (symbol === "#") prefix = "0" + type.toLowerCase(); case "c": exponent = false; case "d": integer = true; precision = 0; break; case "s": scale = -1; type = "r"; break; } if (symbol === "$") prefix = locale_currency[0], suffix = locale_currency[1]; if (type == "r" && !precision) type = "g"; if (precision != null) { if (type == "g") precision = Math.max(1, Math.min(21, precision)); else if (type == "e" || type == "f") precision = Math.max(0, Math.min(20, precision)); } type = d3_format_types.get(type) || d3_format_typeDefault; var zcomma = zfill && comma; return function(value) { var fullSuffix = suffix; if (integer && value % 1) return ""; var negative = value < 0 || value === 0 && 1 / value < 0 ? (value = -value, "-") : sign === "-" ? "" : sign; if (scale < 0) { var unit = d3.formatPrefix(value, precision); value = unit.scale(value); fullSuffix = unit.symbol + suffix; } else { value *= scale; } value = type(value, precision); var i = value.lastIndexOf("."), before, after; if (i < 0) { var j = exponent ? value.lastIndexOf("e") : -1; if (j < 0) before = value, after = ""; else before = value.substring(0, j), after = value.substring(j); } else { before = value.substring(0, i); after = locale_decimal + value.substring(i + 1); } if (!zfill && comma) before = formatGroup(before, Infinity); var length = prefix.length + before.length + after.length + (zcomma ? 0 : negative.length), padding = length < width ? new Array(length = width - length + 1).join(fill) : ""; if (zcomma) before = formatGroup(padding + before, padding.length ? width - after.length : Infinity); negative += prefix; value = before + after; return (align === "<" ? negative + value + padding : align === ">" ? padding + negative + value : align === "^" ? padding.substring(0, length >>= 1) + negative + value + padding.substring(length) : negative + (zcomma ? value : padding + value)) + fullSuffix; }; }; } var d3_format_re = /(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i; var d3_format_types = d3.map({ b: function(x) { return x.toString(2); }, c: function(x) { return String.fromCharCode(x); }, o: function(x) { return x.toString(8); }, x: function(x) { return x.toString(16); }, X: function(x) { return x.toString(16).toUpperCase(); }, g: function(x, p) { return x.toPrecision(p); }, e: function(x, p) { return x.toExponential(p); }, f: function(x, p) { return x.toFixed(p); }, r: function(x, p) { return (x = d3.round(x, d3_format_precision(x, p))).toFixed(Math.max(0, Math.min(20, d3_format_precision(x * (1 + 1e-15), p)))); } }); function d3_format_typeDefault(x) { return x + ""; } var d3_time = d3.time = {}, d3_date = Date; function d3_date_utc() { this._ = new Date(arguments.length > 1 ? Date.UTC.apply(this, arguments) : arguments[0]); } d3_date_utc.prototype = { getDate: function() { return this._.getUTCDate(); }, getDay: function() { return this._.getUTCDay(); }, getFullYear: function() { return this._.getUTCFullYear(); }, getHours: function() { return this._.getUTCHours(); }, getMilliseconds: function() { return this._.getUTCMilliseconds(); }, getMinutes: function() { return this._.getUTCMinutes(); }, getMonth: function() { return this._.getUTCMonth(); }, getSeconds: function() { return this._.getUTCSeconds(); }, getTime: function() { return this._.getTime(); }, getTimezoneOffset: function() { return 0; }, valueOf: function() { return this._.valueOf(); }, setDate: function() { d3_time_prototype.setUTCDate.apply(this._, arguments); }, setDay: function() { d3_time_prototype.setUTCDay.apply(this._, arguments); }, setFullYear: function() { d3_time_prototype.setUTCFullYear.apply(this._, arguments); }, setHours: function() { d3_time_prototype.setUTCHours.apply(this._, arguments); }, setMilliseconds: function() { d3_time_prototype.setUTCMilliseconds.apply(this._, arguments); }, setMinutes: function() { d3_time_prototype.setUTCMinutes.apply(this._, arguments); }, setMonth: function() { d3_time_prototype.setUTCMonth.apply(this._, arguments); }, setSeconds: function() { d3_time_prototype.setUTCSeconds.apply(this._, arguments); }, setTime: function() { d3_time_prototype.setTime.apply(this._, arguments); } }; var d3_time_prototype = Date.prototype; function d3_time_interval(local, step, number) { function round(date) { var d0 = local(date), d1 = offset(d0, 1); return date - d0 < d1 - date ? d0 : d1; } function ceil(date) { step(date = local(new d3_date(date - 1)), 1); return date; } function offset(date, k) { step(date = new d3_date(+date), k); return date; } function range(t0, t1, dt) { var time = ceil(t0), times = []; if (dt > 1) { while (time < t1) { if (!(number(time) % dt)) times.push(new Date(+time)); step(time, 1); } } else { while (time < t1) times.push(new Date(+time)), step(time, 1); } return times; } function range_utc(t0, t1, dt) { try { d3_date = d3_date_utc; var utc = new d3_date_utc(); utc._ = t0; return range(utc, t1, dt); } finally { d3_date = Date; } } local.floor = local; local.round = round; local.ceil = ceil; local.offset = offset; local.range = range; var utc = local.utc = d3_time_interval_utc(local); utc.floor = utc; utc.round = d3_time_interval_utc(round); utc.ceil = d3_time_interval_utc(ceil); utc.offset = d3_time_interval_utc(offset); utc.range = range_utc; return local; } function d3_time_interval_utc(method) { return function(date, k) { try { d3_date = d3_date_utc; var utc = new d3_date_utc(); utc._ = date; return method(utc, k)._; } finally { d3_date = Date; } }; } d3_time.year = d3_time_interval(function(date) { date = d3_time.day(date); date.setMonth(0, 1); return date; }, function(date, offset) { date.setFullYear(date.getFullYear() + offset); }, function(date) { return date.getFullYear(); }); d3_time.years = d3_time.year.range; d3_time.years.utc = d3_time.year.utc.range; d3_time.day = d3_time_interval(function(date) { var day = new d3_date(2e3, 0); day.setFullYear(date.getFullYear(), date.getMonth(), date.getDate()); return day; }, function(date, offset) { date.setDate(date.getDate() + offset); }, function(date) { return date.getDate() - 1; }); d3_time.days = d3_time.day.range; d3_time.days.utc = d3_time.day.utc.range; d3_time.dayOfYear = function(date) { var year = d3_time.year(date); return Math.floor((date - year - (date.getTimezoneOffset() - year.getTimezoneOffset()) * 6e4) / 864e5); }; [ "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday" ].forEach(function(day, i) { i = 7 - i; var interval = d3_time[day] = d3_time_interval(function(date) { (date = d3_time.day(date)).setDate(date.getDate() - (date.getDay() + i) % 7); return date; }, function(date, offset) { date.setDate(date.getDate() + Math.floor(offset) * 7); }, function(date) { var day = d3_time.year(date).getDay(); return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7) - (day !== i); }); d3_time[day + "s"] = interval.range; d3_time[day + "s"].utc = interval.utc.range; d3_time[day + "OfYear"] = function(date) { var day = d3_time.year(date).getDay(); return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7); }; }); d3_time.week = d3_time.sunday; d3_time.weeks = d3_time.sunday.range; d3_time.weeks.utc = d3_time.sunday.utc.range; d3_time.weekOfYear = d3_time.sundayOfYear; function d3_locale_timeFormat(locale) { var locale_dateTime = locale.dateTime, locale_date = locale.date, locale_time = locale.time, locale_periods = locale.periods, locale_days = locale.days, locale_shortDays = locale.shortDays, locale_months = locale.months, locale_shortMonths = locale.shortMonths; function d3_time_format(template) { var n = template.length; function format(date) { var string = [], i = -1, j = 0, c, p, f; while (++i < n) { if (template.charCodeAt(i) === 37) { string.push(template.slice(j, i)); if ((p = d3_time_formatPads[c = template.charAt(++i)]) != null) c = template.charAt(++i); if (f = d3_time_formats[c]) c = f(date, p == null ? c === "e" ? " " : "0" : p); string.push(c); j = i + 1; } } string.push(template.slice(j, i)); return string.join(""); } format.parse = function(string) { var d = { y: 1900, m: 0, d: 1, H: 0, M: 0, S: 0, L: 0, Z: null }, i = d3_time_parse(d, template, string, 0); if (i != string.length) return null; if ("p" in d) d.H = d.H % 12 + d.p * 12; var localZ = d.Z != null && d3_date !== d3_date_utc, date = new (localZ ? d3_date_utc : d3_date)(); if ("j" in d) date.setFullYear(d.y, 0, d.j); else if ("w" in d && ("W" in d || "U" in d)) { date.setFullYear(d.y, 0, 1); date.setFullYear(d.y, 0, "W" in d ? (d.w + 6) % 7 + d.W * 7 - (date.getDay() + 5) % 7 : d.w + d.U * 7 - (date.getDay() + 6) % 7); } else date.setFullYear(d.y, d.m, d.d); date.setHours(d.H + (d.Z / 100 | 0), d.M + d.Z % 100, d.S, d.L); return localZ ? date._ : date; }; format.toString = function() { return template; }; return format; } function d3_time_parse(date, template, string, j) { var c, p, t, i = 0, n = template.length, m = string.length; while (i < n) { if (j >= m) return -1; c = template.charCodeAt(i++); if (c === 37) { t = template.charAt(i++); p = d3_time_parsers[t in d3_time_formatPads ? template.charAt(i++) : t]; if (!p || (j = p(date, string, j)) < 0) return -1; } else if (c != string.charCodeAt(j++)) { return -1; } } return j; } d3_time_format.utc = function(template) { var local = d3_time_format(template); function format(date) { try { d3_date = d3_date_utc; var utc = new d3_date(); utc._ = date; return local(utc); } finally { d3_date = Date; } } format.parse = function(string) { try { d3_date = d3_date_utc; var date = local.parse(string); return date && date._; } finally { d3_date = Date; } }; format.toString = local.toString; return format; }; d3_time_format.multi = d3_time_format.utc.multi = d3_time_formatMulti; var d3_time_periodLookup = d3.map(), d3_time_dayRe = d3_time_formatRe(locale_days), d3_time_dayLookup = d3_time_formatLookup(locale_days), d3_time_dayAbbrevRe = d3_time_formatRe(locale_shortDays), d3_time_dayAbbrevLookup = d3_time_formatLookup(locale_shortDays), d3_time_monthRe = d3_time_formatRe(locale_months), d3_time_monthLookup = d3_time_formatLookup(locale_months), d3_time_monthAbbrevRe = d3_time_formatRe(locale_shortMonths), d3_time_monthAbbrevLookup = d3_time_formatLookup(locale_shortMonths); locale_periods.forEach(function(p, i) { d3_time_periodLookup.set(p.toLowerCase(), i); }); var d3_time_formats = { a: function(d) { return locale_shortDays[d.getDay()]; }, A: function(d) { return locale_days[d.getDay()]; }, b: function(d) { return locale_shortMonths[d.getMonth()]; }, B: function(d) { return locale_months[d.getMonth()]; }, c: d3_time_format(locale_dateTime), d: function(d, p) { return d3_time_formatPad(d.getDate(), p, 2); }, e: function(d, p) { return d3_time_formatPad(d.getDate(), p, 2); }, H: function(d, p) { return d3_time_formatPad(d.getHours(), p, 2); }, I: function(d, p) { return d3_time_formatPad(d.getHours() % 12 || 12, p, 2); }, j: function(d, p) { return d3_time_formatPad(1 + d3_time.dayOfYear(d), p, 3); }, L: function(d, p) { return d3_time_formatPad(d.getMilliseconds(), p, 3); }, m: function(d, p) { return d3_time_formatPad(d.getMonth() + 1, p, 2); }, M: function(d, p) { return d3_time_formatPad(d.getMinutes(), p, 2); }, p: function(d) { return locale_periods[+(d.getHours() >= 12)]; }, S: function(d, p) { return d3_time_formatPad(d.getSeconds(), p, 2); }, U: function(d, p) { return d3_time_formatPad(d3_time.sundayOfYear(d), p, 2); }, w: function(d) { return d.getDay(); }, W: function(d, p) { return d3_time_formatPad(d3_time.mondayOfYear(d), p, 2); }, x: d3_time_format(locale_date), X: d3_time_format(locale_time), y: function(d, p) { return d3_time_formatPad(d.getFullYear() % 100, p, 2); }, Y: function(d, p) { return d3_time_formatPad(d.getFullYear() % 1e4, p, 4); }, Z: d3_time_zone, "%": function() { return "%"; } }; var d3_time_parsers = { a: d3_time_parseWeekdayAbbrev, A: d3_time_parseWeekday, b: d3_time_parseMonthAbbrev, B: d3_time_parseMonth, c: d3_time_parseLocaleFull, d: d3_time_parseDay, e: d3_time_parseDay, H: d3_time_parseHour24, I: d3_time_parseHour24, j: d3_time_parseDayOfYear, L: d3_time_parseMilliseconds, m: d3_time_parseMonthNumber, M: d3_time_parseMinutes, p: d3_time_parseAmPm, S: d3_time_parseSeconds, U: d3_time_parseWeekNumberSunday, w: d3_time_parseWeekdayNumber, W: d3_time_parseWeekNumberMonday, x: d3_time_parseLocaleDate, X: d3_time_parseLocaleTime, y: d3_time_parseYear, Y: d3_time_parseFullYear, Z: d3_time_parseZone, "%": d3_time_parseLiteralPercent }; function d3_time_parseWeekdayAbbrev(date, string, i) { d3_time_dayAbbrevRe.lastIndex = 0; var n = d3_time_dayAbbrevRe.exec(string.slice(i)); return n ? (date.w = d3_time_dayAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; } function d3_time_parseWeekday(date, string, i) { d3_time_dayRe.lastIndex = 0; var n = d3_time_dayRe.exec(string.slice(i)); return n ? (date.w = d3_time_dayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; } function d3_time_parseMonthAbbrev(date, string, i) { d3_time_monthAbbrevRe.lastIndex = 0; var n = d3_time_monthAbbrevRe.exec(string.slice(i)); return n ? (date.m = d3_time_monthAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; } function d3_time_parseMonth(date, string, i) { d3_time_monthRe.lastIndex = 0; var n = d3_time_monthRe.exec(string.slice(i)); return n ? (date.m = d3_time_monthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; } function d3_time_parseLocaleFull(date, string, i) { return d3_time_parse(date, d3_time_formats.c.toString(), string, i); } function d3_time_parseLocaleDate(date, string, i) { return d3_time_parse(date, d3_time_formats.x.toString(), string, i); } function d3_time_parseLocaleTime(date, string, i) { return d3_time_parse(date, d3_time_formats.X.toString(), string, i); } function d3_time_parseAmPm(date, string, i) { var n = d3_time_periodLookup.get(string.slice(i, i += 2).toLowerCase()); return n == null ? -1 : (date.p = n, i); } return d3_time_format; } var d3_time_formatPads = { "-": "", _: " ", "0": "0" }, d3_time_numberRe = /^\s*\d+/, d3_time_percentRe = /^%/; function d3_time_formatPad(value, fill, width) { var sign = value < 0 ? "-" : "", string = (sign ? -value : value) + "", length = string.length; return sign + (length < width ? new Array(width - length + 1).join(fill) + string : string); } function d3_time_formatRe(names) { return new RegExp("^(?:" + names.map(d3.requote).join("|") + ")", "i"); } function d3_time_formatLookup(names) { var map = new d3_Map(), i = -1, n = names.length; while (++i < n) map.set(names[i].toLowerCase(), i); return map; } function d3_time_parseWeekdayNumber(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.slice(i, i + 1)); return n ? (date.w = +n[0], i + n[0].length) : -1; } function d3_time_parseWeekNumberSunday(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.slice(i)); return n ? (date.U = +n[0], i + n[0].length) : -1; } function d3_time_parseWeekNumberMonday(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.slice(i)); return n ? (date.W = +n[0], i + n[0].length) : -1; } function d3_time_parseFullYear(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.slice(i, i + 4)); return n ? (date.y = +n[0], i + n[0].length) : -1; } function d3_time_parseYear(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.slice(i, i + 2)); return n ? (date.y = d3_time_expandYear(+n[0]), i + n[0].length) : -1; } function d3_time_parseZone(date, string, i) { return /^[+-]\d{4}$/.test(string = string.slice(i, i + 5)) ? (date.Z = -string, i + 5) : -1; } function d3_time_expandYear(d) { return d + (d > 68 ? 1900 : 2e3); } function d3_time_parseMonthNumber(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.slice(i, i + 2)); return n ? (date.m = n[0] - 1, i + n[0].length) : -1; } function d3_time_parseDay(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.slice(i, i + 2)); return n ? (date.d = +n[0], i + n[0].length) : -1; } function d3_time_parseDayOfYear(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.slice(i, i + 3)); return n ? (date.j = +n[0], i + n[0].length) : -1; } function d3_time_parseHour24(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.slice(i, i + 2)); return n ? (date.H = +n[0], i + n[0].length) : -1; } function d3_time_parseMinutes(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.slice(i, i + 2)); return n ? (date.M = +n[0], i + n[0].length) : -1; } function d3_time_parseSeconds(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.slice(i, i + 2)); return n ? (date.S = +n[0], i + n[0].length) : -1; } function d3_time_parseMilliseconds(date, string, i) { d3_time_numberRe.lastIndex = 0; var n = d3_time_numberRe.exec(string.slice(i, i + 3)); return n ? (date.L = +n[0], i + n[0].length) : -1; } function d3_time_zone(d) { var z = d.getTimezoneOffset(), zs = z > 0 ? "-" : "+", zh = abs(z) / 60 | 0, zm = abs(z) % 60; return zs + d3_time_formatPad(zh, "0", 2) + d3_time_formatPad(zm, "0", 2); } function d3_time_parseLiteralPercent(date, string, i) { d3_time_percentRe.lastIndex = 0; var n = d3_time_percentRe.exec(string.slice(i, i + 1)); return n ? i + n[0].length : -1; } function d3_time_formatMulti(formats) { var n = formats.length, i = -1; while (++i < n) formats[i][0] = this(formats[i][0]); return function(date) { var i = 0, f = formats[i]; while (!f[1](date)) f = formats[++i]; return f[0](date); }; } d3.locale = function(locale) { return { numberFormat: d3_locale_numberFormat(locale), timeFormat: d3_locale_timeFormat(locale) }; }; var d3_locale_enUS = d3.locale({ decimal: ".", thousands: ",", grouping: [ 3 ], currency: [ "$", "" ], dateTime: "%a %b %e %X %Y", date: "%m/%d/%Y", time: "%H:%M:%S", periods: [ "AM", "PM" ], days: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], shortDays: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], months: [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], shortMonths: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ] }); d3.format = d3_locale_enUS.numberFormat; d3.geo = {}; function d3_adder() {} d3_adder.prototype = { s: 0, t: 0, add: function(y) { d3_adderSum(y, this.t, d3_adderTemp); d3_adderSum(d3_adderTemp.s, this.s, this); if (this.s) this.t += d3_adderTemp.t; else this.s = d3_adderTemp.t; }, reset: function() { this.s = this.t = 0; }, valueOf: function() { return this.s; } }; var d3_adderTemp = new d3_adder(); function d3_adderSum(a, b, o) { var x = o.s = a + b, bv = x - a, av = x - bv; o.t = a - av + (b - bv); } d3.geo.stream = function(object, listener) { if (object && d3_geo_streamObjectType.hasOwnProperty(object.type)) { d3_geo_streamObjectType[object.type](object, listener); } else { d3_geo_streamGeometry(object, listener); } }; function d3_geo_streamGeometry(geometry, listener) { if (geometry && d3_geo_streamGeometryType.hasOwnProperty(geometry.type)) { d3_geo_streamGeometryType[geometry.type](geometry, listener); } } var d3_geo_streamObjectType = { Feature: function(feature, listener) { d3_geo_streamGeometry(feature.geometry, listener); }, FeatureCollection: function(object, listener) { var features = object.features, i = -1, n = features.length; while (++i < n) d3_geo_streamGeometry(features[i].geometry, listener); } }; var d3_geo_streamGeometryType = { Sphere: function(object, listener) { listener.sphere(); }, Point: function(object, listener) { object = object.coordinates; listener.point(object[0], object[1], object[2]); }, MultiPoint: function(object, listener) { var coordinates = object.coordinates, i = -1, n = coordinates.length; while (++i < n) object = coordinates[i], listener.point(object[0], object[1], object[2]); }, LineString: function(object, listener) { d3_geo_streamLine(object.coordinates, listener, 0); }, MultiLineString: function(object, listener) { var coordinates = object.coordinates, i = -1, n = coordinates.length; while (++i < n) d3_geo_streamLine(coordinates[i], listener, 0); }, Polygon: function(object, listener) { d3_geo_streamPolygon(object.coordinates, listener); }, MultiPolygon: function(object, listener) { var coordinates = object.coordinates, i = -1, n = coordinates.length; while (++i < n) d3_geo_streamPolygon(coordinates[i], listener); }, GeometryCollection: function(object, listener) { var geometries = object.geometries, i = -1, n = geometries.length; while (++i < n) d3_geo_streamGeometry(geometries[i], listener); } }; function d3_geo_streamLine(coordinates, listener, closed) { var i = -1, n = coordinates.length - closed, coordinate; listener.lineStart(); while (++i < n) coordinate = coordinates[i], listener.point(coordinate[0], coordinate[1], coordinate[2]); listener.lineEnd(); } function d3_geo_streamPolygon(coordinates, listener) { var i = -1, n = coordinates.length; listener.polygonStart(); while (++i < n) d3_geo_streamLine(coordinates[i], listener, 1); listener.polygonEnd(); } d3.geo.area = function(object) { d3_geo_areaSum = 0; d3.geo.stream(object, d3_geo_area); return d3_geo_areaSum; }; var d3_geo_areaSum, d3_geo_areaRingSum = new d3_adder(); var d3_geo_area = { sphere: function() { d3_geo_areaSum += 4 * π; }, point: d3_noop, lineStart: d3_noop, lineEnd: d3_noop, polygonStart: function() { d3_geo_areaRingSum.reset(); d3_geo_area.lineStart = d3_geo_areaRingStart; }, polygonEnd: function() { var area = 2 * d3_geo_areaRingSum; d3_geo_areaSum += area < 0 ? 4 * π + area : area; d3_geo_area.lineStart = d3_geo_area.lineEnd = d3_geo_area.point = d3_noop; } }; function d3_geo_areaRingStart() { var λ00, φ00, λ0, cosφ0, sinφ0; d3_geo_area.point = function(λ, φ) { d3_geo_area.point = nextPoint; λ0 = (λ00 = λ) * d3_radians, cosφ0 = Math.cos(φ = (φ00 = φ) * d3_radians / 2 + π / 4), sinφ0 = Math.sin(φ); }; function nextPoint(λ, φ) { λ *= d3_radians; φ = φ * d3_radians / 2 + π / 4; var dλ = λ - λ0, sdλ = dλ >= 0 ? 1 : -1, adλ = sdλ * dλ, cosφ = Math.cos(φ), sinφ = Math.sin(φ), k = sinφ0 * sinφ, u = cosφ0 * cosφ + k * Math.cos(adλ), v = k * sdλ * Math.sin(adλ); d3_geo_areaRingSum.add(Math.atan2(v, u)); λ0 = λ, cosφ0 = cosφ, sinφ0 = sinφ; } d3_geo_area.lineEnd = function() { nextPoint(λ00, φ00); }; } function d3_geo_cartesian(spherical) { var λ = spherical[0], φ = spherical[1], cosφ = Math.cos(φ); return [ cosφ * Math.cos(λ), cosφ * Math.sin(λ), Math.sin(φ) ]; } function d3_geo_cartesianDot(a, b) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; } function d3_geo_cartesianCross(a, b) { return [ a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0] ]; } function d3_geo_cartesianAdd(a, b) { a[0] += b[0]; a[1] += b[1]; a[2] += b[2]; } function d3_geo_cartesianScale(vector, k) { return [ vector[0] * k, vector[1] * k, vector[2] * k ]; } function d3_geo_cartesianNormalize(d) { var l = Math.sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]); d[0] /= l; d[1] /= l; d[2] /= l; } function d3_geo_spherical(cartesian) { return [ Math.atan2(cartesian[1], cartesian[0]), d3_asin(cartesian[2]) ]; } function d3_geo_sphericalEqual(a, b) { return abs(a[0] - b[0]) < ε && abs(a[1] - b[1]) < ε; } d3.geo.bounds = function() { var λ0, φ0, λ1, φ1, λ_, λ__, φ__, p0, dλSum, ranges, range; var bound = { point: point, lineStart: lineStart, lineEnd: lineEnd, polygonStart: function() { bound.point = ringPoint; bound.lineStart = ringStart; bound.lineEnd = ringEnd; dλSum = 0; d3_geo_area.polygonStart(); }, polygonEnd: function() { d3_geo_area.polygonEnd(); bound.point = point; bound.lineStart = lineStart; bound.lineEnd = lineEnd; if (d3_geo_areaRingSum < 0) λ0 = -(λ1 = 180), φ0 = -(φ1 = 90); else if (dλSum > ε) φ1 = 90; else if (dλSum < -ε) φ0 = -90; range[0] = λ0, range[1] = λ1; } }; function point(λ, φ) { ranges.push(range = [ λ0 = λ, λ1 = λ ]); if (φ < φ0) φ0 = φ; if (φ > φ1) φ1 = φ; } function linePoint(λ, φ) { var p = d3_geo_cartesian([ λ * d3_radians, φ * d3_radians ]); if (p0) { var normal = d3_geo_cartesianCross(p0, p), equatorial = [ normal[1], -normal[0], 0 ], inflection = d3_geo_cartesianCross(equatorial, normal); d3_geo_cartesianNormalize(inflection); inflection = d3_geo_spherical(inflection); var dλ = λ - λ_, s = dλ > 0 ? 1 : -1, λi = inflection[0] * d3_degrees * s, antimeridian = abs(dλ) > 180; if (antimeridian ^ (s * λ_ < λi && λi < s * λ)) { var φi = inflection[1] * d3_degrees; if (φi > φ1) φ1 = φi; } else if (λi = (λi + 360) % 360 - 180, antimeridian ^ (s * λ_ < λi && λi < s * λ)) { var φi = -inflection[1] * d3_degrees; if (φi < φ0) φ0 = φi; } else { if (φ < φ0) φ0 = φ; if (φ > φ1) φ1 = φ; } if (antimeridian) { if (λ < λ_) { if (angle(λ0, λ) > angle(λ0, λ1)) λ1 = λ; } else { if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ; } } else { if (λ1 >= λ0) { if (λ < λ0) λ0 = λ; if (λ > λ1) λ1 = λ; } else { if (λ > λ_) { if (angle(λ0, λ) > angle(λ0, λ1)) λ1 = λ; } else { if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ; } } } } else { point(λ, φ); } p0 = p, λ_ = λ; } function lineStart() { bound.point = linePoint; } function lineEnd() { range[0] = λ0, range[1] = λ1; bound.point = point; p0 = null; } function ringPoint(λ, φ) { if (p0) { var dλ = λ - λ_; dλSum += abs(dλ) > 180 ? dλ + (dλ > 0 ? 360 : -360) : dλ; } else λ__ = λ, φ__ = φ; d3_geo_area.point(λ, φ); linePoint(λ, φ); } function ringStart() { d3_geo_area.lineStart(); } function ringEnd() { ringPoint(λ__, φ__); d3_geo_area.lineEnd(); if (abs(dλSum) > ε) λ0 = -(λ1 = 180); range[0] = λ0, range[1] = λ1; p0 = null; } function angle(λ0, λ1) { return (λ1 -= λ0) < 0 ? λ1 + 360 : λ1; } function compareRanges(a, b) { return a[0] - b[0]; } function withinRange(x, range) { return range[0] <= range[1] ? range[0] <= x && x <= range[1] : x < range[0] || range[1] < x; } return function(feature) { φ1 = λ1 = -(λ0 = φ0 = Infinity); ranges = []; d3.geo.stream(feature, bound); var n = ranges.length; if (n) { ranges.sort(compareRanges); for (var i = 1, a = ranges[0], b, merged = [ a ]; i < n; ++i) { b = ranges[i]; if (withinRange(b[0], a) || withinRange(b[1], a)) { if (angle(a[0], b[1]) > angle(a[0], a[1])) a[1] = b[1]; if (angle(b[0], a[1]) > angle(a[0], a[1])) a[0] = b[0]; } else { merged.push(a = b); } } var best = -Infinity, dλ; for (var n = merged.length - 1, i = 0, a = merged[n], b; i <= n; a = b, ++i) { b = merged[i]; if ((dλ = angle(a[1], b[0])) > best) best = dλ, λ0 = b[0], λ1 = a[1]; } } ranges = range = null; return λ0 === Infinity || φ0 === Infinity ? [ [ NaN, NaN ], [ NaN, NaN ] ] : [ [ λ0, φ0 ], [ λ1, φ1 ] ]; }; }(); d3.geo.centroid = function(object) { d3_geo_centroidW0 = d3_geo_centroidW1 = d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0; d3.geo.stream(object, d3_geo_centroid); var x = d3_geo_centroidX2, y = d3_geo_centroidY2, z = d3_geo_centroidZ2, m = x * x + y * y + z * z; if (m < ε2) { x = d3_geo_centroidX1, y = d3_geo_centroidY1, z = d3_geo_centroidZ1; if (d3_geo_centroidW1 < ε) x = d3_geo_centroidX0, y = d3_geo_centroidY0, z = d3_geo_centroidZ0; m = x * x + y * y + z * z; if (m < ε2) return [ NaN, NaN ]; } return [ Math.atan2(y, x) * d3_degrees, d3_asin(z / Math.sqrt(m)) * d3_degrees ]; }; var d3_geo_centroidW0, d3_geo_centroidW1, d3_geo_centroidX0, d3_geo_centroidY0, d3_geo_centroidZ0, d3_geo_centroidX1, d3_geo_centroidY1, d3_geo_centroidZ1, d3_geo_centroidX2, d3_geo_centroidY2, d3_geo_centroidZ2; var d3_geo_centroid = { sphere: d3_noop, point: d3_geo_centroidPoint, lineStart: d3_geo_centroidLineStart, lineEnd: d3_geo_centroidLineEnd, polygonStart: function() { d3_geo_centroid.lineStart = d3_geo_centroidRingStart; }, polygonEnd: function() { d3_geo_centroid.lineStart = d3_geo_centroidLineStart; } }; function d3_geo_centroidPoint(λ, φ) { λ *= d3_radians; var cosφ = Math.cos(φ *= d3_radians); d3_geo_centroidPointXYZ(cosφ * Math.cos(λ), cosφ * Math.sin(λ), Math.sin(φ)); } function d3_geo_centroidPointXYZ(x, y, z) { ++d3_geo_centroidW0; d3_geo_centroidX0 += (x - d3_geo_centroidX0) / d3_geo_centroidW0; d3_geo_centroidY0 += (y - d3_geo_centroidY0) / d3_geo_centroidW0; d3_geo_centroidZ0 += (z - d3_geo_centroidZ0) / d3_geo_centroidW0; } function d3_geo_centroidLineStart() { var x0, y0, z0; d3_geo_centroid.point = function(λ, φ) { λ *= d3_radians; var cosφ = Math.cos(φ *= d3_radians); x0 = cosφ * Math.cos(λ); y0 = cosφ * Math.sin(λ); z0 = Math.sin(φ); d3_geo_centroid.point = nextPoint; d3_geo_centroidPointXYZ(x0, y0, z0); }; function nextPoint(λ, φ) { λ *= d3_radians; var cosφ = Math.cos(φ *= d3_radians), x = cosφ * Math.cos(λ), y = cosφ * Math.sin(λ), z = Math.sin(φ), w = Math.atan2(Math.sqrt((w = y0 * z - z0 * y) * w + (w = z0 * x - x0 * z) * w + (w = x0 * y - y0 * x) * w), x0 * x + y0 * y + z0 * z); d3_geo_centroidW1 += w; d3_geo_centroidX1 += w * (x0 + (x0 = x)); d3_geo_centroidY1 += w * (y0 + (y0 = y)); d3_geo_centroidZ1 += w * (z0 + (z0 = z)); d3_geo_centroidPointXYZ(x0, y0, z0); } } function d3_geo_centroidLineEnd() { d3_geo_centroid.point = d3_geo_centroidPoint; } function d3_geo_centroidRingStart() { var λ00, φ00, x0, y0, z0; d3_geo_centroid.point = function(λ, φ) { λ00 = λ, φ00 = φ; d3_geo_centroid.point = nextPoint; λ *= d3_radians; var cosφ = Math.cos(φ *= d3_radians); x0 = cosφ * Math.cos(λ); y0 = cosφ * Math.sin(λ); z0 = Math.sin(φ); d3_geo_centroidPointXYZ(x0, y0, z0); }; d3_geo_centroid.lineEnd = function() { nextPoint(λ00, φ00); d3_geo_centroid.lineEnd = d3_geo_centroidLineEnd; d3_geo_centroid.point = d3_geo_centroidPoint; }; function nextPoint(λ, φ) { λ *= d3_radians; var cosφ = Math.cos(φ *= d3_radians), x = cosφ * Math.cos(λ), y = cosφ * Math.sin(λ), z = Math.sin(φ), cx = y0 * z - z0 * y, cy = z0 * x - x0 * z, cz = x0 * y - y0 * x, m = Math.sqrt(cx * cx + cy * cy + cz * cz), u = x0 * x + y0 * y + z0 * z, v = m && -d3_acos(u) / m, w = Math.atan2(m, u); d3_geo_centroidX2 += v * cx; d3_geo_centroidY2 += v * cy; d3_geo_centroidZ2 += v * cz; d3_geo_centroidW1 += w; d3_geo_centroidX1 += w * (x0 + (x0 = x)); d3_geo_centroidY1 += w * (y0 + (y0 = y)); d3_geo_centroidZ1 += w * (z0 + (z0 = z)); d3_geo_centroidPointXYZ(x0, y0, z0); } } function d3_geo_compose(a, b) { function compose(x, y) { return x = a(x, y), b(x[0], x[1]); } if (a.invert && b.invert) compose.invert = function(x, y) { return x = b.invert(x, y), x && a.invert(x[0], x[1]); }; return compose; } function d3_true() { return true; } function d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener) { var subject = [], clip = []; segments.forEach(function(segment) { if ((n = segment.length - 1) <= 0) return; var n, p0 = segment[0], p1 = segment[n]; if (d3_geo_sphericalEqual(p0, p1)) { listener.lineStart(); for (var i = 0; i < n; ++i) listener.point((p0 = segment[i])[0], p0[1]); listener.lineEnd(); return; } var a = new d3_geo_clipPolygonIntersection(p0, segment, null, true), b = new d3_geo_clipPolygonIntersection(p0, null, a, false); a.o = b; subject.push(a); clip.push(b); a = new d3_geo_clipPolygonIntersection(p1, segment, null, false); b = new d3_geo_clipPolygonIntersection(p1, null, a, true); a.o = b; subject.push(a); clip.push(b); }); clip.sort(compare); d3_geo_clipPolygonLinkCircular(subject); d3_geo_clipPolygonLinkCircular(clip); if (!subject.length) return; for (var i = 0, entry = clipStartInside, n = clip.length; i < n; ++i) { clip[i].e = entry = !entry; } var start = subject[0], points, point; while (1) { var current = start, isSubject = true; while (current.v) if ((current = current.n) === start) return; points = current.z; listener.lineStart(); do { current.v = current.o.v = true; if (current.e) { if (isSubject) { for (var i = 0, n = points.length; i < n; ++i) listener.point((point = points[i])[0], point[1]); } else { interpolate(current.x, current.n.x, 1, listener); } current = current.n; } else { if (isSubject) { points = current.p.z; for (var i = points.length - 1; i >= 0; --i) listener.point((point = points[i])[0], point[1]); } else { interpolate(current.x, current.p.x, -1, listener); } current = current.p; } current = current.o; points = current.z; isSubject = !isSubject; } while (!current.v); listener.lineEnd(); } } function d3_geo_clipPolygonLinkCircular(array) { if (!(n = array.length)) return; var n, i = 0, a = array[0], b; while (++i < n) { a.n = b = array[i]; b.p = a; a = b; } a.n = b = array[0]; b.p = a; } function d3_geo_clipPolygonIntersection(point, points, other, entry) { this.x = point; this.z = points; this.o = other; this.e = entry; this.v = false; this.n = this.p = null; } function d3_geo_clip(pointVisible, clipLine, interpolate, clipStart) { return function(rotate, listener) { var line = clipLine(listener), rotatedClipStart = rotate.invert(clipStart[0], clipStart[1]); var clip = { point: point, lineStart: lineStart, lineEnd: lineEnd, polygonStart: function() { clip.point = pointRing; clip.lineStart = ringStart; clip.lineEnd = ringEnd; segments = []; polygon = []; }, polygonEnd: function() { clip.point = point; clip.lineStart = lineStart; clip.lineEnd = lineEnd; segments = d3.merge(segments); var clipStartInside = d3_geo_pointInPolygon(rotatedClipStart, polygon); if (segments.length) { if (!polygonStarted) listener.polygonStart(), polygonStarted = true; d3_geo_clipPolygon(segments, d3_geo_clipSort, clipStartInside, interpolate, listener); } else if (clipStartInside) { if (!polygonStarted) listener.polygonStart(), polygonStarted = true; listener.lineStart(); interpolate(null, null, 1, listener); listener.lineEnd(); } if (polygonStarted) listener.polygonEnd(), polygonStarted = false; segments = polygon = null; }, sphere: function() { listener.polygonStart(); listener.lineStart(); interpolate(null, null, 1, listener); listener.lineEnd(); listener.polygonEnd(); } }; function point(λ, φ) { var point = rotate(λ, φ); if (pointVisible(λ = point[0], φ = point[1])) listener.point(λ, φ); } function pointLine(λ, φ) { var point = rotate(λ, φ); line.point(point[0], point[1]); } function lineStart() { clip.point = pointLine; line.lineStart(); } function lineEnd() { clip.point = point; line.lineEnd(); } var segments; var buffer = d3_geo_clipBufferListener(), ringListener = clipLine(buffer), polygonStarted = false, polygon, ring; function pointRing(λ, φ) { ring.push([ λ, φ ]); var point = rotate(λ, φ); ringListener.point(point[0], point[1]); } function ringStart() { ringListener.lineStart(); ring = []; } function ringEnd() { pointRing(ring[0][0], ring[0][1]); ringListener.lineEnd(); var clean = ringListener.clean(), ringSegments = buffer.buffer(), segment, n = ringSegments.length; ring.pop(); polygon.push(ring); ring = null; if (!n) return; if (clean & 1) { segment = ringSegments[0]; var n = segment.length - 1, i = -1, point; if (n > 0) { if (!polygonStarted) listener.polygonStart(), polygonStarted = true; listener.lineStart(); while (++i < n) listener.point((point = segment[i])[0], point[1]); listener.lineEnd(); } return; } if (n > 1 && clean & 2) ringSegments.push(ringSegments.pop().concat(ringSegments.shift())); segments.push(ringSegments.filter(d3_geo_clipSegmentLength1)); } return clip; }; } function d3_geo_clipSegmentLength1(segment) { return segment.length > 1; } function d3_geo_clipBufferListener() { var lines = [], line; return { lineStart: function() { lines.push(line = []); }, point: function(λ, φ) { line.push([ λ, φ ]); }, lineEnd: d3_noop, buffer: function() { var buffer = lines; lines = []; line = null; return buffer; }, rejoin: function() { if (lines.length > 1) lines.push(lines.pop().concat(lines.shift())); } }; } function d3_geo_clipSort(a, b) { return ((a = a.x)[0] < 0 ? a[1] - halfπ - ε : halfπ - a[1]) - ((b = b.x)[0] < 0 ? b[1] - halfπ - ε : halfπ - b[1]); } var d3_geo_clipAntimeridian = d3_geo_clip(d3_true, d3_geo_clipAntimeridianLine, d3_geo_clipAntimeridianInterpolate, [ -π, -π / 2 ]); function d3_geo_clipAntimeridianLine(listener) { var λ0 = NaN, φ0 = NaN, sλ0 = NaN, clean; return { lineStart: function() { listener.lineStart(); clean = 1; }, point: function(λ1, φ1) { var sλ1 = λ1 > 0 ? π : -π, dλ = abs(λ1 - λ0); if (abs(dλ - π) < ε) { listener.point(λ0, φ0 = (φ0 + φ1) / 2 > 0 ? halfπ : -halfπ); listener.point(sλ0, φ0); listener.lineEnd(); listener.lineStart(); listener.point(sλ1, φ0); listener.point(λ1, φ0); clean = 0; } else if (sλ0 !== sλ1 && dλ >= π) { if (abs(λ0 - sλ0) < ε) λ0 -= sλ0 * ε; if (abs(λ1 - sλ1) < ε) λ1 -= sλ1 * ε; φ0 = d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1); listener.point(sλ0, φ0); listener.lineEnd(); listener.lineStart(); listener.point(sλ1, φ0); clean = 0; } listener.point(λ0 = λ1, φ0 = φ1); sλ0 = sλ1; }, lineEnd: function() { listener.lineEnd(); λ0 = φ0 = NaN; }, clean: function() { return 2 - clean; } }; } function d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1) { var cosφ0, cosφ1, sinλ0_λ1 = Math.sin(λ0 - λ1); return abs(sinλ0_λ1) > ε ? Math.atan((Math.sin(φ0) * (cosφ1 = Math.cos(φ1)) * Math.sin(λ1) - Math.sin(φ1) * (cosφ0 = Math.cos(φ0)) * Math.sin(λ0)) / (cosφ0 * cosφ1 * sinλ0_λ1)) : (φ0 + φ1) / 2; } function d3_geo_clipAntimeridianInterpolate(from, to, direction, listener) { var φ; if (from == null) { φ = direction * halfπ; listener.point(-π, φ); listener.point(0, φ); listener.point(π, φ); listener.point(π, 0); listener.point(π, -φ); listener.point(0, -φ); listener.point(-π, -φ); listener.point(-π, 0); listener.point(-π, φ); } else if (abs(from[0] - to[0]) > ε) { var s = from[0] < to[0] ? π : -π; φ = direction * s / 2; listener.point(-s, φ); listener.point(0, φ); listener.point(s, φ); } else { listener.point(to[0], to[1]); } } function d3_geo_pointInPolygon(point, polygon) { var meridian = point[0], parallel = point[1], meridianNormal = [ Math.sin(meridian), -Math.cos(meridian), 0 ], polarAngle = 0, winding = 0; d3_geo_areaRingSum.reset(); for (var i = 0, n = polygon.length; i < n; ++i) { var ring = polygon[i], m = ring.length; if (!m) continue; var point0 = ring[0], λ0 = point0[0], φ0 = point0[1] / 2 + π / 4, sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), j = 1; while (true) { if (j === m) j = 0; point = ring[j]; var λ = point[0], φ = point[1] / 2 + π / 4, sinφ = Math.sin(φ), cosφ = Math.cos(φ), dλ = λ - λ0, sdλ = dλ >= 0 ? 1 : -1, adλ = sdλ * dλ, antimeridian = adλ > π, k = sinφ0 * sinφ; d3_geo_areaRingSum.add(Math.atan2(k * sdλ * Math.sin(adλ), cosφ0 * cosφ + k * Math.cos(adλ))); polarAngle += antimeridian ? dλ + sdλ * τ : dλ; if (antimeridian ^ λ0 >= meridian ^ λ >= meridian) { var arc = d3_geo_cartesianCross(d3_geo_cartesian(point0), d3_geo_cartesian(point)); d3_geo_cartesianNormalize(arc); var intersection = d3_geo_cartesianCross(meridianNormal, arc); d3_geo_cartesianNormalize(intersection); var φarc = (antimeridian ^ dλ >= 0 ? -1 : 1) * d3_asin(intersection[2]); if (parallel > φarc || parallel === φarc && (arc[0] || arc[1])) { winding += antimeridian ^ dλ >= 0 ? 1 : -1; } } if (!j++) break; λ0 = λ, sinφ0 = sinφ, cosφ0 = cosφ, point0 = point; } } return (polarAngle < -ε || polarAngle < ε && d3_geo_areaRingSum < 0) ^ winding & 1; } function d3_geo_clipCircle(radius) { var cr = Math.cos(radius), smallRadius = cr > 0, notHemisphere = abs(cr) > ε, interpolate = d3_geo_circleInterpolate(radius, 6 * d3_radians); return d3_geo_clip(visible, clipLine, interpolate, smallRadius ? [ 0, -radius ] : [ -π, radius - π ]); function visible(λ, φ) { return Math.cos(λ) * Math.cos(φ) > cr; } function clipLine(listener) { var point0, c0, v0, v00, clean; return { lineStart: function() { v00 = v0 = false; clean = 1; }, point: function(λ, φ) { var point1 = [ λ, φ ], point2, v = visible(λ, φ), c = smallRadius ? v ? 0 : code(λ, φ) : v ? code(λ + (λ < 0 ? π : -π), φ) : 0; if (!point0 && (v00 = v0 = v)) listener.lineStart(); if (v !== v0) { point2 = intersect(point0, point1); if (d3_geo_sphericalEqual(point0, point2) || d3_geo_sphericalEqual(point1, point2)) { point1[0] += ε; point1[1] += ε; v = visible(point1[0], point1[1]); } } if (v !== v0) { clean = 0; if (v) { listener.lineStart(); point2 = intersect(point1, point0); listener.point(point2[0], point2[1]); } else { point2 = intersect(point0, point1); listener.point(point2[0], point2[1]); listener.lineEnd(); } point0 = point2; } else if (notHemisphere && point0 && smallRadius ^ v) { var t; if (!(c & c0) && (t = intersect(point1, point0, true))) { clean = 0; if (smallRadius) { listener.lineStart(); listener.point(t[0][0], t[0][1]); listener.point(t[1][0], t[1][1]); listener.lineEnd(); } else { listener.point(t[1][0], t[1][1]); listener.lineEnd(); listener.lineStart(); listener.point(t[0][0], t[0][1]); } } } if (v && (!point0 || !d3_geo_sphericalEqual(point0, point1))) { listener.point(point1[0], point1[1]); } point0 = point1, v0 = v, c0 = c; }, lineEnd: function() { if (v0) listener.lineEnd(); point0 = null; }, clean: function() { return clean | (v00 && v0) << 1; } }; } function intersect(a, b, two) { var pa = d3_geo_cartesian(a), pb = d3_geo_cartesian(b); var n1 = [ 1, 0, 0 ], n2 = d3_geo_cartesianCross(pa, pb), n2n2 = d3_geo_cartesianDot(n2, n2), n1n2 = n2[0], determinant = n2n2 - n1n2 * n1n2; if (!determinant) return !two && a; var c1 = cr * n2n2 / determinant, c2 = -cr * n1n2 / determinant, n1xn2 = d3_geo_cartesianCross(n1, n2), A = d3_geo_cartesianScale(n1, c1), B = d3_geo_cartesianScale(n2, c2); d3_geo_cartesianAdd(A, B); var u = n1xn2, w = d3_geo_cartesianDot(A, u), uu = d3_geo_cartesianDot(u, u), t2 = w * w - uu * (d3_geo_cartesianDot(A, A) - 1); if (t2 < 0) return; var t = Math.sqrt(t2), q = d3_geo_cartesianScale(u, (-w - t) / uu); d3_geo_cartesianAdd(q, A); q = d3_geo_spherical(q); if (!two) return q; var λ0 = a[0], λ1 = b[0], φ0 = a[1], φ1 = b[1], z; if (λ1 < λ0) z = λ0, λ0 = λ1, λ1 = z; var δλ = λ1 - λ0, polar = abs(δλ - π) < ε, meridian = polar || δλ < ε; if (!polar && φ1 < φ0) z = φ0, φ0 = φ1, φ1 = z; if (meridian ? polar ? φ0 + φ1 > 0 ^ q[1] < (abs(q[0] - λ0) < ε ? φ0 : φ1) : φ0 <= q[1] && q[1] <= φ1 : δλ > π ^ (λ0 <= q[0] && q[0] <= λ1)) { var q1 = d3_geo_cartesianScale(u, (-w + t) / uu); d3_geo_cartesianAdd(q1, A); return [ q, d3_geo_spherical(q1) ]; } } function code(λ, φ) { var r = smallRadius ? radius : π - radius, code = 0; if (λ < -r) code |= 1; else if (λ > r) code |= 2; if (φ < -r) code |= 4; else if (φ > r) code |= 8; return code; } } function d3_geom_clipLine(x0, y0, x1, y1) { return function(line) { var a = line.a, b = line.b, ax = a.x, ay = a.y, bx = b.x, by = b.y, t0 = 0, t1 = 1, dx = bx - ax, dy = by - ay, r; r = x0 - ax; if (!dx && r > 0) return; r /= dx; if (dx < 0) { if (r < t0) return; if (r < t1) t1 = r; } else if (dx > 0) { if (r > t1) return; if (r > t0) t0 = r; } r = x1 - ax; if (!dx && r < 0) return; r /= dx; if (dx < 0) { if (r > t1) return; if (r > t0) t0 = r; } else if (dx > 0) { if (r < t0) return; if (r < t1) t1 = r; } r = y0 - ay; if (!dy && r > 0) return; r /= dy; if (dy < 0) { if (r < t0) return; if (r < t1) t1 = r; } else if (dy > 0) { if (r > t1) return; if (r > t0) t0 = r; } r = y1 - ay; if (!dy && r < 0) return; r /= dy; if (dy < 0) { if (r > t1) return; if (r > t0) t0 = r; } else if (dy > 0) { if (r < t0) return; if (r < t1) t1 = r; } if (t0 > 0) line.a = { x: ax + t0 * dx, y: ay + t0 * dy }; if (t1 < 1) line.b = { x: ax + t1 * dx, y: ay + t1 * dy }; return line; }; } var d3_geo_clipExtentMAX = 1e9; d3.geo.clipExtent = function() { var x0, y0, x1, y1, stream, clip, clipExtent = { stream: function(output) { if (stream) stream.valid = false; stream = clip(output); stream.valid = true; return stream; }, extent: function(_) { if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ]; clip = d3_geo_clipExtent(x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1]); if (stream) stream.valid = false, stream = null; return clipExtent; } }; return clipExtent.extent([ [ 0, 0 ], [ 960, 500 ] ]); }; function d3_geo_clipExtent(x0, y0, x1, y1) { return function(listener) { var listener_ = listener, bufferListener = d3_geo_clipBufferListener(), clipLine = d3_geom_clipLine(x0, y0, x1, y1), segments, polygon, ring; var clip = { point: point, lineStart: lineStart, lineEnd: lineEnd, polygonStart: function() { listener = bufferListener; segments = []; polygon = []; clean = true; }, polygonEnd: function() { listener = listener_; segments = d3.merge(segments); var clipStartInside = insidePolygon([ x0, y1 ]), inside = clean && clipStartInside, visible = segments.length; if (inside || visible) { listener.polygonStart(); if (inside) { listener.lineStart(); interpolate(null, null, 1, listener); listener.lineEnd(); } if (visible) { d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener); } listener.polygonEnd(); } segments = polygon = ring = null; } }; function insidePolygon(p) { var wn = 0, n = polygon.length, y = p[1]; for (var i = 0; i < n; ++i) { for (var j = 1, v = polygon[i], m = v.length, a = v[0], b; j < m; ++j) { b = v[j]; if (a[1] <= y) { if (b[1] > y && d3_cross2d(a, b, p) > 0) ++wn; } else { if (b[1] <= y && d3_cross2d(a, b, p) < 0) --wn; } a = b; } } return wn !== 0; } function interpolate(from, to, direction, listener) { var a = 0, a1 = 0; if (from == null || (a = corner(from, direction)) !== (a1 = corner(to, direction)) || comparePoints(from, to) < 0 ^ direction > 0) { do { listener.point(a === 0 || a === 3 ? x0 : x1, a > 1 ? y1 : y0); } while ((a = (a + direction + 4) % 4) !== a1); } else { listener.point(to[0], to[1]); } } function pointVisible(x, y) { return x0 <= x && x <= x1 && y0 <= y && y <= y1; } function point(x, y) { if (pointVisible(x, y)) listener.point(x, y); } var x__, y__, v__, x_, y_, v_, first, clean; function lineStart() { clip.point = linePoint; if (polygon) polygon.push(ring = []); first = true; v_ = false; x_ = y_ = NaN; } function lineEnd() { if (segments) { linePoint(x__, y__); if (v__ && v_) bufferListener.rejoin(); segments.push(bufferListener.buffer()); } clip.point = point; if (v_) listener.lineEnd(); } function linePoint(x, y) { x = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, x)); y = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, y)); var v = pointVisible(x, y); if (polygon) ring.push([ x, y ]); if (first) { x__ = x, y__ = y, v__ = v; first = false; if (v) { listener.lineStart(); listener.point(x, y); } } else { if (v && v_) listener.point(x, y); else { var l = { a: { x: x_, y: y_ }, b: { x: x, y: y } }; if (clipLine(l)) { if (!v_) { listener.lineStart(); listener.point(l.a.x, l.a.y); } listener.point(l.b.x, l.b.y); if (!v) listener.lineEnd(); clean = false; } else if (v) { listener.lineStart(); listener.point(x, y); clean = false; } } } x_ = x, y_ = y, v_ = v; } return clip; }; function corner(p, direction) { return abs(p[0] - x0) < ε ? direction > 0 ? 0 : 3 : abs(p[0] - x1) < ε ? direction > 0 ? 2 : 1 : abs(p[1] - y0) < ε ? direction > 0 ? 1 : 0 : direction > 0 ? 3 : 2; } function compare(a, b) { return comparePoints(a.x, b.x); } function comparePoints(a, b) { var ca = corner(a, 1), cb = corner(b, 1); return ca !== cb ? ca - cb : ca === 0 ? b[1] - a[1] : ca === 1 ? a[0] - b[0] : ca === 2 ? a[1] - b[1] : b[0] - a[0]; } } function d3_geo_conic(projectAt) { var φ0 = 0, φ1 = π / 3, m = d3_geo_projectionMutator(projectAt), p = m(φ0, φ1); p.parallels = function(_) { if (!arguments.length) return [ φ0 / π * 180, φ1 / π * 180 ]; return m(φ0 = _[0] * π / 180, φ1 = _[1] * π / 180); }; return p; } function d3_geo_conicEqualArea(φ0, φ1) { var sinφ0 = Math.sin(φ0), n = (sinφ0 + Math.sin(φ1)) / 2, C = 1 + sinφ0 * (2 * n - sinφ0), ρ0 = Math.sqrt(C) / n; function forward(λ, φ) { var ρ = Math.sqrt(C - 2 * n * Math.sin(φ)) / n; return [ ρ * Math.sin(λ *= n), ρ0 - ρ * Math.cos(λ) ]; } forward.invert = function(x, y) { var ρ0_y = ρ0 - y; return [ Math.atan2(x, ρ0_y) / n, d3_asin((C - (x * x + ρ0_y * ρ0_y) * n * n) / (2 * n)) ]; }; return forward; } (d3.geo.conicEqualArea = function() { return d3_geo_conic(d3_geo_conicEqualArea); }).raw = d3_geo_conicEqualArea; d3.geo.albers = function() { return d3.geo.conicEqualArea().rotate([ 96, 0 ]).center([ -.6, 38.7 ]).parallels([ 29.5, 45.5 ]).scale(1070); }; d3.geo.albersUsa = function() { var lower48 = d3.geo.albers(); var alaska = d3.geo.conicEqualArea().rotate([ 154, 0 ]).center([ -2, 58.5 ]).parallels([ 55, 65 ]); var hawaii = d3.geo.conicEqualArea().rotate([ 157, 0 ]).center([ -3, 19.9 ]).parallels([ 8, 18 ]); var point, pointStream = { point: function(x, y) { point = [ x, y ]; } }, lower48Point, alaskaPoint, hawaiiPoint; function albersUsa(coordinates) { var x = coordinates[0], y = coordinates[1]; point = null; (lower48Point(x, y), point) || (alaskaPoint(x, y), point) || hawaiiPoint(x, y); return point; } albersUsa.invert = function(coordinates) { var k = lower48.scale(), t = lower48.translate(), x = (coordinates[0] - t[0]) / k, y = (coordinates[1] - t[1]) / k; return (y >= .12 && y < .234 && x >= -.425 && x < -.214 ? alaska : y >= .166 && y < .234 && x >= -.214 && x < -.115 ? hawaii : lower48).invert(coordinates); }; albersUsa.stream = function(stream) { var lower48Stream = lower48.stream(stream), alaskaStream = alaska.stream(stream), hawaiiStream = hawaii.stream(stream); return { point: function(x, y) { lower48Stream.point(x, y); alaskaStream.point(x, y); hawaiiStream.point(x, y); }, sphere: function() { lower48Stream.sphere(); alaskaStream.sphere(); hawaiiStream.sphere(); }, lineStart: function() { lower48Stream.lineStart(); alaskaStream.lineStart(); hawaiiStream.lineStart(); }, lineEnd: function() { lower48Stream.lineEnd(); alaskaStream.lineEnd(); hawaiiStream.lineEnd(); }, polygonStart: function() { lower48Stream.polygonStart(); alaskaStream.polygonStart(); hawaiiStream.polygonStart(); }, polygonEnd: function() { lower48Stream.polygonEnd(); alaskaStream.polygonEnd(); hawaiiStream.polygonEnd(); } }; }; albersUsa.precision = function(_) { if (!arguments.length) return lower48.precision(); lower48.precision(_); alaska.precision(_); hawaii.precision(_); return albersUsa; }; albersUsa.scale = function(_) { if (!arguments.length) return lower48.scale(); lower48.scale(_); alaska.scale(_ * .35); hawaii.scale(_); return albersUsa.translate(lower48.translate()); }; albersUsa.translate = function(_) { if (!arguments.length) return lower48.translate(); var k = lower48.scale(), x = +_[0], y = +_[1]; lower48Point = lower48.translate(_).clipExtent([ [ x - .455 * k, y - .238 * k ], [ x + .455 * k, y + .238 * k ] ]).stream(pointStream).point; alaskaPoint = alaska.translate([ x - .307 * k, y + .201 * k ]).clipExtent([ [ x - .425 * k + ε, y + .12 * k + ε ], [ x - .214 * k - ε, y + .234 * k - ε ] ]).stream(pointStream).point; hawaiiPoint = hawaii.translate([ x - .205 * k, y + .212 * k ]).clipExtent([ [ x - .214 * k + ε, y + .166 * k + ε ], [ x - .115 * k - ε, y + .234 * k - ε ] ]).stream(pointStream).point; return albersUsa; }; return albersUsa.scale(1070); }; var d3_geo_pathAreaSum, d3_geo_pathAreaPolygon, d3_geo_pathArea = { point: d3_noop, lineStart: d3_noop, lineEnd: d3_noop, polygonStart: function() { d3_geo_pathAreaPolygon = 0; d3_geo_pathArea.lineStart = d3_geo_pathAreaRingStart; }, polygonEnd: function() { d3_geo_pathArea.lineStart = d3_geo_pathArea.lineEnd = d3_geo_pathArea.point = d3_noop; d3_geo_pathAreaSum += abs(d3_geo_pathAreaPolygon / 2); } }; function d3_geo_pathAreaRingStart() { var x00, y00, x0, y0; d3_geo_pathArea.point = function(x, y) { d3_geo_pathArea.point = nextPoint; x00 = x0 = x, y00 = y0 = y; }; function nextPoint(x, y) { d3_geo_pathAreaPolygon += y0 * x - x0 * y; x0 = x, y0 = y; } d3_geo_pathArea.lineEnd = function() { nextPoint(x00, y00); }; } var d3_geo_pathBoundsX0, d3_geo_pathBoundsY0, d3_geo_pathBoundsX1, d3_geo_pathBoundsY1; var d3_geo_pathBounds = { point: d3_geo_pathBoundsPoint, lineStart: d3_noop, lineEnd: d3_noop, polygonStart: d3_noop, polygonEnd: d3_noop }; function d3_geo_pathBoundsPoint(x, y) { if (x < d3_geo_pathBoundsX0) d3_geo_pathBoundsX0 = x; if (x > d3_geo_pathBoundsX1) d3_geo_pathBoundsX1 = x; if (y < d3_geo_pathBoundsY0) d3_geo_pathBoundsY0 = y; if (y > d3_geo_pathBoundsY1) d3_geo_pathBoundsY1 = y; } function d3_geo_pathBuffer() { var pointCircle = d3_geo_pathBufferCircle(4.5), buffer = []; var stream = { point: point, lineStart: function() { stream.point = pointLineStart; }, lineEnd: lineEnd, polygonStart: function() { stream.lineEnd = lineEndPolygon; }, polygonEnd: function() { stream.lineEnd = lineEnd; stream.point = point; }, pointRadius: function(_) { pointCircle = d3_geo_pathBufferCircle(_); return stream; }, result: function() { if (buffer.length) { var result = buffer.join(""); buffer = []; return result; } } }; function point(x, y) { buffer.push("M", x, ",", y, pointCircle); } function pointLineStart(x, y) { buffer.push("M", x, ",", y); stream.point = pointLine; } function pointLine(x, y) { buffer.push("L", x, ",", y); } function lineEnd() { stream.point = point; } function lineEndPolygon() { buffer.push("Z"); } return stream; } function d3_geo_pathBufferCircle(radius) { return "m0," + radius + "a" + radius + "," + radius + " 0 1,1 0," + -2 * radius + "a" + radius + "," + radius + " 0 1,1 0," + 2 * radius + "z"; } var d3_geo_pathCentroid = { point: d3_geo_pathCentroidPoint, lineStart: d3_geo_pathCentroidLineStart, lineEnd: d3_geo_pathCentroidLineEnd, polygonStart: function() { d3_geo_pathCentroid.lineStart = d3_geo_pathCentroidRingStart; }, polygonEnd: function() { d3_geo_pathCentroid.point = d3_geo_pathCentroidPoint; d3_geo_pathCentroid.lineStart = d3_geo_pathCentroidLineStart; d3_geo_pathCentroid.lineEnd = d3_geo_pathCentroidLineEnd; } }; function d3_geo_pathCentroidPoint(x, y) { d3_geo_centroidX0 += x; d3_geo_centroidY0 += y; ++d3_geo_centroidZ0; } function d3_geo_pathCentroidLineStart() { var x0, y0; d3_geo_pathCentroid.point = function(x, y) { d3_geo_pathCentroid.point = nextPoint; d3_geo_pathCentroidPoint(x0 = x, y0 = y); }; function nextPoint(x, y) { var dx = x - x0, dy = y - y0, z = Math.sqrt(dx * dx + dy * dy); d3_geo_centroidX1 += z * (x0 + x) / 2; d3_geo_centroidY1 += z * (y0 + y) / 2; d3_geo_centroidZ1 += z; d3_geo_pathCentroidPoint(x0 = x, y0 = y); } } function d3_geo_pathCentroidLineEnd() { d3_geo_pathCentroid.point = d3_geo_pathCentroidPoint; } function d3_geo_pathCentroidRingStart() { var x00, y00, x0, y0; d3_geo_pathCentroid.point = function(x, y) { d3_geo_pathCentroid.point = nextPoint; d3_geo_pathCentroidPoint(x00 = x0 = x, y00 = y0 = y); }; function nextPoint(x, y) { var dx = x - x0, dy = y - y0, z = Math.sqrt(dx * dx + dy * dy); d3_geo_centroidX1 += z * (x0 + x) / 2; d3_geo_centroidY1 += z * (y0 + y) / 2; d3_geo_centroidZ1 += z; z = y0 * x - x0 * y; d3_geo_centroidX2 += z * (x0 + x); d3_geo_centroidY2 += z * (y0 + y); d3_geo_centroidZ2 += z * 3; d3_geo_pathCentroidPoint(x0 = x, y0 = y); } d3_geo_pathCentroid.lineEnd = function() { nextPoint(x00, y00); }; } function d3_geo_pathContext(context) { var pointRadius = 4.5; var stream = { point: point, lineStart: function() { stream.point = pointLineStart; }, lineEnd: lineEnd, polygonStart: function() { stream.lineEnd = lineEndPolygon; }, polygonEnd: function() { stream.lineEnd = lineEnd; stream.point = point; }, pointRadius: function(_) { pointRadius = _; return stream; }, result: d3_noop }; function point(x, y) { context.moveTo(x + pointRadius, y); context.arc(x, y, pointRadius, 0, τ); } function pointLineStart(x, y) { context.moveTo(x, y); stream.point = pointLine; } function pointLine(x, y) { context.lineTo(x, y); } function lineEnd() { stream.point = point; } function lineEndPolygon() { context.closePath(); } return stream; } function d3_geo_resample(project) { var δ2 = .5, cosMinDistance = Math.cos(30 * d3_radians), maxDepth = 16; function resample(stream) { return (maxDepth ? resampleRecursive : resampleNone)(stream); } function resampleNone(stream) { return d3_geo_transformPoint(stream, function(x, y) { x = project(x, y); stream.point(x[0], x[1]); }); } function resampleRecursive(stream) { var λ00, φ00, x00, y00, a00, b00, c00, λ0, x0, y0, a0, b0, c0; var resample = { point: point, lineStart: lineStart, lineEnd: lineEnd, polygonStart: function() { stream.polygonStart(); resample.lineStart = ringStart; }, polygonEnd: function() { stream.polygonEnd(); resample.lineStart = lineStart; } }; function point(x, y) { x = project(x, y); stream.point(x[0], x[1]); } function lineStart() { x0 = NaN; resample.point = linePoint; stream.lineStart(); } function linePoint(λ, φ) { var c = d3_geo_cartesian([ λ, φ ]), p = project(λ, φ); resampleLineTo(x0, y0, λ0, a0, b0, c0, x0 = p[0], y0 = p[1], λ0 = λ, a0 = c[0], b0 = c[1], c0 = c[2], maxDepth, stream); stream.point(x0, y0); } function lineEnd() { resample.point = point; stream.lineEnd(); } function ringStart() { lineStart(); resample.point = ringPoint; resample.lineEnd = ringEnd; } function ringPoint(λ, φ) { linePoint(λ00 = λ, φ00 = φ), x00 = x0, y00 = y0, a00 = a0, b00 = b0, c00 = c0; resample.point = linePoint; } function ringEnd() { resampleLineTo(x0, y0, λ0, a0, b0, c0, x00, y00, λ00, a00, b00, c00, maxDepth, stream); resample.lineEnd = lineEnd; lineEnd(); } return resample; } function resampleLineTo(x0, y0, λ0, a0, b0, c0, x1, y1, λ1, a1, b1, c1, depth, stream) { var dx = x1 - x0, dy = y1 - y0, d2 = dx * dx + dy * dy; if (d2 > 4 * δ2 && depth--) { var a = a0 + a1, b = b0 + b1, c = c0 + c1, m = Math.sqrt(a * a + b * b + c * c), φ2 = Math.asin(c /= m), λ2 = abs(abs(c) - 1) < ε || abs(λ0 - λ1) < ε ? (λ0 + λ1) / 2 : Math.atan2(b, a), p = project(λ2, φ2), x2 = p[0], y2 = p[1], dx2 = x2 - x0, dy2 = y2 - y0, dz = dy * dx2 - dx * dy2; if (dz * dz / d2 > δ2 || abs((dx * dx2 + dy * dy2) / d2 - .5) > .3 || a0 * a1 + b0 * b1 + c0 * c1 < cosMinDistance) { resampleLineTo(x0, y0, λ0, a0, b0, c0, x2, y2, λ2, a /= m, b /= m, c, depth, stream); stream.point(x2, y2); resampleLineTo(x2, y2, λ2, a, b, c, x1, y1, λ1, a1, b1, c1, depth, stream); } } } resample.precision = function(_) { if (!arguments.length) return Math.sqrt(δ2); maxDepth = (δ2 = _ * _) > 0 && 16; return resample; }; return resample; } d3.geo.path = function() { var pointRadius = 4.5, projection, context, projectStream, contextStream, cacheStream; function path(object) { if (object) { if (typeof pointRadius === "function") contextStream.pointRadius(+pointRadius.apply(this, arguments)); if (!cacheStream || !cacheStream.valid) cacheStream = projectStream(contextStream); d3.geo.stream(object, cacheStream); } return contextStream.result(); } path.area = function(object) { d3_geo_pathAreaSum = 0; d3.geo.stream(object, projectStream(d3_geo_pathArea)); return d3_geo_pathAreaSum; }; path.centroid = function(object) { d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0; d3.geo.stream(object, projectStream(d3_geo_pathCentroid)); return d3_geo_centroidZ2 ? [ d3_geo_centroidX2 / d3_geo_centroidZ2, d3_geo_centroidY2 / d3_geo_centroidZ2 ] : d3_geo_centroidZ1 ? [ d3_geo_centroidX1 / d3_geo_centroidZ1, d3_geo_centroidY1 / d3_geo_centroidZ1 ] : d3_geo_centroidZ0 ? [ d3_geo_centroidX0 / d3_geo_centroidZ0, d3_geo_centroidY0 / d3_geo_centroidZ0 ] : [ NaN, NaN ]; }; path.bounds = function(object) { d3_geo_pathBoundsX1 = d3_geo_pathBoundsY1 = -(d3_geo_pathBoundsX0 = d3_geo_pathBoundsY0 = Infinity); d3.geo.stream(object, projectStream(d3_geo_pathBounds)); return [ [ d3_geo_pathBoundsX0, d3_geo_pathBoundsY0 ], [ d3_geo_pathBoundsX1, d3_geo_pathBoundsY1 ] ]; }; path.projection = function(_) { if (!arguments.length) return projection; projectStream = (projection = _) ? _.stream || d3_geo_pathProjectStream(_) : d3_identity; return reset(); }; path.context = function(_) { if (!arguments.length) return context; contextStream = (context = _) == null ? new d3_geo_pathBuffer() : new d3_geo_pathContext(_); if (typeof pointRadius !== "function") contextStream.pointRadius(pointRadius); return reset(); }; path.pointRadius = function(_) { if (!arguments.length) return pointRadius; pointRadius = typeof _ === "function" ? _ : (contextStream.pointRadius(+_), +_); return path; }; function reset() { cacheStream = null; return path; } return path.projection(d3.geo.albersUsa()).context(null); }; function d3_geo_pathProjectStream(project) { var resample = d3_geo_resample(function(x, y) { return project([ x * d3_degrees, y * d3_degrees ]); }); return function(stream) { return d3_geo_projectionRadians(resample(stream)); }; } d3.geo.transform = function(methods) { return { stream: function(stream) { var transform = new d3_geo_transform(stream); for (var k in methods) transform[k] = methods[k]; return transform; } }; }; function d3_geo_transform(stream) { this.stream = stream; } d3_geo_transform.prototype = { point: function(x, y) { this.stream.point(x, y); }, sphere: function() { this.stream.sphere(); }, lineStart: function() { this.stream.lineStart(); }, lineEnd: function() { this.stream.lineEnd(); }, polygonStart: function() { this.stream.polygonStart(); }, polygonEnd: function() { this.stream.polygonEnd(); } }; function d3_geo_transformPoint(stream, point) { return { point: point, sphere: function() { stream.sphere(); }, lineStart: function() { stream.lineStart(); }, lineEnd: function() { stream.lineEnd(); }, polygonStart: function() { stream.polygonStart(); }, polygonEnd: function() { stream.polygonEnd(); } }; } d3.geo.projection = d3_geo_projection; d3.geo.projectionMutator = d3_geo_projectionMutator; function d3_geo_projection(project) { return d3_geo_projectionMutator(function() { return project; })(); } function d3_geo_projectionMutator(projectAt) { var project, rotate, projectRotate, projectResample = d3_geo_resample(function(x, y) { x = project(x, y); return [ x[0] * k + δx, δy - x[1] * k ]; }), k = 150, x = 480, y = 250, λ = 0, φ = 0, δλ = 0, δφ = 0, δγ = 0, δx, δy, preclip = d3_geo_clipAntimeridian, postclip = d3_identity, clipAngle = null, clipExtent = null, stream; function projection(point) { point = projectRotate(point[0] * d3_radians, point[1] * d3_radians); return [ point[0] * k + δx, δy - point[1] * k ]; } function invert(point) { point = projectRotate.invert((point[0] - δx) / k, (δy - point[1]) / k); return point && [ point[0] * d3_degrees, point[1] * d3_degrees ]; } projection.stream = function(output) { if (stream) stream.valid = false; stream = d3_geo_projectionRadians(preclip(rotate, projectResample(postclip(output)))); stream.valid = true; return stream; }; projection.clipAngle = function(_) { if (!arguments.length) return clipAngle; preclip = _ == null ? (clipAngle = _, d3_geo_clipAntimeridian) : d3_geo_clipCircle((clipAngle = +_) * d3_radians); return invalidate(); }; projection.clipExtent = function(_) { if (!arguments.length) return clipExtent; clipExtent = _; postclip = _ ? d3_geo_clipExtent(_[0][0], _[0][1], _[1][0], _[1][1]) : d3_identity; return invalidate(); }; projection.scale = function(_) { if (!arguments.length) return k; k = +_; return reset(); }; projection.translate = function(_) { if (!arguments.length) return [ x, y ]; x = +_[0]; y = +_[1]; return reset(); }; projection.center = function(_) { if (!arguments.length) return [ λ * d3_degrees, φ * d3_degrees ]; λ = _[0] % 360 * d3_radians; φ = _[1] % 360 * d3_radians; return reset(); }; projection.rotate = function(_) { if (!arguments.length) return [ δλ * d3_degrees, δφ * d3_degrees, δγ * d3_degrees ]; δλ = _[0] % 360 * d3_radians; δφ = _[1] % 360 * d3_radians; δγ = _.length > 2 ? _[2] % 360 * d3_radians : 0; return reset(); }; d3.rebind(projection, projectResample, "precision"); function reset() { projectRotate = d3_geo_compose(rotate = d3_geo_rotation(δλ, δφ, δγ), project); var center = project(λ, φ); δx = x - center[0] * k; δy = y + center[1] * k; return invalidate(); } function invalidate() { if (stream) stream.valid = false, stream = null; return projection; } return function() { project = projectAt.apply(this, arguments); projection.invert = project.invert && invert; return reset(); }; } function d3_geo_projectionRadians(stream) { return d3_geo_transformPoint(stream, function(x, y) { stream.point(x * d3_radians, y * d3_radians); }); } function d3_geo_equirectangular(λ, φ) { return [ λ, φ ]; } (d3.geo.equirectangular = function() { return d3_geo_projection(d3_geo_equirectangular); }).raw = d3_geo_equirectangular.invert = d3_geo_equirectangular; d3.geo.rotation = function(rotate) { rotate = d3_geo_rotation(rotate[0] % 360 * d3_radians, rotate[1] * d3_radians, rotate.length > 2 ? rotate[2] * d3_radians : 0); function forward(coordinates) { coordinates = rotate(coordinates[0] * d3_radians, coordinates[1] * d3_radians); return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates; } forward.invert = function(coordinates) { coordinates = rotate.invert(coordinates[0] * d3_radians, coordinates[1] * d3_radians); return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates; }; return forward; }; function d3_geo_identityRotation(λ, φ) { return [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ]; } d3_geo_identityRotation.invert = d3_geo_equirectangular; function d3_geo_rotation(δλ, δφ, δγ) { return δλ ? δφ || δγ ? d3_geo_compose(d3_geo_rotationλ(δλ), d3_geo_rotationφγ(δφ, δγ)) : d3_geo_rotationλ(δλ) : δφ || δγ ? d3_geo_rotationφγ(δφ, δγ) : d3_geo_identityRotation; } function d3_geo_forwardRotationλ(δλ) { return function(λ, φ) { return λ += δλ, [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ]; }; } function d3_geo_rotationλ(δλ) { var rotation = d3_geo_forwardRotationλ(δλ); rotation.invert = d3_geo_forwardRotationλ(-δλ); return rotation; } function d3_geo_rotationφγ(δφ, δγ) { var cosδφ = Math.cos(δφ), sinδφ = Math.sin(δφ), cosδγ = Math.cos(δγ), sinδγ = Math.sin(δγ); function rotation(λ, φ) { var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδφ + x * sinδφ; return [ Math.atan2(y * cosδγ - k * sinδγ, x * cosδφ - z * sinδφ), d3_asin(k * cosδγ + y * sinδγ) ]; } rotation.invert = function(λ, φ) { var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδγ - y * sinδγ; return [ Math.atan2(y * cosδγ + z * sinδγ, x * cosδφ + k * sinδφ), d3_asin(k * cosδφ - x * sinδφ) ]; }; return rotation; } d3.geo.circle = function() { var origin = [ 0, 0 ], angle, precision = 6, interpolate; function circle() { var center = typeof origin === "function" ? origin.apply(this, arguments) : origin, rotate = d3_geo_rotation(-center[0] * d3_radians, -center[1] * d3_radians, 0).invert, ring = []; interpolate(null, null, 1, { point: function(x, y) { ring.push(x = rotate(x, y)); x[0] *= d3_degrees, x[1] *= d3_degrees; } }); return { type: "Polygon", coordinates: [ ring ] }; } circle.origin = function(x) { if (!arguments.length) return origin; origin = x; return circle; }; circle.angle = function(x) { if (!arguments.length) return angle; interpolate = d3_geo_circleInterpolate((angle = +x) * d3_radians, precision * d3_radians); return circle; }; circle.precision = function(_) { if (!arguments.length) return precision; interpolate = d3_geo_circleInterpolate(angle * d3_radians, (precision = +_) * d3_radians); return circle; }; return circle.angle(90); }; function d3_geo_circleInterpolate(radius, precision) { var cr = Math.cos(radius), sr = Math.sin(radius); return function(from, to, direction, listener) { var step = direction * precision; if (from != null) { from = d3_geo_circleAngle(cr, from); to = d3_geo_circleAngle(cr, to); if (direction > 0 ? from < to : from > to) from += direction * τ; } else { from = radius + direction * τ; to = radius - .5 * step; } for (var point, t = from; direction > 0 ? t > to : t < to; t -= step) { listener.point((point = d3_geo_spherical([ cr, -sr * Math.cos(t), -sr * Math.sin(t) ]))[0], point[1]); } }; } function d3_geo_circleAngle(cr, point) { var a = d3_geo_cartesian(point); a[0] -= cr; d3_geo_cartesianNormalize(a); var angle = d3_acos(-a[1]); return ((-a[2] < 0 ? -angle : angle) + 2 * Math.PI - ε) % (2 * Math.PI); } d3.geo.distance = function(a, b) { var Δλ = (b[0] - a[0]) * d3_radians, φ0 = a[1] * d3_radians, φ1 = b[1] * d3_radians, sinΔλ = Math.sin(Δλ), cosΔλ = Math.cos(Δλ), sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), sinφ1 = Math.sin(φ1), cosφ1 = Math.cos(φ1), t; return Math.atan2(Math.sqrt((t = cosφ1 * sinΔλ) * t + (t = cosφ0 * sinφ1 - sinφ0 * cosφ1 * cosΔλ) * t), sinφ0 * sinφ1 + cosφ0 * cosφ1 * cosΔλ); }; d3.geo.graticule = function() { var x1, x0, X1, X0, y1, y0, Y1, Y0, dx = 10, dy = dx, DX = 90, DY = 360, x, y, X, Y, precision = 2.5; function graticule() { return { type: "MultiLineString", coordinates: lines() }; } function lines() { return d3.range(Math.ceil(X0 / DX) * DX, X1, DX).map(X).concat(d3.range(Math.ceil(Y0 / DY) * DY, Y1, DY).map(Y)).concat(d3.range(Math.ceil(x0 / dx) * dx, x1, dx).filter(function(x) { return abs(x % DX) > ε; }).map(x)).concat(d3.range(Math.ceil(y0 / dy) * dy, y1, dy).filter(function(y) { return abs(y % DY) > ε; }).map(y)); } graticule.lines = function() { return lines().map(function(coordinates) { return { type: "LineString", coordinates: coordinates }; }); }; graticule.outline = function() { return { type: "Polygon", coordinates: [ X(X0).concat(Y(Y1).slice(1), X(X1).reverse().slice(1), Y(Y0).reverse().slice(1)) ] }; }; graticule.extent = function(_) { if (!arguments.length) return graticule.minorExtent(); return graticule.majorExtent(_).minorExtent(_); }; graticule.majorExtent = function(_) { if (!arguments.length) return [ [ X0, Y0 ], [ X1, Y1 ] ]; X0 = +_[0][0], X1 = +_[1][0]; Y0 = +_[0][1], Y1 = +_[1][1]; if (X0 > X1) _ = X0, X0 = X1, X1 = _; if (Y0 > Y1) _ = Y0, Y0 = Y1, Y1 = _; return graticule.precision(precision); }; graticule.minorExtent = function(_) { if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ]; x0 = +_[0][0], x1 = +_[1][0]; y0 = +_[0][1], y1 = +_[1][1]; if (x0 > x1) _ = x0, x0 = x1, x1 = _; if (y0 > y1) _ = y0, y0 = y1, y1 = _; return graticule.precision(precision); }; graticule.step = function(_) { if (!arguments.length) return graticule.minorStep(); return graticule.majorStep(_).minorStep(_); }; graticule.majorStep = function(_) { if (!arguments.length) return [ DX, DY ]; DX = +_[0], DY = +_[1]; return graticule; }; graticule.minorStep = function(_) { if (!arguments.length) return [ dx, dy ]; dx = +_[0], dy = +_[1]; return graticule; }; graticule.precision = function(_) { if (!arguments.length) return precision; precision = +_; x = d3_geo_graticuleX(y0, y1, 90); y = d3_geo_graticuleY(x0, x1, precision); X = d3_geo_graticuleX(Y0, Y1, 90); Y = d3_geo_graticuleY(X0, X1, precision); return graticule; }; return graticule.majorExtent([ [ -180, -90 + ε ], [ 180, 90 - ε ] ]).minorExtent([ [ -180, -80 - ε ], [ 180, 80 + ε ] ]); }; function d3_geo_graticuleX(y0, y1, dy) { var y = d3.range(y0, y1 - ε, dy).concat(y1); return function(x) { return y.map(function(y) { return [ x, y ]; }); }; } function d3_geo_graticuleY(x0, x1, dx) { var x = d3.range(x0, x1 - ε, dx).concat(x1); return function(y) { return x.map(function(x) { return [ x, y ]; }); }; } function d3_source(d) { return d.source; } function d3_target(d) { return d.target; } d3.geo.greatArc = function() { var source = d3_source, source_, target = d3_target, target_; function greatArc() { return { type: "LineString", coordinates: [ source_ || source.apply(this, arguments), target_ || target.apply(this, arguments) ] }; } greatArc.distance = function() { return d3.geo.distance(source_ || source.apply(this, arguments), target_ || target.apply(this, arguments)); }; greatArc.source = function(_) { if (!arguments.length) return source; source = _, source_ = typeof _ === "function" ? null : _; return greatArc; }; greatArc.target = function(_) { if (!arguments.length) return target; target = _, target_ = typeof _ === "function" ? null : _; return greatArc; }; greatArc.precision = function() { return arguments.length ? greatArc : 0; }; return greatArc; }; d3.geo.interpolate = function(source, target) { return d3_geo_interpolate(source[0] * d3_radians, source[1] * d3_radians, target[0] * d3_radians, target[1] * d3_radians); }; function d3_geo_interpolate(x0, y0, x1, y1) { var cy0 = Math.cos(y0), sy0 = Math.sin(y0), cy1 = Math.cos(y1), sy1 = Math.sin(y1), kx0 = cy0 * Math.cos(x0), ky0 = cy0 * Math.sin(x0), kx1 = cy1 * Math.cos(x1), ky1 = cy1 * Math.sin(x1), d = 2 * Math.asin(Math.sqrt(d3_haversin(y1 - y0) + cy0 * cy1 * d3_haversin(x1 - x0))), k = 1 / Math.sin(d); var interpolate = d ? function(t) { var B = Math.sin(t *= d) * k, A = Math.sin(d - t) * k, x = A * kx0 + B * kx1, y = A * ky0 + B * ky1, z = A * sy0 + B * sy1; return [ Math.atan2(y, x) * d3_degrees, Math.atan2(z, Math.sqrt(x * x + y * y)) * d3_degrees ]; } : function() { return [ x0 * d3_degrees, y0 * d3_degrees ]; }; interpolate.distance = d; return interpolate; } d3.geo.length = function(object) { d3_geo_lengthSum = 0; d3.geo.stream(object, d3_geo_length); return d3_geo_lengthSum; }; var d3_geo_lengthSum; var d3_geo_length = { sphere: d3_noop, point: d3_noop, lineStart: d3_geo_lengthLineStart, lineEnd: d3_noop, polygonStart: d3_noop, polygonEnd: d3_noop }; function d3_geo_lengthLineStart() { var λ0, sinφ0, cosφ0; d3_geo_length.point = function(λ, φ) { λ0 = λ * d3_radians, sinφ0 = Math.sin(φ *= d3_radians), cosφ0 = Math.cos(φ); d3_geo_length.point = nextPoint; }; d3_geo_length.lineEnd = function() { d3_geo_length.point = d3_geo_length.lineEnd = d3_noop; }; function nextPoint(λ, φ) { var sinφ = Math.sin(φ *= d3_radians), cosφ = Math.cos(φ), t = abs((λ *= d3_radians) - λ0), cosΔλ = Math.cos(t); d3_geo_lengthSum += Math.atan2(Math.sqrt((t = cosφ * Math.sin(t)) * t + (t = cosφ0 * sinφ - sinφ0 * cosφ * cosΔλ) * t), sinφ0 * sinφ + cosφ0 * cosφ * cosΔλ); λ0 = λ, sinφ0 = sinφ, cosφ0 = cosφ; } } function d3_geo_azimuthal(scale, angle) { function azimuthal(λ, φ) { var cosλ = Math.cos(λ), cosφ = Math.cos(φ), k = scale(cosλ * cosφ); return [ k * cosφ * Math.sin(λ), k * Math.sin(φ) ]; } azimuthal.invert = function(x, y) { var ρ = Math.sqrt(x * x + y * y), c = angle(ρ), sinc = Math.sin(c), cosc = Math.cos(c); return [ Math.atan2(x * sinc, ρ * cosc), Math.asin(ρ && y * sinc / ρ) ]; }; return azimuthal; } var d3_geo_azimuthalEqualArea = d3_geo_azimuthal(function(cosλcosφ) { return Math.sqrt(2 / (1 + cosλcosφ)); }, function(ρ) { return 2 * Math.asin(ρ / 2); }); (d3.geo.azimuthalEqualArea = function() { return d3_geo_projection(d3_geo_azimuthalEqualArea); }).raw = d3_geo_azimuthalEqualArea; var d3_geo_azimuthalEquidistant = d3_geo_azimuthal(function(cosλcosφ) { var c = Math.acos(cosλcosφ); return c && c / Math.sin(c); }, d3_identity); (d3.geo.azimuthalEquidistant = function() { return d3_geo_projection(d3_geo_azimuthalEquidistant); }).raw = d3_geo_azimuthalEquidistant; function d3_geo_conicConformal(φ0, φ1) { var cosφ0 = Math.cos(φ0), t = function(φ) { return Math.tan(π / 4 + φ / 2); }, n = φ0 === φ1 ? Math.sin(φ0) : Math.log(cosφ0 / Math.cos(φ1)) / Math.log(t(φ1) / t(φ0)), F = cosφ0 * Math.pow(t(φ0), n) / n; if (!n) return d3_geo_mercator; function forward(λ, φ) { if (F > 0) { if (φ < -halfπ + ε) φ = -halfπ + ε; } else { if (φ > halfπ - ε) φ = halfπ - ε; } var ρ = F / Math.pow(t(φ), n); return [ ρ * Math.sin(n * λ), F - ρ * Math.cos(n * λ) ]; } forward.invert = function(x, y) { var ρ0_y = F - y, ρ = d3_sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y); return [ Math.atan2(x, ρ0_y) / n, 2 * Math.atan(Math.pow(F / ρ, 1 / n)) - halfπ ]; }; return forward; } (d3.geo.conicConformal = function() { return d3_geo_conic(d3_geo_conicConformal); }).raw = d3_geo_conicConformal; function d3_geo_conicEquidistant(φ0, φ1) { var cosφ0 = Math.cos(φ0), n = φ0 === φ1 ? Math.sin(φ0) : (cosφ0 - Math.cos(φ1)) / (φ1 - φ0), G = cosφ0 / n + φ0; if (abs(n) < ε) return d3_geo_equirectangular; function forward(λ, φ) { var ρ = G - φ; return [ ρ * Math.sin(n * λ), G - ρ * Math.cos(n * λ) ]; } forward.invert = function(x, y) { var ρ0_y = G - y; return [ Math.atan2(x, ρ0_y) / n, G - d3_sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y) ]; }; return forward; } (d3.geo.conicEquidistant = function() { return d3_geo_conic(d3_geo_conicEquidistant); }).raw = d3_geo_conicEquidistant; var d3_geo_gnomonic = d3_geo_azimuthal(function(cosλcosφ) { return 1 / cosλcosφ; }, Math.atan); (d3.geo.gnomonic = function() { return d3_geo_projection(d3_geo_gnomonic); }).raw = d3_geo_gnomonic; function d3_geo_mercator(λ, φ) { return [ λ, Math.log(Math.tan(π / 4 + φ / 2)) ]; } d3_geo_mercator.invert = function(x, y) { return [ x, 2 * Math.atan(Math.exp(y)) - halfπ ]; }; function d3_geo_mercatorProjection(project) { var m = d3_geo_projection(project), scale = m.scale, translate = m.translate, clipExtent = m.clipExtent, clipAuto; m.scale = function() { var v = scale.apply(m, arguments); return v === m ? clipAuto ? m.clipExtent(null) : m : v; }; m.translate = function() { var v = translate.apply(m, arguments); return v === m ? clipAuto ? m.clipExtent(null) : m : v; }; m.clipExtent = function(_) { var v = clipExtent.apply(m, arguments); if (v === m) { if (clipAuto = _ == null) { var k = π * scale(), t = translate(); clipExtent([ [ t[0] - k, t[1] - k ], [ t[0] + k, t[1] + k ] ]); } } else if (clipAuto) { v = null; } return v; }; return m.clipExtent(null); } (d3.geo.mercator = function() { return d3_geo_mercatorProjection(d3_geo_mercator); }).raw = d3_geo_mercator; var d3_geo_orthographic = d3_geo_azimuthal(function() { return 1; }, Math.asin); (d3.geo.orthographic = function() { return d3_geo_projection(d3_geo_orthographic); }).raw = d3_geo_orthographic; var d3_geo_stereographic = d3_geo_azimuthal(function(cosλcosφ) { return 1 / (1 + cosλcosφ); }, function(ρ) { return 2 * Math.atan(ρ); }); (d3.geo.stereographic = function() { return d3_geo_projection(d3_geo_stereographic); }).raw = d3_geo_stereographic; function d3_geo_transverseMercator(λ, φ) { return [ Math.log(Math.tan(π / 4 + φ / 2)), -λ ]; } d3_geo_transverseMercator.invert = function(x, y) { return [ -y, 2 * Math.atan(Math.exp(x)) - halfπ ]; }; (d3.geo.transverseMercator = function() { var projection = d3_geo_mercatorProjection(d3_geo_transverseMercator), center = projection.center, rotate = projection.rotate; projection.center = function(_) { return _ ? center([ -_[1], _[0] ]) : (_ = center(), [ _[1], -_[0] ]); }; projection.rotate = function(_) { return _ ? rotate([ _[0], _[1], _.length > 2 ? _[2] + 90 : 90 ]) : (_ = rotate(), [ _[0], _[1], _[2] - 90 ]); }; return rotate([ 0, 0, 90 ]); }).raw = d3_geo_transverseMercator; d3.geom = {}; function d3_geom_pointX(d) { return d[0]; } function d3_geom_pointY(d) { return d[1]; } d3.geom.hull = function(vertices) { var x = d3_geom_pointX, y = d3_geom_pointY; if (arguments.length) return hull(vertices); function hull(data) { if (data.length < 3) return []; var fx = d3_functor(x), fy = d3_functor(y), i, n = data.length, points = [], flippedPoints = []; for (i = 0; i < n; i++) { points.push([ +fx.call(this, data[i], i), +fy.call(this, data[i], i), i ]); } points.sort(d3_geom_hullOrder); for (i = 0; i < n; i++) flippedPoints.push([ points[i][0], -points[i][1] ]); var upper = d3_geom_hullUpper(points), lower = d3_geom_hullUpper(flippedPoints); var skipLeft = lower[0] === upper[0], skipRight = lower[lower.length - 1] === upper[upper.length - 1], polygon = []; for (i = upper.length - 1; i >= 0; --i) polygon.push(data[points[upper[i]][2]]); for (i = +skipLeft; i < lower.length - skipRight; ++i) polygon.push(data[points[lower[i]][2]]); return polygon; } hull.x = function(_) { return arguments.length ? (x = _, hull) : x; }; hull.y = function(_) { return arguments.length ? (y = _, hull) : y; }; return hull; }; function d3_geom_hullUpper(points) { var n = points.length, hull = [ 0, 1 ], hs = 2; for (var i = 2; i < n; i++) { while (hs > 1 && d3_cross2d(points[hull[hs - 2]], points[hull[hs - 1]], points[i]) <= 0) --hs; hull[hs++] = i; } return hull.slice(0, hs); } function d3_geom_hullOrder(a, b) { return a[0] - b[0] || a[1] - b[1]; } d3.geom.polygon = function(coordinates) { d3_subclass(coordinates, d3_geom_polygonPrototype); return coordinates; }; var d3_geom_polygonPrototype = d3.geom.polygon.prototype = []; d3_geom_polygonPrototype.area = function() { var i = -1, n = this.length, a, b = this[n - 1], area = 0; while (++i < n) { a = b; b = this[i]; area += a[1] * b[0] - a[0] * b[1]; } return area * .5; }; d3_geom_polygonPrototype.centroid = function(k) { var i = -1, n = this.length, x = 0, y = 0, a, b = this[n - 1], c; if (!arguments.length) k = -1 / (6 * this.area()); while (++i < n) { a = b; b = this[i]; c = a[0] * b[1] - b[0] * a[1]; x += (a[0] + b[0]) * c; y += (a[1] + b[1]) * c; } return [ x * k, y * k ]; }; d3_geom_polygonPrototype.clip = function(subject) { var input, closed = d3_geom_polygonClosed(subject), i = -1, n = this.length - d3_geom_polygonClosed(this), j, m, a = this[n - 1], b, c, d; while (++i < n) { input = subject.slice(); subject.length = 0; b = this[i]; c = input[(m = input.length - closed) - 1]; j = -1; while (++j < m) { d = input[j]; if (d3_geom_polygonInside(d, a, b)) { if (!d3_geom_polygonInside(c, a, b)) { subject.push(d3_geom_polygonIntersect(c, d, a, b)); } subject.push(d); } else if (d3_geom_polygonInside(c, a, b)) { subject.push(d3_geom_polygonIntersect(c, d, a, b)); } c = d; } if (closed) subject.push(subject[0]); a = b; } return subject; }; function d3_geom_polygonInside(p, a, b) { return (b[0] - a[0]) * (p[1] - a[1]) < (b[1] - a[1]) * (p[0] - a[0]); } function d3_geom_polygonIntersect(c, d, a, b) { var x1 = c[0], x3 = a[0], x21 = d[0] - x1, x43 = b[0] - x3, y1 = c[1], y3 = a[1], y21 = d[1] - y1, y43 = b[1] - y3, ua = (x43 * (y1 - y3) - y43 * (x1 - x3)) / (y43 * x21 - x43 * y21); return [ x1 + ua * x21, y1 + ua * y21 ]; } function d3_geom_polygonClosed(coordinates) { var a = coordinates[0], b = coordinates[coordinates.length - 1]; return !(a[0] - b[0] || a[1] - b[1]); } var d3_geom_voronoiEdges, d3_geom_voronoiCells, d3_geom_voronoiBeaches, d3_geom_voronoiBeachPool = [], d3_geom_voronoiFirstCircle, d3_geom_voronoiCircles, d3_geom_voronoiCirclePool = []; function d3_geom_voronoiBeach() { d3_geom_voronoiRedBlackNode(this); this.edge = this.site = this.circle = null; } function d3_geom_voronoiCreateBeach(site) { var beach = d3_geom_voronoiBeachPool.pop() || new d3_geom_voronoiBeach(); beach.site = site; return beach; } function d3_geom_voronoiDetachBeach(beach) { d3_geom_voronoiDetachCircle(beach); d3_geom_voronoiBeaches.remove(beach); d3_geom_voronoiBeachPool.push(beach); d3_geom_voronoiRedBlackNode(beach); } function d3_geom_voronoiRemoveBeach(beach) { var circle = beach.circle, x = circle.x, y = circle.cy, vertex = { x: x, y: y }, previous = beach.P, next = beach.N, disappearing = [ beach ]; d3_geom_voronoiDetachBeach(beach); var lArc = previous; while (lArc.circle && abs(x - lArc.circle.x) < ε && abs(y - lArc.circle.cy) < ε) { previous = lArc.P; disappearing.unshift(lArc); d3_geom_voronoiDetachBeach(lArc); lArc = previous; } disappearing.unshift(lArc); d3_geom_voronoiDetachCircle(lArc); var rArc = next; while (rArc.circle && abs(x - rArc.circle.x) < ε && abs(y - rArc.circle.cy) < ε) { next = rArc.N; disappearing.push(rArc); d3_geom_voronoiDetachBeach(rArc); rArc = next; } disappearing.push(rArc); d3_geom_voronoiDetachCircle(rArc); var nArcs = disappearing.length, iArc; for (iArc = 1; iArc < nArcs; ++iArc) { rArc = disappearing[iArc]; lArc = disappearing[iArc - 1]; d3_geom_voronoiSetEdgeEnd(rArc.edge, lArc.site, rArc.site, vertex); } lArc = disappearing[0]; rArc = disappearing[nArcs - 1]; rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, rArc.site, null, vertex); d3_geom_voronoiAttachCircle(lArc); d3_geom_voronoiAttachCircle(rArc); } function d3_geom_voronoiAddBeach(site) { var x = site.x, directrix = site.y, lArc, rArc, dxl, dxr, node = d3_geom_voronoiBeaches._; while (node) { dxl = d3_geom_voronoiLeftBreakPoint(node, directrix) - x; if (dxl > ε) node = node.L; else { dxr = x - d3_geom_voronoiRightBreakPoint(node, directrix); if (dxr > ε) { if (!node.R) { lArc = node; break; } node = node.R; } else { if (dxl > -ε) { lArc = node.P; rArc = node; } else if (dxr > -ε) { lArc = node; rArc = node.N; } else { lArc = rArc = node; } break; } } } var newArc = d3_geom_voronoiCreateBeach(site); d3_geom_voronoiBeaches.insert(lArc, newArc); if (!lArc && !rArc) return; if (lArc === rArc) { d3_geom_voronoiDetachCircle(lArc); rArc = d3_geom_voronoiCreateBeach(lArc.site); d3_geom_voronoiBeaches.insert(newArc, rArc); newArc.edge = rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site); d3_geom_voronoiAttachCircle(lArc); d3_geom_voronoiAttachCircle(rArc); return; } if (!rArc) { newArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site); return; } d3_geom_voronoiDetachCircle(lArc); d3_geom_voronoiDetachCircle(rArc); var lSite = lArc.site, ax = lSite.x, ay = lSite.y, bx = site.x - ax, by = site.y - ay, rSite = rArc.site, cx = rSite.x - ax, cy = rSite.y - ay, d = 2 * (bx * cy - by * cx), hb = bx * bx + by * by, hc = cx * cx + cy * cy, vertex = { x: (cy * hb - by * hc) / d + ax, y: (bx * hc - cx * hb) / d + ay }; d3_geom_voronoiSetEdgeEnd(rArc.edge, lSite, rSite, vertex); newArc.edge = d3_geom_voronoiCreateEdge(lSite, site, null, vertex); rArc.edge = d3_geom_voronoiCreateEdge(site, rSite, null, vertex); d3_geom_voronoiAttachCircle(lArc); d3_geom_voronoiAttachCircle(rArc); } function d3_geom_voronoiLeftBreakPoint(arc, directrix) { var site = arc.site, rfocx = site.x, rfocy = site.y, pby2 = rfocy - directrix; if (!pby2) return rfocx; var lArc = arc.P; if (!lArc) return -Infinity; site = lArc.site; var lfocx = site.x, lfocy = site.y, plby2 = lfocy - directrix; if (!plby2) return lfocx; var hl = lfocx - rfocx, aby2 = 1 / pby2 - 1 / plby2, b = hl / plby2; if (aby2) return (-b + Math.sqrt(b * b - 2 * aby2 * (hl * hl / (-2 * plby2) - lfocy + plby2 / 2 + rfocy - pby2 / 2))) / aby2 + rfocx; return (rfocx + lfocx) / 2; } function d3_geom_voronoiRightBreakPoint(arc, directrix) { var rArc = arc.N; if (rArc) return d3_geom_voronoiLeftBreakPoint(rArc, directrix); var site = arc.site; return site.y === directrix ? site.x : Infinity; } function d3_geom_voronoiCell(site) { this.site = site; this.edges = []; } d3_geom_voronoiCell.prototype.prepare = function() { var halfEdges = this.edges, iHalfEdge = halfEdges.length, edge; while (iHalfEdge--) { edge = halfEdges[iHalfEdge].edge; if (!edge.b || !edge.a) halfEdges.splice(iHalfEdge, 1); } halfEdges.sort(d3_geom_voronoiHalfEdgeOrder); return halfEdges.length; }; function d3_geom_voronoiCloseCells(extent) { var x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], x2, y2, x3, y3, cells = d3_geom_voronoiCells, iCell = cells.length, cell, iHalfEdge, halfEdges, nHalfEdges, start, end; while (iCell--) { cell = cells[iCell]; if (!cell || !cell.prepare()) continue; halfEdges = cell.edges; nHalfEdges = halfEdges.length; iHalfEdge = 0; while (iHalfEdge < nHalfEdges) { end = halfEdges[iHalfEdge].end(), x3 = end.x, y3 = end.y; start = halfEdges[++iHalfEdge % nHalfEdges].start(), x2 = start.x, y2 = start.y; if (abs(x3 - x2) > ε || abs(y3 - y2) > ε) { halfEdges.splice(iHalfEdge, 0, new d3_geom_voronoiHalfEdge(d3_geom_voronoiCreateBorderEdge(cell.site, end, abs(x3 - x0) < ε && y1 - y3 > ε ? { x: x0, y: abs(x2 - x0) < ε ? y2 : y1 } : abs(y3 - y1) < ε && x1 - x3 > ε ? { x: abs(y2 - y1) < ε ? x2 : x1, y: y1 } : abs(x3 - x1) < ε && y3 - y0 > ε ? { x: x1, y: abs(x2 - x1) < ε ? y2 : y0 } : abs(y3 - y0) < ε && x3 - x0 > ε ? { x: abs(y2 - y0) < ε ? x2 : x0, y: y0 } : null), cell.site, null)); ++nHalfEdges; } } } } function d3_geom_voronoiHalfEdgeOrder(a, b) { return b.angle - a.angle; } function d3_geom_voronoiCircle() { d3_geom_voronoiRedBlackNode(this); this.x = this.y = this.arc = this.site = this.cy = null; } function d3_geom_voronoiAttachCircle(arc) { var lArc = arc.P, rArc = arc.N; if (!lArc || !rArc) return; var lSite = lArc.site, cSite = arc.site, rSite = rArc.site; if (lSite === rSite) return; var bx = cSite.x, by = cSite.y, ax = lSite.x - bx, ay = lSite.y - by, cx = rSite.x - bx, cy = rSite.y - by; var d = 2 * (ax * cy - ay * cx); if (d >= -ε2) return; var ha = ax * ax + ay * ay, hc = cx * cx + cy * cy, x = (cy * ha - ay * hc) / d, y = (ax * hc - cx * ha) / d, cy = y + by; var circle = d3_geom_voronoiCirclePool.pop() || new d3_geom_voronoiCircle(); circle.arc = arc; circle.site = cSite; circle.x = x + bx; circle.y = cy + Math.sqrt(x * x + y * y); circle.cy = cy; arc.circle = circle; var before = null, node = d3_geom_voronoiCircles._; while (node) { if (circle.y < node.y || circle.y === node.y && circle.x <= node.x) { if (node.L) node = node.L; else { before = node.P; break; } } else { if (node.R) node = node.R; else { before = node; break; } } } d3_geom_voronoiCircles.insert(before, circle); if (!before) d3_geom_voronoiFirstCircle = circle; } function d3_geom_voronoiDetachCircle(arc) { var circle = arc.circle; if (circle) { if (!circle.P) d3_geom_voronoiFirstCircle = circle.N; d3_geom_voronoiCircles.remove(circle); d3_geom_voronoiCirclePool.push(circle); d3_geom_voronoiRedBlackNode(circle); arc.circle = null; } } function d3_geom_voronoiClipEdges(extent) { var edges = d3_geom_voronoiEdges, clip = d3_geom_clipLine(extent[0][0], extent[0][1], extent[1][0], extent[1][1]), i = edges.length, e; while (i--) { e = edges[i]; if (!d3_geom_voronoiConnectEdge(e, extent) || !clip(e) || abs(e.a.x - e.b.x) < ε && abs(e.a.y - e.b.y) < ε) { e.a = e.b = null; edges.splice(i, 1); } } } function d3_geom_voronoiConnectEdge(edge, extent) { var vb = edge.b; if (vb) return true; var va = edge.a, x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], lSite = edge.l, rSite = edge.r, lx = lSite.x, ly = lSite.y, rx = rSite.x, ry = rSite.y, fx = (lx + rx) / 2, fy = (ly + ry) / 2, fm, fb; if (ry === ly) { if (fx < x0 || fx >= x1) return; if (lx > rx) { if (!va) va = { x: fx, y: y0 }; else if (va.y >= y1) return; vb = { x: fx, y: y1 }; } else { if (!va) va = { x: fx, y: y1 }; else if (va.y < y0) return; vb = { x: fx, y: y0 }; } } else { fm = (lx - rx) / (ry - ly); fb = fy - fm * fx; if (fm < -1 || fm > 1) { if (lx > rx) { if (!va) va = { x: (y0 - fb) / fm, y: y0 }; else if (va.y >= y1) return; vb = { x: (y1 - fb) / fm, y: y1 }; } else { if (!va) va = { x: (y1 - fb) / fm, y: y1 }; else if (va.y < y0) return; vb = { x: (y0 - fb) / fm, y: y0 }; } } else { if (ly < ry) { if (!va) va = { x: x0, y: fm * x0 + fb }; else if (va.x >= x1) return; vb = { x: x1, y: fm * x1 + fb }; } else { if (!va) va = { x: x1, y: fm * x1 + fb }; else if (va.x < x0) return; vb = { x: x0, y: fm * x0 + fb }; } } } edge.a = va; edge.b = vb; return true; } function d3_geom_voronoiEdge(lSite, rSite) { this.l = lSite; this.r = rSite; this.a = this.b = null; } function d3_geom_voronoiCreateEdge(lSite, rSite, va, vb) { var edge = new d3_geom_voronoiEdge(lSite, rSite); d3_geom_voronoiEdges.push(edge); if (va) d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, va); if (vb) d3_geom_voronoiSetEdgeEnd(edge, rSite, lSite, vb); d3_geom_voronoiCells[lSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, lSite, rSite)); d3_geom_voronoiCells[rSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, rSite, lSite)); return edge; } function d3_geom_voronoiCreateBorderEdge(lSite, va, vb) { var edge = new d3_geom_voronoiEdge(lSite, null); edge.a = va; edge.b = vb; d3_geom_voronoiEdges.push(edge); return edge; } function d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, vertex) { if (!edge.a && !edge.b) { edge.a = vertex; edge.l = lSite; edge.r = rSite; } else if (edge.l === rSite) { edge.b = vertex; } else { edge.a = vertex; } } function d3_geom_voronoiHalfEdge(edge, lSite, rSite) { var va = edge.a, vb = edge.b; this.edge = edge; this.site = lSite; this.angle = rSite ? Math.atan2(rSite.y - lSite.y, rSite.x - lSite.x) : edge.l === lSite ? Math.atan2(vb.x - va.x, va.y - vb.y) : Math.atan2(va.x - vb.x, vb.y - va.y); } d3_geom_voronoiHalfEdge.prototype = { start: function() { return this.edge.l === this.site ? this.edge.a : this.edge.b; }, end: function() { return this.edge.l === this.site ? this.edge.b : this.edge.a; } }; function d3_geom_voronoiRedBlackTree() { this._ = null; } function d3_geom_voronoiRedBlackNode(node) { node.U = node.C = node.L = node.R = node.P = node.N = null; } d3_geom_voronoiRedBlackTree.prototype = { insert: function(after, node) { var parent, grandpa, uncle; if (after) { node.P = after; node.N = after.N; if (after.N) after.N.P = node; after.N = node; if (after.R) { after = after.R; while (after.L) after = after.L; after.L = node; } else { after.R = node; } parent = after; } else if (this._) { after = d3_geom_voronoiRedBlackFirst(this._); node.P = null; node.N = after; after.P = after.L = node; parent = after; } else { node.P = node.N = null; this._ = node; parent = null; } node.L = node.R = null; node.U = parent; node.C = true; after = node; while (parent && parent.C) { grandpa = parent.U; if (parent === grandpa.L) { uncle = grandpa.R; if (uncle && uncle.C) { parent.C = uncle.C = false; grandpa.C = true; after = grandpa; } else { if (after === parent.R) { d3_geom_voronoiRedBlackRotateLeft(this, parent); after = parent; parent = after.U; } parent.C = false; grandpa.C = true; d3_geom_voronoiRedBlackRotateRight(this, grandpa); } } else { uncle = grandpa.L; if (uncle && uncle.C) { parent.C = uncle.C = false; grandpa.C = true; after = grandpa; } else { if (after === parent.L) { d3_geom_voronoiRedBlackRotateRight(this, parent); after = parent; parent = after.U; } parent.C = false; grandpa.C = true; d3_geom_voronoiRedBlackRotateLeft(this, grandpa); } } parent = after.U; } this._.C = false; }, remove: function(node) { if (node.N) node.N.P = node.P; if (node.P) node.P.N = node.N; node.N = node.P = null; var parent = node.U, sibling, left = node.L, right = node.R, next, red; if (!left) next = right; else if (!right) next = left; else next = d3_geom_voronoiRedBlackFirst(right); if (parent) { if (parent.L === node) parent.L = next; else parent.R = next; } else { this._ = next; } if (left && right) { red = next.C; next.C = node.C; next.L = left; left.U = next; if (next !== right) { parent = next.U; next.U = node.U; node = next.R; parent.L = node; next.R = right; right.U = next; } else { next.U = parent; parent = next; node = next.R; } } else { red = node.C; node = next; } if (node) node.U = parent; if (red) return; if (node && node.C) { node.C = false; return; } do { if (node === this._) break; if (node === parent.L) { sibling = parent.R; if (sibling.C) { sibling.C = false; parent.C = true; d3_geom_voronoiRedBlackRotateLeft(this, parent); sibling = parent.R; } if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) { if (!sibling.R || !sibling.R.C) { sibling.L.C = false; sibling.C = true; d3_geom_voronoiRedBlackRotateRight(this, sibling); sibling = parent.R; } sibling.C = parent.C; parent.C = sibling.R.C = false; d3_geom_voronoiRedBlackRotateLeft(this, parent); node = this._; break; } } else { sibling = parent.L; if (sibling.C) { sibling.C = false; parent.C = true; d3_geom_voronoiRedBlackRotateRight(this, parent); sibling = parent.L; } if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) { if (!sibling.L || !sibling.L.C) { sibling.R.C = false; sibling.C = true; d3_geom_voronoiRedBlackRotateLeft(this, sibling); sibling = parent.L; } sibling.C = parent.C; parent.C = sibling.L.C = false; d3_geom_voronoiRedBlackRotateRight(this, parent); node = this._; break; } } sibling.C = true; node = parent; parent = parent.U; } while (!node.C); if (node) node.C = false; } }; function d3_geom_voronoiRedBlackRotateLeft(tree, node) { var p = node, q = node.R, parent = p.U; if (parent) { if (parent.L === p) parent.L = q; else parent.R = q; } else { tree._ = q; } q.U = parent; p.U = q; p.R = q.L; if (p.R) p.R.U = p; q.L = p; } function d3_geom_voronoiRedBlackRotateRight(tree, node) { var p = node, q = node.L, parent = p.U; if (parent) { if (parent.L === p) parent.L = q; else parent.R = q; } else { tree._ = q; } q.U = parent; p.U = q; p.L = q.R; if (p.L) p.L.U = p; q.R = p; } function d3_geom_voronoiRedBlackFirst(node) { while (node.L) node = node.L; return node; } function d3_geom_voronoi(sites, bbox) { var site = sites.sort(d3_geom_voronoiVertexOrder).pop(), x0, y0, circle; d3_geom_voronoiEdges = []; d3_geom_voronoiCells = new Array(sites.length); d3_geom_voronoiBeaches = new d3_geom_voronoiRedBlackTree(); d3_geom_voronoiCircles = new d3_geom_voronoiRedBlackTree(); while (true) { circle = d3_geom_voronoiFirstCircle; if (site && (!circle || site.y < circle.y || site.y === circle.y && site.x < circle.x)) { if (site.x !== x0 || site.y !== y0) { d3_geom_voronoiCells[site.i] = new d3_geom_voronoiCell(site); d3_geom_voronoiAddBeach(site); x0 = site.x, y0 = site.y; } site = sites.pop(); } else if (circle) { d3_geom_voronoiRemoveBeach(circle.arc); } else { break; } } if (bbox) d3_geom_voronoiClipEdges(bbox), d3_geom_voronoiCloseCells(bbox); var diagram = { cells: d3_geom_voronoiCells, edges: d3_geom_voronoiEdges }; d3_geom_voronoiBeaches = d3_geom_voronoiCircles = d3_geom_voronoiEdges = d3_geom_voronoiCells = null; return diagram; } function d3_geom_voronoiVertexOrder(a, b) { return b.y - a.y || b.x - a.x; } d3.geom.voronoi = function(points) { var x = d3_geom_pointX, y = d3_geom_pointY, fx = x, fy = y, clipExtent = d3_geom_voronoiClipExtent; if (points) return voronoi(points); function voronoi(data) { var polygons = new Array(data.length), x0 = clipExtent[0][0], y0 = clipExtent[0][1], x1 = clipExtent[1][0], y1 = clipExtent[1][1]; d3_geom_voronoi(sites(data), clipExtent).cells.forEach(function(cell, i) { var edges = cell.edges, site = cell.site, polygon = polygons[i] = edges.length ? edges.map(function(e) { var s = e.start(); return [ s.x, s.y ]; }) : site.x >= x0 && site.x <= x1 && site.y >= y0 && site.y <= y1 ? [ [ x0, y1 ], [ x1, y1 ], [ x1, y0 ], [ x0, y0 ] ] : []; polygon.point = data[i]; }); return polygons; } function sites(data) { return data.map(function(d, i) { return { x: Math.round(fx(d, i) / ε) * ε, y: Math.round(fy(d, i) / ε) * ε, i: i }; }); } voronoi.links = function(data) { return d3_geom_voronoi(sites(data)).edges.filter(function(edge) { return edge.l && edge.r; }).map(function(edge) { return { source: data[edge.l.i], target: data[edge.r.i] }; }); }; voronoi.triangles = function(data) { var triangles = []; d3_geom_voronoi(sites(data)).cells.forEach(function(cell, i) { var site = cell.site, edges = cell.edges.sort(d3_geom_voronoiHalfEdgeOrder), j = -1, m = edges.length, e0, s0, e1 = edges[m - 1].edge, s1 = e1.l === site ? e1.r : e1.l; while (++j < m) { e0 = e1; s0 = s1; e1 = edges[j].edge; s1 = e1.l === site ? e1.r : e1.l; if (i < s0.i && i < s1.i && d3_geom_voronoiTriangleArea(site, s0, s1) < 0) { triangles.push([ data[i], data[s0.i], data[s1.i] ]); } } }); return triangles; }; voronoi.x = function(_) { return arguments.length ? (fx = d3_functor(x = _), voronoi) : x; }; voronoi.y = function(_) { return arguments.length ? (fy = d3_functor(y = _), voronoi) : y; }; voronoi.clipExtent = function(_) { if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent; clipExtent = _ == null ? d3_geom_voronoiClipExtent : _; return voronoi; }; voronoi.size = function(_) { if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent && clipExtent[1]; return voronoi.clipExtent(_ && [ [ 0, 0 ], _ ]); }; return voronoi; }; var d3_geom_voronoiClipExtent = [ [ -1e6, -1e6 ], [ 1e6, 1e6 ] ]; function d3_geom_voronoiTriangleArea(a, b, c) { return (a.x - c.x) * (b.y - a.y) - (a.x - b.x) * (c.y - a.y); } d3.geom.delaunay = function(vertices) { return d3.geom.voronoi().triangles(vertices); }; d3.geom.quadtree = function(points, x1, y1, x2, y2) { var x = d3_geom_pointX, y = d3_geom_pointY, compat; if (compat = arguments.length) { x = d3_geom_quadtreeCompatX; y = d3_geom_quadtreeCompatY; if (compat === 3) { y2 = y1; x2 = x1; y1 = x1 = 0; } return quadtree(points); } function quadtree(data) { var d, fx = d3_functor(x), fy = d3_functor(y), xs, ys, i, n, x1_, y1_, x2_, y2_; if (x1 != null) { x1_ = x1, y1_ = y1, x2_ = x2, y2_ = y2; } else { x2_ = y2_ = -(x1_ = y1_ = Infinity); xs = [], ys = []; n = data.length; if (compat) for (i = 0; i < n; ++i) { d = data[i]; if (d.x < x1_) x1_ = d.x; if (d.y < y1_) y1_ = d.y; if (d.x > x2_) x2_ = d.x; if (d.y > y2_) y2_ = d.y; xs.push(d.x); ys.push(d.y); } else for (i = 0; i < n; ++i) { var x_ = +fx(d = data[i], i), y_ = +fy(d, i); if (x_ < x1_) x1_ = x_; if (y_ < y1_) y1_ = y_; if (x_ > x2_) x2_ = x_; if (y_ > y2_) y2_ = y_; xs.push(x_); ys.push(y_); } } var dx = x2_ - x1_, dy = y2_ - y1_; if (dx > dy) y2_ = y1_ + dx; else x2_ = x1_ + dy; function insert(n, d, x, y, x1, y1, x2, y2) { if (isNaN(x) || isNaN(y)) return; if (n.leaf) { var nx = n.x, ny = n.y; if (nx != null) { if (abs(nx - x) + abs(ny - y) < .01) { insertChild(n, d, x, y, x1, y1, x2, y2); } else { var nPoint = n.point; n.x = n.y = n.point = null; insertChild(n, nPoint, nx, ny, x1, y1, x2, y2); insertChild(n, d, x, y, x1, y1, x2, y2); } } else { n.x = x, n.y = y, n.point = d; } } else { insertChild(n, d, x, y, x1, y1, x2, y2); } } function insertChild(n, d, x, y, x1, y1, x2, y2) { var xm = (x1 + x2) * .5, ym = (y1 + y2) * .5, right = x >= xm, below = y >= ym, i = below << 1 | right; n.leaf = false; n = n.nodes[i] || (n.nodes[i] = d3_geom_quadtreeNode()); if (right) x1 = xm; else x2 = xm; if (below) y1 = ym; else y2 = ym; insert(n, d, x, y, x1, y1, x2, y2); } var root = d3_geom_quadtreeNode(); root.add = function(d) { insert(root, d, +fx(d, ++i), +fy(d, i), x1_, y1_, x2_, y2_); }; root.visit = function(f) { d3_geom_quadtreeVisit(f, root, x1_, y1_, x2_, y2_); }; root.find = function(point) { return d3_geom_quadtreeFind(root, point[0], point[1], x1_, y1_, x2_, y2_); }; i = -1; if (x1 == null) { while (++i < n) { insert(root, data[i], xs[i], ys[i], x1_, y1_, x2_, y2_); } --i; } else data.forEach(root.add); xs = ys = data = d = null; return root; } quadtree.x = function(_) { return arguments.length ? (x = _, quadtree) : x; }; quadtree.y = function(_) { return arguments.length ? (y = _, quadtree) : y; }; quadtree.extent = function(_) { if (!arguments.length) return x1 == null ? null : [ [ x1, y1 ], [ x2, y2 ] ]; if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = +_[0][0], y1 = +_[0][1], x2 = +_[1][0], y2 = +_[1][1]; return quadtree; }; quadtree.size = function(_) { if (!arguments.length) return x1 == null ? null : [ x2 - x1, y2 - y1 ]; if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = y1 = 0, x2 = +_[0], y2 = +_[1]; return quadtree; }; return quadtree; }; function d3_geom_quadtreeCompatX(d) { return d.x; } function d3_geom_quadtreeCompatY(d) { return d.y; } function d3_geom_quadtreeNode() { return { leaf: true, nodes: [], point: null, x: null, y: null }; } function d3_geom_quadtreeVisit(f, node, x1, y1, x2, y2) { if (!f(node, x1, y1, x2, y2)) { var sx = (x1 + x2) * .5, sy = (y1 + y2) * .5, children = node.nodes; if (children[0]) d3_geom_quadtreeVisit(f, children[0], x1, y1, sx, sy); if (children[1]) d3_geom_quadtreeVisit(f, children[1], sx, y1, x2, sy); if (children[2]) d3_geom_quadtreeVisit(f, children[2], x1, sy, sx, y2); if (children[3]) d3_geom_quadtreeVisit(f, children[3], sx, sy, x2, y2); } } function d3_geom_quadtreeFind(root, x, y, x0, y0, x3, y3) { var minDistance2 = Infinity, closestPoint; (function find(node, x1, y1, x2, y2) { if (x1 > x3 || y1 > y3 || x2 < x0 || y2 < y0) return; if (point = node.point) { var point, dx = x - node.x, dy = y - node.y, distance2 = dx * dx + dy * dy; if (distance2 < minDistance2) { var distance = Math.sqrt(minDistance2 = distance2); x0 = x - distance, y0 = y - distance; x3 = x + distance, y3 = y + distance; closestPoint = point; } } var children = node.nodes, xm = (x1 + x2) * .5, ym = (y1 + y2) * .5, right = x >= xm, below = y >= ym; for (var i = below << 1 | right, j = i + 4; i < j; ++i) { if (node = children[i & 3]) switch (i & 3) { case 0: find(node, x1, y1, xm, ym); break; case 1: find(node, xm, y1, x2, ym); break; case 2: find(node, x1, ym, xm, y2); break; case 3: find(node, xm, ym, x2, y2); break; } } })(root, x0, y0, x3, y3); return closestPoint; } d3.interpolateRgb = d3_interpolateRgb; function d3_interpolateRgb(a, b) { a = d3.rgb(a); b = d3.rgb(b); var ar = a.r, ag = a.g, ab = a.b, br = b.r - ar, bg = b.g - ag, bb = b.b - ab; return function(t) { return "#" + d3_rgb_hex(Math.round(ar + br * t)) + d3_rgb_hex(Math.round(ag + bg * t)) + d3_rgb_hex(Math.round(ab + bb * t)); }; } d3.interpolateObject = d3_interpolateObject; function d3_interpolateObject(a, b) { var i = {}, c = {}, k; for (k in a) { if (k in b) { i[k] = d3_interpolate(a[k], b[k]); } else { c[k] = a[k]; } } for (k in b) { if (!(k in a)) { c[k] = b[k]; } } return function(t) { for (k in i) c[k] = i[k](t); return c; }; } d3.interpolateNumber = d3_interpolateNumber; function d3_interpolateNumber(a, b) { a = +a, b = +b; return function(t) { return a * (1 - t) + b * t; }; } d3.interpolateString = d3_interpolateString; function d3_interpolateString(a, b) { var bi = d3_interpolate_numberA.lastIndex = d3_interpolate_numberB.lastIndex = 0, am, bm, bs, i = -1, s = [], q = []; a = a + "", b = b + ""; while ((am = d3_interpolate_numberA.exec(a)) && (bm = d3_interpolate_numberB.exec(b))) { if ((bs = bm.index) > bi) { bs = b.slice(bi, bs); if (s[i]) s[i] += bs; else s[++i] = bs; } if ((am = am[0]) === (bm = bm[0])) { if (s[i]) s[i] += bm; else s[++i] = bm; } else { s[++i] = null; q.push({ i: i, x: d3_interpolateNumber(am, bm) }); } bi = d3_interpolate_numberB.lastIndex; } if (bi < b.length) { bs = b.slice(bi); if (s[i]) s[i] += bs; else s[++i] = bs; } return s.length < 2 ? q[0] ? (b = q[0].x, function(t) { return b(t) + ""; }) : function() { return b; } : (b = q.length, function(t) { for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t); return s.join(""); }); } var d3_interpolate_numberA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g, d3_interpolate_numberB = new RegExp(d3_interpolate_numberA.source, "g"); d3.interpolate = d3_interpolate; function d3_interpolate(a, b) { var i = d3.interpolators.length, f; while (--i >= 0 && !(f = d3.interpolators[i](a, b))) ; return f; } d3.interpolators = [ function(a, b) { var t = typeof b; return (t === "string" ? d3_rgb_names.has(b) || /^(#|rgb\(|hsl\()/.test(b) ? d3_interpolateRgb : d3_interpolateString : b instanceof d3_color ? d3_interpolateRgb : Array.isArray(b) ? d3_interpolateArray : t === "object" && isNaN(b) ? d3_interpolateObject : d3_interpolateNumber)(a, b); } ]; d3.interpolateArray = d3_interpolateArray; function d3_interpolateArray(a, b) { var x = [], c = [], na = a.length, nb = b.length, n0 = Math.min(a.length, b.length), i; for (i = 0; i < n0; ++i) x.push(d3_interpolate(a[i], b[i])); for (;i < na; ++i) c[i] = a[i]; for (;i < nb; ++i) c[i] = b[i]; return function(t) { for (i = 0; i < n0; ++i) c[i] = x[i](t); return c; }; } var d3_ease_default = function() { return d3_identity; }; var d3_ease = d3.map({ linear: d3_ease_default, poly: d3_ease_poly, quad: function() { return d3_ease_quad; }, cubic: function() { return d3_ease_cubic; }, sin: function() { return d3_ease_sin; }, exp: function() { return d3_ease_exp; }, circle: function() { return d3_ease_circle; }, elastic: d3_ease_elastic, back: d3_ease_back, bounce: function() { return d3_ease_bounce; } }); var d3_ease_mode = d3.map({ "in": d3_identity, out: d3_ease_reverse, "in-out": d3_ease_reflect, "out-in": function(f) { return d3_ease_reflect(d3_ease_reverse(f)); } }); d3.ease = function(name) { var i = name.indexOf("-"), t = i >= 0 ? name.slice(0, i) : name, m = i >= 0 ? name.slice(i + 1) : "in"; t = d3_ease.get(t) || d3_ease_default; m = d3_ease_mode.get(m) || d3_identity; return d3_ease_clamp(m(t.apply(null, d3_arraySlice.call(arguments, 1)))); }; function d3_ease_clamp(f) { return function(t) { return t <= 0 ? 0 : t >= 1 ? 1 : f(t); }; } function d3_ease_reverse(f) { return function(t) { return 1 - f(1 - t); }; } function d3_ease_reflect(f) { return function(t) { return .5 * (t < .5 ? f(2 * t) : 2 - f(2 - 2 * t)); }; } function d3_ease_quad(t) { return t * t; } function d3_ease_cubic(t) { return t * t * t; } function d3_ease_cubicInOut(t) { if (t <= 0) return 0; if (t >= 1) return 1; var t2 = t * t, t3 = t2 * t; return 4 * (t < .5 ? t3 : 3 * (t - t2) + t3 - .75); } function d3_ease_poly(e) { return function(t) { return Math.pow(t, e); }; } function d3_ease_sin(t) { return 1 - Math.cos(t * halfπ); } function d3_ease_exp(t) { return Math.pow(2, 10 * (t - 1)); } function d3_ease_circle(t) { return 1 - Math.sqrt(1 - t * t); } function d3_ease_elastic(a, p) { var s; if (arguments.length < 2) p = .45; if (arguments.length) s = p / τ * Math.asin(1 / a); else a = 1, s = p / 4; return function(t) { return 1 + a * Math.pow(2, -10 * t) * Math.sin((t - s) * τ / p); }; } function d3_ease_back(s) { if (!s) s = 1.70158; return function(t) { return t * t * ((s + 1) * t - s); }; } function d3_ease_bounce(t) { return t < 1 / 2.75 ? 7.5625 * t * t : t < 2 / 2.75 ? 7.5625 * (t -= 1.5 / 2.75) * t + .75 : t < 2.5 / 2.75 ? 7.5625 * (t -= 2.25 / 2.75) * t + .9375 : 7.5625 * (t -= 2.625 / 2.75) * t + .984375; } d3.interpolateHcl = d3_interpolateHcl; function d3_interpolateHcl(a, b) { a = d3.hcl(a); b = d3.hcl(b); var ah = a.h, ac = a.c, al = a.l, bh = b.h - ah, bc = b.c - ac, bl = b.l - al; if (isNaN(bc)) bc = 0, ac = isNaN(ac) ? b.c : ac; if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360; return function(t) { return d3_hcl_lab(ah + bh * t, ac + bc * t, al + bl * t) + ""; }; } d3.interpolateHsl = d3_interpolateHsl; function d3_interpolateHsl(a, b) { a = d3.hsl(a); b = d3.hsl(b); var ah = a.h, as = a.s, al = a.l, bh = b.h - ah, bs = b.s - as, bl = b.l - al; if (isNaN(bs)) bs = 0, as = isNaN(as) ? b.s : as; if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360; return function(t) { return d3_hsl_rgb(ah + bh * t, as + bs * t, al + bl * t) + ""; }; } d3.interpolateLab = d3_interpolateLab; function d3_interpolateLab(a, b) { a = d3.lab(a); b = d3.lab(b); var al = a.l, aa = a.a, ab = a.b, bl = b.l - al, ba = b.a - aa, bb = b.b - ab; return function(t) { return d3_lab_rgb(al + bl * t, aa + ba * t, ab + bb * t) + ""; }; } d3.interpolateRound = d3_interpolateRound; function d3_interpolateRound(a, b) { b -= a; return function(t) { return Math.round(a + b * t); }; } d3.transform = function(string) { var g = d3_document.createElementNS(d3.ns.prefix.svg, "g"); return (d3.transform = function(string) { if (string != null) { g.setAttribute("transform", string); var t = g.transform.baseVal.consolidate(); } return new d3_transform(t ? t.matrix : d3_transformIdentity); })(string); }; function d3_transform(m) { var r0 = [ m.a, m.b ], r1 = [ m.c, m.d ], kx = d3_transformNormalize(r0), kz = d3_transformDot(r0, r1), ky = d3_transformNormalize(d3_transformCombine(r1, r0, -kz)) || 0; if (r0[0] * r1[1] < r1[0] * r0[1]) { r0[0] *= -1; r0[1] *= -1; kx *= -1; kz *= -1; } this.rotate = (kx ? Math.atan2(r0[1], r0[0]) : Math.atan2(-r1[0], r1[1])) * d3_degrees; this.translate = [ m.e, m.f ]; this.scale = [ kx, ky ]; this.skew = ky ? Math.atan2(kz, ky) * d3_degrees : 0; } d3_transform.prototype.toString = function() { return "translate(" + this.translate + ")rotate(" + this.rotate + ")skewX(" + this.skew + ")scale(" + this.scale + ")"; }; function d3_transformDot(a, b) { return a[0] * b[0] + a[1] * b[1]; } function d3_transformNormalize(a) { var k = Math.sqrt(d3_transformDot(a, a)); if (k) { a[0] /= k; a[1] /= k; } return k; } function d3_transformCombine(a, b, k) { a[0] += k * b[0]; a[1] += k * b[1]; return a; } var d3_transformIdentity = { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 }; d3.interpolateTransform = d3_interpolateTransform; function d3_interpolateTransform(a, b) { var s = [], q = [], n, A = d3.transform(a), B = d3.transform(b), ta = A.translate, tb = B.translate, ra = A.rotate, rb = B.rotate, wa = A.skew, wb = B.skew, ka = A.scale, kb = B.scale; if (ta[0] != tb[0] || ta[1] != tb[1]) { s.push("translate(", null, ",", null, ")"); q.push({ i: 1, x: d3_interpolateNumber(ta[0], tb[0]) }, { i: 3, x: d3_interpolateNumber(ta[1], tb[1]) }); } else if (tb[0] || tb[1]) { s.push("translate(" + tb + ")"); } else { s.push(""); } if (ra != rb) { if (ra - rb > 180) rb += 360; else if (rb - ra > 180) ra += 360; q.push({ i: s.push(s.pop() + "rotate(", null, ")") - 2, x: d3_interpolateNumber(ra, rb) }); } else if (rb) { s.push(s.pop() + "rotate(" + rb + ")"); } if (wa != wb) { q.push({ i: s.push(s.pop() + "skewX(", null, ")") - 2, x: d3_interpolateNumber(wa, wb) }); } else if (wb) { s.push(s.pop() + "skewX(" + wb + ")"); } if (ka[0] != kb[0] || ka[1] != kb[1]) { n = s.push(s.pop() + "scale(", null, ",", null, ")"); q.push({ i: n - 4, x: d3_interpolateNumber(ka[0], kb[0]) }, { i: n - 2, x: d3_interpolateNumber(ka[1], kb[1]) }); } else if (kb[0] != 1 || kb[1] != 1) { s.push(s.pop() + "scale(" + kb + ")"); } n = q.length; return function(t) { var i = -1, o; while (++i < n) s[(o = q[i]).i] = o.x(t); return s.join(""); }; } function d3_uninterpolateNumber(a, b) { b = (b -= a = +a) || 1 / b; return function(x) { return (x - a) / b; }; } function d3_uninterpolateClamp(a, b) { b = (b -= a = +a) || 1 / b; return function(x) { return Math.max(0, Math.min(1, (x - a) / b)); }; } d3.layout = {}; d3.layout.bundle = function() { return function(links) { var paths = [], i = -1, n = links.length; while (++i < n) paths.push(d3_layout_bundlePath(links[i])); return paths; }; }; function d3_layout_bundlePath(link) { var start = link.source, end = link.target, lca = d3_layout_bundleLeastCommonAncestor(start, end), points = [ start ]; while (start !== lca) { start = start.parent; points.push(start); } var k = points.length; while (end !== lca) { points.splice(k, 0, end); end = end.parent; } return points; } function d3_layout_bundleAncestors(node) { var ancestors = [], parent = node.parent; while (parent != null) { ancestors.push(node); node = parent; parent = parent.parent; } ancestors.push(node); return ancestors; } function d3_layout_bundleLeastCommonAncestor(a, b) { if (a === b) return a; var aNodes = d3_layout_bundleAncestors(a), bNodes = d3_layout_bundleAncestors(b), aNode = aNodes.pop(), bNode = bNodes.pop(), sharedNode = null; while (aNode === bNode) { sharedNode = aNode; aNode = aNodes.pop(); bNode = bNodes.pop(); } return sharedNode; } d3.layout.chord = function() { var chord = {}, chords, groups, matrix, n, padding = 0, sortGroups, sortSubgroups, sortChords; function relayout() { var subgroups = {}, groupSums = [], groupIndex = d3.range(n), subgroupIndex = [], k, x, x0, i, j; chords = []; groups = []; k = 0, i = -1; while (++i < n) { x = 0, j = -1; while (++j < n) { x += matrix[i][j]; } groupSums.push(x); subgroupIndex.push(d3.range(n)); k += x; } if (sortGroups) { groupIndex.sort(function(a, b) { return sortGroups(groupSums[a], groupSums[b]); }); } if (sortSubgroups) { subgroupIndex.forEach(function(d, i) { d.sort(function(a, b) { return sortSubgroups(matrix[i][a], matrix[i][b]); }); }); } k = (τ - padding * n) / k; x = 0, i = -1; while (++i < n) { x0 = x, j = -1; while (++j < n) { var di = groupIndex[i], dj = subgroupIndex[di][j], v = matrix[di][dj], a0 = x, a1 = x += v * k; subgroups[di + "-" + dj] = { index: di, subindex: dj, startAngle: a0, endAngle: a1, value: v }; } groups[di] = { index: di, startAngle: x0, endAngle: x, value: (x - x0) / k }; x += padding; } i = -1; while (++i < n) { j = i - 1; while (++j < n) { var source = subgroups[i + "-" + j], target = subgroups[j + "-" + i]; if (source.value || target.value) { chords.push(source.value < target.value ? { source: target, target: source } : { source: source, target: target }); } } } if (sortChords) resort(); } function resort() { chords.sort(function(a, b) { return sortChords((a.source.value + a.target.value) / 2, (b.source.value + b.target.value) / 2); }); } chord.matrix = function(x) { if (!arguments.length) return matrix; n = (matrix = x) && matrix.length; chords = groups = null; return chord; }; chord.padding = function(x) { if (!arguments.length) return padding; padding = x; chords = groups = null; return chord; }; chord.sortGroups = function(x) { if (!arguments.length) return sortGroups; sortGroups = x; chords = groups = null; return chord; }; chord.sortSubgroups = function(x) { if (!arguments.length) return sortSubgroups; sortSubgroups = x; chords = null; return chord; }; chord.sortChords = function(x) { if (!arguments.length) return sortChords; sortChords = x; if (chords) resort(); return chord; }; chord.chords = function() { if (!chords) relayout(); return chords; }; chord.groups = function() { if (!groups) relayout(); return groups; }; return chord; }; d3.layout.force = function() { var force = {}, event = d3.dispatch("start", "tick", "end"), size = [ 1, 1 ], drag, alpha, friction = .9, linkDistance = d3_layout_forceLinkDistance, linkStrength = d3_layout_forceLinkStrength, charge = -30, chargeDistance2 = d3_layout_forceChargeDistance2, gravity = .1, theta2 = .64, nodes = [], links = [], distances, strengths, charges; function repulse(node) { return function(quad, x1, _, x2) { if (quad.point !== node) { var dx = quad.cx - node.x, dy = quad.cy - node.y, dw = x2 - x1, dn = dx * dx + dy * dy; if (dw * dw / theta2 < dn) { if (dn < chargeDistance2) { var k = quad.charge / dn; node.px -= dx * k; node.py -= dy * k; } return true; } if (quad.point && dn && dn < chargeDistance2) { var k = quad.pointCharge / dn; node.px -= dx * k; node.py -= dy * k; } } return !quad.charge; }; } force.tick = function() { if ((alpha *= .99) < .005) { event.end({ type: "end", alpha: alpha = 0 }); return true; } var n = nodes.length, m = links.length, q, i, o, s, t, l, k, x, y; for (i = 0; i < m; ++i) { o = links[i]; s = o.source; t = o.target; x = t.x - s.x; y = t.y - s.y; if (l = x * x + y * y) { l = alpha * strengths[i] * ((l = Math.sqrt(l)) - distances[i]) / l; x *= l; y *= l; t.x -= x * (k = s.weight / (t.weight + s.weight)); t.y -= y * k; s.x += x * (k = 1 - k); s.y += y * k; } } if (k = alpha * gravity) { x = size[0] / 2; y = size[1] / 2; i = -1; if (k) while (++i < n) { o = nodes[i]; o.x += (x - o.x) * k; o.y += (y - o.y) * k; } } if (charge) { d3_layout_forceAccumulate(q = d3.geom.quadtree(nodes), alpha, charges); i = -1; while (++i < n) { if (!(o = nodes[i]).fixed) { q.visit(repulse(o)); } } } i = -1; while (++i < n) { o = nodes[i]; if (o.fixed) { o.x = o.px; o.y = o.py; } else { o.x -= (o.px - (o.px = o.x)) * friction; o.y -= (o.py - (o.py = o.y)) * friction; } } event.tick({ type: "tick", alpha: alpha }); }; force.nodes = function(x) { if (!arguments.length) return nodes; nodes = x; return force; }; force.links = function(x) { if (!arguments.length) return links; links = x; return force; }; force.size = function(x) { if (!arguments.length) return size; size = x; return force; }; force.linkDistance = function(x) { if (!arguments.length) return linkDistance; linkDistance = typeof x === "function" ? x : +x; return force; }; force.distance = force.linkDistance; force.linkStrength = function(x) { if (!arguments.length) return linkStrength; linkStrength = typeof x === "function" ? x : +x; return force; }; force.friction = function(x) { if (!arguments.length) return friction; friction = +x; return force; }; force.charge = function(x) { if (!arguments.length) return charge; charge = typeof x === "function" ? x : +x; return force; }; force.chargeDistance = function(x) { if (!arguments.length) return Math.sqrt(chargeDistance2); chargeDistance2 = x * x; return force; }; force.gravity = function(x) { if (!arguments.length) return gravity; gravity = +x; return force; }; force.theta = function(x) { if (!arguments.length) return Math.sqrt(theta2); theta2 = x * x; return force; }; force.alpha = function(x) { if (!arguments.length) return alpha; x = +x; if (alpha) { if (x > 0) alpha = x; else alpha = 0; } else if (x > 0) { event.start({ type: "start", alpha: alpha = x }); d3.timer(force.tick); } return force; }; force.start = function() { var i, n = nodes.length, m = links.length, w = size[0], h = size[1], neighbors, o; for (i = 0; i < n; ++i) { (o = nodes[i]).index = i; o.weight = 0; } for (i = 0; i < m; ++i) { o = links[i]; if (typeof o.source == "number") o.source = nodes[o.source]; if (typeof o.target == "number") o.target = nodes[o.target]; ++o.source.weight; ++o.target.weight; } for (i = 0; i < n; ++i) { o = nodes[i]; if (isNaN(o.x)) o.x = position("x", w); if (isNaN(o.y)) o.y = position("y", h); if (isNaN(o.px)) o.px = o.x; if (isNaN(o.py)) o.py = o.y; } distances = []; if (typeof linkDistance === "function") for (i = 0; i < m; ++i) distances[i] = +linkDistance.call(this, links[i], i); else for (i = 0; i < m; ++i) distances[i] = linkDistance; strengths = []; if (typeof linkStrength === "function") for (i = 0; i < m; ++i) strengths[i] = +linkStrength.call(this, links[i], i); else for (i = 0; i < m; ++i) strengths[i] = linkStrength; charges = []; if (typeof charge === "function") for (i = 0; i < n; ++i) charges[i] = +charge.call(this, nodes[i], i); else for (i = 0; i < n; ++i) charges[i] = charge; function position(dimension, size) { if (!neighbors) { neighbors = new Array(n); for (j = 0; j < n; ++j) { neighbors[j] = []; } for (j = 0; j < m; ++j) { var o = links[j]; neighbors[o.source.index].push(o.target); neighbors[o.target.index].push(o.source); } } var candidates = neighbors[i], j = -1, l = candidates.length, x; while (++j < l) if (!isNaN(x = candidates[j][dimension])) return x; return Math.random() * size; } return force.resume(); }; force.resume = function() { return force.alpha(.1); }; force.stop = function() { return force.alpha(0); }; force.drag = function() { if (!drag) drag = d3.behavior.drag().origin(d3_identity).on("dragstart.force", d3_layout_forceDragstart).on("drag.force", dragmove).on("dragend.force", d3_layout_forceDragend); if (!arguments.length) return drag; this.on("mouseover.force", d3_layout_forceMouseover).on("mouseout.force", d3_layout_forceMouseout).call(drag); }; function dragmove(d) { d.px = d3.event.x, d.py = d3.event.y; force.resume(); } return d3.rebind(force, event, "on"); }; function d3_layout_forceDragstart(d) { d.fixed |= 2; } function d3_layout_forceDragend(d) { d.fixed &= ~6; } function d3_layout_forceMouseover(d) { d.fixed |= 4; d.px = d.x, d.py = d.y; } function d3_layout_forceMouseout(d) { d.fixed &= ~4; } function d3_layout_forceAccumulate(quad, alpha, charges) { var cx = 0, cy = 0; quad.charge = 0; if (!quad.leaf) { var nodes = quad.nodes, n = nodes.length, i = -1, c; while (++i < n) { c = nodes[i]; if (c == null) continue; d3_layout_forceAccumulate(c, alpha, charges); quad.charge += c.charge; cx += c.charge * c.cx; cy += c.charge * c.cy; } } if (quad.point) { if (!quad.leaf) { quad.point.x += Math.random() - .5; quad.point.y += Math.random() - .5; } var k = alpha * charges[quad.point.index]; quad.charge += quad.pointCharge = k; cx += k * quad.point.x; cy += k * quad.point.y; } quad.cx = cx / quad.charge; quad.cy = cy / quad.charge; } var d3_layout_forceLinkDistance = 20, d3_layout_forceLinkStrength = 1, d3_layout_forceChargeDistance2 = Infinity; d3.layout.hierarchy = function() { var sort = d3_layout_hierarchySort, children = d3_layout_hierarchyChildren, value = d3_layout_hierarchyValue; function hierarchy(root) { var stack = [ root ], nodes = [], node; root.depth = 0; while ((node = stack.pop()) != null) { nodes.push(node); if ((childs = children.call(hierarchy, node, node.depth)) && (n = childs.length)) { var n, childs, child; while (--n >= 0) { stack.push(child = childs[n]); child.parent = node; child.depth = node.depth + 1; } if (value) node.value = 0; node.children = childs; } else { if (value) node.value = +value.call(hierarchy, node, node.depth) || 0; delete node.children; } } d3_layout_hierarchyVisitAfter(root, function(node) { var childs, parent; if (sort && (childs = node.children)) childs.sort(sort); if (value && (parent = node.parent)) parent.value += node.value; }); return nodes; } hierarchy.sort = function(x) { if (!arguments.length) return sort; sort = x; return hierarchy; }; hierarchy.children = function(x) { if (!arguments.length) return children; children = x; return hierarchy; }; hierarchy.value = function(x) { if (!arguments.length) return value; value = x; return hierarchy; }; hierarchy.revalue = function(root) { if (value) { d3_layout_hierarchyVisitBefore(root, function(node) { if (node.children) node.value = 0; }); d3_layout_hierarchyVisitAfter(root, function(node) { var parent; if (!node.children) node.value = +value.call(hierarchy, node, node.depth) || 0; if (parent = node.parent) parent.value += node.value; }); } return root; }; return hierarchy; }; function d3_layout_hierarchyRebind(object, hierarchy) { d3.rebind(object, hierarchy, "sort", "children", "value"); object.nodes = object; object.links = d3_layout_hierarchyLinks; return object; } function d3_layout_hierarchyVisitBefore(node, callback) { var nodes = [ node ]; while ((node = nodes.pop()) != null) { callback(node); if ((children = node.children) && (n = children.length)) { var n, children; while (--n >= 0) nodes.push(children[n]); } } } function d3_layout_hierarchyVisitAfter(node, callback) { var nodes = [ node ], nodes2 = []; while ((node = nodes.pop()) != null) { nodes2.push(node); if ((children = node.children) && (n = children.length)) { var i = -1, n, children; while (++i < n) nodes.push(children[i]); } } while ((node = nodes2.pop()) != null) { callback(node); } } function d3_layout_hierarchyChildren(d) { return d.children; } function d3_layout_hierarchyValue(d) { return d.value; } function d3_layout_hierarchySort(a, b) { return b.value - a.value; } function d3_layout_hierarchyLinks(nodes) { return d3.merge(nodes.map(function(parent) { return (parent.children || []).map(function(child) { return { source: parent, target: child }; }); })); } d3.layout.partition = function() { var hierarchy = d3.layout.hierarchy(), size = [ 1, 1 ]; function position(node, x, dx, dy) { var children = node.children; node.x = x; node.y = node.depth * dy; node.dx = dx; node.dy = dy; if (children && (n = children.length)) { var i = -1, n, c, d; dx = node.value ? dx / node.value : 0; while (++i < n) { position(c = children[i], x, d = c.value * dx, dy); x += d; } } } function depth(node) { var children = node.children, d = 0; if (children && (n = children.length)) { var i = -1, n; while (++i < n) d = Math.max(d, depth(children[i])); } return 1 + d; } function partition(d, i) { var nodes = hierarchy.call(this, d, i); position(nodes[0], 0, size[0], size[1] / depth(nodes[0])); return nodes; } partition.size = function(x) { if (!arguments.length) return size; size = x; return partition; }; return d3_layout_hierarchyRebind(partition, hierarchy); }; d3.layout.pie = function() { var value = Number, sort = d3_layout_pieSortByValue, startAngle = 0, endAngle = τ, padAngle = 0; function pie(data) { var n = data.length, values = data.map(function(d, i) { return +value.call(pie, d, i); }), a = +(typeof startAngle === "function" ? startAngle.apply(this, arguments) : startAngle), da = (typeof endAngle === "function" ? endAngle.apply(this, arguments) : endAngle) - a, p = Math.min(Math.abs(da) / n, +(typeof padAngle === "function" ? padAngle.apply(this, arguments) : padAngle)), pa = p * (da < 0 ? -1 : 1), k = (da - n * pa) / d3.sum(values), index = d3.range(n), arcs = [], v; if (sort != null) index.sort(sort === d3_layout_pieSortByValue ? function(i, j) { return values[j] - values[i]; } : function(i, j) { return sort(data[i], data[j]); }); index.forEach(function(i) { arcs[i] = { data: data[i], value: v = values[i], startAngle: a, endAngle: a += v * k + pa, padAngle: p }; }); return arcs; } pie.value = function(_) { if (!arguments.length) return value; value = _; return pie; }; pie.sort = function(_) { if (!arguments.length) return sort; sort = _; return pie; }; pie.startAngle = function(_) { if (!arguments.length) return startAngle; startAngle = _; return pie; }; pie.endAngle = function(_) { if (!arguments.length) return endAngle; endAngle = _; return pie; }; pie.padAngle = function(_) { if (!arguments.length) return padAngle; padAngle = _; return pie; }; return pie; }; var d3_layout_pieSortByValue = {}; d3.layout.stack = function() { var values = d3_identity, order = d3_layout_stackOrderDefault, offset = d3_layout_stackOffsetZero, out = d3_layout_stackOut, x = d3_layout_stackX, y = d3_layout_stackY; function stack(data, index) { if (!(n = data.length)) return data; var series = data.map(function(d, i) { return values.call(stack, d, i); }); var points = series.map(function(d) { return d.map(function(v, i) { return [ x.call(stack, v, i), y.call(stack, v, i) ]; }); }); var orders = order.call(stack, points, index); series = d3.permute(series, orders); points = d3.permute(points, orders); var offsets = offset.call(stack, points, index); var m = series[0].length, n, i, j, o; for (j = 0; j < m; ++j) { out.call(stack, series[0][j], o = offsets[j], points[0][j][1]); for (i = 1; i < n; ++i) { out.call(stack, series[i][j], o += points[i - 1][j][1], points[i][j][1]); } } return data; } stack.values = function(x) { if (!arguments.length) return values; values = x; return stack; }; stack.order = function(x) { if (!arguments.length) return order; order = typeof x === "function" ? x : d3_layout_stackOrders.get(x) || d3_layout_stackOrderDefault; return stack; }; stack.offset = function(x) { if (!arguments.length) return offset; offset = typeof x === "function" ? x : d3_layout_stackOffsets.get(x) || d3_layout_stackOffsetZero; return stack; }; stack.x = function(z) { if (!arguments.length) return x; x = z; return stack; }; stack.y = function(z) { if (!arguments.length) return y; y = z; return stack; }; stack.out = function(z) { if (!arguments.length) return out; out = z; return stack; }; return stack; }; function d3_layout_stackX(d) { return d.x; } function d3_layout_stackY(d) { return d.y; } function d3_layout_stackOut(d, y0, y) { d.y0 = y0; d.y = y; } var d3_layout_stackOrders = d3.map({ "inside-out": function(data) { var n = data.length, i, j, max = data.map(d3_layout_stackMaxIndex), sums = data.map(d3_layout_stackReduceSum), index = d3.range(n).sort(function(a, b) { return max[a] - max[b]; }), top = 0, bottom = 0, tops = [], bottoms = []; for (i = 0; i < n; ++i) { j = index[i]; if (top < bottom) { top += sums[j]; tops.push(j); } else { bottom += sums[j]; bottoms.push(j); } } return bottoms.reverse().concat(tops); }, reverse: function(data) { return d3.range(data.length).reverse(); }, "default": d3_layout_stackOrderDefault }); var d3_layout_stackOffsets = d3.map({ silhouette: function(data) { var n = data.length, m = data[0].length, sums = [], max = 0, i, j, o, y0 = []; for (j = 0; j < m; ++j) { for (i = 0, o = 0; i < n; i++) o += data[i][j][1]; if (o > max) max = o; sums.push(o); } for (j = 0; j < m; ++j) { y0[j] = (max - sums[j]) / 2; } return y0; }, wiggle: function(data) { var n = data.length, x = data[0], m = x.length, i, j, k, s1, s2, s3, dx, o, o0, y0 = []; y0[0] = o = o0 = 0; for (j = 1; j < m; ++j) { for (i = 0, s1 = 0; i < n; ++i) s1 += data[i][j][1]; for (i = 0, s2 = 0, dx = x[j][0] - x[j - 1][0]; i < n; ++i) { for (k = 0, s3 = (data[i][j][1] - data[i][j - 1][1]) / (2 * dx); k < i; ++k) { s3 += (data[k][j][1] - data[k][j - 1][1]) / dx; } s2 += s3 * data[i][j][1]; } y0[j] = o -= s1 ? s2 / s1 * dx : 0; if (o < o0) o0 = o; } for (j = 0; j < m; ++j) y0[j] -= o0; return y0; }, expand: function(data) { var n = data.length, m = data[0].length, k = 1 / n, i, j, o, y0 = []; for (j = 0; j < m; ++j) { for (i = 0, o = 0; i < n; i++) o += data[i][j][1]; if (o) for (i = 0; i < n; i++) data[i][j][1] /= o; else for (i = 0; i < n; i++) data[i][j][1] = k; } for (j = 0; j < m; ++j) y0[j] = 0; return y0; }, zero: d3_layout_stackOffsetZero }); function d3_layout_stackOrderDefault(data) { return d3.range(data.length); } function d3_layout_stackOffsetZero(data) { var j = -1, m = data[0].length, y0 = []; while (++j < m) y0[j] = 0; return y0; } function d3_layout_stackMaxIndex(array) { var i = 1, j = 0, v = array[0][1], k, n = array.length; for (;i < n; ++i) { if ((k = array[i][1]) > v) { j = i; v = k; } } return j; } function d3_layout_stackReduceSum(d) { return d.reduce(d3_layout_stackSum, 0); } function d3_layout_stackSum(p, d) { return p + d[1]; } d3.layout.histogram = function() { var frequency = true, valuer = Number, ranger = d3_layout_histogramRange, binner = d3_layout_histogramBinSturges; function histogram(data, i) { var bins = [], values = data.map(valuer, this), range = ranger.call(this, values, i), thresholds = binner.call(this, range, values, i), bin, i = -1, n = values.length, m = thresholds.length - 1, k = frequency ? 1 : 1 / n, x; while (++i < m) { bin = bins[i] = []; bin.dx = thresholds[i + 1] - (bin.x = thresholds[i]); bin.y = 0; } if (m > 0) { i = -1; while (++i < n) { x = values[i]; if (x >= range[0] && x <= range[1]) { bin = bins[d3.bisect(thresholds, x, 1, m) - 1]; bin.y += k; bin.push(data[i]); } } } return bins; } histogram.value = function(x) { if (!arguments.length) return valuer; valuer = x; return histogram; }; histogram.range = function(x) { if (!arguments.length) return ranger; ranger = d3_functor(x); return histogram; }; histogram.bins = function(x) { if (!arguments.length) return binner; binner = typeof x === "number" ? function(range) { return d3_layout_histogramBinFixed(range, x); } : d3_functor(x); return histogram; }; histogram.frequency = function(x) { if (!arguments.length) return frequency; frequency = !!x; return histogram; }; return histogram; }; function d3_layout_histogramBinSturges(range, values) { return d3_layout_histogramBinFixed(range, Math.ceil(Math.log(values.length) / Math.LN2 + 1)); } function d3_layout_histogramBinFixed(range, n) { var x = -1, b = +range[0], m = (range[1] - b) / n, f = []; while (++x <= n) f[x] = m * x + b; return f; } function d3_layout_histogramRange(values) { return [ d3.min(values), d3.max(values) ]; } d3.layout.pack = function() { var hierarchy = d3.layout.hierarchy().sort(d3_layout_packSort), padding = 0, size = [ 1, 1 ], radius; function pack(d, i) { var nodes = hierarchy.call(this, d, i), root = nodes[0], w = size[0], h = size[1], r = radius == null ? Math.sqrt : typeof radius === "function" ? radius : function() { return radius; }; root.x = root.y = 0; d3_layout_hierarchyVisitAfter(root, function(d) { d.r = +r(d.value); }); d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings); if (padding) { var dr = padding * (radius ? 1 : Math.max(2 * root.r / w, 2 * root.r / h)) / 2; d3_layout_hierarchyVisitAfter(root, function(d) { d.r += dr; }); d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings); d3_layout_hierarchyVisitAfter(root, function(d) { d.r -= dr; }); } d3_layout_packTransform(root, w / 2, h / 2, radius ? 1 : 1 / Math.max(2 * root.r / w, 2 * root.r / h)); return nodes; } pack.size = function(_) { if (!arguments.length) return size; size = _; return pack; }; pack.radius = function(_) { if (!arguments.length) return radius; radius = _ == null || typeof _ === "function" ? _ : +_; return pack; }; pack.padding = function(_) { if (!arguments.length) return padding; padding = +_; return pack; }; return d3_layout_hierarchyRebind(pack, hierarchy); }; function d3_layout_packSort(a, b) { return a.value - b.value; } function d3_layout_packInsert(a, b) { var c = a._pack_next; a._pack_next = b; b._pack_prev = a; b._pack_next = c; c._pack_prev = b; } function d3_layout_packSplice(a, b) { a._pack_next = b; b._pack_prev = a; } function d3_layout_packIntersects(a, b) { var dx = b.x - a.x, dy = b.y - a.y, dr = a.r + b.r; return .999 * dr * dr > dx * dx + dy * dy; } function d3_layout_packSiblings(node) { if (!(nodes = node.children) || !(n = nodes.length)) return; var nodes, xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity, a, b, c, i, j, k, n; function bound(node) { xMin = Math.min(node.x - node.r, xMin); xMax = Math.max(node.x + node.r, xMax); yMin = Math.min(node.y - node.r, yMin); yMax = Math.max(node.y + node.r, yMax); } nodes.forEach(d3_layout_packLink); a = nodes[0]; a.x = -a.r; a.y = 0; bound(a); if (n > 1) { b = nodes[1]; b.x = b.r; b.y = 0; bound(b); if (n > 2) { c = nodes[2]; d3_layout_packPlace(a, b, c); bound(c); d3_layout_packInsert(a, c); a._pack_prev = c; d3_layout_packInsert(c, b); b = a._pack_next; for (i = 3; i < n; i++) { d3_layout_packPlace(a, b, c = nodes[i]); var isect = 0, s1 = 1, s2 = 1; for (j = b._pack_next; j !== b; j = j._pack_next, s1++) { if (d3_layout_packIntersects(j, c)) { isect = 1; break; } } if (isect == 1) { for (k = a._pack_prev; k !== j._pack_prev; k = k._pack_prev, s2++) { if (d3_layout_packIntersects(k, c)) { break; } } } if (isect) { if (s1 < s2 || s1 == s2 && b.r < a.r) d3_layout_packSplice(a, b = j); else d3_layout_packSplice(a = k, b); i--; } else { d3_layout_packInsert(a, c); b = c; bound(c); } } } } var cx = (xMin + xMax) / 2, cy = (yMin + yMax) / 2, cr = 0; for (i = 0; i < n; i++) { c = nodes[i]; c.x -= cx; c.y -= cy; cr = Math.max(cr, c.r + Math.sqrt(c.x * c.x + c.y * c.y)); } node.r = cr; nodes.forEach(d3_layout_packUnlink); } function d3_layout_packLink(node) { node._pack_next = node._pack_prev = node; } function d3_layout_packUnlink(node) { delete node._pack_next; delete node._pack_prev; } function d3_layout_packTransform(node, x, y, k) { var children = node.children; node.x = x += k * node.x; node.y = y += k * node.y; node.r *= k; if (children) { var i = -1, n = children.length; while (++i < n) d3_layout_packTransform(children[i], x, y, k); } } function d3_layout_packPlace(a, b, c) { var db = a.r + c.r, dx = b.x - a.x, dy = b.y - a.y; if (db && (dx || dy)) { var da = b.r + c.r, dc = dx * dx + dy * dy; da *= da; db *= db; var x = .5 + (db - da) / (2 * dc), y = Math.sqrt(Math.max(0, 2 * da * (db + dc) - (db -= dc) * db - da * da)) / (2 * dc); c.x = a.x + x * dx + y * dy; c.y = a.y + x * dy - y * dx; } else { c.x = a.x + db; c.y = a.y; } } d3.layout.tree = function() { var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = null; function tree(d, i) { var nodes = hierarchy.call(this, d, i), root0 = nodes[0], root1 = wrapTree(root0); d3_layout_hierarchyVisitAfter(root1, firstWalk), root1.parent.m = -root1.z; d3_layout_hierarchyVisitBefore(root1, secondWalk); if (nodeSize) d3_layout_hierarchyVisitBefore(root0, sizeNode); else { var left = root0, right = root0, bottom = root0; d3_layout_hierarchyVisitBefore(root0, function(node) { if (node.x < left.x) left = node; if (node.x > right.x) right = node; if (node.depth > bottom.depth) bottom = node; }); var tx = separation(left, right) / 2 - left.x, kx = size[0] / (right.x + separation(right, left) / 2 + tx), ky = size[1] / (bottom.depth || 1); d3_layout_hierarchyVisitBefore(root0, function(node) { node.x = (node.x + tx) * kx; node.y = node.depth * ky; }); } return nodes; } function wrapTree(root0) { var root1 = { A: null, children: [ root0 ] }, queue = [ root1 ], node1; while ((node1 = queue.pop()) != null) { for (var children = node1.children, child, i = 0, n = children.length; i < n; ++i) { queue.push((children[i] = child = { _: children[i], parent: node1, children: (child = children[i].children) && child.slice() || [], A: null, a: null, z: 0, m: 0, c: 0, s: 0, t: null, i: i }).a = child); } } return root1.children[0]; } function firstWalk(v) { var children = v.children, siblings = v.parent.children, w = v.i ? siblings[v.i - 1] : null; if (children.length) { d3_layout_treeShift(v); var midpoint = (children[0].z + children[children.length - 1].z) / 2; if (w) { v.z = w.z + separation(v._, w._); v.m = v.z - midpoint; } else { v.z = midpoint; } } else if (w) { v.z = w.z + separation(v._, w._); } v.parent.A = apportion(v, w, v.parent.A || siblings[0]); } function secondWalk(v) { v._.x = v.z + v.parent.m; v.m += v.parent.m; } function apportion(v, w, ancestor) { if (w) { var vip = v, vop = v, vim = w, vom = vip.parent.children[0], sip = vip.m, sop = vop.m, sim = vim.m, som = vom.m, shift; while (vim = d3_layout_treeRight(vim), vip = d3_layout_treeLeft(vip), vim && vip) { vom = d3_layout_treeLeft(vom); vop = d3_layout_treeRight(vop); vop.a = v; shift = vim.z + sim - vip.z - sip + separation(vim._, vip._); if (shift > 0) { d3_layout_treeMove(d3_layout_treeAncestor(vim, v, ancestor), v, shift); sip += shift; sop += shift; } sim += vim.m; sip += vip.m; som += vom.m; sop += vop.m; } if (vim && !d3_layout_treeRight(vop)) { vop.t = vim; vop.m += sim - sop; } if (vip && !d3_layout_treeLeft(vom)) { vom.t = vip; vom.m += sip - som; ancestor = v; } } return ancestor; } function sizeNode(node) { node.x *= size[0]; node.y = node.depth * size[1]; } tree.separation = function(x) { if (!arguments.length) return separation; separation = x; return tree; }; tree.size = function(x) { if (!arguments.length) return nodeSize ? null : size; nodeSize = (size = x) == null ? sizeNode : null; return tree; }; tree.nodeSize = function(x) { if (!arguments.length) return nodeSize ? size : null; nodeSize = (size = x) == null ? null : sizeNode; return tree; }; return d3_layout_hierarchyRebind(tree, hierarchy); }; function d3_layout_treeSeparation(a, b) { return a.parent == b.parent ? 1 : 2; } function d3_layout_treeLeft(v) { var children = v.children; return children.length ? children[0] : v.t; } function d3_layout_treeRight(v) { var children = v.children, n; return (n = children.length) ? children[n - 1] : v.t; } function d3_layout_treeMove(wm, wp, shift) { var change = shift / (wp.i - wm.i); wp.c -= change; wp.s += shift; wm.c += change; wp.z += shift; wp.m += shift; } function d3_layout_treeShift(v) { var shift = 0, change = 0, children = v.children, i = children.length, w; while (--i >= 0) { w = children[i]; w.z += shift; w.m += shift; shift += w.s + (change += w.c); } } function d3_layout_treeAncestor(vim, v, ancestor) { return vim.a.parent === v.parent ? vim.a : ancestor; } d3.layout.cluster = function() { var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = false; function cluster(d, i) { var nodes = hierarchy.call(this, d, i), root = nodes[0], previousNode, x = 0; d3_layout_hierarchyVisitAfter(root, function(node) { var children = node.children; if (children && children.length) { node.x = d3_layout_clusterX(children); node.y = d3_layout_clusterY(children); } else { node.x = previousNode ? x += separation(node, previousNode) : 0; node.y = 0; previousNode = node; } }); var left = d3_layout_clusterLeft(root), right = d3_layout_clusterRight(root), x0 = left.x - separation(left, right) / 2, x1 = right.x + separation(right, left) / 2; d3_layout_hierarchyVisitAfter(root, nodeSize ? function(node) { node.x = (node.x - root.x) * size[0]; node.y = (root.y - node.y) * size[1]; } : function(node) { node.x = (node.x - x0) / (x1 - x0) * size[0]; node.y = (1 - (root.y ? node.y / root.y : 1)) * size[1]; }); return nodes; } cluster.separation = function(x) { if (!arguments.length) return separation; separation = x; return cluster; }; cluster.size = function(x) { if (!arguments.length) return nodeSize ? null : size; nodeSize = (size = x) == null; return cluster; }; cluster.nodeSize = function(x) { if (!arguments.length) return nodeSize ? size : null; nodeSize = (size = x) != null; return cluster; }; return d3_layout_hierarchyRebind(cluster, hierarchy); }; function d3_layout_clusterY(children) { return 1 + d3.max(children, function(child) { return child.y; }); } function d3_layout_clusterX(children) { return children.reduce(function(x, child) { return x + child.x; }, 0) / children.length; } function d3_layout_clusterLeft(node) { var children = node.children; return children && children.length ? d3_layout_clusterLeft(children[0]) : node; } function d3_layout_clusterRight(node) { var children = node.children, n; return children && (n = children.length) ? d3_layout_clusterRight(children[n - 1]) : node; } d3.layout.treemap = function() { var hierarchy = d3.layout.hierarchy(), round = Math.round, size = [ 1, 1 ], padding = null, pad = d3_layout_treemapPadNull, sticky = false, stickies, mode = "squarify", ratio = .5 * (1 + Math.sqrt(5)); function scale(children, k) { var i = -1, n = children.length, child, area; while (++i < n) { area = (child = children[i]).value * (k < 0 ? 0 : k); child.area = isNaN(area) || area <= 0 ? 0 : area; } } function squarify(node) { var children = node.children; if (children && children.length) { var rect = pad(node), row = [], remaining = children.slice(), child, best = Infinity, score, u = mode === "slice" ? rect.dx : mode === "dice" ? rect.dy : mode === "slice-dice" ? node.depth & 1 ? rect.dy : rect.dx : Math.min(rect.dx, rect.dy), n; scale(remaining, rect.dx * rect.dy / node.value); row.area = 0; while ((n = remaining.length) > 0) { row.push(child = remaining[n - 1]); row.area += child.area; if (mode !== "squarify" || (score = worst(row, u)) <= best) { remaining.pop(); best = score; } else { row.area -= row.pop().area; position(row, u, rect, false); u = Math.min(rect.dx, rect.dy); row.length = row.area = 0; best = Infinity; } } if (row.length) { position(row, u, rect, true); row.length = row.area = 0; } children.forEach(squarify); } } function stickify(node) { var children = node.children; if (children && children.length) { var rect = pad(node), remaining = children.slice(), child, row = []; scale(remaining, rect.dx * rect.dy / node.value); row.area = 0; while (child = remaining.pop()) { row.push(child); row.area += child.area; if (child.z != null) { position(row, child.z ? rect.dx : rect.dy, rect, !remaining.length); row.length = row.area = 0; } } children.forEach(stickify); } } function worst(row, u) { var s = row.area, r, rmax = 0, rmin = Infinity, i = -1, n = row.length; while (++i < n) { if (!(r = row[i].area)) continue; if (r < rmin) rmin = r; if (r > rmax) rmax = r; } s *= s; u *= u; return s ? Math.max(u * rmax * ratio / s, s / (u * rmin * ratio)) : Infinity; } function position(row, u, rect, flush) { var i = -1, n = row.length, x = rect.x, y = rect.y, v = u ? round(row.area / u) : 0, o; if (u == rect.dx) { if (flush || v > rect.dy) v = rect.dy; while (++i < n) { o = row[i]; o.x = x; o.y = y; o.dy = v; x += o.dx = Math.min(rect.x + rect.dx - x, v ? round(o.area / v) : 0); } o.z = true; o.dx += rect.x + rect.dx - x; rect.y += v; rect.dy -= v; } else { if (flush || v > rect.dx) v = rect.dx; while (++i < n) { o = row[i]; o.x = x; o.y = y; o.dx = v; y += o.dy = Math.min(rect.y + rect.dy - y, v ? round(o.area / v) : 0); } o.z = false; o.dy += rect.y + rect.dy - y; rect.x += v; rect.dx -= v; } } function treemap(d) { var nodes = stickies || hierarchy(d), root = nodes[0]; root.x = 0; root.y = 0; root.dx = size[0]; root.dy = size[1]; if (stickies) hierarchy.revalue(root); scale([ root ], root.dx * root.dy / root.value); (stickies ? stickify : squarify)(root); if (sticky) stickies = nodes; return nodes; } treemap.size = function(x) { if (!arguments.length) return size; size = x; return treemap; }; treemap.padding = function(x) { if (!arguments.length) return padding; function padFunction(node) { var p = x.call(treemap, node, node.depth); return p == null ? d3_layout_treemapPadNull(node) : d3_layout_treemapPad(node, typeof p === "number" ? [ p, p, p, p ] : p); } function padConstant(node) { return d3_layout_treemapPad(node, x); } var type; pad = (padding = x) == null ? d3_layout_treemapPadNull : (type = typeof x) === "function" ? padFunction : type === "number" ? (x = [ x, x, x, x ], padConstant) : padConstant; return treemap; }; treemap.round = function(x) { if (!arguments.length) return round != Number; round = x ? Math.round : Number; return treemap; }; treemap.sticky = function(x) { if (!arguments.length) return sticky; sticky = x; stickies = null; return treemap; }; treemap.ratio = function(x) { if (!arguments.length) return ratio; ratio = x; return treemap; }; treemap.mode = function(x) { if (!arguments.length) return mode; mode = x + ""; return treemap; }; return d3_layout_hierarchyRebind(treemap, hierarchy); }; function d3_layout_treemapPadNull(node) { return { x: node.x, y: node.y, dx: node.dx, dy: node.dy }; } function d3_layout_treemapPad(node, padding) { var x = node.x + padding[3], y = node.y + padding[0], dx = node.dx - padding[1] - padding[3], dy = node.dy - padding[0] - padding[2]; if (dx < 0) { x += dx / 2; dx = 0; } if (dy < 0) { y += dy / 2; dy = 0; } return { x: x, y: y, dx: dx, dy: dy }; } d3.random = { normal: function(µ, σ) { var n = arguments.length; if (n < 2) σ = 1; if (n < 1) µ = 0; return function() { var x, y, r; do { x = Math.random() * 2 - 1; y = Math.random() * 2 - 1; r = x * x + y * y; } while (!r || r > 1); return µ + σ * x * Math.sqrt(-2 * Math.log(r) / r); }; }, logNormal: function() { var random = d3.random.normal.apply(d3, arguments); return function() { return Math.exp(random()); }; }, bates: function(m) { var random = d3.random.irwinHall(m); return function() { return random() / m; }; }, irwinHall: function(m) { return function() { for (var s = 0, j = 0; j < m; j++) s += Math.random(); return s; }; } }; d3.scale = {}; function d3_scaleExtent(domain) { var start = domain[0], stop = domain[domain.length - 1]; return start < stop ? [ start, stop ] : [ stop, start ]; } function d3_scaleRange(scale) { return scale.rangeExtent ? scale.rangeExtent() : d3_scaleExtent(scale.range()); } function d3_scale_bilinear(domain, range, uninterpolate, interpolate) { var u = uninterpolate(domain[0], domain[1]), i = interpolate(range[0], range[1]); return function(x) { return i(u(x)); }; } function d3_scale_nice(domain, nice) { var i0 = 0, i1 = domain.length - 1, x0 = domain[i0], x1 = domain[i1], dx; if (x1 < x0) { dx = i0, i0 = i1, i1 = dx; dx = x0, x0 = x1, x1 = dx; } domain[i0] = nice.floor(x0); domain[i1] = nice.ceil(x1); return domain; } function d3_scale_niceStep(step) { return step ? { floor: function(x) { return Math.floor(x / step) * step; }, ceil: function(x) { return Math.ceil(x / step) * step; } } : d3_scale_niceIdentity; } var d3_scale_niceIdentity = { floor: d3_identity, ceil: d3_identity }; function d3_scale_polylinear(domain, range, uninterpolate, interpolate) { var u = [], i = [], j = 0, k = Math.min(domain.length, range.length) - 1; if (domain[k] < domain[0]) { domain = domain.slice().reverse(); range = range.slice().reverse(); } while (++j <= k) { u.push(uninterpolate(domain[j - 1], domain[j])); i.push(interpolate(range[j - 1], range[j])); } return function(x) { var j = d3.bisect(domain, x, 1, k) - 1; return i[j](u[j](x)); }; } d3.scale.linear = function() { return d3_scale_linear([ 0, 1 ], [ 0, 1 ], d3_interpolate, false); }; function d3_scale_linear(domain, range, interpolate, clamp) { var output, input; function rescale() { var linear = Math.min(domain.length, range.length) > 2 ? d3_scale_polylinear : d3_scale_bilinear, uninterpolate = clamp ? d3_uninterpolateClamp : d3_uninterpolateNumber; output = linear(domain, range, uninterpolate, interpolate); input = linear(range, domain, uninterpolate, d3_interpolate); return scale; } function scale(x) { return output(x); } scale.invert = function(y) { return input(y); }; scale.domain = function(x) { if (!arguments.length) return domain; domain = x.map(Number); return rescale(); }; scale.range = function(x) { if (!arguments.length) return range; range = x; return rescale(); }; scale.rangeRound = function(x) { return scale.range(x).interpolate(d3_interpolateRound); }; scale.clamp = function(x) { if (!arguments.length) return clamp; clamp = x; return rescale(); }; scale.interpolate = function(x) { if (!arguments.length) return interpolate; interpolate = x; return rescale(); }; scale.ticks = function(m) { return d3_scale_linearTicks(domain, m); }; scale.tickFormat = function(m, format) { return d3_scale_linearTickFormat(domain, m, format); }; scale.nice = function(m) { d3_scale_linearNice(domain, m); return rescale(); }; scale.copy = function() { return d3_scale_linear(domain, range, interpolate, clamp); }; return rescale(); } function d3_scale_linearRebind(scale, linear) { return d3.rebind(scale, linear, "range", "rangeRound", "interpolate", "clamp"); } function d3_scale_linearNice(domain, m) { return d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2])); } function d3_scale_linearTickRange(domain, m) { if (m == null) m = 10; var extent = d3_scaleExtent(domain), span = extent[1] - extent[0], step = Math.pow(10, Math.floor(Math.log(span / m) / Math.LN10)), err = m / span * step; if (err <= .15) step *= 10; else if (err <= .35) step *= 5; else if (err <= .75) step *= 2; extent[0] = Math.ceil(extent[0] / step) * step; extent[1] = Math.floor(extent[1] / step) * step + step * .5; extent[2] = step; return extent; } function d3_scale_linearTicks(domain, m) { return d3.range.apply(d3, d3_scale_linearTickRange(domain, m)); } function d3_scale_linearTickFormat(domain, m, format) { var range = d3_scale_linearTickRange(domain, m); if (format) { var match = d3_format_re.exec(format); match.shift(); if (match[8] === "s") { var prefix = d3.formatPrefix(Math.max(abs(range[0]), abs(range[1]))); if (!match[7]) match[7] = "." + d3_scale_linearPrecision(prefix.scale(range[2])); match[8] = "f"; format = d3.format(match.join("")); return function(d) { return format(prefix.scale(d)) + prefix.symbol; }; } if (!match[7]) match[7] = "." + d3_scale_linearFormatPrecision(match[8], range); format = match.join(""); } else { format = ",." + d3_scale_linearPrecision(range[2]) + "f"; } return d3.format(format); } var d3_scale_linearFormatSignificant = { s: 1, g: 1, p: 1, r: 1, e: 1 }; function d3_scale_linearPrecision(value) { return -Math.floor(Math.log(value) / Math.LN10 + .01); } function d3_scale_linearFormatPrecision(type, range) { var p = d3_scale_linearPrecision(range[2]); return type in d3_scale_linearFormatSignificant ? Math.abs(p - d3_scale_linearPrecision(Math.max(abs(range[0]), abs(range[1])))) + +(type !== "e") : p - (type === "%") * 2; } d3.scale.log = function() { return d3_scale_log(d3.scale.linear().domain([ 0, 1 ]), 10, true, [ 1, 10 ]); }; function d3_scale_log(linear, base, positive, domain) { function log(x) { return (positive ? Math.log(x < 0 ? 0 : x) : -Math.log(x > 0 ? 0 : -x)) / Math.log(base); } function pow(x) { return positive ? Math.pow(base, x) : -Math.pow(base, -x); } function scale(x) { return linear(log(x)); } scale.invert = function(x) { return pow(linear.invert(x)); }; scale.domain = function(x) { if (!arguments.length) return domain; positive = x[0] >= 0; linear.domain((domain = x.map(Number)).map(log)); return scale; }; scale.base = function(_) { if (!arguments.length) return base; base = +_; linear.domain(domain.map(log)); return scale; }; scale.nice = function() { var niced = d3_scale_nice(domain.map(log), positive ? Math : d3_scale_logNiceNegative); linear.domain(niced); domain = niced.map(pow); return scale; }; scale.ticks = function() { var extent = d3_scaleExtent(domain), ticks = [], u = extent[0], v = extent[1], i = Math.floor(log(u)), j = Math.ceil(log(v)), n = base % 1 ? 2 : base; if (isFinite(j - i)) { if (positive) { for (;i < j; i++) for (var k = 1; k < n; k++) ticks.push(pow(i) * k); ticks.push(pow(i)); } else { ticks.push(pow(i)); for (;i++ < j; ) for (var k = n - 1; k > 0; k--) ticks.push(pow(i) * k); } for (i = 0; ticks[i] < u; i++) {} for (j = ticks.length; ticks[j - 1] > v; j--) {} ticks = ticks.slice(i, j); } return ticks; }; scale.tickFormat = function(n, format) { if (!arguments.length) return d3_scale_logFormat; if (arguments.length < 2) format = d3_scale_logFormat; else if (typeof format !== "function") format = d3.format(format); var k = Math.max(.1, n / scale.ticks().length), f = positive ? (e = 1e-12, Math.ceil) : (e = -1e-12, Math.floor), e; return function(d) { return d / pow(f(log(d) + e)) <= k ? format(d) : ""; }; }; scale.copy = function() { return d3_scale_log(linear.copy(), base, positive, domain); }; return d3_scale_linearRebind(scale, linear); } var d3_scale_logFormat = d3.format(".0e"), d3_scale_logNiceNegative = { floor: function(x) { return -Math.ceil(-x); }, ceil: function(x) { return -Math.floor(-x); } }; d3.scale.pow = function() { return d3_scale_pow(d3.scale.linear(), 1, [ 0, 1 ]); }; function d3_scale_pow(linear, exponent, domain) { var powp = d3_scale_powPow(exponent), powb = d3_scale_powPow(1 / exponent); function scale(x) { return linear(powp(x)); } scale.invert = function(x) { return powb(linear.invert(x)); }; scale.domain = function(x) { if (!arguments.length) return domain; linear.domain((domain = x.map(Number)).map(powp)); return scale; }; scale.ticks = function(m) { return d3_scale_linearTicks(domain, m); }; scale.tickFormat = function(m, format) { return d3_scale_linearTickFormat(domain, m, format); }; scale.nice = function(m) { return scale.domain(d3_scale_linearNice(domain, m)); }; scale.exponent = function(x) { if (!arguments.length) return exponent; powp = d3_scale_powPow(exponent = x); powb = d3_scale_powPow(1 / exponent); linear.domain(domain.map(powp)); return scale; }; scale.copy = function() { return d3_scale_pow(linear.copy(), exponent, domain); }; return d3_scale_linearRebind(scale, linear); } function d3_scale_powPow(e) { return function(x) { return x < 0 ? -Math.pow(-x, e) : Math.pow(x, e); }; } d3.scale.sqrt = function() { return d3.scale.pow().exponent(.5); }; d3.scale.ordinal = function() { return d3_scale_ordinal([], { t: "range", a: [ [] ] }); }; function d3_scale_ordinal(domain, ranger) { var index, range, rangeBand; function scale(x) { return range[((index.get(x) || (ranger.t === "range" ? index.set(x, domain.push(x)) : NaN)) - 1) % range.length]; } function steps(start, step) { return d3.range(domain.length).map(function(i) { return start + step * i; }); } scale.domain = function(x) { if (!arguments.length) return domain; domain = []; index = new d3_Map(); var i = -1, n = x.length, xi; while (++i < n) if (!index.has(xi = x[i])) index.set(xi, domain.push(xi)); return scale[ranger.t].apply(scale, ranger.a); }; scale.range = function(x) { if (!arguments.length) return range; range = x; rangeBand = 0; ranger = { t: "range", a: arguments }; return scale; }; scale.rangePoints = function(x, padding) { if (arguments.length < 2) padding = 0; var start = x[0], stop = x[1], step = domain.length < 2 ? (start = (start + stop) / 2, 0) : (stop - start) / (domain.length - 1 + padding); range = steps(start + step * padding / 2, step); rangeBand = 0; ranger = { t: "rangePoints", a: arguments }; return scale; }; scale.rangeRoundPoints = function(x, padding) { if (arguments.length < 2) padding = 0; var start = x[0], stop = x[1], step = domain.length < 2 ? (start = stop = Math.round((start + stop) / 2), 0) : (stop - start) / (domain.length - 1 + padding) | 0; range = steps(start + Math.round(step * padding / 2 + (stop - start - (domain.length - 1 + padding) * step) / 2), step); rangeBand = 0; ranger = { t: "rangeRoundPoints", a: arguments }; return scale; }; scale.rangeBands = function(x, padding, outerPadding) { if (arguments.length < 2) padding = 0; if (arguments.length < 3) outerPadding = padding; var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = (stop - start) / (domain.length - padding + 2 * outerPadding); range = steps(start + step * outerPadding, step); if (reverse) range.reverse(); rangeBand = step * (1 - padding); ranger = { t: "rangeBands", a: arguments }; return scale; }; scale.rangeRoundBands = function(x, padding, outerPadding) { if (arguments.length < 2) padding = 0; if (arguments.length < 3) outerPadding = padding; var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = Math.floor((stop - start) / (domain.length - padding + 2 * outerPadding)); range = steps(start + Math.round((stop - start - (domain.length - padding) * step) / 2), step); if (reverse) range.reverse(); rangeBand = Math.round(step * (1 - padding)); ranger = { t: "rangeRoundBands", a: arguments }; return scale; }; scale.rangeBand = function() { return rangeBand; }; scale.rangeExtent = function() { return d3_scaleExtent(ranger.a[0]); }; scale.copy = function() { return d3_scale_ordinal(domain, ranger); }; return scale.domain(domain); } d3.scale.category10 = function() { return d3.scale.ordinal().range(d3_category10); }; d3.scale.category20 = function() { return d3.scale.ordinal().range(d3_category20); }; d3.scale.category20b = function() { return d3.scale.ordinal().range(d3_category20b); }; d3.scale.category20c = function() { return d3.scale.ordinal().range(d3_category20c); }; var d3_category10 = [ 2062260, 16744206, 2924588, 14034728, 9725885, 9197131, 14907330, 8355711, 12369186, 1556175 ].map(d3_rgbString); var d3_category20 = [ 2062260, 11454440, 16744206, 16759672, 2924588, 10018698, 14034728, 16750742, 9725885, 12955861, 9197131, 12885140, 14907330, 16234194, 8355711, 13092807, 12369186, 14408589, 1556175, 10410725 ].map(d3_rgbString); var d3_category20b = [ 3750777, 5395619, 7040719, 10264286, 6519097, 9216594, 11915115, 13556636, 9202993, 12426809, 15186514, 15190932, 8666169, 11356490, 14049643, 15177372, 8077683, 10834324, 13528509, 14589654 ].map(d3_rgbString); var d3_category20c = [ 3244733, 7057110, 10406625, 13032431, 15095053, 16616764, 16625259, 16634018, 3253076, 7652470, 10607003, 13101504, 7695281, 10394312, 12369372, 14342891, 6513507, 9868950, 12434877, 14277081 ].map(d3_rgbString); d3.scale.quantile = function() { return d3_scale_quantile([], []); }; function d3_scale_quantile(domain, range) { var thresholds; function rescale() { var k = 0, q = range.length; thresholds = []; while (++k < q) thresholds[k - 1] = d3.quantile(domain, k / q); return scale; } function scale(x) { if (!isNaN(x = +x)) return range[d3.bisect(thresholds, x)]; } scale.domain = function(x) { if (!arguments.length) return domain; domain = x.map(d3_number).filter(d3_numeric).sort(d3_ascending); return rescale(); }; scale.range = function(x) { if (!arguments.length) return range; range = x; return rescale(); }; scale.quantiles = function() { return thresholds; }; scale.invertExtent = function(y) { y = range.indexOf(y); return y < 0 ? [ NaN, NaN ] : [ y > 0 ? thresholds[y - 1] : domain[0], y < thresholds.length ? thresholds[y] : domain[domain.length - 1] ]; }; scale.copy = function() { return d3_scale_quantile(domain, range); }; return rescale(); } d3.scale.quantize = function() { return d3_scale_quantize(0, 1, [ 0, 1 ]); }; function d3_scale_quantize(x0, x1, range) { var kx, i; function scale(x) { return range[Math.max(0, Math.min(i, Math.floor(kx * (x - x0))))]; } function rescale() { kx = range.length / (x1 - x0); i = range.length - 1; return scale; } scale.domain = function(x) { if (!arguments.length) return [ x0, x1 ]; x0 = +x[0]; x1 = +x[x.length - 1]; return rescale(); }; scale.range = function(x) { if (!arguments.length) return range; range = x; return rescale(); }; scale.invertExtent = function(y) { y = range.indexOf(y); y = y < 0 ? NaN : y / kx + x0; return [ y, y + 1 / kx ]; }; scale.copy = function() { return d3_scale_quantize(x0, x1, range); }; return rescale(); } d3.scale.threshold = function() { return d3_scale_threshold([ .5 ], [ 0, 1 ]); }; function d3_scale_threshold(domain, range) { function scale(x) { if (x <= x) return range[d3.bisect(domain, x)]; } scale.domain = function(_) { if (!arguments.length) return domain; domain = _; return scale; }; scale.range = function(_) { if (!arguments.length) return range; range = _; return scale; }; scale.invertExtent = function(y) { y = range.indexOf(y); return [ domain[y - 1], domain[y] ]; }; scale.copy = function() { return d3_scale_threshold(domain, range); }; return scale; } d3.scale.identity = function() { return d3_scale_identity([ 0, 1 ]); }; function d3_scale_identity(domain) { function identity(x) { return +x; } identity.invert = identity; identity.domain = identity.range = function(x) { if (!arguments.length) return domain; domain = x.map(identity); return identity; }; identity.ticks = function(m) { return d3_scale_linearTicks(domain, m); }; identity.tickFormat = function(m, format) { return d3_scale_linearTickFormat(domain, m, format); }; identity.copy = function() { return d3_scale_identity(domain); }; return identity; } d3.svg = {}; function d3_zero() { return 0; } d3.svg.arc = function() { var innerRadius = d3_svg_arcInnerRadius, outerRadius = d3_svg_arcOuterRadius, cornerRadius = d3_zero, padRadius = d3_svg_arcAuto, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle, padAngle = d3_svg_arcPadAngle; function arc() { var r0 = Math.max(0, +innerRadius.apply(this, arguments)), r1 = Math.max(0, +outerRadius.apply(this, arguments)), a0 = startAngle.apply(this, arguments) - halfπ, a1 = endAngle.apply(this, arguments) - halfπ, da = Math.abs(a1 - a0), cw = a0 > a1 ? 0 : 1; if (r1 < r0) rc = r1, r1 = r0, r0 = rc; if (da >= τε) return circleSegment(r1, cw) + (r0 ? circleSegment(r0, 1 - cw) : "") + "Z"; var rc, cr, rp, ap, p0 = 0, p1 = 0, x0, y0, x1, y1, x2, y2, x3, y3, path = []; if (ap = (+padAngle.apply(this, arguments) || 0) / 2) { rp = padRadius === d3_svg_arcAuto ? Math.sqrt(r0 * r0 + r1 * r1) : +padRadius.apply(this, arguments); if (!cw) p1 *= -1; if (r1) p1 = d3_asin(rp / r1 * Math.sin(ap)); if (r0) p0 = d3_asin(rp / r0 * Math.sin(ap)); } if (r1) { x0 = r1 * Math.cos(a0 + p1); y0 = r1 * Math.sin(a0 + p1); x1 = r1 * Math.cos(a1 - p1); y1 = r1 * Math.sin(a1 - p1); var l1 = Math.abs(a1 - a0 - 2 * p1) <= π ? 0 : 1; if (p1 && d3_svg_arcSweep(x0, y0, x1, y1) === cw ^ l1) { var h1 = (a0 + a1) / 2; x0 = r1 * Math.cos(h1); y0 = r1 * Math.sin(h1); x1 = y1 = null; } } else { x0 = y0 = 0; } if (r0) { x2 = r0 * Math.cos(a1 - p0); y2 = r0 * Math.sin(a1 - p0); x3 = r0 * Math.cos(a0 + p0); y3 = r0 * Math.sin(a0 + p0); var l0 = Math.abs(a0 - a1 + 2 * p0) <= π ? 0 : 1; if (p0 && d3_svg_arcSweep(x2, y2, x3, y3) === 1 - cw ^ l0) { var h0 = (a0 + a1) / 2; x2 = r0 * Math.cos(h0); y2 = r0 * Math.sin(h0); x3 = y3 = null; } } else { x2 = y2 = 0; } if ((rc = Math.min(Math.abs(r1 - r0) / 2, +cornerRadius.apply(this, arguments))) > .001) { cr = r0 < r1 ^ cw ? 0 : 1; var oc = x3 == null ? [ x2, y2 ] : x1 == null ? [ x0, y0 ] : d3_geom_polygonIntersect([ x0, y0 ], [ x3, y3 ], [ x1, y1 ], [ x2, y2 ]), ax = x0 - oc[0], ay = y0 - oc[1], bx = x1 - oc[0], by = y1 - oc[1], kc = 1 / Math.sin(Math.acos((ax * bx + ay * by) / (Math.sqrt(ax * ax + ay * ay) * Math.sqrt(bx * bx + by * by))) / 2), lc = Math.sqrt(oc[0] * oc[0] + oc[1] * oc[1]); if (x1 != null) { var rc1 = Math.min(rc, (r1 - lc) / (kc + 1)), t30 = d3_svg_arcCornerTangents(x3 == null ? [ x2, y2 ] : [ x3, y3 ], [ x0, y0 ], r1, rc1, cw), t12 = d3_svg_arcCornerTangents([ x1, y1 ], [ x2, y2 ], r1, rc1, cw); if (rc === rc1) { path.push("M", t30[0], "A", rc1, ",", rc1, " 0 0,", cr, " ", t30[1], "A", r1, ",", r1, " 0 ", 1 - cw ^ d3_svg_arcSweep(t30[1][0], t30[1][1], t12[1][0], t12[1][1]), ",", cw, " ", t12[1], "A", rc1, ",", rc1, " 0 0,", cr, " ", t12[0]); } else { path.push("M", t30[0], "A", rc1, ",", rc1, " 0 1,", cr, " ", t12[0]); } } else { path.push("M", x0, ",", y0); } if (x3 != null) { var rc0 = Math.min(rc, (r0 - lc) / (kc - 1)), t03 = d3_svg_arcCornerTangents([ x0, y0 ], [ x3, y3 ], r0, -rc0, cw), t21 = d3_svg_arcCornerTangents([ x2, y2 ], x1 == null ? [ x0, y0 ] : [ x1, y1 ], r0, -rc0, cw); if (rc === rc0) { path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t21[1], "A", r0, ",", r0, " 0 ", cw ^ d3_svg_arcSweep(t21[1][0], t21[1][1], t03[1][0], t03[1][1]), ",", 1 - cw, " ", t03[1], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]); } else { path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]); } } else { path.push("L", x2, ",", y2); } } else { path.push("M", x0, ",", y0); if (x1 != null) path.push("A", r1, ",", r1, " 0 ", l1, ",", cw, " ", x1, ",", y1); path.push("L", x2, ",", y2); if (x3 != null) path.push("A", r0, ",", r0, " 0 ", l0, ",", 1 - cw, " ", x3, ",", y3); } path.push("Z"); return path.join(""); } function circleSegment(r1, cw) { return "M0," + r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + -r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + r1; } arc.innerRadius = function(v) { if (!arguments.length) return innerRadius; innerRadius = d3_functor(v); return arc; }; arc.outerRadius = function(v) { if (!arguments.length) return outerRadius; outerRadius = d3_functor(v); return arc; }; arc.cornerRadius = function(v) { if (!arguments.length) return cornerRadius; cornerRadius = d3_functor(v); return arc; }; arc.padRadius = function(v) { if (!arguments.length) return padRadius; padRadius = v == d3_svg_arcAuto ? d3_svg_arcAuto : d3_functor(v); return arc; }; arc.startAngle = function(v) { if (!arguments.length) return startAngle; startAngle = d3_functor(v); return arc; }; arc.endAngle = function(v) { if (!arguments.length) return endAngle; endAngle = d3_functor(v); return arc; }; arc.padAngle = function(v) { if (!arguments.length) return padAngle; padAngle = d3_functor(v); return arc; }; arc.centroid = function() { var r = (+innerRadius.apply(this, arguments) + +outerRadius.apply(this, arguments)) / 2, a = (+startAngle.apply(this, arguments) + +endAngle.apply(this, arguments)) / 2 - halfπ; return [ Math.cos(a) * r, Math.sin(a) * r ]; }; return arc; }; var d3_svg_arcAuto = "auto"; function d3_svg_arcInnerRadius(d) { return d.innerRadius; } function d3_svg_arcOuterRadius(d) { return d.outerRadius; } function d3_svg_arcStartAngle(d) { return d.startAngle; } function d3_svg_arcEndAngle(d) { return d.endAngle; } function d3_svg_arcPadAngle(d) { return d && d.padAngle; } function d3_svg_arcSweep(x0, y0, x1, y1) { return (x0 - x1) * y0 - (y0 - y1) * x0 > 0 ? 0 : 1; } function d3_svg_arcCornerTangents(p0, p1, r1, rc, cw) { var x01 = p0[0] - p1[0], y01 = p0[1] - p1[1], lo = (cw ? rc : -rc) / Math.sqrt(x01 * x01 + y01 * y01), ox = lo * y01, oy = -lo * x01, x1 = p0[0] + ox, y1 = p0[1] + oy, x2 = p1[0] + ox, y2 = p1[1] + oy, x3 = (x1 + x2) / 2, y3 = (y1 + y2) / 2, dx = x2 - x1, dy = y2 - y1, d2 = dx * dx + dy * dy, r = r1 - rc, D = x1 * y2 - x2 * y1, d = (dy < 0 ? -1 : 1) * Math.sqrt(r * r * d2 - D * D), cx0 = (D * dy - dx * d) / d2, cy0 = (-D * dx - dy * d) / d2, cx1 = (D * dy + dx * d) / d2, cy1 = (-D * dx + dy * d) / d2, dx0 = cx0 - x3, dy0 = cy0 - y3, dx1 = cx1 - x3, dy1 = cy1 - y3; if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) cx0 = cx1, cy0 = cy1; return [ [ cx0 - ox, cy0 - oy ], [ cx0 * r1 / r, cy0 * r1 / r ] ]; } function d3_svg_line(projection) { var x = d3_geom_pointX, y = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, tension = .7; function line(data) { var segments = [], points = [], i = -1, n = data.length, d, fx = d3_functor(x), fy = d3_functor(y); function segment() { segments.push("M", interpolate(projection(points), tension)); } while (++i < n) { if (defined.call(this, d = data[i], i)) { points.push([ +fx.call(this, d, i), +fy.call(this, d, i) ]); } else if (points.length) { segment(); points = []; } } if (points.length) segment(); return segments.length ? segments.join("") : null; } line.x = function(_) { if (!arguments.length) return x; x = _; return line; }; line.y = function(_) { if (!arguments.length) return y; y = _; return line; }; line.defined = function(_) { if (!arguments.length) return defined; defined = _; return line; }; line.interpolate = function(_) { if (!arguments.length) return interpolateKey; if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key; return line; }; line.tension = function(_) { if (!arguments.length) return tension; tension = _; return line; }; return line; } d3.svg.line = function() { return d3_svg_line(d3_identity); }; var d3_svg_lineInterpolators = d3.map({ linear: d3_svg_lineLinear, "linear-closed": d3_svg_lineLinearClosed, step: d3_svg_lineStep, "step-before": d3_svg_lineStepBefore, "step-after": d3_svg_lineStepAfter, basis: d3_svg_lineBasis, "basis-open": d3_svg_lineBasisOpen, "basis-closed": d3_svg_lineBasisClosed, bundle: d3_svg_lineBundle, cardinal: d3_svg_lineCardinal, "cardinal-open": d3_svg_lineCardinalOpen, "cardinal-closed": d3_svg_lineCardinalClosed, monotone: d3_svg_lineMonotone }); d3_svg_lineInterpolators.forEach(function(key, value) { value.key = key; value.closed = /-closed$/.test(key); }); function d3_svg_lineLinear(points) { return points.join("L"); } function d3_svg_lineLinearClosed(points) { return d3_svg_lineLinear(points) + "Z"; } function d3_svg_lineStep(points) { var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; while (++i < n) path.push("H", (p[0] + (p = points[i])[0]) / 2, "V", p[1]); if (n > 1) path.push("H", p[0]); return path.join(""); } function d3_svg_lineStepBefore(points) { var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; while (++i < n) path.push("V", (p = points[i])[1], "H", p[0]); return path.join(""); } function d3_svg_lineStepAfter(points) { var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; while (++i < n) path.push("H", (p = points[i])[0], "V", p[1]); return path.join(""); } function d3_svg_lineCardinalOpen(points, tension) { return points.length < 4 ? d3_svg_lineLinear(points) : points[1] + d3_svg_lineHermite(points.slice(1, -1), d3_svg_lineCardinalTangents(points, tension)); } function d3_svg_lineCardinalClosed(points, tension) { return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite((points.push(points[0]), points), d3_svg_lineCardinalTangents([ points[points.length - 2] ].concat(points, [ points[1] ]), tension)); } function d3_svg_lineCardinal(points, tension) { return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineCardinalTangents(points, tension)); } function d3_svg_lineHermite(points, tangents) { if (tangents.length < 1 || points.length != tangents.length && points.length != tangents.length + 2) { return d3_svg_lineLinear(points); } var quad = points.length != tangents.length, path = "", p0 = points[0], p = points[1], t0 = tangents[0], t = t0, pi = 1; if (quad) { path += "Q" + (p[0] - t0[0] * 2 / 3) + "," + (p[1] - t0[1] * 2 / 3) + "," + p[0] + "," + p[1]; p0 = points[1]; pi = 2; } if (tangents.length > 1) { t = tangents[1]; p = points[pi]; pi++; path += "C" + (p0[0] + t0[0]) + "," + (p0[1] + t0[1]) + "," + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1]; for (var i = 2; i < tangents.length; i++, pi++) { p = points[pi]; t = tangents[i]; path += "S" + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1]; } } if (quad) { var lp = points[pi]; path += "Q" + (p[0] + t[0] * 2 / 3) + "," + (p[1] + t[1] * 2 / 3) + "," + lp[0] + "," + lp[1]; } return path; } function d3_svg_lineCardinalTangents(points, tension) { var tangents = [], a = (1 - tension) / 2, p0, p1 = points[0], p2 = points[1], i = 1, n = points.length; while (++i < n) { p0 = p1; p1 = p2; p2 = points[i]; tangents.push([ a * (p2[0] - p0[0]), a * (p2[1] - p0[1]) ]); } return tangents; } function d3_svg_lineBasis(points) { if (points.length < 3) return d3_svg_lineLinear(points); var i = 1, n = points.length, pi = points[0], x0 = pi[0], y0 = pi[1], px = [ x0, x0, x0, (pi = points[1])[0] ], py = [ y0, y0, y0, pi[1] ], path = [ x0, ",", y0, "L", d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ]; points.push(points[n - 1]); while (++i <= n) { pi = points[i]; px.shift(); px.push(pi[0]); py.shift(); py.push(pi[1]); d3_svg_lineBasisBezier(path, px, py); } points.pop(); path.push("L", pi); return path.join(""); } function d3_svg_lineBasisOpen(points) { if (points.length < 4) return d3_svg_lineLinear(points); var path = [], i = -1, n = points.length, pi, px = [ 0 ], py = [ 0 ]; while (++i < 3) { pi = points[i]; px.push(pi[0]); py.push(pi[1]); } path.push(d3_svg_lineDot4(d3_svg_lineBasisBezier3, px) + "," + d3_svg_lineDot4(d3_svg_lineBasisBezier3, py)); --i; while (++i < n) { pi = points[i]; px.shift(); px.push(pi[0]); py.shift(); py.push(pi[1]); d3_svg_lineBasisBezier(path, px, py); } return path.join(""); } function d3_svg_lineBasisClosed(points) { var path, i = -1, n = points.length, m = n + 4, pi, px = [], py = []; while (++i < 4) { pi = points[i % n]; px.push(pi[0]); py.push(pi[1]); } path = [ d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ]; --i; while (++i < m) { pi = points[i % n]; px.shift(); px.push(pi[0]); py.shift(); py.push(pi[1]); d3_svg_lineBasisBezier(path, px, py); } return path.join(""); } function d3_svg_lineBundle(points, tension) { var n = points.length - 1; if (n) { var x0 = points[0][0], y0 = points[0][1], dx = points[n][0] - x0, dy = points[n][1] - y0, i = -1, p, t; while (++i <= n) { p = points[i]; t = i / n; p[0] = tension * p[0] + (1 - tension) * (x0 + t * dx); p[1] = tension * p[1] + (1 - tension) * (y0 + t * dy); } } return d3_svg_lineBasis(points); } function d3_svg_lineDot4(a, b) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]; } var d3_svg_lineBasisBezier1 = [ 0, 2 / 3, 1 / 3, 0 ], d3_svg_lineBasisBezier2 = [ 0, 1 / 3, 2 / 3, 0 ], d3_svg_lineBasisBezier3 = [ 0, 1 / 6, 2 / 3, 1 / 6 ]; function d3_svg_lineBasisBezier(path, x, y) { path.push("C", d3_svg_lineDot4(d3_svg_lineBasisBezier1, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier1, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, y)); } function d3_svg_lineSlope(p0, p1) { return (p1[1] - p0[1]) / (p1[0] - p0[0]); } function d3_svg_lineFiniteDifferences(points) { var i = 0, j = points.length - 1, m = [], p0 = points[0], p1 = points[1], d = m[0] = d3_svg_lineSlope(p0, p1); while (++i < j) { m[i] = (d + (d = d3_svg_lineSlope(p0 = p1, p1 = points[i + 1]))) / 2; } m[i] = d; return m; } function d3_svg_lineMonotoneTangents(points) { var tangents = [], d, a, b, s, m = d3_svg_lineFiniteDifferences(points), i = -1, j = points.length - 1; while (++i < j) { d = d3_svg_lineSlope(points[i], points[i + 1]); if (abs(d) < ε) { m[i] = m[i + 1] = 0; } else { a = m[i] / d; b = m[i + 1] / d; s = a * a + b * b; if (s > 9) { s = d * 3 / Math.sqrt(s); m[i] = s * a; m[i + 1] = s * b; } } } i = -1; while (++i <= j) { s = (points[Math.min(j, i + 1)][0] - points[Math.max(0, i - 1)][0]) / (6 * (1 + m[i] * m[i])); tangents.push([ s || 0, m[i] * s || 0 ]); } return tangents; } function d3_svg_lineMonotone(points) { return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineMonotoneTangents(points)); } d3.svg.line.radial = function() { var line = d3_svg_line(d3_svg_lineRadial); line.radius = line.x, delete line.x; line.angle = line.y, delete line.y; return line; }; function d3_svg_lineRadial(points) { var point, i = -1, n = points.length, r, a; while (++i < n) { point = points[i]; r = point[0]; a = point[1] - halfπ; point[0] = r * Math.cos(a); point[1] = r * Math.sin(a); } return points; } function d3_svg_area(projection) { var x0 = d3_geom_pointX, x1 = d3_geom_pointX, y0 = 0, y1 = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, interpolateReverse = interpolate, L = "L", tension = .7; function area(data) { var segments = [], points0 = [], points1 = [], i = -1, n = data.length, d, fx0 = d3_functor(x0), fy0 = d3_functor(y0), fx1 = x0 === x1 ? function() { return x; } : d3_functor(x1), fy1 = y0 === y1 ? function() { return y; } : d3_functor(y1), x, y; function segment() { segments.push("M", interpolate(projection(points1), tension), L, interpolateReverse(projection(points0.reverse()), tension), "Z"); } while (++i < n) { if (defined.call(this, d = data[i], i)) { points0.push([ x = +fx0.call(this, d, i), y = +fy0.call(this, d, i) ]); points1.push([ +fx1.call(this, d, i), +fy1.call(this, d, i) ]); } else if (points0.length) { segment(); points0 = []; points1 = []; } } if (points0.length) segment(); return segments.length ? segments.join("") : null; } area.x = function(_) { if (!arguments.length) return x1; x0 = x1 = _; return area; }; area.x0 = function(_) { if (!arguments.length) return x0; x0 = _; return area; }; area.x1 = function(_) { if (!arguments.length) return x1; x1 = _; return area; }; area.y = function(_) { if (!arguments.length) return y1; y0 = y1 = _; return area; }; area.y0 = function(_) { if (!arguments.length) return y0; y0 = _; return area; }; area.y1 = function(_) { if (!arguments.length) return y1; y1 = _; return area; }; area.defined = function(_) { if (!arguments.length) return defined; defined = _; return area; }; area.interpolate = function(_) { if (!arguments.length) return interpolateKey; if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key; interpolateReverse = interpolate.reverse || interpolate; L = interpolate.closed ? "M" : "L"; return area; }; area.tension = function(_) { if (!arguments.length) return tension; tension = _; return area; }; return area; } d3_svg_lineStepBefore.reverse = d3_svg_lineStepAfter; d3_svg_lineStepAfter.reverse = d3_svg_lineStepBefore; d3.svg.area = function() { return d3_svg_area(d3_identity); }; d3.svg.area.radial = function() { var area = d3_svg_area(d3_svg_lineRadial); area.radius = area.x, delete area.x; area.innerRadius = area.x0, delete area.x0; area.outerRadius = area.x1, delete area.x1; area.angle = area.y, delete area.y; area.startAngle = area.y0, delete area.y0; area.endAngle = area.y1, delete area.y1; return area; }; d3.svg.chord = function() { var source = d3_source, target = d3_target, radius = d3_svg_chordRadius, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle; function chord(d, i) { var s = subgroup(this, source, d, i), t = subgroup(this, target, d, i); return "M" + s.p0 + arc(s.r, s.p1, s.a1 - s.a0) + (equals(s, t) ? curve(s.r, s.p1, s.r, s.p0) : curve(s.r, s.p1, t.r, t.p0) + arc(t.r, t.p1, t.a1 - t.a0) + curve(t.r, t.p1, s.r, s.p0)) + "Z"; } function subgroup(self, f, d, i) { var subgroup = f.call(self, d, i), r = radius.call(self, subgroup, i), a0 = startAngle.call(self, subgroup, i) - halfπ, a1 = endAngle.call(self, subgroup, i) - halfπ; return { r: r, a0: a0, a1: a1, p0: [ r * Math.cos(a0), r * Math.sin(a0) ], p1: [ r * Math.cos(a1), r * Math.sin(a1) ] }; } function equals(a, b) { return a.a0 == b.a0 && a.a1 == b.a1; } function arc(r, p, a) { return "A" + r + "," + r + " 0 " + +(a > π) + ",1 " + p; } function curve(r0, p0, r1, p1) { return "Q 0,0 " + p1; } chord.radius = function(v) { if (!arguments.length) return radius; radius = d3_functor(v); return chord; }; chord.source = function(v) { if (!arguments.length) return source; source = d3_functor(v); return chord; }; chord.target = function(v) { if (!arguments.length) return target; target = d3_functor(v); return chord; }; chord.startAngle = function(v) { if (!arguments.length) return startAngle; startAngle = d3_functor(v); return chord; }; chord.endAngle = function(v) { if (!arguments.length) return endAngle; endAngle = d3_functor(v); return chord; }; return chord; }; function d3_svg_chordRadius(d) { return d.radius; } d3.svg.diagonal = function() { var source = d3_source, target = d3_target, projection = d3_svg_diagonalProjection; function diagonal(d, i) { var p0 = source.call(this, d, i), p3 = target.call(this, d, i), m = (p0.y + p3.y) / 2, p = [ p0, { x: p0.x, y: m }, { x: p3.x, y: m }, p3 ]; p = p.map(projection); return "M" + p[0] + "C" + p[1] + " " + p[2] + " " + p[3]; } diagonal.source = function(x) { if (!arguments.length) return source; source = d3_functor(x); return diagonal; }; diagonal.target = function(x) { if (!arguments.length) return target; target = d3_functor(x); return diagonal; }; diagonal.projection = function(x) { if (!arguments.length) return projection; projection = x; return diagonal; }; return diagonal; }; function d3_svg_diagonalProjection(d) { return [ d.x, d.y ]; } d3.svg.diagonal.radial = function() { var diagonal = d3.svg.diagonal(), projection = d3_svg_diagonalProjection, projection_ = diagonal.projection; diagonal.projection = function(x) { return arguments.length ? projection_(d3_svg_diagonalRadialProjection(projection = x)) : projection; }; return diagonal; }; function d3_svg_diagonalRadialProjection(projection) { return function() { var d = projection.apply(this, arguments), r = d[0], a = d[1] - halfπ; return [ r * Math.cos(a), r * Math.sin(a) ]; }; } d3.svg.symbol = function() { var type = d3_svg_symbolType, size = d3_svg_symbolSize; function symbol(d, i) { return (d3_svg_symbols.get(type.call(this, d, i)) || d3_svg_symbolCircle)(size.call(this, d, i)); } symbol.type = function(x) { if (!arguments.length) return type; type = d3_functor(x); return symbol; }; symbol.size = function(x) { if (!arguments.length) return size; size = d3_functor(x); return symbol; }; return symbol; }; function d3_svg_symbolSize() { return 64; } function d3_svg_symbolType() { return "circle"; } function d3_svg_symbolCircle(size) { var r = Math.sqrt(size / π); return "M0," + r + "A" + r + "," + r + " 0 1,1 0," + -r + "A" + r + "," + r + " 0 1,1 0," + r + "Z"; } var d3_svg_symbols = d3.map({ circle: d3_svg_symbolCircle, cross: function(size) { var r = Math.sqrt(size / 5) / 2; return "M" + -3 * r + "," + -r + "H" + -r + "V" + -3 * r + "H" + r + "V" + -r + "H" + 3 * r + "V" + r + "H" + r + "V" + 3 * r + "H" + -r + "V" + r + "H" + -3 * r + "Z"; }, diamond: function(size) { var ry = Math.sqrt(size / (2 * d3_svg_symbolTan30)), rx = ry * d3_svg_symbolTan30; return "M0," + -ry + "L" + rx + ",0" + " 0," + ry + " " + -rx + ",0" + "Z"; }, square: function(size) { var r = Math.sqrt(size) / 2; return "M" + -r + "," + -r + "L" + r + "," + -r + " " + r + "," + r + " " + -r + "," + r + "Z"; }, "triangle-down": function(size) { var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2; return "M0," + ry + "L" + rx + "," + -ry + " " + -rx + "," + -ry + "Z"; }, "triangle-up": function(size) { var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2; return "M0," + -ry + "L" + rx + "," + ry + " " + -rx + "," + ry + "Z"; } }); d3.svg.symbolTypes = d3_svg_symbols.keys(); var d3_svg_symbolSqrt3 = Math.sqrt(3), d3_svg_symbolTan30 = Math.tan(30 * d3_radians); d3_selectionPrototype.transition = function(name) { var id = d3_transitionInheritId || ++d3_transitionId, ns = d3_transitionNamespace(name), subgroups = [], subgroup, node, transition = d3_transitionInherit || { time: Date.now(), ease: d3_ease_cubicInOut, delay: 0, duration: 250 }; for (var j = -1, m = this.length; ++j < m; ) { subgroups.push(subgroup = []); for (var group = this[j], i = -1, n = group.length; ++i < n; ) { if (node = group[i]) d3_transitionNode(node, i, ns, id, transition); subgroup.push(node); } } return d3_transition(subgroups, ns, id); }; d3_selectionPrototype.interrupt = function(name) { return this.each(name == null ? d3_selection_interrupt : d3_selection_interruptNS(d3_transitionNamespace(name))); }; var d3_selection_interrupt = d3_selection_interruptNS(d3_transitionNamespace()); function d3_selection_interruptNS(ns) { return function() { var lock, active; if ((lock = this[ns]) && (active = lock[lock.active])) { if (--lock.count) delete lock[lock.active]; else delete this[ns]; lock.active += .5; active.event && active.event.interrupt.call(this, this.__data__, active.index); } }; } function d3_transition(groups, ns, id) { d3_subclass(groups, d3_transitionPrototype); groups.namespace = ns; groups.id = id; return groups; } var d3_transitionPrototype = [], d3_transitionId = 0, d3_transitionInheritId, d3_transitionInherit; d3_transitionPrototype.call = d3_selectionPrototype.call; d3_transitionPrototype.empty = d3_selectionPrototype.empty; d3_transitionPrototype.node = d3_selectionPrototype.node; d3_transitionPrototype.size = d3_selectionPrototype.size; d3.transition = function(selection, name) { return selection && selection.transition ? d3_transitionInheritId ? selection.transition(name) : selection : d3.selection().transition(selection); }; d3.transition.prototype = d3_transitionPrototype; d3_transitionPrototype.select = function(selector) { var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnode, node; selector = d3_selection_selector(selector); for (var j = -1, m = this.length; ++j < m; ) { subgroups.push(subgroup = []); for (var group = this[j], i = -1, n = group.length; ++i < n; ) { if ((node = group[i]) && (subnode = selector.call(node, node.__data__, i, j))) { if ("__data__" in node) subnode.__data__ = node.__data__; d3_transitionNode(subnode, i, ns, id, node[ns][id]); subgroup.push(subnode); } else { subgroup.push(null); } } } return d3_transition(subgroups, ns, id); }; d3_transitionPrototype.selectAll = function(selector) { var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnodes, node, subnode, transition; selector = d3_selection_selectorAll(selector); for (var j = -1, m = this.length; ++j < m; ) { for (var group = this[j], i = -1, n = group.length; ++i < n; ) { if (node = group[i]) { transition = node[ns][id]; subnodes = selector.call(node, node.__data__, i, j); subgroups.push(subgroup = []); for (var k = -1, o = subnodes.length; ++k < o; ) { if (subnode = subnodes[k]) d3_transitionNode(subnode, k, ns, id, transition); subgroup.push(subnode); } } } } return d3_transition(subgroups, ns, id); }; d3_transitionPrototype.filter = function(filter) { var subgroups = [], subgroup, group, node; if (typeof filter !== "function") filter = d3_selection_filter(filter); for (var j = 0, m = this.length; j < m; j++) { subgroups.push(subgroup = []); for (var group = this[j], i = 0, n = group.length; i < n; i++) { if ((node = group[i]) && filter.call(node, node.__data__, i, j)) { subgroup.push(node); } } } return d3_transition(subgroups, this.namespace, this.id); }; d3_transitionPrototype.tween = function(name, tween) { var id = this.id, ns = this.namespace; if (arguments.length < 2) return this.node()[ns][id].tween.get(name); return d3_selection_each(this, tween == null ? function(node) { node[ns][id].tween.remove(name); } : function(node) { node[ns][id].tween.set(name, tween); }); }; function d3_transition_tween(groups, name, value, tween) { var id = groups.id, ns = groups.namespace; return d3_selection_each(groups, typeof value === "function" ? function(node, i, j) { node[ns][id].tween.set(name, tween(value.call(node, node.__data__, i, j))); } : (value = tween(value), function(node) { node[ns][id].tween.set(name, value); })); } d3_transitionPrototype.attr = function(nameNS, value) { if (arguments.length < 2) { for (value in nameNS) this.attr(value, nameNS[value]); return this; } var interpolate = nameNS == "transform" ? d3_interpolateTransform : d3_interpolate, name = d3.ns.qualify(nameNS); function attrNull() { this.removeAttribute(name); } function attrNullNS() { this.removeAttributeNS(name.space, name.local); } function attrTween(b) { return b == null ? attrNull : (b += "", function() { var a = this.getAttribute(name), i; return a !== b && (i = interpolate(a, b), function(t) { this.setAttribute(name, i(t)); }); }); } function attrTweenNS(b) { return b == null ? attrNullNS : (b += "", function() { var a = this.getAttributeNS(name.space, name.local), i; return a !== b && (i = interpolate(a, b), function(t) { this.setAttributeNS(name.space, name.local, i(t)); }); }); } return d3_transition_tween(this, "attr." + nameNS, value, name.local ? attrTweenNS : attrTween); }; d3_transitionPrototype.attrTween = function(nameNS, tween) { var name = d3.ns.qualify(nameNS); function attrTween(d, i) { var f = tween.call(this, d, i, this.getAttribute(name)); return f && function(t) { this.setAttribute(name, f(t)); }; } function attrTweenNS(d, i) { var f = tween.call(this, d, i, this.getAttributeNS(name.space, name.local)); return f && function(t) { this.setAttributeNS(name.space, name.local, f(t)); }; } return this.tween("attr." + nameNS, name.local ? attrTweenNS : attrTween); }; d3_transitionPrototype.style = function(name, value, priority) { var n = arguments.length; if (n < 3) { if (typeof name !== "string") { if (n < 2) value = ""; for (priority in name) this.style(priority, name[priority], value); return this; } priority = ""; } function styleNull() { this.style.removeProperty(name); } function styleString(b) { return b == null ? styleNull : (b += "", function() { var a = d3_window(this).getComputedStyle(this, null).getPropertyValue(name), i; return a !== b && (i = d3_interpolate(a, b), function(t) { this.style.setProperty(name, i(t), priority); }); }); } return d3_transition_tween(this, "style." + name, value, styleString); }; d3_transitionPrototype.styleTween = function(name, tween, priority) { if (arguments.length < 3) priority = ""; function styleTween(d, i) { var f = tween.call(this, d, i, d3_window(this).getComputedStyle(this, null).getPropertyValue(name)); return f && function(t) { this.style.setProperty(name, f(t), priority); }; } return this.tween("style." + name, styleTween); }; d3_transitionPrototype.text = function(value) { return d3_transition_tween(this, "text", value, d3_transition_text); }; function d3_transition_text(b) { if (b == null) b = ""; return function() { this.textContent = b; }; } d3_transitionPrototype.remove = function() { var ns = this.namespace; return this.each("end.transition", function() { var p; if (this[ns].count < 2 && (p = this.parentNode)) p.removeChild(this); }); }; d3_transitionPrototype.ease = function(value) { var id = this.id, ns = this.namespace; if (arguments.length < 1) return this.node()[ns][id].ease; if (typeof value !== "function") value = d3.ease.apply(d3, arguments); return d3_selection_each(this, function(node) { node[ns][id].ease = value; }); }; d3_transitionPrototype.delay = function(value) { var id = this.id, ns = this.namespace; if (arguments.length < 1) return this.node()[ns][id].delay; return d3_selection_each(this, typeof value === "function" ? function(node, i, j) { node[ns][id].delay = +value.call(node, node.__data__, i, j); } : (value = +value, function(node) { node[ns][id].delay = value; })); }; d3_transitionPrototype.duration = function(value) { var id = this.id, ns = this.namespace; if (arguments.length < 1) return this.node()[ns][id].duration; return d3_selection_each(this, typeof value === "function" ? function(node, i, j) { node[ns][id].duration = Math.max(1, value.call(node, node.__data__, i, j)); } : (value = Math.max(1, value), function(node) { node[ns][id].duration = value; })); }; d3_transitionPrototype.each = function(type, listener) { var id = this.id, ns = this.namespace; if (arguments.length < 2) { var inherit = d3_transitionInherit, inheritId = d3_transitionInheritId; try { d3_transitionInheritId = id; d3_selection_each(this, function(node, i, j) { d3_transitionInherit = node[ns][id]; type.call(node, node.__data__, i, j); }); } finally { d3_transitionInherit = inherit; d3_transitionInheritId = inheritId; } } else { d3_selection_each(this, function(node) { var transition = node[ns][id]; (transition.event || (transition.event = d3.dispatch("start", "end", "interrupt"))).on(type, listener); }); } return this; }; d3_transitionPrototype.transition = function() { var id0 = this.id, id1 = ++d3_transitionId, ns = this.namespace, subgroups = [], subgroup, group, node, transition; for (var j = 0, m = this.length; j < m; j++) { subgroups.push(subgroup = []); for (var group = this[j], i = 0, n = group.length; i < n; i++) { if (node = group[i]) { transition = node[ns][id0]; d3_transitionNode(node, i, ns, id1, { time: transition.time, ease: transition.ease, delay: transition.delay + transition.duration, duration: transition.duration }); } subgroup.push(node); } } return d3_transition(subgroups, ns, id1); }; function d3_transitionNamespace(name) { return name == null ? "__transition__" : "__transition_" + name + "__"; } function d3_transitionNode(node, i, ns, id, inherit) { var lock = node[ns] || (node[ns] = { active: 0, count: 0 }), transition = lock[id]; if (!transition) { var time = inherit.time; transition = lock[id] = { tween: new d3_Map(), time: time, delay: inherit.delay, duration: inherit.duration, ease: inherit.ease, index: i }; inherit = null; ++lock.count; d3.timer(function(elapsed) { var delay = transition.delay, duration, ease, timer = d3_timer_active, tweened = []; timer.t = delay + time; if (delay <= elapsed) return start(elapsed - delay); timer.c = start; function start(elapsed) { if (lock.active > id) return stop(); var active = lock[lock.active]; if (active) { --lock.count; delete lock[lock.active]; active.event && active.event.interrupt.call(node, node.__data__, active.index); } lock.active = id; transition.event && transition.event.start.call(node, node.__data__, i); transition.tween.forEach(function(key, value) { if (value = value.call(node, node.__data__, i)) { tweened.push(value); } }); ease = transition.ease; duration = transition.duration; d3.timer(function() { timer.c = tick(elapsed || 1) ? d3_true : tick; return 1; }, 0, time); } function tick(elapsed) { if (lock.active !== id) return 1; var t = elapsed / duration, e = ease(t), n = tweened.length; while (n > 0) { tweened[--n].call(node, e); } if (t >= 1) { transition.event && transition.event.end.call(node, node.__data__, i); return stop(); } } function stop() { if (--lock.count) delete lock[id]; else delete node[ns]; return 1; } }, 0, time); } } d3.svg.axis = function() { var scale = d3.scale.linear(), orient = d3_svg_axisDefaultOrient, innerTickSize = 6, outerTickSize = 6, tickPadding = 3, tickArguments_ = [ 10 ], tickValues = null, tickFormat_; function axis(g) { g.each(function() { var g = d3.select(this); var scale0 = this.__chart__ || scale, scale1 = this.__chart__ = scale.copy(); var ticks = tickValues == null ? scale1.ticks ? scale1.ticks.apply(scale1, tickArguments_) : scale1.domain() : tickValues, tickFormat = tickFormat_ == null ? scale1.tickFormat ? scale1.tickFormat.apply(scale1, tickArguments_) : d3_identity : tickFormat_, tick = g.selectAll(".tick").data(ticks, scale1), tickEnter = tick.enter().insert("g", ".domain").attr("class", "tick").style("opacity", ε), tickExit = d3.transition(tick.exit()).style("opacity", ε).remove(), tickUpdate = d3.transition(tick.order()).style("opacity", 1), tickSpacing = Math.max(innerTickSize, 0) + tickPadding, tickTransform; var range = d3_scaleRange(scale1), path = g.selectAll(".domain").data([ 0 ]), pathUpdate = (path.enter().append("path").attr("class", "domain"), d3.transition(path)); tickEnter.append("line"); tickEnter.append("text"); var lineEnter = tickEnter.select("line"), lineUpdate = tickUpdate.select("line"), text = tick.select("text").text(tickFormat), textEnter = tickEnter.select("text"), textUpdate = tickUpdate.select("text"), sign = orient === "top" || orient === "left" ? -1 : 1, x1, x2, y1, y2; if (orient === "bottom" || orient === "top") { tickTransform = d3_svg_axisX, x1 = "x", y1 = "y", x2 = "x2", y2 = "y2"; text.attr("dy", sign < 0 ? "0em" : ".71em").style("text-anchor", "middle"); pathUpdate.attr("d", "M" + range[0] + "," + sign * outerTickSize + "V0H" + range[1] + "V" + sign * outerTickSize); } else { tickTransform = d3_svg_axisY, x1 = "y", y1 = "x", x2 = "y2", y2 = "x2"; text.attr("dy", ".32em").style("text-anchor", sign < 0 ? "end" : "start"); pathUpdate.attr("d", "M" + sign * outerTickSize + "," + range[0] + "H0V" + range[1] + "H" + sign * outerTickSize); } lineEnter.attr(y2, sign * innerTickSize); textEnter.attr(y1, sign * tickSpacing); lineUpdate.attr(x2, 0).attr(y2, sign * innerTickSize); textUpdate.attr(x1, 0).attr(y1, sign * tickSpacing); if (scale1.rangeBand) { var x = scale1, dx = x.rangeBand() / 2; scale0 = scale1 = function(d) { return x(d) + dx; }; } else if (scale0.rangeBand) { scale0 = scale1; } else { tickExit.call(tickTransform, scale1, scale0); } tickEnter.call(tickTransform, scale0, scale1); tickUpdate.call(tickTransform, scale1, scale1); }); } axis.scale = function(x) { if (!arguments.length) return scale; scale = x; return axis; }; axis.orient = function(x) { if (!arguments.length) return orient; orient = x in d3_svg_axisOrients ? x + "" : d3_svg_axisDefaultOrient; return axis; }; axis.ticks = function() { if (!arguments.length) return tickArguments_; tickArguments_ = arguments; return axis; }; axis.tickValues = function(x) { if (!arguments.length) return tickValues; tickValues = x; return axis; }; axis.tickFormat = function(x) { if (!arguments.length) return tickFormat_; tickFormat_ = x; return axis; }; axis.tickSize = function(x) { var n = arguments.length; if (!n) return innerTickSize; innerTickSize = +x; outerTickSize = +arguments[n - 1]; return axis; }; axis.innerTickSize = function(x) { if (!arguments.length) return innerTickSize; innerTickSize = +x; return axis; }; axis.outerTickSize = function(x) { if (!arguments.length) return outerTickSize; outerTickSize = +x; return axis; }; axis.tickPadding = function(x) { if (!arguments.length) return tickPadding; tickPadding = +x; return axis; }; axis.tickSubdivide = function() { return arguments.length && axis; }; return axis; }; var d3_svg_axisDefaultOrient = "bottom", d3_svg_axisOrients = { top: 1, right: 1, bottom: 1, left: 1 }; function d3_svg_axisX(selection, x0, x1) { selection.attr("transform", function(d) { var v0 = x0(d); return "translate(" + (isFinite(v0) ? v0 : x1(d)) + ",0)"; }); } function d3_svg_axisY(selection, y0, y1) { selection.attr("transform", function(d) { var v0 = y0(d); return "translate(0," + (isFinite(v0) ? v0 : y1(d)) + ")"; }); } d3.svg.brush = function() { var event = d3_eventDispatch(brush, "brushstart", "brush", "brushend"), x = null, y = null, xExtent = [ 0, 0 ], yExtent = [ 0, 0 ], xExtentDomain, yExtentDomain, xClamp = true, yClamp = true, resizes = d3_svg_brushResizes[0]; function brush(g) { g.each(function() { var g = d3.select(this).style("pointer-events", "all").style("-webkit-tap-highlight-color", "rgba(0,0,0,0)").on("mousedown.brush", brushstart).on("touchstart.brush", brushstart); var background = g.selectAll(".background").data([ 0 ]); background.enter().append("rect").attr("class", "background").style("visibility", "hidden").style("cursor", "crosshair"); g.selectAll(".extent").data([ 0 ]).enter().append("rect").attr("class", "extent").style("cursor", "move"); var resize = g.selectAll(".resize").data(resizes, d3_identity); resize.exit().remove(); resize.enter().append("g").attr("class", function(d) { return "resize " + d; }).style("cursor", function(d) { return d3_svg_brushCursor[d]; }).append("rect").attr("x", function(d) { return /[ew]$/.test(d) ? -3 : null; }).attr("y", function(d) { return /^[ns]/.test(d) ? -3 : null; }).attr("width", 6).attr("height", 6).style("visibility", "hidden"); resize.style("display", brush.empty() ? "none" : null); var gUpdate = d3.transition(g), backgroundUpdate = d3.transition(background), range; if (x) { range = d3_scaleRange(x); backgroundUpdate.attr("x", range[0]).attr("width", range[1] - range[0]); redrawX(gUpdate); } if (y) { range = d3_scaleRange(y); backgroundUpdate.attr("y", range[0]).attr("height", range[1] - range[0]); redrawY(gUpdate); } redraw(gUpdate); }); } brush.event = function(g) { g.each(function() { var event_ = event.of(this, arguments), extent1 = { x: xExtent, y: yExtent, i: xExtentDomain, j: yExtentDomain }, extent0 = this.__chart__ || extent1; this.__chart__ = extent1; if (d3_transitionInheritId) { d3.select(this).transition().each("start.brush", function() { xExtentDomain = extent0.i; yExtentDomain = extent0.j; xExtent = extent0.x; yExtent = extent0.y; event_({ type: "brushstart" }); }).tween("brush:brush", function() { var xi = d3_interpolateArray(xExtent, extent1.x), yi = d3_interpolateArray(yExtent, extent1.y); xExtentDomain = yExtentDomain = null; return function(t) { xExtent = extent1.x = xi(t); yExtent = extent1.y = yi(t); event_({ type: "brush", mode: "resize" }); }; }).each("end.brush", function() { xExtentDomain = extent1.i; yExtentDomain = extent1.j; event_({ type: "brush", mode: "resize" }); event_({ type: "brushend" }); }); } else { event_({ type: "brushstart" }); event_({ type: "brush", mode: "resize" }); event_({ type: "brushend" }); } }); }; function redraw(g) { g.selectAll(".resize").attr("transform", function(d) { return "translate(" + xExtent[+/e$/.test(d)] + "," + yExtent[+/^s/.test(d)] + ")"; }); } function redrawX(g) { g.select(".extent").attr("x", xExtent[0]); g.selectAll(".extent,.n>rect,.s>rect").attr("width", xExtent[1] - xExtent[0]); } function redrawY(g) { g.select(".extent").attr("y", yExtent[0]); g.selectAll(".extent,.e>rect,.w>rect").attr("height", yExtent[1] - yExtent[0]); } function brushstart() { var target = this, eventTarget = d3.select(d3.event.target), event_ = event.of(target, arguments), g = d3.select(target), resizing = eventTarget.datum(), resizingX = !/^(n|s)$/.test(resizing) && x, resizingY = !/^(e|w)$/.test(resizing) && y, dragging = eventTarget.classed("extent"), dragRestore = d3_event_dragSuppress(target), center, origin = d3.mouse(target), offset; var w = d3.select(d3_window(target)).on("keydown.brush", keydown).on("keyup.brush", keyup); if (d3.event.changedTouches) { w.on("touchmove.brush", brushmove).on("touchend.brush", brushend); } else { w.on("mousemove.brush", brushmove).on("mouseup.brush", brushend); } g.interrupt().selectAll("*").interrupt(); if (dragging) { origin[0] = xExtent[0] - origin[0]; origin[1] = yExtent[0] - origin[1]; } else if (resizing) { var ex = +/w$/.test(resizing), ey = +/^n/.test(resizing); offset = [ xExtent[1 - ex] - origin[0], yExtent[1 - ey] - origin[1] ]; origin[0] = xExtent[ex]; origin[1] = yExtent[ey]; } else if (d3.event.altKey) center = origin.slice(); g.style("pointer-events", "none").selectAll(".resize").style("display", null); d3.select("body").style("cursor", eventTarget.style("cursor")); event_({ type: "brushstart" }); brushmove(); function keydown() { if (d3.event.keyCode == 32) { if (!dragging) { center = null; origin[0] -= xExtent[1]; origin[1] -= yExtent[1]; dragging = 2; } d3_eventPreventDefault(); } } function keyup() { if (d3.event.keyCode == 32 && dragging == 2) { origin[0] += xExtent[1]; origin[1] += yExtent[1]; dragging = 0; d3_eventPreventDefault(); } } function brushmove() { var point = d3.mouse(target), moved = false; if (offset) { point[0] += offset[0]; point[1] += offset[1]; } if (!dragging) { if (d3.event.altKey) { if (!center) center = [ (xExtent[0] + xExtent[1]) / 2, (yExtent[0] + yExtent[1]) / 2 ]; origin[0] = xExtent[+(point[0] < center[0])]; origin[1] = yExtent[+(point[1] < center[1])]; } else center = null; } if (resizingX && move1(point, x, 0)) { redrawX(g); moved = true; } if (resizingY && move1(point, y, 1)) { redrawY(g); moved = true; } if (moved) { redraw(g); event_({ type: "brush", mode: dragging ? "move" : "resize" }); } } function move1(point, scale, i) { var range = d3_scaleRange(scale), r0 = range[0], r1 = range[1], position = origin[i], extent = i ? yExtent : xExtent, size = extent[1] - extent[0], min, max; if (dragging) { r0 -= position; r1 -= size + position; } min = (i ? yClamp : xClamp) ? Math.max(r0, Math.min(r1, point[i])) : point[i]; if (dragging) { max = (min += position) + size; } else { if (center) position = Math.max(r0, Math.min(r1, 2 * center[i] - min)); if (position < min) { max = min; min = position; } else { max = position; } } if (extent[0] != min || extent[1] != max) { if (i) yExtentDomain = null; else xExtentDomain = null; extent[0] = min; extent[1] = max; return true; } } function brushend() { brushmove(); g.style("pointer-events", "all").selectAll(".resize").style("display", brush.empty() ? "none" : null); d3.select("body").style("cursor", null); w.on("mousemove.brush", null).on("mouseup.brush", null).on("touchmove.brush", null).on("touchend.brush", null).on("keydown.brush", null).on("keyup.brush", null); dragRestore(); event_({ type: "brushend" }); } } brush.x = function(z) { if (!arguments.length) return x; x = z; resizes = d3_svg_brushResizes[!x << 1 | !y]; return brush; }; brush.y = function(z) { if (!arguments.length) return y; y = z; resizes = d3_svg_brushResizes[!x << 1 | !y]; return brush; }; brush.clamp = function(z) { if (!arguments.length) return x && y ? [ xClamp, yClamp ] : x ? xClamp : y ? yClamp : null; if (x && y) xClamp = !!z[0], yClamp = !!z[1]; else if (x) xClamp = !!z; else if (y) yClamp = !!z; return brush; }; brush.extent = function(z) { var x0, x1, y0, y1, t; if (!arguments.length) { if (x) { if (xExtentDomain) { x0 = xExtentDomain[0], x1 = xExtentDomain[1]; } else { x0 = xExtent[0], x1 = xExtent[1]; if (x.invert) x0 = x.invert(x0), x1 = x.invert(x1); if (x1 < x0) t = x0, x0 = x1, x1 = t; } } if (y) { if (yExtentDomain) { y0 = yExtentDomain[0], y1 = yExtentDomain[1]; } else { y0 = yExtent[0], y1 = yExtent[1]; if (y.invert) y0 = y.invert(y0), y1 = y.invert(y1); if (y1 < y0) t = y0, y0 = y1, y1 = t; } } return x && y ? [ [ x0, y0 ], [ x1, y1 ] ] : x ? [ x0, x1 ] : y && [ y0, y1 ]; } if (x) { x0 = z[0], x1 = z[1]; if (y) x0 = x0[0], x1 = x1[0]; xExtentDomain = [ x0, x1 ]; if (x.invert) x0 = x(x0), x1 = x(x1); if (x1 < x0) t = x0, x0 = x1, x1 = t; if (x0 != xExtent[0] || x1 != xExtent[1]) xExtent = [ x0, x1 ]; } if (y) { y0 = z[0], y1 = z[1]; if (x) y0 = y0[1], y1 = y1[1]; yExtentDomain = [ y0, y1 ]; if (y.invert) y0 = y(y0), y1 = y(y1); if (y1 < y0) t = y0, y0 = y1, y1 = t; if (y0 != yExtent[0] || y1 != yExtent[1]) yExtent = [ y0, y1 ]; } return brush; }; brush.clear = function() { if (!brush.empty()) { xExtent = [ 0, 0 ], yExtent = [ 0, 0 ]; xExtentDomain = yExtentDomain = null; } return brush; }; brush.empty = function() { return !!x && xExtent[0] == xExtent[1] || !!y && yExtent[0] == yExtent[1]; }; return d3.rebind(brush, event, "on"); }; var d3_svg_brushCursor = { n: "ns-resize", e: "ew-resize", s: "ns-resize", w: "ew-resize", nw: "nwse-resize", ne: "nesw-resize", se: "nwse-resize", sw: "nesw-resize" }; var d3_svg_brushResizes = [ [ "n", "e", "s", "w", "nw", "ne", "se", "sw" ], [ "e", "w" ], [ "n", "s" ], [] ]; var d3_time_format = d3_time.format = d3_locale_enUS.timeFormat; var d3_time_formatUtc = d3_time_format.utc; var d3_time_formatIso = d3_time_formatUtc("%Y-%m-%dT%H:%M:%S.%LZ"); d3_time_format.iso = Date.prototype.toISOString && +new Date("2000-01-01T00:00:00.000Z") ? d3_time_formatIsoNative : d3_time_formatIso; function d3_time_formatIsoNative(date) { return date.toISOString(); } d3_time_formatIsoNative.parse = function(string) { var date = new Date(string); return isNaN(date) ? null : date; }; d3_time_formatIsoNative.toString = d3_time_formatIso.toString; d3_time.second = d3_time_interval(function(date) { return new d3_date(Math.floor(date / 1e3) * 1e3); }, function(date, offset) { date.setTime(date.getTime() + Math.floor(offset) * 1e3); }, function(date) { return date.getSeconds(); }); d3_time.seconds = d3_time.second.range; d3_time.seconds.utc = d3_time.second.utc.range; d3_time.minute = d3_time_interval(function(date) { return new d3_date(Math.floor(date / 6e4) * 6e4); }, function(date, offset) { date.setTime(date.getTime() + Math.floor(offset) * 6e4); }, function(date) { return date.getMinutes(); }); d3_time.minutes = d3_time.minute.range; d3_time.minutes.utc = d3_time.minute.utc.range; d3_time.hour = d3_time_interval(function(date) { var timezone = date.getTimezoneOffset() / 60; return new d3_date((Math.floor(date / 36e5 - timezone) + timezone) * 36e5); }, function(date, offset) { date.setTime(date.getTime() + Math.floor(offset) * 36e5); }, function(date) { return date.getHours(); }); d3_time.hours = d3_time.hour.range; d3_time.hours.utc = d3_time.hour.utc.range; d3_time.month = d3_time_interval(function(date) { date = d3_time.day(date); date.setDate(1); return date; }, function(date, offset) { date.setMonth(date.getMonth() + offset); }, function(date) { return date.getMonth(); }); d3_time.months = d3_time.month.range; d3_time.months.utc = d3_time.month.utc.range; function d3_time_scale(linear, methods, format) { function scale(x) { return linear(x); } scale.invert = function(x) { return d3_time_scaleDate(linear.invert(x)); }; scale.domain = function(x) { if (!arguments.length) return linear.domain().map(d3_time_scaleDate); linear.domain(x); return scale; }; function tickMethod(extent, count) { var span = extent[1] - extent[0], target = span / count, i = d3.bisect(d3_time_scaleSteps, target); return i == d3_time_scaleSteps.length ? [ methods.year, d3_scale_linearTickRange(extent.map(function(d) { return d / 31536e6; }), count)[2] ] : !i ? [ d3_time_scaleMilliseconds, d3_scale_linearTickRange(extent, count)[2] ] : methods[target / d3_time_scaleSteps[i - 1] < d3_time_scaleSteps[i] / target ? i - 1 : i]; } scale.nice = function(interval, skip) { var domain = scale.domain(), extent = d3_scaleExtent(domain), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" && tickMethod(extent, interval); if (method) interval = method[0], skip = method[1]; function skipped(date) { return !isNaN(date) && !interval.range(date, d3_time_scaleDate(+date + 1), skip).length; } return scale.domain(d3_scale_nice(domain, skip > 1 ? { floor: function(date) { while (skipped(date = interval.floor(date))) date = d3_time_scaleDate(date - 1); return date; }, ceil: function(date) { while (skipped(date = interval.ceil(date))) date = d3_time_scaleDate(+date + 1); return date; } } : interval)); }; scale.ticks = function(interval, skip) { var extent = d3_scaleExtent(scale.domain()), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" ? tickMethod(extent, interval) : !interval.range && [ { range: interval }, skip ]; if (method) interval = method[0], skip = method[1]; return interval.range(extent[0], d3_time_scaleDate(+extent[1] + 1), skip < 1 ? 1 : skip); }; scale.tickFormat = function() { return format; }; scale.copy = function() { return d3_time_scale(linear.copy(), methods, format); }; return d3_scale_linearRebind(scale, linear); } function d3_time_scaleDate(t) { return new Date(t); } var d3_time_scaleSteps = [ 1e3, 5e3, 15e3, 3e4, 6e4, 3e5, 9e5, 18e5, 36e5, 108e5, 216e5, 432e5, 864e5, 1728e5, 6048e5, 2592e6, 7776e6, 31536e6 ]; var d3_time_scaleLocalMethods = [ [ d3_time.second, 1 ], [ d3_time.second, 5 ], [ d3_time.second, 15 ], [ d3_time.second, 30 ], [ d3_time.minute, 1 ], [ d3_time.minute, 5 ], [ d3_time.minute, 15 ], [ d3_time.minute, 30 ], [ d3_time.hour, 1 ], [ d3_time.hour, 3 ], [ d3_time.hour, 6 ], [ d3_time.hour, 12 ], [ d3_time.day, 1 ], [ d3_time.day, 2 ], [ d3_time.week, 1 ], [ d3_time.month, 1 ], [ d3_time.month, 3 ], [ d3_time.year, 1 ] ]; var d3_time_scaleLocalFormat = d3_time_format.multi([ [ ".%L", function(d) { return d.getMilliseconds(); } ], [ ":%S", function(d) { return d.getSeconds(); } ], [ "%I:%M", function(d) { return d.getMinutes(); } ], [ "%I %p", function(d) { return d.getHours(); } ], [ "%a %d", function(d) { return d.getDay() && d.getDate() != 1; } ], [ "%b %d", function(d) { return d.getDate() != 1; } ], [ "%B", function(d) { return d.getMonth(); } ], [ "%Y", d3_true ] ]); var d3_time_scaleMilliseconds = { range: function(start, stop, step) { return d3.range(Math.ceil(start / step) * step, +stop, step).map(d3_time_scaleDate); }, floor: d3_identity, ceil: d3_identity }; d3_time_scaleLocalMethods.year = d3_time.year; d3_time.scale = function() { return d3_time_scale(d3.scale.linear(), d3_time_scaleLocalMethods, d3_time_scaleLocalFormat); }; var d3_time_scaleUtcMethods = d3_time_scaleLocalMethods.map(function(m) { return [ m[0].utc, m[1] ]; }); var d3_time_scaleUtcFormat = d3_time_formatUtc.multi([ [ ".%L", function(d) { return d.getUTCMilliseconds(); } ], [ ":%S", function(d) { return d.getUTCSeconds(); } ], [ "%I:%M", function(d) { return d.getUTCMinutes(); } ], [ "%I %p", function(d) { return d.getUTCHours(); } ], [ "%a %d", function(d) { return d.getUTCDay() && d.getUTCDate() != 1; } ], [ "%b %d", function(d) { return d.getUTCDate() != 1; } ], [ "%B", function(d) { return d.getUTCMonth(); } ], [ "%Y", d3_true ] ]); d3_time_scaleUtcMethods.year = d3_time.year.utc; d3_time.scale.utc = function() { return d3_time_scale(d3.scale.linear(), d3_time_scaleUtcMethods, d3_time_scaleUtcFormat); }; d3.text = d3_xhrType(function(request) { return request.responseText; }); d3.json = function(url, callback) { return d3_xhr(url, "application/json", d3_json, callback); }; function d3_json(request) { return JSON.parse(request.responseText); } d3.html = function(url, callback) { return d3_xhr(url, "text/html", d3_html, callback); }; function d3_html(request) { var range = d3_document.createRange(); range.selectNode(d3_document.body); return range.createContextualFragment(request.responseText); } d3.xml = d3_xhrType(function(request) { return request.responseXML; }); if (typeof define === "function" && define.amd) define(d3); else if (typeof module === "object" && module.exports) module.exports = d3; this.d3 = d3; }();
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ module.exports = function (updatedModules, renewedModules) { var unacceptedModules = updatedModules.filter(function (moduleId) { return renewedModules && renewedModules.indexOf(moduleId) < 0; }); var log = require("./log"); if (unacceptedModules.length > 0) { log( "warning", "[HMR] The following modules couldn't be hot updated: (They would need a full reload!)" ); unacceptedModules.forEach(function (moduleId) { log("warning", "[HMR] - " + moduleId); }); } if (!renewedModules || renewedModules.length === 0) { log("info", "[HMR] Nothing hot updated."); } else { log("info", "[HMR] Updated modules:"); renewedModules.forEach(function (moduleId) { if (typeof moduleId === "string" && moduleId.indexOf("!") !== -1) { var parts = moduleId.split("!"); log.groupCollapsed("info", "[HMR] - " + parts.pop()); log("info", "[HMR] - " + moduleId); log.groupEnd("info"); } else { log("info", "[HMR] - " + moduleId); } }); var numberIds = renewedModules.every(function (moduleId) { return typeof moduleId === "number"; }); if (numberIds) log( "info", '[HMR] Consider using the optimization.moduleIds: "named" for module names.' ); } };
module.exports={A:{A:{"2":"J C G E B A VB"},B:{"2":"D Y g H L"},C:{"2":"TB z F I J C G E B A D Y g H L M N O P Q R S T U V W X v Z a b RB QB","516":"0 1 3 4 5 q r s x y u t","580":"c d e f K h i j k l m n o p"},D:{"2":"F I J C G E B A D Y g H L M N O P Q R S T U V W X v Z a b c d e","132":"f K h","260":"0 1 3 4 5 9 i j k l m n o p q r s x y u t FB BB UB CB DB"},E:{"2":"8 F I J C G E B A EB GB HB IB JB KB","1090":"LB"},F:{"2":"6 7 E A D H L M N O P Q R MB NB OB PB SB w","132":"S T U","260":"V W X v Z a b c d e f K h i j k l m n o p q r s"},G:{"2":"2 8 G AB WB XB YB ZB aB bB cB dB","1090":"A"},H:{"2":"eB"},I:{"2":"2 z F fB gB hB iB jB kB","260":"t"},J:{"2":"C B"},K:{"2":"6 7 B A D w","260":"K"},L:{"260":"9"},M:{"516":"u"},N:{"2":"B A"},O:{"260":"lB"},P:{"260":"F I"},Q:{"260":"mB"},R:{"260":"nB"}},B:5,C:"Web Animations API"};
'use strict'; /** * @ngdoc overview * @name ngSanitize * @description */ /* * HTML Parser By Misko Hevery (misko@hevery.com) * based on: HTML Parser By John Resig (ejohn.org) * Original code by Erik Arvidsson, Mozilla Public License * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js * * // Use like so: * htmlParser(htmlString, { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * }); * */ /** * @ngdoc service * @name ngSanitize.$sanitize * @function * * @description * The input is sanitized by parsing the html into tokens. All safe tokens (from a whitelist) are * then serialized back to properly escaped html string. This means that no unsafe input can make * it into the returned string, however, since our parser is more strict than a typical browser * parser, it's possible that some obscure input, which would be recognized as valid HTML by a * browser, won't make it through the sanitizer. * * @param {string} html Html input. * @returns {string} Sanitized html. * * @example <doc:example module="ngSanitize"> <doc:source> <script> function Ctrl($scope) { $scope.snippet = '<p style="color:blue">an html\n' + '<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n' + 'snippet</p>'; } </script> <div ng-controller="Ctrl"> Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea> <table> <tr> <td>Filter</td> <td>Source</td> <td>Rendered</td> </tr> <tr id="html-filter"> <td>html filter</td> <td> <pre>&lt;div ng-bind-html="snippet"&gt;<br/>&lt;/div&gt;</pre> </td> <td> <div ng-bind-html="snippet"></div> </td> </tr> <tr id="escaped-html"> <td>no filter</td> <td><pre>&lt;div ng-bind="snippet"&gt;<br/>&lt;/div&gt;</pre></td> <td><div ng-bind="snippet"></div></td> </tr> <tr id="html-unsafe-filter"> <td>unsafe html filter</td> <td><pre>&lt;div ng-bind-html-unsafe="snippet"&gt;<br/>&lt;/div&gt;</pre></td> <td><div ng-bind-html-unsafe="snippet"></div></td> </tr> </table> </div> </doc:source> <doc:scenario> it('should sanitize the html snippet ', function() { expect(using('#html-filter').element('div').html()). toBe('<p>an html\n<em>click here</em>\nsnippet</p>'); }); it('should escape snippet without any filter', function() { expect(using('#escaped-html').element('div').html()). toBe("&lt;p style=\"color:blue\"&gt;an html\n" + "&lt;em onmouseover=\"this.textContent='PWN3D!'\"&gt;click here&lt;/em&gt;\n" + "snippet&lt;/p&gt;"); }); it('should inline raw snippet if filtered as unsafe', function() { expect(using('#html-unsafe-filter').element("div").html()). toBe("<p style=\"color:blue\">an html\n" + "<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" + "snippet</p>"); }); it('should update', function() { input('snippet').enter('new <b>text</b>'); expect(using('#html-filter').binding('snippet')).toBe('new <b>text</b>'); expect(using('#escaped-html').element('div').html()).toBe("new &lt;b&gt;text&lt;/b&gt;"); expect(using('#html-unsafe-filter').binding("snippet")).toBe('new <b>text</b>'); }); </doc:scenario> </doc:example> */ var $sanitize = function(html) { var buf = []; htmlParser(html, htmlSanitizeWriter(buf)); return buf.join(''); }; // Regular Expressions for parsing tags and attributes var START_TAG_REGEXP = /^<\s*([\w:-]+)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*>/, END_TAG_REGEXP = /^<\s*\/\s*([\w:-]+)[^>]*>/, ATTR_REGEXP = /([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g, BEGIN_TAG_REGEXP = /^</, BEGING_END_TAGE_REGEXP = /^<\s*\//, COMMENT_REGEXP = /<!--(.*?)-->/g, CDATA_REGEXP = /<!\[CDATA\[(.*?)]]>/g, URI_REGEXP = /^((ftp|https?):\/\/|mailto:|tel:|#)/, NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g; // Match everything outside of normal chars and " (quote character) // Good source of info about elements and attributes // http://dev.w3.org/html5/spec/Overview.html#semantics // http://simon.html5.org/html-elements // Safe Void Elements - HTML5 // http://dev.w3.org/html5/spec/Overview.html#void-elements var voidElements = makeMap("area,br,col,hr,img,wbr"); // Elements that you can, intentionally, leave open (and which close themselves) // http://dev.w3.org/html5/spec/Overview.html#optional-tags var optionalEndTagBlockElements = makeMap("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr"), optionalEndTagInlineElements = makeMap("rp,rt"), optionalEndTagElements = angular.extend({}, optionalEndTagInlineElements, optionalEndTagBlockElements); // Safe Block Elements - HTML5 var blockElements = angular.extend({}, optionalEndTagBlockElements, makeMap("address,article,aside," + "blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,h6," + "header,hgroup,hr,ins,map,menu,nav,ol,pre,script,section,table,ul")); // Inline Elements - HTML5 var inlineElements = angular.extend({}, optionalEndTagInlineElements, makeMap("a,abbr,acronym,b,bdi,bdo," + "big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s,samp,small," + "span,strike,strong,sub,sup,time,tt,u,var")); // Special Elements (can contain anything) var specialElements = makeMap("script,style"); var validElements = angular.extend({}, voidElements, blockElements, inlineElements, optionalEndTagElements); //Attributes that have href and hence need to be sanitized var uriAttrs = makeMap("background,cite,href,longdesc,src,usemap"); var validAttrs = angular.extend({}, uriAttrs, makeMap( 'abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,'+ 'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,'+ 'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,'+ 'scope,scrolling,shape,span,start,summary,target,title,type,'+ 'valign,value,vspace,width')); function makeMap(str) { var obj = {}, items = str.split(','), i; for (i = 0; i < items.length; i++) obj[items[i]] = true; return obj; } /** * @example * htmlParser(htmlString, { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * }); * * @param {string} html string * @param {object} handler */ function htmlParser( html, handler ) { var index, chars, match, stack = [], last = html; stack.last = function() { return stack[ stack.length - 1 ]; }; while ( html ) { chars = true; // Make sure we're not in a script or style element if ( !stack.last() || !specialElements[ stack.last() ] ) { // Comment if ( html.indexOf("<!--") === 0 ) { index = html.indexOf("-->"); if ( index >= 0 ) { if (handler.comment) handler.comment( html.substring( 4, index ) ); html = html.substring( index + 3 ); chars = false; } // end tag } else if ( BEGING_END_TAGE_REGEXP.test(html) ) { match = html.match( END_TAG_REGEXP ); if ( match ) { html = html.substring( match[0].length ); match[0].replace( END_TAG_REGEXP, parseEndTag ); chars = false; } // start tag } else if ( BEGIN_TAG_REGEXP.test(html) ) { match = html.match( START_TAG_REGEXP ); if ( match ) { html = html.substring( match[0].length ); match[0].replace( START_TAG_REGEXP, parseStartTag ); chars = false; } } if ( chars ) { index = html.indexOf("<"); var text = index < 0 ? html : html.substring( 0, index ); html = index < 0 ? "" : html.substring( index ); if (handler.chars) handler.chars( decodeEntities(text) ); } } else { html = html.replace(new RegExp("(.*)<\\s*\\/\\s*" + stack.last() + "[^>]*>", 'i'), function(all, text){ text = text. replace(COMMENT_REGEXP, "$1"). replace(CDATA_REGEXP, "$1"); if (handler.chars) handler.chars( decodeEntities(text) ); return ""; }); parseEndTag( "", stack.last() ); } if ( html == last ) { throw "Parse Error: " + html; } last = html; } // Clean up any remaining tags parseEndTag(); function parseStartTag( tag, tagName, rest, unary ) { tagName = angular.lowercase(tagName); if ( blockElements[ tagName ] ) { while ( stack.last() && inlineElements[ stack.last() ] ) { parseEndTag( "", stack.last() ); } } if ( optionalEndTagElements[ tagName ] && stack.last() == tagName ) { parseEndTag( "", tagName ); } unary = voidElements[ tagName ] || !!unary; if ( !unary ) stack.push( tagName ); var attrs = {}; rest.replace(ATTR_REGEXP, function(match, name, doubleQuotedValue, singleQoutedValue, unqoutedValue) { var value = doubleQuotedValue || singleQoutedValue || unqoutedValue || ''; attrs[name] = decodeEntities(value); }); if (handler.start) handler.start( tagName, attrs, unary ); } function parseEndTag( tag, tagName ) { var pos = 0, i; tagName = angular.lowercase(tagName); if ( tagName ) // Find the closest opened tag of the same type for ( pos = stack.length - 1; pos >= 0; pos-- ) if ( stack[ pos ] == tagName ) break; if ( pos >= 0 ) { // Close all the open elements, up the stack for ( i = stack.length - 1; i >= pos; i-- ) if (handler.end) handler.end( stack[ i ] ); // Remove the open elements from the stack stack.length = pos; } } } /** * decodes all entities into regular string * @param value * @returns {string} A string with decoded entities. */ var hiddenPre=document.createElement("pre"); function decodeEntities(value) { hiddenPre.innerHTML=value.replace(/</g,"&lt;"); return hiddenPre.innerText || hiddenPre.textContent || ''; } /** * Escapes all potentially dangerous characters, so that the * resulting string can be safely inserted into attribute or * element text. * @param value * @returns escaped text */ function encodeEntities(value) { return value. replace(/&/g, '&amp;'). replace(NON_ALPHANUMERIC_REGEXP, function(value){ return '&#' + value.charCodeAt(0) + ';'; }). replace(/</g, '&lt;'). replace(/>/g, '&gt;'); } /** * create an HTML/XML writer which writes to buffer * @param {Array} buf use buf.jain('') to get out sanitized html string * @returns {object} in the form of { * start: function(tag, attrs, unary) {}, * end: function(tag) {}, * chars: function(text) {}, * comment: function(text) {} * } */ function htmlSanitizeWriter(buf){ var ignore = false; var out = angular.bind(buf, buf.push); return { start: function(tag, attrs, unary){ tag = angular.lowercase(tag); if (!ignore && specialElements[tag]) { ignore = tag; } if (!ignore && validElements[tag] == true) { out('<'); out(tag); angular.forEach(attrs, function(value, key){ var lkey=angular.lowercase(key); if (validAttrs[lkey]==true && (uriAttrs[lkey]!==true || value.match(URI_REGEXP))) { out(' '); out(key); out('="'); out(encodeEntities(value)); out('"'); } }); out(unary ? '/>' : '>'); } }, end: function(tag){ tag = angular.lowercase(tag); if (!ignore && validElements[tag] == true) { out('</'); out(tag); out('>'); } if (tag == ignore) { ignore = false; } }, chars: function(chars){ if (!ignore) { out(encodeEntities(chars)); } } }; } // define ngSanitize module and register $sanitize service angular.module('ngSanitize', []).value('$sanitize', $sanitize);
'use strict'; var webpack = require('webpack'); var config = require('./webpack.config.base.js'); if (process.env.NODE_ENV !== 'test') { config.entry = [ 'webpack-dev-server/client?http://localhost:3000', 'webpack/hot/dev-server' ].concat(config.entry); } config.devtool = 'cheap-module-eval-source-map'; config.plugins = config.plugins.concat([ new webpack.HotModuleReplacementPlugin() ]); config.module.loaders = config.module.loaders.concat([ {test: /\.jsx?$/, loaders: [ 'react-hot', 'babel'], exclude: /node_modules/} ]); module.exports = config;
/* YUI 3.18.1 (build f7e7bcb) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('parallel', function (Y, NAME) { /** * A concurrent parallel processor to help in running several async functions. * @module parallel * @main parallel */ /** A concurrent parallel processor to help in running several async functions. var stack = new Y.Parallel(); for (var i = 0; i < 15; i++) { Y.io('./api/json/' + i, { on: { success: stack.add(function() { }) } }); } stack.done(function() { }); @class Parallel @param {Object} o A config object @param {Object} [o.context=Y] The execution context of the callback to done */ Y.Parallel = function(o) { this.config = o || {}; this.results = []; this.context = this.config.context || Y; this.total = 0; this.finished = 0; }; Y.Parallel.prototype = { /** * An Array of results from all the callbacks in the stack * @property results * @type Array */ results: null, /** * The total items in the stack * @property total * @type Number */ total: null, /** * The number of stacked callbacks executed * @property finished * @type Number */ finished: null, /** * Add a callback to the stack * @method add * @param {Function} fn The function callback we are waiting for */ add: function (fn) { var self = this, index = self.total; self.total += 1; return function () { self.finished++; self.results[index] = (fn && fn.apply(self.context, arguments)) || (arguments.length === 1 ? arguments[0] : Y.Array(arguments)); self.test(); }; }, /** * Test to see if all registered items in the stack have completed, if so call the callback to `done` * @method test */ test: function () { var self = this; if (self.finished >= self.total && self.callback) { self.callback.call(self.context, self.results, self.data); } }, /** * The method to call when all the items in the stack are complete. * @method done * @param {Function} callback The callback to execute on complete * @param {Mixed} callback.results The results of all the callbacks in the stack * @param {Mixed} [callback.data] The data given to the `done` method * @param {Mixed} data Mixed data to pass to the success callback */ done: function (callback, data) { this.callback = callback; this.data = data; this.test(); } }; }, '3.18.1', {"requires": ["yui-base"]});
/* Copyright (c) 2004-2009, 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 */ if(!dojo._hasResource["dojox.av.FLAudio"]){ dojo._hasResource["dojox.av.FLAudio"]=true; dojo.provide("dojox.av.FLAudio"); dojo.experimental("dojox.av.FLAudio"); dojo.require("dijit._Widget"); dojo.require("dojox.embed.Flash"); dojo.require("dojox.av._Media"); dojo.require("dojox.timing.doLater"); dojo.declare("dojox.av.FLAudio",null,{id:"",initialVolume:0.7,initialPan:0,isDebug:false,statusInterval:200,_swfPath:dojo.moduleUrl("dojox.av","resources/audio.swf"),constructor:function(_1){ dojo.mixin(this,_1||{}); if(!this.id){ this.id="flaudio_"+new Date().getTime(); } this.domNode=dojo.doc.createElement("div"); dojo.style(this.domNode,{postion:"relative",width:"1px",height:"1px",top:"1px",left:"1px"}); dojo.body().appendChild(this.domNode); this.init(); },init:function(){ this._subs=[]; this.initialVolume=this._normalizeVolume(this.initialVolume); var _2={path:this._swfPath.uri,width:"1px",height:"1px",minimumVersion:9,expressInstall:true,params:{wmode:"transparent"},vars:{id:this.id,autoPlay:this.autoPlay,initialVolume:this.initialVolume,initialPan:this.initialPan,statusInterval:this.statusInterval,isDebug:this.isDebug}}; this._sub("mediaError","onError"); this._sub("filesProgress","onLoadStatus"); this._sub("filesAllLoaded","onAllLoaded"); this._sub("mediaPosition","onPlayStatus"); this._sub("mediaMeta","onID3"); this._flashObject=new dojox.embed.Flash(_2,this.domNode); this._flashObject.onError=function(_3){ console.warn("Flash Error:",_3); alert(_3); }; this._flashObject.onLoad=dojo.hitch(this,function(_4){ this.flashMedia=_4; this.isPlaying=this.autoPlay; this.isStopped=!this.autoPlay; this.onLoad(this.flashMedia); }); },load:function(_5){ if(dojox.timing.doLater(this.flashMedia,this)){ return false; } if(!_5.url){ throw new Error("An url is required for loading media"); return false; }else{ _5.url=this._normalizeUrl(_5.url); } this.flashMedia.load(_5); return _5.url; },doPlay:function(_6){ this.flashMedia.doPlay(_6); },pause:function(_7){ this.flashMedia.pause(_7); },stop:function(_8){ this.flashMedia.doStop(_8); },setVolume:function(_9){ this.flashMedia.setVolume(_9); },setPan:function(_a){ this.flashMedia.setPan(_a); },getVolume:function(_b){ return this.flashMedia.getVolume(_b); },getPan:function(_c){ return this.flashMedia.getPan(_c); },onError:function(_d){ console.warn("SWF ERROR:",_d); },onLoadStatus:function(_e){ },onAllLoaded:function(){ },onPlayStatus:function(_f){ },onLoad:function(){ },onID3:function(evt){ },destroy:function(){ if(!this.flashMedia){ this._cons.push(dojo.connect(this,"onLoad",this,"destroy")); return; } dojo.forEach(this._subs,function(s){ dojo.unsubscribe(s); }); dojo.forEach(this._cons,function(c){ dojo.disconnect(c); }); this._flashObject.destroy(); },_sub:function(_13,_14){ dojo.subscribe(this.id+"/"+_13,this,_14); },_normalizeVolume:function(vol){ if(vol>1){ while(vol>1){ vol*=0.1; } } return vol; },_normalizeUrl:function(_16){ if(_16&&_16.toLowerCase().indexOf("http")<0){ var loc=window.location.href.split("/"); loc.pop(); loc=loc.join("/")+"/"; _16=loc+_16; } return _16; }}); }
var _ = require('lodash'), Promise = require('bluebird'), cheerio = require('cheerio'), crypto = require('crypto'), downsize = require('downsize'), RSS = require('rss'), url = require('url'), config = require('../../../config'), api = require('../../../api'), filters = require('../../../filters'), generate, generateFeed, getFeedXml, feedCache = {}; function isTag(req) { return req.originalUrl.indexOf('/' + config.routeKeywords.tag + '/') !== -1; } function isAuthor(req) { return req.originalUrl.indexOf('/' + config.routeKeywords.author + '/') !== -1; } function handleError(next) { return function handleError(err) { return next(err); }; } function getOptions(req, pageParam, slugParam) { var options = {}; if (pageParam) { options.page = pageParam; } if (isTag(req)) { options.tag = slugParam; } if (isAuthor(req)) { options.author = slugParam; } options.include = 'author,tags,fields'; return options; } function getData(options) { var ops = { title: api.settings.read('title'), description: api.settings.read('description'), permalinks: api.settings.read('permalinks'), results: api.posts.browse(options) }; return Promise.props(ops).then(function (result) { var titleStart = ''; if (options.tag) { titleStart = result.results.meta.filters.tags[0].name + ' - ' || ''; } if (options.author) { titleStart = result.results.meta.filters.author.name + ' - ' || ''; } return { title: titleStart + result.title.settings[0].value, description: result.description.settings[0].value, permalinks: result.permalinks.settings[0], results: result.results }; }); } function getBaseUrl(req, slugParam) { var baseUrl = config.paths.subdir; if (isTag(req)) { baseUrl += '/' + config.routeKeywords.tag + '/' + slugParam + '/rss/'; } else if (isAuthor(req)) { baseUrl += '/' + config.routeKeywords.author + '/' + slugParam + '/rss/'; } else { baseUrl += '/rss/'; } return baseUrl; } function processUrls(html, siteUrl, itemUrl) { var htmlContent = cheerio.load(html, {decodeEntities: false}); // convert relative resource urls to absolute ['href', 'src'].forEach(function forEach(attributeName) { htmlContent('[' + attributeName + ']').each(function each(ix, el) { var baseUrl, attributeValue, parsed; el = htmlContent(el); attributeValue = el.attr(attributeName); // if URL is absolute move on to the next element try { parsed = url.parse(attributeValue); if (parsed.protocol) { return; } } catch (e) { return; } // compose an absolute URL // if the relative URL begins with a '/' use the blog URL (including sub-directory) // as the base URL, otherwise use the post's URL. baseUrl = attributeValue[0] === '/' ? siteUrl : itemUrl; attributeValue = config.urlJoin(baseUrl, attributeValue); el.attr(attributeName, attributeValue); }); }); return htmlContent; } getFeedXml = function getFeedXml(path, data) { var dataHash = crypto.createHash('md5').update(JSON.stringify(data)).digest('hex'); if (!feedCache[path] || feedCache[path].hash !== dataHash) { // We need to regenerate feedCache[path] = { hash: dataHash, xml: generateFeed(data) }; } return feedCache[path].xml; }; generateFeed = function generateFeed(data) { var feed = new RSS({ title: data.title, description: data.description, generator: 'Ghost ' + data.version, feed_url: data.feedUrl, site_url: data.siteUrl, ttl: '60', custom_namespaces: { content: 'http://purl.org/rss/1.0/modules/content/', media: 'http://search.yahoo.com/mrss/' } }); data.results.posts.forEach(function forEach(post) { var itemUrl = config.urlFor('post', {post: post, permalinks: data.permalinks, secure: data.secure}, true), htmlContent = processUrls(post.html, data.siteUrl, itemUrl), item = { title: post.title, description: post.meta_description || downsize(htmlContent.html(), {words: 50}), guid: post.uuid, url: itemUrl, date: post.published_at, categories: _.pluck(post.tags, 'name'), author: post.author ? post.author.name : null, custom_elements: [] }, imageUrl; if (post.image) { imageUrl = config.urlFor('image', {image: post.image, secure: data.secure}, true); // Add a media content tag item.custom_elements.push({ 'media:content': { _attr: { url: imageUrl, medium: 'image' } } }); // Also add the image to the content, because not all readers support media:content htmlContent('p').first().before('<img src="' + imageUrl + '" />'); htmlContent('img').attr('alt', post.title); } item.custom_elements.push({ 'content:encoded': { _cdata: htmlContent.html() } }); filters.doFilter('rss.item', item, post).then(function then(item) { feed.item(item); }); }); return filters.doFilter('rss.feed', feed).then(function then(feed) { return feed.xml(); }); }; generate = function generate(req, res, next) { // Initialize RSS var pageParam = req.params.page !== undefined ? parseInt(req.params.page, 10) : 1, slugParam = req.params.slug, baseUrl = getBaseUrl(req, slugParam), options = getOptions(req, pageParam, slugParam); // No negative pages, or page 1 if (isNaN(pageParam) || pageParam < 1 || (req.params.page !== undefined && pageParam === 1)) { return res.redirect(baseUrl); } return getData(options).then(function then(data) { var maxPage = data.results.meta.pagination.pages; // If page is greater than number of pages we have, redirect to last page if (pageParam > maxPage) { return res.redirect(baseUrl + maxPage + '/'); } data.version = res.locals.safeVersion; data.siteUrl = config.urlFor('home', {secure: req.secure}, true); data.feedUrl = config.urlFor({relativeUrl: baseUrl, secure: req.secure}, true); data.secure = req.secure; return getFeedXml(req.originalUrl, data).then(function then(feedXml) { res.set('Content-Type', 'text/xml; charset=UTF-8'); res.send(feedXml); }); }).catch(handleError(next)); }; module.exports = generate;
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v14.2.0 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function QuerySelector(selector) { return querySelectorFunc.bind(this, selector); } exports.QuerySelector = QuerySelector; function RefSelector(ref) { return querySelectorFunc.bind(this, '[ref=' + ref + ']'); } exports.RefSelector = RefSelector; function querySelectorFunc(selector, classPrototype, methodOrAttributeName, index) { if (selector === null) { console.error('ag-Grid: QuerySelector selector should not be null'); return; } if (typeof index === 'number') { console.error('ag-Grid: QuerySelector should be on an attribute'); return; } // it's an attribute on the class var props = getOrCreateProps(classPrototype, classPrototype.constructor.name); if (!props.querySelectors) { props.querySelectors = []; } props.querySelectors.push({ attributeName: methodOrAttributeName, querySelector: selector }); } function Listener(eventName) { return listenerFunc.bind(this, eventName); } exports.Listener = Listener; function listenerFunc(eventName, target, methodName, descriptor) { if (eventName === null) { console.error('ag-Grid: EventListener eventName should not be null'); return; } // it's an attribute on the class var props = getOrCreateProps(target, target.constructor.name); if (!props.listenerMethods) { props.listenerMethods = []; } props.listenerMethods.push({ methodName: methodName, eventName: eventName }); } function getOrCreateProps(target, instanceName) { if (!target.__agComponentMetaData) { target.__agComponentMetaData = {}; } if (!target.__agComponentMetaData[instanceName]) { target.__agComponentMetaData[instanceName] = {}; } return target.__agComponentMetaData[instanceName]; }
(function (window) { "use strict"; var AppEnlight = { version: '0.4.0', options: { apiKey: "" }, errorReportBuffer: [], slowReportBuffer: [], logBuffer: [], requestInfo: null, init: function (options) { var self = this; if (typeof options.server === 'undefined') { options.server = "https://api.appenlight.com"; } if (typeof options.apiKey === 'undefined') { options.apiKey = "undefined"; } if (typeof options.protocol_version === 'undefined') { options.protocol_version = "0.5"; } if (typeof options.windowOnError === 'undefined' || options.windowOnError == false) { TraceKit.collectWindowErrors = false; } if (typeof options.sendInterval === 'undefined') { options.sendInterval = 1000; } if (typeof options.tracekitRemoteFetching === 'undefined') { options.tracekitRemoteFetching = true; } if (typeof options.tracekitContextLines === 'undefined') { options.tracekitContextLines = 11; } if (options.sendInterval >= 1000) { this.createSendInterval(options.sendInterval); } this.options = options; this.requestInfo = { url: window.location.href }; this.reportsEndpoint = options.server + '/api/reports?public_api_key=' + this.options.apiKey + "&protocol_version=" + this.options.protocol_version; this.logsEndpoint = options.server + '/api/logs?public_api_key=' + this.options.apiKey + "&protocol_version=" + this.options.protocol_version; TraceKit.remoteFetching = options.tracekitRemoteFetching; TraceKit.linesOfContext = options.tracekitContextLines; TraceKit.report.subscribe(function (errorReport) { self.handleError(errorReport); }); }, createSendInterval: function (time_iv) { var self = this; this.send_iv = setInterval(function () { self.sendReports(); self.sendLogs(); }, time_iv); }, setRequestInfo: function (info) { for (var i in info) { this.requestInfo[i] = info[i]; } }, grabError: function (exception) { // we need to catch rethrown exception but throw an error from TraceKit try { TraceKit.report(exception); } catch (new_exception) { if (exception !== new_exception) { throw new_exception; } } }, handleError: function (errorReport) { if (errorReport.mode == 'stack') { var error_msg = errorReport.name + ': ' + errorReport.message; } else { var error_msg = errorReport.message; } // console.log(errorReport); var report = { "client": "javascript", "language": "javascript", "error": error_msg, "occurences": 1, "priority": 5, "server": '', "http_status": 500, "request": {}, "traceback": [], }; report.user_agent = window.navigator.userAgent; report.start_time = new Date().toJSON(); if (this.requestInfo != null) { for (var i in this.requestInfo) { report[i] = this.requestInfo[i]; } } if (typeof report.request_id == 'undefined' || !report.request_id) { report.request_id = this.genUUID4(); } console.log(errorReport); // grab last 100 frames in reversed order var stack_slice = errorReport.stack.reverse().slice(-100); for (var i = 0; i < stack_slice.length; i++) { var context = ''; try{ if (stack_slice[i].context){ for(var j = 0; j < stack_slice[i].context.length; j++){ var line = stack_slice[i].context[j]; if (line.length > 300){ context += '<minified-context>'; } else{ context += line; } context += '\n'; } } } catch(e){} var stackline = {'cline': context, 'file': stack_slice[i].url, 'fn': stack_slice[i].func, 'line': stack_slice[i].line, 'vars': []}; report.traceback.push(stackline); } if(report.traceback.length > 0){ report.traceback[report.traceback.length - 1].cline = context + '\n' + error_msg; } this.errorReportBuffer.push(report); }, log: function (level, message, namespace, uuid) { if (typeof namespace == 'undefined') { var namespace = window.location.pathname; } if (typeof uuid == 'undefined') { var uuid = null; } this.logBuffer.push( { "log_level": level.toUpperCase(), "message": message, "date": new Date().toJSON(), "namespace": namespace }) if (this.requestInfo != null && typeof this.requestInfo.server != 'undefined') { this.logBuffer[this.logBuffer.length - 1].server = this.requestInfo.server; } }, genUUID4: function () { return '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); } ); }, sendReports: function () { if (this.errorReportBuffer.length < 1) { return true; } var data = this.errorReportBuffer; this.submitData(this.reportsEndpoint, data); this.errorReportBuffer = []; return true; }, sendLogs: function () { if (this.logBuffer.length < 1) { return true; } var data = this.logBuffer; this.submitData(this.logsEndpoint, data); this.logBuffer = []; return true; }, submitData: function (endpoint, data) { var xhr = new window.XMLHttpRequest(); if (!xhr && window.ActiveXObject) { xhr = new window.ActiveXObject("Microsoft.XMLHTTP"); } xhr.open("POST", endpoint, true); xhr.setRequestHeader("Content-Type", "application/json"); xhr.send(JSON.stringify(data)); } } window.AppEnlight = AppEnlight; if ( typeof define === "function" && define.amd ) { define( "appenlight", [], function() { return AppEnlight; }); } }(window)); // Version 0.3.1 /* TraceKit - Cross browser stack traces - github.com/csnover/TraceKit MIT license */ (function(window, undefined) { if (!window) { return; } var TraceKit = {}; var _oldTraceKit = window.TraceKit; // global reference to slice var _slice = [].slice; var UNKNOWN_FUNCTION = '?'; /** * _has, a better form of hasOwnProperty * Example: _has(MainHostObject, property) === true/false * * @param {Object} object to check property * @param {string} key to check */ function _has(object, key) { return Object.prototype.hasOwnProperty.call(object, key); } function _isUndefined(what) { return typeof what === 'undefined'; } /** * TraceKit.noConflict: Export TraceKit out to another variable * Example: var TK = TraceKit.noConflict() */ TraceKit.noConflict = function noConflict() { window.TraceKit = _oldTraceKit; return TraceKit; }; /** * TraceKit.wrap: Wrap any function in a TraceKit reporter * Example: func = TraceKit.wrap(func); * * @param {Function} func Function to be wrapped * @return {Function} The wrapped func */ TraceKit.wrap = function traceKitWrapper(func) { function wrapped() { try { return func.apply(this, arguments); } catch (e) { TraceKit.report(e); throw e; } } return wrapped; }; /** * TraceKit.report: cross-browser processing of unhandled exceptions * * Syntax: * TraceKit.report.subscribe(function(stackInfo) { ... }) * TraceKit.report.unsubscribe(function(stackInfo) { ... }) * TraceKit.report(exception) * try { ...code... } catch(ex) { TraceKit.report(ex); } * * Supports: * - Firefox: full stack trace with line numbers, plus column number * on top frame; column number is not guaranteed * - Opera: full stack trace with line and column numbers * - Chrome: full stack trace with line and column numbers * - Safari: line and column number for the top frame only; some frames * may be missing, and column number is not guaranteed * - IE: line and column number for the top frame only; some frames * may be missing, and column number is not guaranteed * * In theory, TraceKit should work on all of the following versions: * - IE5.5+ (only 8.0 tested) * - Firefox 0.9+ (only 3.5+ tested) * - Opera 7+ (only 10.50 tested; versions 9 and earlier may require * Exceptions Have Stacktrace to be enabled in opera:config) * - Safari 3+ (only 4+ tested) * - Chrome 1+ (only 5+ tested) * - Konqueror 3.5+ (untested) * * Requires TraceKit.computeStackTrace. * * Tries to catch all unhandled exceptions and report them to the * subscribed handlers. Please note that TraceKit.report will rethrow the * exception. This is REQUIRED in order to get a useful stack trace in IE. * If the exception does not reach the top of the browser, you will only * get a stack trace from the point where TraceKit.report was called. * * Handlers receive a stackInfo object as described in the * TraceKit.computeStackTrace docs. */ TraceKit.report = (function reportModuleWrapper() { var handlers = [], lastArgs = null, lastException = null, lastExceptionStack = null; /** * Add a crash handler. * @param {Function} handler */ function subscribe(handler) { installGlobalHandler(); handlers.push(handler); } /** * Remove a crash handler. * @param {Function} handler */ function unsubscribe(handler) { for (var i = handlers.length - 1; i >= 0; --i) { if (handlers[i] === handler) { handlers.splice(i, 1); } } } /** * Dispatch stack information to all handlers. * @param {Object.<string, *>} stack */ function notifyHandlers(stack, isWindowError) { var exception = null; if (isWindowError && !TraceKit.collectWindowErrors) { return; } for (var i in handlers) { if (_has(handlers, i)) { try { handlers[i].apply(null, [stack].concat(_slice.call(arguments, 2))); } catch (inner) { exception = inner; } } } if (exception) { throw exception; } } var _oldOnerrorHandler, _onErrorHandlerInstalled; /** * Ensures all global unhandled exceptions are recorded. * Supported by Gecko and IE. * @param {string} message Error message. * @param {string} url URL of script that generated the exception. * @param {(number|string)} lineNo The line number at which the error * occurred. * @param {?(number|string)} columnNo The column number at which the error * occurred. * @param {?Error} errorObj The actual Error object. */ function traceKitWindowOnError(message, url, lineNo, columnNo, errorObj) { var stack = null; if (lastExceptionStack) { TraceKit.computeStackTrace.augmentStackTraceWithInitialElement(lastExceptionStack, url, lineNo, message); processLastException(); } else if (errorObj) { stack = TraceKit.computeStackTrace(errorObj); notifyHandlers(stack, true); } else { var location = { 'url': url, 'line': lineNo, 'column': columnNo }; location.func = TraceKit.computeStackTrace.guessFunctionName(location.url, location.line); location.context = TraceKit.computeStackTrace.gatherContext(location.url, location.line); stack = { 'mode': 'onerror', 'message': message, 'stack': [location] }; notifyHandlers(stack, true); } if (_oldOnerrorHandler) { return _oldOnerrorHandler.apply(this, arguments); } return false; } function installGlobalHandler () { if (_onErrorHandlerInstalled === true) { return; } _oldOnerrorHandler = window.onerror; window.onerror = traceKitWindowOnError; _onErrorHandlerInstalled = true; } function processLastException() { var _lastExceptionStack = lastExceptionStack, _lastArgs = lastArgs; lastArgs = null; lastExceptionStack = null; lastException = null; notifyHandlers.apply(null, [_lastExceptionStack, false].concat(_lastArgs)); } /** * Reports an unhandled Error to TraceKit. * @param {Error} ex */ function report(ex) { if (lastExceptionStack) { if (lastException === ex) { return; // already caught by an inner catch block, ignore } else { processLastException(); } } var stack = TraceKit.computeStackTrace(ex); lastExceptionStack = stack; lastException = ex; lastArgs = _slice.call(arguments, 1); // If the stack trace is incomplete, wait for 2 seconds for // slow slow IE to see if onerror occurs or not before reporting // this exception; otherwise, we will end up with an incomplete // stack trace window.setTimeout(function () { if (lastException === ex) { processLastException(); } }, (stack.incomplete ? 2000 : 0)); throw ex; // re-throw to propagate to the top level (and cause window.onerror) } report.subscribe = subscribe; report.unsubscribe = unsubscribe; return report; }()); /** * TraceKit.computeStackTrace: cross-browser stack traces in JavaScript * * Syntax: * s = TraceKit.computeStackTrace.ofCaller([depth]) * s = TraceKit.computeStackTrace(exception) // consider using TraceKit.report instead (see below) * Returns: * s.name - exception name * s.message - exception message * s.stack[i].url - JavaScript or HTML file URL * s.stack[i].func - function name, or empty for anonymous functions (if guessing did not work) * s.stack[i].args - arguments passed to the function, if known * s.stack[i].line - line number, if known * s.stack[i].column - column number, if known * s.stack[i].context - an array of source code lines; the middle element corresponds to the correct line# * s.mode - 'stack', 'stacktrace', 'multiline', 'callers', 'onerror', or 'failed' -- method used to collect the stack trace * * Supports: * - Firefox: full stack trace with line numbers and unreliable column * number on top frame * - Opera 10: full stack trace with line and column numbers * - Opera 9-: full stack trace with line numbers * - Chrome: full stack trace with line and column numbers * - Safari: line and column number for the topmost stacktrace element * only * - IE: no line numbers whatsoever * * Tries to guess names of anonymous functions by looking for assignments * in the source code. In IE and Safari, we have to guess source file names * by searching for function bodies inside all page scripts. This will not * work for scripts that are loaded cross-domain. * Here be dragons: some function names may be guessed incorrectly, and * duplicate functions may be mismatched. * * TraceKit.computeStackTrace should only be used for tracing purposes. * Logging of unhandled exceptions should be done with TraceKit.report, * which builds on top of TraceKit.computeStackTrace and provides better * IE support by utilizing the window.onerror event to retrieve information * about the top of the stack. * * Note: In IE and Safari, no stack trace is recorded on the Error object, * so computeStackTrace instead walks its *own* chain of callers. * This means that: * * in Safari, some methods may be missing from the stack trace; * * in IE, the topmost function in the stack trace will always be the * caller of computeStackTrace. * * This is okay for tracing (because you are likely to be calling * computeStackTrace from the function you want to be the topmost element * of the stack trace anyway), but not okay for logging unhandled * exceptions (because your catch block will likely be far away from the * inner function that actually caused the exception). * * Tracing example: * function trace(message) { * var stackInfo = TraceKit.computeStackTrace.ofCaller(); * var data = message + "\n"; * for(var i in stackInfo.stack) { * var item = stackInfo.stack[i]; * data += (item.func || '[anonymous]') + "() in " + item.url + ":" + (item.line || '0') + "\n"; * } * if (window.console) * console.info(data); * else * alert(data); * } */ TraceKit.computeStackTrace = (function computeStackTraceWrapper() { var debug = false, sourceCache = {}; /** * Attempts to retrieve source code via XMLHttpRequest, which is used * to look up anonymous function names. * @param {string} url URL of source code. * @return {string} Source contents. */ function loadSource(url) { if (!TraceKit.remoteFetching) { //Only attempt request if remoteFetching is on. return ''; } try { var getXHR = function() { try { return new window.XMLHttpRequest(); } catch (e) { // explicitly bubble up the exception if not found return new window.ActiveXObject('Microsoft.XMLHTTP'); } }; var request = getXHR(); request.open('GET', url, false); request.send(''); return request.responseText; } catch (e) { return ''; } } /** * Retrieves source code from the source code cache. * @param {string} url URL of source code. * @return {Array.<string>} Source contents. */ function getSource(url) { if (typeof url !== 'string') { return []; } if (!_has(sourceCache, url)) { // URL needs to be able to fetched within the acceptable domain. Otherwise, // cross-domain errors will be triggered. var source = ''; var domain = ''; try { domain = document.domain; } catch (e) {} if (url.indexOf(domain) !== -1) { source = loadSource(url); } sourceCache[url] = source ? source.split('\n') : []; } return sourceCache[url]; } /** * Tries to use an externally loaded copy of source code to determine * the name of a function by looking at the name of the variable it was * assigned to, if any. * @param {string} url URL of source code. * @param {(string|number)} lineNo Line number in source code. * @return {string} The function name, if discoverable. */ function guessFunctionName(url, lineNo) { var reFunctionArgNames = /function ([^(]*)\(([^)]*)\)/, reGuessFunction = /['"]?([0-9A-Za-z$_]+)['"]?\s*[:=]\s*(function|eval|new Function)/, line = '', maxLines = 10, source = getSource(url), m; if (!source.length) { return UNKNOWN_FUNCTION; } // Walk backwards from the first line in the function until we find the line which // matches the pattern above, which is the function definition for (var i = 0; i < maxLines; ++i) { line = source[lineNo - i] + line; if (!_isUndefined(line)) { if ((m = reGuessFunction.exec(line))) { return m[1]; } else if ((m = reFunctionArgNames.exec(line))) { return m[1]; } } } return UNKNOWN_FUNCTION; } /** * Retrieves the surrounding lines from where an exception occurred. * @param {string} url URL of source code. * @param {(string|number)} line Line number in source code to centre * around for context. * @return {?Array.<string>} Lines of source code. */ function gatherContext(url, line) { var source = getSource(url); if (!source.length) { return null; } var context = [], // linesBefore & linesAfter are inclusive with the offending line. // if linesOfContext is even, there will be one extra line // *before* the offending line. linesBefore = Math.floor(TraceKit.linesOfContext / 2), // Add one extra line if linesOfContext is odd linesAfter = linesBefore + (TraceKit.linesOfContext % 2), start = Math.max(0, line - linesBefore - 1), end = Math.min(source.length, line + linesAfter - 1); line -= 1; // convert to 0-based index for (var i = start; i < end; ++i) { if (!_isUndefined(source[i])) { context.push(source[i]); } } return context.length > 0 ? context : null; } /** * Escapes special characters, except for whitespace, in a string to be * used inside a regular expression as a string literal. * @param {string} text The string. * @return {string} The escaped string literal. */ function escapeRegExp(text) { return text.replace(/[\-\[\]{}()*+?.,\\\^$|#]/g, '\\$&'); } /** * Escapes special characters in a string to be used inside a regular * expression as a string literal. Also ensures that HTML entities will * be matched the same as their literal friends. * @param {string} body The string. * @return {string} The escaped string. */ function escapeCodeAsRegExpForMatchingInsideHTML(body) { return escapeRegExp(body).replace('<', '(?:<|&lt;)').replace('>', '(?:>|&gt;)').replace('&', '(?:&|&amp;)').replace('"', '(?:"|&quot;)').replace(/\s+/g, '\\s+'); } /** * Determines where a code fragment occurs in the source code. * @param {RegExp} re The function definition. * @param {Array.<string>} urls A list of URLs to search. * @return {?Object.<string, (string|number)>} An object containing * the url, line, and column number of the defined function. */ function findSourceInUrls(re, urls) { var source, m; for (var i = 0, j = urls.length; i < j; ++i) { // console.log('searching', urls[i]); if ((source = getSource(urls[i])).length) { source = source.join('\n'); if ((m = re.exec(source))) { // console.log('Found function in ' + urls[i]); return { 'url': urls[i], 'line': source.substring(0, m.index).split('\n').length, 'column': m.index - source.lastIndexOf('\n', m.index) - 1 }; } } } // console.log('no match'); return null; } /** * Determines at which column a code fragment occurs on a line of the * source code. * @param {string} fragment The code fragment. * @param {string} url The URL to search. * @param {(string|number)} line The line number to examine. * @return {?number} The column number. */ function findSourceInLine(fragment, url, line) { var source = getSource(url), re = new RegExp('\\b' + escapeRegExp(fragment) + '\\b'), m; line -= 1; if (source && source.length > line && (m = re.exec(source[line]))) { return m.index; } return null; } /** * Determines where a function was defined within the source code. * @param {(Function|string)} func A function reference or serialized * function definition. * @return {?Object.<string, (string|number)>} An object containing * the url, line, and column number of the defined function. */ function findSourceByFunctionBody(func) { if (_isUndefined(document)) { return; } var urls = [window.location.href], scripts = document.getElementsByTagName('script'), body, code = '' + func, codeRE = /^function(?:\s+([\w$]+))?\s*\(([\w\s,]*)\)\s*\{\s*(\S[\s\S]*\S)\s*\}\s*$/, eventRE = /^function on([\w$]+)\s*\(event\)\s*\{\s*(\S[\s\S]*\S)\s*\}\s*$/, re, parts, result; for (var i = 0; i < scripts.length; ++i) { var script = scripts[i]; if (script.src) { urls.push(script.src); } } if (!(parts = codeRE.exec(code))) { re = new RegExp(escapeRegExp(code).replace(/\s+/g, '\\s+')); } // not sure if this is really necessary, but I don’t have a test // corpus large enough to confirm that and it was in the original. else { var name = parts[1] ? '\\s+' + parts[1] : '', args = parts[2].split(',').join('\\s*,\\s*'); body = escapeRegExp(parts[3]).replace(/;$/, ';?'); // semicolon is inserted if the function ends with a comment.replace(/\s+/g, '\\s+'); re = new RegExp('function' + name + '\\s*\\(\\s*' + args + '\\s*\\)\\s*{\\s*' + body + '\\s*}'); } // look for a normal function definition if ((result = findSourceInUrls(re, urls))) { return result; } // look for an old-school event handler function if ((parts = eventRE.exec(code))) { var event = parts[1]; body = escapeCodeAsRegExpForMatchingInsideHTML(parts[2]); // look for a function defined in HTML as an onXXX handler re = new RegExp('on' + event + '=[\\\'"]\\s*' + body + '\\s*[\\\'"]', 'i'); if ((result = findSourceInUrls(re, urls[0]))) { return result; } // look for ??? re = new RegExp(body); if ((result = findSourceInUrls(re, urls))) { return result; } } return null; } // Contents of Exception in various browsers. // // SAFARI: // ex.message = Can't find variable: qq // ex.line = 59 // ex.sourceId = 580238192 // ex.sourceURL = http://... // ex.expressionBeginOffset = 96 // ex.expressionCaretOffset = 98 // ex.expressionEndOffset = 98 // ex.name = ReferenceError // // FIREFOX: // ex.message = qq is not defined // ex.fileName = http://... // ex.lineNumber = 59 // ex.columnNumber = 69 // ex.stack = ...stack trace... (see the example below) // ex.name = ReferenceError // // CHROME: // ex.message = qq is not defined // ex.name = ReferenceError // ex.type = not_defined // ex.arguments = ['aa'] // ex.stack = ...stack trace... // // INTERNET EXPLORER: // ex.message = ... // ex.name = ReferenceError // // OPERA: // ex.message = ...message... (see the example below) // ex.name = ReferenceError // ex.opera#sourceloc = 11 (pretty much useless, duplicates the info in ex.message) // ex.stacktrace = n/a; see 'opera:config#UserPrefs|Exceptions Have Stacktrace' /** * Computes stack trace information from the stack property. * Chrome and Gecko use this property. * @param {Error} ex * @return {?Object.<string, *>} Stack trace information. */ function computeStackTraceFromStackProp(ex) { if (!ex.stack) { return null; } var chrome = /^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i, gecko = /^\s*(.*?)(?:\((.*?)\))?@?((?:file|https?|blob|chrome|\[).*?)(?::(\d+))?(?::(\d+))?\s*$/i, winjs = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:ms-appx|https?|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i, lines = ex.stack.split('\n'), stack = [], parts, element, reference = /^(.*) is undefined$/.exec(ex.message); for (var i = 0, j = lines.length; i < j; ++i) { if ((parts = chrome.exec(lines[i]))) { var isNative = parts[2] && parts[2].indexOf('native') !== -1; element = { 'url': !isNative ? parts[2] : null, 'func': parts[1] || UNKNOWN_FUNCTION, 'args': isNative ? [parts[2]] : [], 'line': parts[3] ? +parts[3] : null, 'column': parts[4] ? +parts[4] : null }; } else if ( parts = winjs.exec(lines[i]) ) { element = { 'url': parts[2], 'func': parts[1] || UNKNOWN_FUNCTION, 'args': [], 'line': +parts[3], 'column': parts[4] ? +parts[4] : null }; } else if ((parts = gecko.exec(lines[i]))) { element = { 'url': parts[3], 'func': parts[1] || UNKNOWN_FUNCTION, 'args': parts[2] ? parts[2].split(',') : [], 'line': parts[4] ? +parts[4] : null, 'column': parts[5] ? +parts[5] : null }; } else { continue; } if (!element.func && element.line) { element.func = guessFunctionName(element.url, element.line); } if (element.line) { element.context = gatherContext(element.url, element.line); } stack.push(element); } if (!stack.length) { return null; } if (stack[0] && stack[0].line && !stack[0].column && reference) { stack[0].column = findSourceInLine(reference[1], stack[0].url, stack[0].line); } else if (!stack[0].column && !_isUndefined(ex.columnNumber)) { // FireFox uses this awesome columnNumber property for its top frame // Also note, Firefox's column number is 0-based and everything else expects 1-based, // so adding 1 stack[0].column = ex.columnNumber + 1; } return { 'mode': 'stack', 'name': ex.name, 'message': ex.message, 'stack': stack }; } /** * Computes stack trace information from the stacktrace property. * Opera 10+ uses this property. * @param {Error} ex * @return {?Object.<string, *>} Stack trace information. */ function computeStackTraceFromStacktraceProp(ex) { // Access and store the stacktrace property before doing ANYTHING // else to it because Opera is not very good at providing it // reliably in other circumstances. var stacktrace = ex.stacktrace; if (!stacktrace) { return; } var opera10Regex = / line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i, opera11Regex = / line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^\)]+))\((.*)\))? in (.*):\s*$/i, lines = stacktrace.split('\n'), stack = [], parts; for (var line = 0; line < lines.length; line += 2) { var element = null; if ((parts = opera10Regex.exec(lines[line]))) { element = { 'url': parts[2], 'line': +parts[1], 'column': null, 'func': parts[3], 'args':[] }; } else if ((parts = opera11Regex.exec(lines[line]))) { element = { 'url': parts[6], 'line': +parts[1], 'column': +parts[2], 'func': parts[3] || parts[4], 'args': parts[5] ? parts[5].split(',') : [] }; } if (element) { if (!element.func && element.line) { element.func = guessFunctionName(element.url, element.line); } if (element.line) { try { element.context = gatherContext(element.url, element.line); } catch (exc) {} } if (!element.context) { element.context = [lines[line + 1]]; } stack.push(element); } } if (!stack.length) { return null; } return { 'mode': 'stacktrace', 'name': ex.name, 'message': ex.message, 'stack': stack }; } /** * NOT TESTED. * Computes stack trace information from an error message that includes * the stack trace. * Opera 9 and earlier use this method if the option to show stack * traces is turned on in opera:config. * @param {Error} ex * @return {?Object.<string, *>} Stack information. */ function computeStackTraceFromOperaMultiLineMessage(ex) { // TODO: Clean this function up // Opera includes a stack trace into the exception message. An example is: // // Statement on line 3: Undefined variable: undefinedFunc // Backtrace: // Line 3 of linked script file://localhost/Users/andreyvit/Projects/TraceKit/javascript-client/sample.js: In function zzz // undefinedFunc(a); // Line 7 of inline#1 script in file://localhost/Users/andreyvit/Projects/TraceKit/javascript-client/sample.html: In function yyy // zzz(x, y, z); // Line 3 of inline#1 script in file://localhost/Users/andreyvit/Projects/TraceKit/javascript-client/sample.html: In function xxx // yyy(a, a, a); // Line 1 of function script // try { xxx('hi'); return false; } catch(ex) { TraceKit.report(ex); } // ... var lines = ex.message.split('\n'); if (lines.length < 4) { return null; } var lineRE1 = /^\s*Line (\d+) of linked script ((?:file|https?|blob)\S+)(?:: in function (\S+))?\s*$/i, lineRE2 = /^\s*Line (\d+) of inline#(\d+) script in ((?:file|https?|blob)\S+)(?:: in function (\S+))?\s*$/i, lineRE3 = /^\s*Line (\d+) of function script\s*$/i, stack = [], scripts = document.getElementsByTagName('script'), inlineScriptBlocks = [], parts; for (var s in scripts) { if (_has(scripts, s) && !scripts[s].src) { inlineScriptBlocks.push(scripts[s]); } } for (var line = 2; line < lines.length; line += 2) { var item = null; if ((parts = lineRE1.exec(lines[line]))) { item = { 'url': parts[2], 'func': parts[3], 'args': [], 'line': +parts[1], 'column': null }; } else if ((parts = lineRE2.exec(lines[line]))) { item = { 'url': parts[3], 'func': parts[4], 'args': [], 'line': +parts[1], 'column': null // TODO: Check to see if inline#1 (+parts[2]) points to the script number or column number. }; var relativeLine = (+parts[1]); // relative to the start of the <SCRIPT> block var script = inlineScriptBlocks[parts[2] - 1]; if (script) { var source = getSource(item.url); if (source) { source = source.join('\n'); var pos = source.indexOf(script.innerText); if (pos >= 0) { item.line = relativeLine + source.substring(0, pos).split('\n').length; } } } } else if ((parts = lineRE3.exec(lines[line]))) { var url = window.location.href.replace(/#.*$/, ''); var re = new RegExp(escapeCodeAsRegExpForMatchingInsideHTML(lines[line + 1])); var src = findSourceInUrls(re, [url]); item = { 'url': url, 'func': '', 'args': [], 'line': src ? src.line : parts[1], 'column': null }; } if (item) { if (!item.func) { item.func = guessFunctionName(item.url, item.line); } var context = gatherContext(item.url, item.line); var midline = (context ? context[Math.floor(context.length / 2)] : null); if (context && midline.replace(/^\s*/, '') === lines[line + 1].replace(/^\s*/, '')) { item.context = context; } else { // if (context) alert("Context mismatch. Correct midline:\n" + lines[i+1] + "\n\nMidline:\n" + midline + "\n\nContext:\n" + context.join("\n") + "\n\nURL:\n" + item.url); item.context = [lines[line + 1]]; } stack.push(item); } } if (!stack.length) { return null; // could not parse multiline exception message as Opera stack trace } return { 'mode': 'multiline', 'name': ex.name, 'message': lines[0], 'stack': stack }; } /** * Adds information about the first frame to incomplete stack traces. * Safari and IE require this to get complete data on the first frame. * @param {Object.<string, *>} stackInfo Stack trace information from * one of the compute* methods. * @param {string} url The URL of the script that caused an error. * @param {(number|string)} lineNo The line number of the script that * caused an error. * @param {string=} message The error generated by the browser, which * hopefully contains the name of the object that caused the error. * @return {boolean} Whether or not the stack information was * augmented. */ function augmentStackTraceWithInitialElement(stackInfo, url, lineNo, message) { var initial = { 'url': url, 'line': lineNo }; if (initial.url && initial.line) { stackInfo.incomplete = false; if (!initial.func) { initial.func = guessFunctionName(initial.url, initial.line); } if (!initial.context) { initial.context = gatherContext(initial.url, initial.line); } var reference = / '([^']+)' /.exec(message); if (reference) { initial.column = findSourceInLine(reference[1], initial.url, initial.line); } if (stackInfo.stack.length > 0) { if (stackInfo.stack[0].url === initial.url) { if (stackInfo.stack[0].line === initial.line) { return false; // already in stack trace } else if (!stackInfo.stack[0].line && stackInfo.stack[0].func === initial.func) { stackInfo.stack[0].line = initial.line; stackInfo.stack[0].context = initial.context; return false; } } } stackInfo.stack.unshift(initial); stackInfo.partial = true; return true; } else { stackInfo.incomplete = true; } return false; } /** * Computes stack trace information by walking the arguments.caller * chain at the time the exception occurred. This will cause earlier * frames to be missed but is the only way to get any stack trace in * Safari and IE. The top frame is restored by * {@link augmentStackTraceWithInitialElement}. * @param {Error} ex * @return {?Object.<string, *>} Stack trace information. */ function computeStackTraceByWalkingCallerChain(ex, depth) { var functionName = /function\s+([_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*)?\s*\(/i, stack = [], funcs = {}, recursion = false, parts, item, source; for (var curr = computeStackTraceByWalkingCallerChain.caller; curr && !recursion; curr = curr.caller) { if (curr === computeStackTrace || curr === TraceKit.report) { // console.log('skipping internal function'); continue; } item = { 'url': null, 'func': UNKNOWN_FUNCTION, 'args': [], 'line': null, 'column': null }; if (curr.name) { item.func = curr.name; } else if ((parts = functionName.exec(curr.toString()))) { item.func = parts[1]; } if (typeof item.func === 'undefined') { try { item.func = parts.input.substring(0, parts.input.indexOf('{')); } catch (e) { } } if ((source = findSourceByFunctionBody(curr))) { item.url = source.url; item.line = source.line; if (item.func === UNKNOWN_FUNCTION) { item.func = guessFunctionName(item.url, item.line); } var reference = / '([^']+)' /.exec(ex.message || ex.description); if (reference) { item.column = findSourceInLine(reference[1], source.url, source.line); } } if (funcs['' + curr]) { recursion = true; }else{ funcs['' + curr] = true; } stack.push(item); } if (depth) { // console.log('depth is ' + depth); // console.log('stack is ' + stack.length); stack.splice(0, depth); } var result = { 'mode': 'callers', 'name': ex.name, 'message': ex.message, 'stack': stack }; augmentStackTraceWithInitialElement(result, ex.sourceURL || ex.fileName, ex.line || ex.lineNumber, ex.message || ex.description); return result; } /** * Computes a stack trace for an exception. * @param {Error} ex * @param {(string|number)=} depth */ function computeStackTrace(ex, depth) { var stack = null; depth = (depth == null ? 0 : +depth); try { // This must be tried first because Opera 10 *destroys* // its stacktrace property if you try to access the stack // property first!! stack = computeStackTraceFromStacktraceProp(ex); if (stack) { return stack; } } catch (e) { if (debug) { throw e; } } try { stack = computeStackTraceFromStackProp(ex); if (stack) { return stack; } } catch (e) { if (debug) { throw e; } } try { stack = computeStackTraceFromOperaMultiLineMessage(ex); if (stack) { return stack; } } catch (e) { if (debug) { throw e; } } try { stack = computeStackTraceByWalkingCallerChain(ex, depth + 1); if (stack) { return stack; } } catch (e) { if (debug) { throw e; } } return { 'mode': 'failed' }; } /** * Logs a stacktrace starting from the previous call and working down. * @param {(number|string)=} depth How many frames deep to trace. * @return {Object.<string, *>} Stack trace information. */ function computeStackTraceOfCaller(depth) { depth = (depth == null ? 0 : +depth) + 1; // "+ 1" because "ofCaller" should drop one frame try { throw new Error(); } catch (ex) { return computeStackTrace(ex, depth + 1); } } computeStackTrace.augmentStackTraceWithInitialElement = augmentStackTraceWithInitialElement; computeStackTrace.guessFunctionName = guessFunctionName; computeStackTrace.gatherContext = gatherContext; computeStackTrace.ofCaller = computeStackTraceOfCaller; computeStackTrace.getSource = getSource; return computeStackTrace; }()); /** * Extends support for global error handling for asynchronous browser * functions. Adopted from Closure Library's errorhandler.js */ TraceKit.extendToAsynchronousCallbacks = function () { var _helper = function _helper(fnName) { var originalFn = window[fnName]; window[fnName] = function traceKitAsyncExtension() { // Make a copy of the arguments var args = _slice.call(arguments); var originalCallback = args[0]; if (typeof (originalCallback) === 'function') { args[0] = TraceKit.wrap(originalCallback); } // IE < 9 doesn't support .call/.apply on setInterval/setTimeout, but it // also only supports 2 argument and doesn't care what "this" is, so we // can just call the original function directly. if (originalFn.apply) { return originalFn.apply(this, args); } else { return originalFn(args[0], args[1]); } }; }; _helper('setTimeout'); _helper('setInterval'); }; //Default options: if (!TraceKit.remoteFetching) { TraceKit.remoteFetching = true; } if (!TraceKit.collectWindowErrors) { TraceKit.collectWindowErrors = true; } if (!TraceKit.linesOfContext || TraceKit.linesOfContext < 1) { // 5 lines before, the offending line, 5 lines after TraceKit.linesOfContext = 11; } // Export to global object window.TraceKit = TraceKit; }(typeof window !== 'undefined' ? window : global));
declare module 'os-tmpdir' { declare module.exports: () => string; }
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'scayt', 'eu', { about: 'SCAYTi buruz', aboutTab: 'Honi buruz', addWord: 'Hitza Gehitu', allCaps: 'Ignore All-Caps Words', // MISSING dic_create: 'Create', // MISSING dic_delete: 'Delete', // MISSING dic_field_name: 'Dictionary name', // MISSING dic_info: 'Initially the User Dictionary is stored in a Cookie. However, Cookies are limited in size. When the User Dictionary grows to a point where it cannot be stored in a Cookie, then the dictionary may be stored on our server. To store your personal dictionary on our server you should specify a name for your dictionary. If you already have a stored dictionary, please type its name and click the Restore button.', // MISSING dic_rename: 'Rename', // MISSING dic_restore: 'Restore', // MISSING dictionariesTab: 'Hiztegiak', disable: 'Desgaitu SCAYT', emptyDic: 'Hiztegiaren izena ezin da hutsik egon.', enable: 'Gaitu SCAYT', ignore: 'Baztertu', ignoreAll: 'Denak baztertu', ignoreDomainNames: 'Ignore Domain Names', // MISSING langs: 'Hizkuntzak', languagesTab: 'Hizkuntzak', mixedCase: 'Ignore Words with Mixed Case', // MISSING mixedWithDigits: 'Ignore Words with Numbers', // MISSING moreSuggestions: 'Iradokizun gehiago', opera_title: 'Not supported by Opera', // MISSING options: 'Aukerak', optionsTab: 'Aukerak', title: 'Ortografia Zuzenketa Idatzi Ahala (SCAYT)', toggle: 'SCAYT aldatu', noSuggestions: 'No suggestion' });
/* * @name Iteration * @description Iteration with a "for" structure to construct repetitive forms. */ var y; var num = 14; function setup() { createCanvas(720, 360); background(102); noStroke(); // Draw white bars fill(255); y = 60; for(var i = 0; i < num/3; i++) { rect(50, y, 475, 10); y+=20; } // Gray bars fill(51); y = 40; for(var i = 0; i < num; i++) { rect(405, y, 30, 10); y += 20; } y = 50; for(var i = 0; i < num; i++) { rect(425, y, 30, 10); y += 20; } // Thin lines y = 45; fill(0); for(var i = 0; i < num-1; i++) { rect(120, y, 40, 1); y+= 20; } }
/** * @author mrdoob / http://mrdoob.com/ * @author *kile / http://kile.stravaganza.org/ * @author philogb / http://blog.thejit.org/ * @author mikael emtinger / http://gomo.se/ * @author egraether / http://egraether.com/ * @author WestLangley / http://github.com/WestLangley */ THREE.Vector3 = function ( x, y, z ) { this.x = x || 0; this.y = y || 0; this.z = z || 0; }; THREE.Vector3.prototype = { constructor: THREE.Vector3, set: function ( x, y, z ) { this.x = x; this.y = y; this.z = z; return this; }, setX: function ( x ) { this.x = x; return this; }, setY: function ( y ) { this.y = y; return this; }, setZ: function ( z ) { this.z = z; return this; }, setComponent: function ( index, value ) { switch ( index ) { case 0: this.x = value; break; case 1: this.y = value; break; case 2: this.z = value; break; default: throw new Error( 'index is out of range: ' + index ); } }, getComponent: function ( index ) { switch ( index ) { case 0: return this.x; case 1: return this.y; case 2: return this.z; default: throw new Error( 'index is out of range: ' + index ); } }, copy: function ( v ) { this.x = v.x; this.y = v.y; this.z = v.z; return this; }, add: function ( v, w ) { if ( w !== undefined ) { console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' ); return this.addVectors( v, w ); } this.x += v.x; this.y += v.y; this.z += v.z; return this; }, addScalar: function ( s ) { this.x += s; this.y += s; this.z += s; return this; }, addVectors: function ( a, b ) { this.x = a.x + b.x; this.y = a.y + b.y; this.z = a.z + b.z; return this; }, sub: function ( v, w ) { if ( w !== undefined ) { console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' ); return this.subVectors( v, w ); } this.x -= v.x; this.y -= v.y; this.z -= v.z; return this; }, subVectors: function ( a, b ) { this.x = a.x - b.x; this.y = a.y - b.y; this.z = a.z - b.z; return this; }, multiply: function ( v, w ) { if ( w !== undefined ) { console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' ); return this.multiplyVectors( v, w ); } this.x *= v.x; this.y *= v.y; this.z *= v.z; return this; }, multiplyScalar: function ( scalar ) { this.x *= scalar; this.y *= scalar; this.z *= scalar; return this; }, multiplyVectors: function ( a, b ) { this.x = a.x * b.x; this.y = a.y * b.y; this.z = a.z * b.z; return this; }, applyEuler: function () { var quaternion; return function ( euler ) { if ( euler instanceof THREE.Euler === false ) { console.error( 'THREE.Vector3: .applyEuler() now expects a Euler rotation rather than a Vector3 and order.' ); } if ( quaternion === undefined ) quaternion = new THREE.Quaternion(); this.applyQuaternion( quaternion.setFromEuler( euler ) ); return this; }; }(), applyAxisAngle: function () { var quaternion; return function ( axis, angle ) { if ( quaternion === undefined ) quaternion = new THREE.Quaternion(); this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) ); return this; }; }(), applyMatrix3: function ( m ) { var x = this.x; var y = this.y; var z = this.z; var e = m.elements; this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z; this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z; this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z; return this; }, applyMatrix4: function ( m ) { // input: THREE.Matrix4 affine matrix var x = this.x, y = this.y, z = this.z; var e = m.elements; this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ]; this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ]; this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ]; return this; }, applyProjection: function ( m ) { // input: THREE.Matrix4 projection matrix var x = this.x, y = this.y, z = this.z; var e = m.elements; var d = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); // perspective divide this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * d; this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * d; this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * d; return this; }, applyQuaternion: function ( q ) { var x = this.x; var y = this.y; var z = this.z; var qx = q.x; var qy = q.y; var qz = q.z; var qw = q.w; // calculate quat * vector var ix = qw * x + qy * z - qz * y; var iy = qw * y + qz * x - qx * z; var iz = qw * z + qx * y - qy * x; var iw = - qx * x - qy * y - qz * z; // calculate result * inverse quat this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy; this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz; this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx; return this; }, project: function () { var matrix; return function ( camera ) { if ( matrix === undefined ) matrix = new THREE.Matrix4(); matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) ); return this.applyProjection( matrix ); }; }(), unproject: function () { var matrix; return function ( camera ) { if ( matrix === undefined ) matrix = new THREE.Matrix4(); matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) ); return this.applyProjection( matrix ); }; }(), transformDirection: function ( m ) { // input: THREE.Matrix4 affine matrix // vector interpreted as a direction var x = this.x, y = this.y, z = this.z; var e = m.elements; this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z; this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z; this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z; this.normalize(); return this; }, divide: function ( v ) { this.x /= v.x; this.y /= v.y; this.z /= v.z; return this; }, divideScalar: function ( scalar ) { if ( scalar !== 0 ) { var invScalar = 1 / scalar; this.x *= invScalar; this.y *= invScalar; this.z *= invScalar; } else { this.x = 0; this.y = 0; this.z = 0; } return this; }, min: function ( v ) { if ( this.x > v.x ) { this.x = v.x; } if ( this.y > v.y ) { this.y = v.y; } if ( this.z > v.z ) { this.z = v.z; } return this; }, max: function ( v ) { if ( this.x < v.x ) { this.x = v.x; } if ( this.y < v.y ) { this.y = v.y; } if ( this.z < v.z ) { this.z = v.z; } return this; }, clamp: function ( min, max ) { // This function assumes min < max, if this assumption isn't true it will not operate correctly if ( this.x < min.x ) { this.x = min.x; } else if ( this.x > max.x ) { this.x = max.x; } if ( this.y < min.y ) { this.y = min.y; } else if ( this.y > max.y ) { this.y = max.y; } if ( this.z < min.z ) { this.z = min.z; } else if ( this.z > max.z ) { this.z = max.z; } return this; }, clampScalar: ( function () { var min, max; return function ( minVal, maxVal ) { if ( min === undefined ) { min = new THREE.Vector3(); max = new THREE.Vector3(); } min.set( minVal, minVal, minVal ); max.set( maxVal, maxVal, maxVal ); return this.clamp( min, max ); }; } )(), floor: function () { this.x = Math.floor( this.x ); this.y = Math.floor( this.y ); this.z = Math.floor( this.z ); return this; }, ceil: function () { this.x = Math.ceil( this.x ); this.y = Math.ceil( this.y ); this.z = Math.ceil( this.z ); return this; }, round: function () { this.x = Math.round( this.x ); this.y = Math.round( this.y ); this.z = Math.round( this.z ); return this; }, roundToZero: function () { this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x ); this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y ); this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z ); return this; }, negate: function () { this.x = - this.x; this.y = - this.y; this.z = - this.z; return this; }, dot: function ( v ) { return this.x * v.x + this.y * v.y + this.z * v.z; }, lengthSq: function () { return this.x * this.x + this.y * this.y + this.z * this.z; }, length: function () { return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z ); }, lengthManhattan: function () { return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ); }, normalize: function () { return this.divideScalar( this.length() ); }, setLength: function ( l ) { var oldLength = this.length(); if ( oldLength !== 0 && l !== oldLength ) { this.multiplyScalar( l / oldLength ); } return this; }, lerp: function ( v, alpha ) { this.x += ( v.x - this.x ) * alpha; this.y += ( v.y - this.y ) * alpha; this.z += ( v.z - this.z ) * alpha; return this; }, cross: function ( v, w ) { if ( w !== undefined ) { console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' ); return this.crossVectors( v, w ); } var x = this.x, y = this.y, z = this.z; this.x = y * v.z - z * v.y; this.y = z * v.x - x * v.z; this.z = x * v.y - y * v.x; return this; }, crossVectors: function ( a, b ) { var ax = a.x, ay = a.y, az = a.z; var bx = b.x, by = b.y, bz = b.z; this.x = ay * bz - az * by; this.y = az * bx - ax * bz; this.z = ax * by - ay * bx; return this; }, projectOnVector: function () { var v1, dot; return function ( vector ) { if ( v1 === undefined ) v1 = new THREE.Vector3(); v1.copy( vector ).normalize(); dot = this.dot( v1 ); return this.copy( v1 ).multiplyScalar( dot ); }; }(), projectOnPlane: function () { var v1; return function ( planeNormal ) { if ( v1 === undefined ) v1 = new THREE.Vector3(); v1.copy( this ).projectOnVector( planeNormal ); return this.sub( v1 ); } }(), reflect: function () { // reflect incident vector off plane orthogonal to normal // normal is assumed to have unit length var v1; return function ( normal ) { if ( v1 === undefined ) v1 = new THREE.Vector3(); return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) ); } }(), angleTo: function ( v ) { var theta = this.dot( v ) / ( this.length() * v.length() ); // clamp, to handle numerical problems return Math.acos( THREE.Math.clamp( theta, - 1, 1 ) ); }, distanceTo: function ( v ) { return Math.sqrt( this.distanceToSquared( v ) ); }, distanceToSquared: function ( v ) { var dx = this.x - v.x; var dy = this.y - v.y; var dz = this.z - v.z; return dx * dx + dy * dy + dz * dz; }, setEulerFromRotationMatrix: function ( m, order ) { console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' ); }, setEulerFromQuaternion: function ( q, order ) { console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' ); }, getPositionFromMatrix: function ( m ) { console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' ); return this.setFromMatrixPosition( m ); }, getScaleFromMatrix: function ( m ) { console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' ); return this.setFromMatrixScale( m ); }, getColumnFromMatrix: function ( index, matrix ) { console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' ); return this.setFromMatrixColumn( index, matrix ); }, setFromMatrixPosition: function ( m ) { this.x = m.elements[ 12 ]; this.y = m.elements[ 13 ]; this.z = m.elements[ 14 ]; return this; }, setFromMatrixScale: function ( m ) { var sx = this.set( m.elements[ 0 ], m.elements[ 1 ], m.elements[ 2 ] ).length(); var sy = this.set( m.elements[ 4 ], m.elements[ 5 ], m.elements[ 6 ] ).length(); var sz = this.set( m.elements[ 8 ], m.elements[ 9 ], m.elements[ 10 ] ).length(); this.x = sx; this.y = sy; this.z = sz; return this; }, setFromMatrixColumn: function ( index, matrix ) { var offset = index * 4; var me = matrix.elements; this.x = me[ offset ]; this.y = me[ offset + 1 ]; this.z = me[ offset + 2 ]; return this; }, equals: function ( v ) { return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) ); }, fromArray: function ( array, offset ) { if ( offset === undefined ) offset = 0; this.x = array[ offset ]; this.y = array[ offset + 1 ]; this.z = array[ offset + 2 ]; return this; }, toArray: function ( array, offset ) { if ( array === undefined ) array = []; if ( offset === undefined ) offset = 0; array[ offset ] = this.x; array[ offset + 1 ] = this.y; array[ offset + 2 ] = this.z; return array; }, fromAttribute: function ( attribute, index, offset ) { if ( offset === undefined ) offset = 0; index = index * attribute.itemSize + offset; this.x = attribute.array[ index ]; this.y = attribute.array[ index + 1 ]; this.z = attribute.array[ index + 2 ]; return this; }, clone: function () { return new THREE.Vector3( this.x, this.y, this.z ); } };
ANGULAR1_TUT = [ { id: "0", title: 'Bootstrapping', seoTitle: 'Bootstrapping', route: "tutorials.angular1.bootstrapping", path: "/tutorials/angular1/bootstrapping", contentTemplate: 'tutorial.step_00.html', video: '//www.youtube.com/embed/s2RWlIrkCaE?list=PLhCf3AUOg4PgQoY_A6xWDQ70yaNtPYtZd', commitDiff: 'a00a945d0a503c99efaff1e9a20dfe6f9205821f' }, { id: "1", title: 'Static Template', seoTitle: 'Static Template', route: "tutorials.angular1.static-template", path: "/tutorials/angular1/static-template", contentTemplate: 'tutorial.step_01.html', video: '//www.youtube.com/embed/xUod-yoDfEE?list=PLhCf3AUOg4PgQoY_A6xWDQ70yaNtPYtZd' }, { id: "2", title: 'Dynamic Template', seoTitle: 'Dynamic Template', route: "tutorials.angular1.dynamic-template", path: "/tutorials/angular1/dynamic-template", contentTemplate: 'tutorial.step_02.html', video: '//www.youtube.com/embed/xUod-yoDfEE?list=PLhCf3AUOg4PgQoY_A6xWDQ70yaNtPYtZd' }, { id: "3", title: '3-Way data binding', seoTitle: '3-Way data binding', route: "tutorials.angular1.3-way-data-binding", path: "/tutorials/angular1/3-way-data-binding", contentTemplate: 'tutorial.step_03.html', video: '//www.youtube.com/embed/xUod-yoDfEE?list=PLhCf3AUOg4PgQoY_A6xWDQ70yaNtPYtZd' }, { id: "4", title: 'Adding/removing objects and Angular event handling', seoTitle: 'Adding/removing objects and Angular event handling', route: "tutorials.angular1.adding-removing-objects-and-angular-event-handling", path: "/tutorials/angular1/adding-removing-objects-and-angular-event-handling", contentTemplate: 'tutorial.step_04.html', video: '//www.youtube.com/embed/ijKsWglJI0k?list=PLhCf3AUOg4PgQoY_A6xWDQ70yaNtPYtZd' }, { id: "5", title: 'Routing & Multiple Views', seoTitle: 'Routing and Multiple Views', route: "tutorials.angular1.routing-and-multiple-views", path: "/tutorials/angular1/routing-and-multiple-views", contentTemplate: 'tutorial.step_05.html', video: '//www.youtube.com/embed/oScHP7Vd7as?list=PLhCf3AUOg4PgQoY_A6xWDQ70yaNtPYtZd' }, { id: "6", title: 'Bind one object', seoTitle: 'Bind one object', route: "tutorials.angular1.bind-one-object", path: "/tutorials/angular1/bind-one-object", contentTemplate: 'tutorial.step_06.html', video: '//www.youtube.com/embed/kRen9GlR3K8?list=PLhCf3AUOg4PgQoY_A6xWDQ70yaNtPYtZd' }, { id: "7", title: 'Folder structure', seoTitle: 'Folder structure', route: "tutorials.angular1.folder-structure", path: "/tutorials/angular1/folder-structure", contentTemplate: 'tutorial.step_07.html', video: '//www.youtube.com/embed/l3nTv4GuJrY?list=PLhCf3AUOg4PgQoY_A6xWDQ70yaNtPYtZd' }, { id: "8", title: 'User accounts, authentication and permissions', seoTitle: 'User accounts, authentication and permissions', route: "tutorials.angular1.user-accounts-authentication-and-permissions", path: "/tutorials/angular1/user-accounts-authentication-and-permissions", contentTemplate: 'tutorial.step_08.html', video: '//www.youtube.com/embed/PgS-IAMn9Ig?list=PLhCf3AUOg4PgQoY_A6xWDQ70yaNtPYtZd' }, { id: "9", title: 'Privacy and publish-subscribe functions', seoTitle: 'Privacy and publish-subscribe functions', route: "tutorials.angular1.privacy-and-publish-subscribe-functions", path: "/tutorials/angular1/privacy-and-publish-subscribe-functions", contentTemplate: 'tutorial.step_09.html', video: '//www.youtube.com/embed/wAHi7ilDHko?list=PLhCf3AUOg4PgQoY_A6xWDQ70yaNtPYtZd' }, { id: "10", title: 'Deploying your app', seoTitle: 'Deploying your app', route: "tutorials.angular1.deploying-your-app", path: "/tutorials/angular1/deploying-your-app", contentTemplate: 'tutorial.step_10.html', video: '//www.youtube.com/embed/2WnZBKv9H9o?list=PLhCf3AUOg4PgQoY_A6xWDQ70yaNtPYtZd' }, { id: "11", title: 'Running your app on Android or iOS with PhoneGap', seoTitle: 'Running your app on Android or iOS with PhoneGap', route: "tutorials.angular1.running-your-app-on-android-or-ios-with-phoneGap", path: "/tutorials/angular1/running-your-app-on-android-or-ios-with-phoneGap", contentTemplate: 'tutorial.step_11.html', video: '//www.youtube.com/embed/5vZOI2fi13U?list=PLhCf3AUOg4PgQoY_A6xWDQ70yaNtPYtZd' }, { id: "12", title: 'Search, sort, pagination and reactive vars', seoTitle: 'Search, sort, pagination and reactive vars', route: "tutorials.angular1.search-sort-pagination-and-reactive-vars", path: "/tutorials/angular1/search-sort-pagination-and-reactive-vars", contentTemplate: 'tutorial.step_12.html', video: '//www.youtube.com/embed/8XQI2XpyH18?list=PLhCf3AUOg4PgQoY_A6xWDQ70yaNtPYtZd' }, { id: "13", title: 'Using and creating AngularJS filters', seoTitle: 'Using and creating AngularJS filters', route: "tutorials.angular1.using-and-creating-angularjs-filters", path: "/tutorials/angular1/using-and-creating-angularjs-filters", contentTemplate: 'tutorial.step_13.html', video: '//www.youtube.com/embed/S049FI8TP4A?list=PLhCf3AUOg4PgQoY_A6xWDQ70yaNtPYtZd' }, { id: "14", title: 'Meteor methods with promises', seoTitle: 'Meteor methods with promises', route: "tutorials.angular1.meteor-methods-with-promises", path: "/tutorials/angular1/meteor-methods-with-promises", contentTemplate: 'tutorial.step_14.html', video: '//www.youtube.com/embed/qNUjZjfaYt8?list=PLhCf3AUOg4PgQoY_A6xWDQ70yaNtPYtZd' }, { id: "15", title: 'Conditional template directives with AngularJS', seoTitle: 'Conditional template directives with AngularJS', route: "tutorials.angular1.conditional-template-directives-with-angularjs", path: "/tutorials/angular1/conditional-template-directives-with-angularjs", contentTemplate: 'tutorial.step_15.html', video: '//www.youtube.com/embed/KSlVThsNCss?list=PLhCf3AUOg4PgQoY_A6xWDQ70yaNtPYtZd' }, { id: "16", title: 'Google Maps', seoTitle: 'Google Maps', route: "tutorials.angular1.google-maps", path: "/tutorials/angular1/google-maps", contentTemplate: 'tutorial.step_16.html', video: '//www.youtube.com/embed/A6qsm_RDc9Y?list=PLhCf3AUOg4PgQoY_A6xWDQ70yaNtPYtZd' }, { id: "17", title: 'CSS, LESS and Bootstrap', seoTitle: 'CSS, LESS and Bootstrap', route: "tutorials.angular1.css-less-and-bootstrap", path: "/tutorials/angular1/css-less-and-bootstrap", contentTemplate: 'tutorial.step_17.html', video: '//www.youtube.com/embed/A6qsm_RDc9Y?list=PLhCf3AUOg4PgQoY_A6xWDQ70yaNtPYtZd' }, { id: "18", title: 'angular-material and custom Angular auth forms', seoTitle: 'angular-material and custom Angular auth forms', route: "tutorials.angular1.angular-material-and-custom-angular-auth-forms", path: "/tutorials/angular1/angular-material-and-custom-angular-auth-forms", contentTemplate: 'tutorial.step_18.html', video: '//www.youtube.com/embed/A6qsm_RDc9Y?list=PLhCf3AUOg4PgQoY_A6xWDQ70yaNtPYtZd' }, { id: "19", title: '3rdParty Libraries', seoTitle: '3rdParty Libraries', route: "tutorials.angular1.3rd-party-libraries", path: "/tutorials/angular1/3rd-party-libraries", contentTemplate: 'tutorial.step_19.html', video: '//www.youtube.com/embed/A6qsm_RDc9Y?list=PLhCf3AUOg4PgQoY_A6xWDQ70yaNtPYtZd' }, { id: "20", title: 'Handling Files with CollectionFS', seoTitle: 'Handling Files with CollectionFS', route: "tutorials.angular1.handling-files-with-collectionfs", path: "/tutorials/angular1/handling-files-with-collectionfs", contentTemplate: 'tutorial.step_20.html', video: '//www.youtube.com/embed/A6qsm_RDc9Y?list=PLhCf3AUOg4PgQoY_A6xWDQ70yaNtPYtZd', previousCodeStep: '18' }, { id: "21", title: 'Next Steps', seoTitle: 'Next Steps', route: "tutorials.angular1.next-steps", path: "/tutorials/angular1/next-steps", contentTemplate: 'tutorial.next_steps.html' } ];
/* * $Id: base64.js,v 2.15 2014/04/05 12:58:57 dankogai Exp dankogai $ * * Licensed under the BSD 3-Clause License. * http://opensource.org/licenses/BSD-3-Clause * * References: * http://en.wikipedia.org/wiki/Base64 */ (function(global) { 'use strict'; // existing version for noConflict() var _Base64 = global.Base64; var version = "2.1.9"; // if node.js, we use Buffer var buffer; if (typeof module !== 'undefined' && module.exports) { try { buffer = require('buffer').Buffer; } catch (err) {} } // constants var b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; var b64tab = function(bin) { var t = {}; for (var i = 0, l = bin.length; i < l; i++) t[bin.charAt(i)] = i; return t; }(b64chars); var fromCharCode = String.fromCharCode; // encoder stuff var cb_utob = function(c) { if (c.length < 2) { var cc = c.charCodeAt(0); return cc < 0x80 ? c : cc < 0x800 ? (fromCharCode(0xc0 | (cc >>> 6)) + fromCharCode(0x80 | (cc & 0x3f))) : (fromCharCode(0xe0 | ((cc >>> 12) & 0x0f)) + fromCharCode(0x80 | ((cc >>> 6) & 0x3f)) + fromCharCode(0x80 | ( cc & 0x3f))); } else { var cc = 0x10000 + (c.charCodeAt(0) - 0xD800) * 0x400 + (c.charCodeAt(1) - 0xDC00); return (fromCharCode(0xf0 | ((cc >>> 18) & 0x07)) + fromCharCode(0x80 | ((cc >>> 12) & 0x3f)) + fromCharCode(0x80 | ((cc >>> 6) & 0x3f)) + fromCharCode(0x80 | ( cc & 0x3f))); } }; var re_utob = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g; var utob = function(u) { return u.replace(re_utob, cb_utob); }; var cb_encode = function(ccc) { var padlen = [0, 2, 1][ccc.length % 3], ord = ccc.charCodeAt(0) << 16 | ((ccc.length > 1 ? ccc.charCodeAt(1) : 0) << 8) | ((ccc.length > 2 ? ccc.charCodeAt(2) : 0)), chars = [ b64chars.charAt( ord >>> 18), b64chars.charAt((ord >>> 12) & 63), padlen >= 2 ? '=' : b64chars.charAt((ord >>> 6) & 63), padlen >= 1 ? '=' : b64chars.charAt(ord & 63) ]; return chars.join(''); }; var btoa = global.btoa ? function(b) { return global.btoa(b); } : function(b) { return b.replace(/[\s\S]{1,3}/g, cb_encode); }; var _encode = buffer ? function (u) { return (u.constructor === buffer.constructor ? u : new buffer(u)) .toString('base64') } : function (u) { return btoa(utob(u)) } ; var encode = function(u, urisafe) { return !urisafe ? _encode(String(u)) : _encode(String(u)).replace(/[+\/]/g, function(m0) { return m0 == '+' ? '-' : '_'; }).replace(/=/g, ''); }; var encodeURI = function(u) { return encode(u, true) }; // decoder stuff var re_btou = new RegExp([ '[\xC0-\xDF][\x80-\xBF]', '[\xE0-\xEF][\x80-\xBF]{2}', '[\xF0-\xF7][\x80-\xBF]{3}' ].join('|'), 'g'); var cb_btou = function(cccc) { switch(cccc.length) { case 4: var cp = ((0x07 & cccc.charCodeAt(0)) << 18) | ((0x3f & cccc.charCodeAt(1)) << 12) | ((0x3f & cccc.charCodeAt(2)) << 6) | (0x3f & cccc.charCodeAt(3)), offset = cp - 0x10000; return (fromCharCode((offset >>> 10) + 0xD800) + fromCharCode((offset & 0x3FF) + 0xDC00)); case 3: return fromCharCode( ((0x0f & cccc.charCodeAt(0)) << 12) | ((0x3f & cccc.charCodeAt(1)) << 6) | (0x3f & cccc.charCodeAt(2)) ); default: return fromCharCode( ((0x1f & cccc.charCodeAt(0)) << 6) | (0x3f & cccc.charCodeAt(1)) ); } }; var btou = function(b) { return b.replace(re_btou, cb_btou); }; var cb_decode = function(cccc) { var len = cccc.length, padlen = len % 4, n = (len > 0 ? b64tab[cccc.charAt(0)] << 18 : 0) | (len > 1 ? b64tab[cccc.charAt(1)] << 12 : 0) | (len > 2 ? b64tab[cccc.charAt(2)] << 6 : 0) | (len > 3 ? b64tab[cccc.charAt(3)] : 0), chars = [ fromCharCode( n >>> 16), fromCharCode((n >>> 8) & 0xff), fromCharCode( n & 0xff) ]; chars.length -= [0, 0, 2, 1][padlen]; return chars.join(''); }; var atob = global.atob ? function(a) { return global.atob(a); } : function(a){ return a.replace(/[\s\S]{1,4}/g, cb_decode); }; var _decode = buffer ? function(a) { return (a.constructor === buffer.constructor ? a : new buffer(a, 'base64')).toString(); } : function(a) { return btou(atob(a)) }; var decode = function(a){ return _decode( String(a).replace(/[-_]/g, function(m0) { return m0 == '-' ? '+' : '/' }) .replace(/[^A-Za-z0-9\+\/]/g, '') ); }; var noConflict = function() { var Base64 = global.Base64; global.Base64 = _Base64; return Base64; }; // export Base64 global.Base64 = { VERSION: version, atob: atob, btoa: btoa, fromBase64: decode, toBase64: encode, utob: utob, encode: encode, encodeURI: encodeURI, btou: btou, decode: decode, noConflict: noConflict }; // if ES5 is available, make Base64.extendString() available if (typeof Object.defineProperty === 'function') { var noEnum = function(v){ return {value:v,enumerable:false,writable:true,configurable:true}; }; global.Base64.extendString = function () { Object.defineProperty( String.prototype, 'fromBase64', noEnum(function () { return decode(this) })); Object.defineProperty( String.prototype, 'toBase64', noEnum(function (urisafe) { return encode(this, urisafe) })); Object.defineProperty( String.prototype, 'toBase64URI', noEnum(function () { return encode(this, true) })); }; } // that's it! if (global['Meteor']) { Base64 = global.Base64; // for normal export in Meteor.js } })(this);
define(["./kernel", "./lang", "./array", "./config"], function(dojo, lang, ArrayUtil, config){ var Color = dojo.Color = function(/*Array|String|Object*/ color){ // summary: // Takes a named string, hex string, array of rgb or rgba values, // an object with r, g, b, and a properties, or another `Color` object // and creates a new Color instance to work from. // // example: // Work with a Color instance: // | require(["dojo/_base/color"], function(Color){ // | var c = new Color(); // | c.setColor([0,0,0]); // black // | var hex = c.toHex(); // #000000 // | }); // // example: // Work with a node's color: // | // | require(["dojo/_base/color", "dojo/dom-style"], function(Color, domStyle){ // | var color = domStyle("someNode", "backgroundColor"); // | var n = new Color(color); // | // adjust the color some // | n.r *= .5; // | console.log(n.toString()); // rgb(128, 255, 255); // | }); if(color){ this.setColor(color); } }; // FIXME: // there's got to be a more space-efficient way to encode or discover // these!! Use hex? Color.named = { // summary: // Dictionary list of all CSS named colors, by name. Values are 3-item arrays with corresponding RG and B values. "black": [0,0,0], "silver": [192,192,192], "gray": [128,128,128], "white": [255,255,255], "maroon": [128,0,0], "red": [255,0,0], "purple": [128,0,128], "fuchsia":[255,0,255], "green": [0,128,0], "lime": [0,255,0], "olive": [128,128,0], "yellow": [255,255,0], "navy": [0,0,128], "blue": [0,0,255], "teal": [0,128,128], "aqua": [0,255,255], "transparent": config.transparentColor || [0,0,0,0] }; lang.extend(Color, { r: 255, g: 255, b: 255, a: 1, _set: function(r, g, b, a){ var t = this; t.r = r; t.g = g; t.b = b; t.a = a; }, setColor: function(/*Array|String|Object*/ color){ // summary: // Takes a named string, hex string, array of rgb or rgba values, // an object with r, g, b, and a properties, or another `Color` object // and sets this color instance to that value. // // example: // | require(["dojo/_base/color"], function(Color){ // | var c = new Color(); // no color // | c.setColor("#ededed"); // greyish // | }); if(lang.isString(color)){ Color.fromString(color, this); }else if(lang.isArray(color)){ Color.fromArray(color, this); }else{ this._set(color.r, color.g, color.b, color.a); if(!(color instanceof Color)){ this.sanitize(); } } return this; // Color }, sanitize: function(){ // summary: // Ensures the object has correct attributes // description: // the default implementation does nothing, include dojo.colors to // augment it with real checks return this; // Color }, toRgb: function(){ // summary: // Returns 3 component array of rgb values // example: // | require(["dojo/_base/color"], function(Color){ // | var c = new Color("#000000"); // | console.log(c.toRgb()); // [0,0,0] // | }); var t = this; return [t.r, t.g, t.b]; // Array }, toRgba: function(){ // summary: // Returns a 4 component array of rgba values from the color // represented by this object. var t = this; return [t.r, t.g, t.b, t.a]; // Array }, toHex: function(){ // summary: // Returns a CSS color string in hexadecimal representation // example: // | require(["dojo/_base/color"], function(Color){ // | console.log(new Color([0,0,0]).toHex()); // #000000 // | }); var arr = ArrayUtil.map(["r", "g", "b"], function(x){ var s = this[x].toString(16); return s.length < 2 ? "0" + s : s; }, this); return "#" + arr.join(""); // String }, toCss: function(/*Boolean?*/ includeAlpha){ // summary: // Returns a css color string in rgb(a) representation // example: // | require(["dojo/_base/color"], function(Color){ // | var c = new Color("#FFF").toCss(); // | console.log(c); // rgb('255','255','255') // | }); var t = this, rgb = t.r + ", " + t.g + ", " + t.b; return (includeAlpha ? "rgba(" + rgb + ", " + t.a : "rgb(" + rgb) + ")"; // String }, toString: function(){ // summary: // Returns a visual representation of the color return this.toCss(true); // String } }); Color.blendColors = dojo.blendColors = function( /*Color*/ start, /*Color*/ end, /*Number*/ weight, /*Color?*/ obj ){ // summary: // Blend colors end and start with weight from 0 to 1, 0.5 being a 50/50 blend, // can reuse a previously allocated Color object for the result var t = obj || new Color(); t.r = Math.round(start.r + (end.r - start.r) * weight); t.g = Math.round(start.g + (end.g - start.g) * weight); t.b = Math.round(start.b + (end.b - start.b) * weight); t.a = start.a + (end.a - start.a) * weight; return t.sanitize(); // Color }; Color.fromRgb = dojo.colorFromRgb = function(/*String*/ color, /*Color?*/ obj){ // summary: // Returns a `Color` instance from a string of the form // "rgb(...)" or "rgba(...)". Optionally accepts a `Color` // object to update with the parsed value and return instead of // creating a new object. // returns: // A Color object. If obj is passed, it will be the return value. var m = color.toLowerCase().match(/^rgba?\(([\s\.,0-9]+)\)/); return m && Color.fromArray(m[1].split(/\s*,\s*/), obj); // Color }; Color.fromHex = dojo.colorFromHex = function(/*String*/ color, /*Color?*/ obj){ // summary: // Converts a hex string with a '#' prefix to a color object. // Supports 12-bit #rgb shorthand. Optionally accepts a // `Color` object to update with the parsed value. // // returns: // A Color object. If obj is passed, it will be the return value. // // example: // | require(["dojo/_base/color"], function(Color){ // | var thing = new Color().fromHex("#ededed"); // grey, longhand // | var thing2 = new Color().fromHex("#000"); // black, shorthand // | }); var t = obj || new Color(), bits = (color.length == 4) ? 4 : 8, mask = (1 << bits) - 1; color = Number("0x" + color.substr(1)); if(isNaN(color)){ return null; // Color } ArrayUtil.forEach(["b", "g", "r"], function(x){ var c = color & mask; color >>= bits; t[x] = bits == 4 ? 17 * c : c; }); t.a = 1; return t; // Color }; Color.fromArray = dojo.colorFromArray = function(/*Array*/ a, /*Color?*/ obj){ // summary: // Builds a `Color` from a 3 or 4 element array, mapping each // element in sequence to the rgb(a) values of the color. // example: // | require(["dojo/_base/color"], function(Color){ // | var myColor = new Color().fromArray([237,237,237,0.5]); // grey, 50% alpha // | }); // returns: // A Color object. If obj is passed, it will be the return value. var t = obj || new Color(); t._set(Number(a[0]), Number(a[1]), Number(a[2]), Number(a[3])); if(isNaN(t.a)){ t.a = 1; } return t.sanitize(); // Color }; Color.fromString = dojo.colorFromString = function(/*String*/ str, /*Color?*/ obj){ // summary: // Parses `str` for a color value. Accepts hex, rgb, and rgba // style color values. // description: // Acceptable input values for str may include arrays of any form // accepted by dojo.colorFromArray, hex strings such as "#aaaaaa", or // rgb or rgba strings such as "rgb(133, 200, 16)" or "rgba(10, 10, // 10, 50)" // returns: // A Color object. If obj is passed, it will be the return value. var a = Color.named[str]; return a && Color.fromArray(a, obj) || Color.fromRgb(str, obj) || Color.fromHex(str, obj); // Color }; return Color; });
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _streamConfig = require('./schemas/streamConfig.json'); var _streamConfig2 = _interopRequireDefault(_streamConfig); var _tv = require('tv4'); var _tv2 = _interopRequireDefault(_tv); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * @typedef {string} cell */ /** * @typedef {cell[]} validateData~column */ /** * @param {formatData~config} config * @returns {undefined} */ exports.default = function () { var config = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var result = void 0; result = _tv2.default.validateResult(config, _streamConfig2.default); if (!result.valid) { /* eslint-disable no-console */ console.log('config', config); console.log('error', { message: result.error.message, params: result.error.params, dataPath: result.error.dataPath, schemaPath: result.error.schemaPath }); /* eslint-enable no-console */ throw new Error('Invalid config.'); } }; module.exports = exports['default']; //# sourceMappingURL=validateStreamConfig.js.map
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); }; import { Injectable } from 'angular2/core'; /** * A backend for http that uses the `XMLHttpRequest` browser API. * * Take care not to evaluate this in non-browser contexts. */ export let BrowserXhr = class { constructor() { } build() { return (new XMLHttpRequest()); } }; BrowserXhr = __decorate([ Injectable(), __metadata('design:paramtypes', []) ], BrowserXhr);
/* * bootstrap-table - v1.8.0 - 2015-05-22 * https://github.com/wenzhixin/bootstrap-table * Copyright (c) 2015 zhixin wen * Licensed MIT License */ !function(a){"use strict";a.fn.bootstrapTable.locales["ar-SA"]={formatLoadingMessage:function(){return"جاري التحميل, يرجى الإنتظار..."},formatRecordsPerPage:function(a){return a+" سجل لكل صفحة"},formatShowingRows:function(a,b,c){return"الظاهر "+a+" إلى "+b+" من "+c+" سجل"},formatSearch:function(){return"بحث"},formatNoMatches:function(){return"لا توجد نتائج مطابقة للبحث"},formatPaginationSwitch:function(){return"إخفاءإظهار ترقيم الصفحات"},formatRefresh:function(){return"تحديث"},formatToggle:function(){return"تغيير"},formatColumns:function(){return"أعمدة"}},a.extend(a.fn.bootstrapTable.defaults,a.fn.bootstrapTable.locales["ar-SA"])}(jQuery);
module.exports = /******/ (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] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.l = 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; /******/ // identity function for calling harmory imports with the correct context /******/ __webpack_require__.i = function(value) { return value; }; /******/ // define getter function for harmory exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ }; /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 228); /******/ }) /************************************************************************/ /******/ ({ /***/ 117: /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /***/ 150: /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ /* styles */ __webpack_require__(117) /* script */ __vue_exports__ = __webpack_require__(71) /* template */ var __vue_template__ = __webpack_require__(184) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns module.exports = __vue_exports__ /***/ }, /***/ 184: /***/ function(module, exports) { module.exports={render:function (){with(this) { return _h('div', { staticClass: "mint-swipe" }, [_h('div', { ref: "wrap", staticClass: "mint-swipe-items-wrap" }, [_t("default")]), " ", _h('div', { directives: [{ name: "show", value: (showIndicators), expression: "showIndicators" }], staticClass: "mint-swipe-indicators" }, [(pages) && _l((pages), function(page, $index) { return _h('div', { staticClass: "mint-swipe-indicator", class: { 'is-active': $index === index } }) })])]) }},staticRenderFns: []} /***/ }, /***/ 195: /***/ function(module, exports) { var trim = function (string) { return (string || '').replace(/^[\s\uFEFF]+|[\s\uFEFF]+$/g, ''); }; var hasClass = function (el, cls) { if (!el || !cls) return false; if (cls.indexOf(' ') != -1) throw new Error('className should not contain space.'); if (el.classList) { return el.classList.contains(cls); } else { return (' ' + el.className + ' ').indexOf(' ' + cls + ' ') > -1; } }; var addClass = function (el, cls) { if (!el) return; var curClass = el.className; var classes = (cls || '').split(' '); for (var i = 0, j = classes.length; i < j; i++) { var clsName = classes[i]; if (!clsName) continue; if (el.classList) { el.classList.add(clsName); } else { if (!hasClass(el, clsName)) { curClass += ' ' + clsName; } } } if (!el.classList) { el.className = curClass; } }; var removeClass = function (el, cls) { if (!el || !cls) return; var classes = cls.split(' '); var curClass = ' ' + el.className + ' '; for (var i = 0, j = classes.length; i < j; i++) { var clsName = classes[i]; if (!clsName) continue; if (el.classList) { el.classList.remove(clsName); } else { if (hasClass(el, clsName)) { curClass = curClass.replace(' ' + clsName + ' ', ' '); } } } if (!el.classList) { el.className = trim(curClass); } }; module.exports = { hasClass: hasClass, addClass: addClass, removeClass: removeClass }; /***/ }, /***/ 196: /***/ function(module, exports) { var bindEvent = (function() { if(document.addEventListener) { return function(element, event, handler) { if (element && event && handler) { element.addEventListener(event, handler, false); } }; } else { return function(element, event, handler) { if (element && event && handler) { element.attachEvent('on' + event, handler); } }; } })(); var unbindEvent = (function() { if(document.removeEventListener) { return function(element, event, handler) { if (element && event) { element.removeEventListener(event, handler, false); } }; } else { return function(element, event, handler) { if (element && event) { element.detachEvent('on' + event, handler); } }; } })(); var bindOnce = function(el, event, fn) { var listener = function() { if (fn) { fn.apply(this, arguments); } unbindEvent(el, event, listener); }; bindEvent(el, event, listener); }; module.exports = { on: bindEvent, off: unbindEvent, once: bindOnce }; /***/ }, /***/ 228: /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(37); /***/ }, /***/ 37: /***/ function(module, exports, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__src_swipe_vue__ = __webpack_require__(150); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__src_swipe_vue___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0__src_swipe_vue__); /* harmony default export */ exports["default"] = __WEBPACK_IMPORTED_MODULE_0__src_swipe_vue___default.a; /***/ }, /***/ 71: /***/ function(module, exports, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_wind_dom_src_event__ = __webpack_require__(196); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_wind_dom_src_event___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_wind_dom_src_event__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_wind_dom_src_class__ = __webpack_require__(195); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_wind_dom_src_class___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1_wind_dom_src_class__); // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // /* harmony default export */ exports["default"] = { name: 'mt-swipe', created: function created() { this.dragState = {}; }, data: function data() { return { ready: false, dragging: false, userScrolling: false, animating: false, index: 0, pages: [], timer: null, reInitTimer: null, noDrag: false }; }, props: { speed: { type: Number, default: 300 }, auto: { type: Number, default: 3000 }, continuous: { type: Boolean, default: true }, showIndicators: { type: Boolean, default: true }, noDragWhenSingle: { type: Boolean, default: true }, prevent: { type: Boolean, default: false } }, methods: { swipeItemCreated: function swipeItemCreated() { var this$1 = this; if (!this.ready) return; clearTimeout(this.reInitTimer); this.reInitTimer = setTimeout(function () { this$1.reInitPages(); }, 100); }, swipeItemDestroyed: function swipeItemDestroyed() { var this$1 = this; if (!this.ready) return; clearTimeout(this.reInitTimer); this.reInitTimer = setTimeout(function () { this$1.reInitPages(); }, 100); }, translate: function translate(element, offset, speed, callback) { var arguments$1 = arguments; var this$1 = this; if (speed) { this.animating = true; element.style.webkitTransition = '-webkit-transform ' + speed + 'ms ease-in-out'; setTimeout(function () { element.style.webkitTransform = "translate3d(" + offset + "px, 0, 0)"; }, 50); var called = false; var transitionEndCallback = function () { if (called) return; called = true; this$1.animating = false; element.style.webkitTransition = ''; element.style.webkitTransform = ''; if (callback) { callback.apply(this$1, arguments$1); } }; __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0_wind_dom_src_event__["once"])(element, 'webkitTransitionEnd', transitionEndCallback); setTimeout(transitionEndCallback, speed + 100); // webkitTransitionEnd maybe not fire on lower version android. } else { element.style.webkitTransition = ''; element.style.webkitTransform = "translate3d(" + offset + "px, 0, 0)"; } }, reInitPages: function reInitPages() { var children = this.$children; this.noDrag = children.length === 1 && this.noDragWhenSingle; var pages = []; this.index = 0; children.forEach(function(child, index) { pages.push(child.$el); __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1_wind_dom_src_class__["removeClass"])(child.$el, 'is-active'); if (index === 0) { __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1_wind_dom_src_class__["addClass"])(child.$el, 'is-active'); } }); this.pages = pages; }, doAnimate: function doAnimate(towards, options) { var this$1 = this; if (this.$children.length === 0) return; if (!options && this.$children.length < 2) return; var prevPage, nextPage, currentPage, pageWidth, offsetLeft; var speed = this.speed || 300; var index = this.index; var pages = this.pages; var pageCount = pages.length; if (!options) { pageWidth = this.$el.clientWidth; currentPage = pages[index]; prevPage = pages[index - 1]; nextPage = pages[index + 1]; if (this.continuous && pages.length > 1) { if (!prevPage) { prevPage = pages[pages.length - 1]; } if (!nextPage) { nextPage = pages[0]; } } if (prevPage) { prevPage.style.display = 'block'; this.translate(prevPage, -pageWidth); } if (nextPage) { nextPage.style.display = 'block'; this.translate(nextPage, pageWidth); } } else { prevPage = options.prevPage; currentPage = options.currentPage; nextPage = options.nextPage; pageWidth = options.pageWidth; offsetLeft = options.offsetLeft; } var newIndex; var oldPage = this.$children[index].$el; if (towards === 'prev') { if (index > 0) { newIndex = index - 1; } if (this.continuous && index === 0) { newIndex = pageCount - 1; } } else if (towards === 'next') { if (index < pageCount - 1) { newIndex = index + 1; } if (this.continuous && index === pageCount - 1) { newIndex = 0; } } var callback = function () { if (newIndex !== undefined) { var newPage = this$1.$children[newIndex].$el; __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1_wind_dom_src_class__["removeClass"])(oldPage, 'is-active'); __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1_wind_dom_src_class__["addClass"])(newPage, 'is-active'); this$1.index = newIndex; } if (prevPage) { prevPage.style.display = ''; } if (nextPage) { nextPage.style.display = ''; } }; setTimeout(function () { if (towards === 'next') { this$1.translate(currentPage, -pageWidth, speed, callback); if (nextPage) { this$1.translate(nextPage, 0, speed); } } else if (towards === 'prev') { this$1.translate(currentPage, pageWidth, speed, callback); if (prevPage) { this$1.translate(prevPage, 0, speed); } } else { this$1.translate(currentPage, 0, speed, callback); if (typeof offsetLeft !== 'undefined') { if (prevPage && offsetLeft > 0) { this$1.translate(prevPage, pageWidth * -1, speed); } if (nextPage && offsetLeft < 0) { this$1.translate(nextPage, pageWidth, speed); } } else { if (prevPage) { this$1.translate(prevPage, pageWidth * -1, speed); } if (nextPage) { this$1.translate(nextPage, pageWidth, speed); } } } }, 10); }, next: function next() { this.doAnimate('next'); }, prev: function prev() { this.doAnimate('prev'); }, doOnTouchStart: function doOnTouchStart(event) { if (this.noDrag) return; var element = this.$el; var dragState = this.dragState; var touch = event.touches[0]; dragState.startTime = new Date(); dragState.startLeft = touch.pageX; dragState.startTop = touch.pageY; dragState.startTopAbsolute = touch.clientY; dragState.pageWidth = element.offsetWidth; dragState.pageHeight = element.offsetHeight; var prevPage = this.$children[this.index - 1]; var dragPage = this.$children[this.index]; var nextPage = this.$children[this.index + 1]; if (this.continuous && this.pages.length > 1) { if (!prevPage) { prevPage = this.$children[this.$children.length - 1]; } if (!nextPage) { nextPage = this.$children[0]; } } dragState.prevPage = prevPage ? prevPage.$el : null; dragState.dragPage = dragPage ? dragPage.$el : null; dragState.nextPage = nextPage ? nextPage.$el : null; if (dragState.prevPage) { dragState.prevPage.style.display = 'block'; } if (dragState.nextPage) { dragState.nextPage.style.display = 'block'; } }, doOnTouchMove: function doOnTouchMove(event) { if (this.noDrag) return; var dragState = this.dragState; var touch = event.touches[0]; dragState.currentLeft = touch.pageX; dragState.currentTop = touch.pageY; dragState.currentTopAbsolute = touch.clientY; var offsetLeft = dragState.currentLeft - dragState.startLeft; var offsetTop = dragState.currentTopAbsolute - dragState.startTopAbsolute; var distanceX = Math.abs(offsetLeft); var distanceY = Math.abs(offsetTop); if (distanceX < 5 || (distanceX >= 5 && distanceY >= 1.73 * distanceX)) { this.userScrolling = true; return; } else { this.userScrolling = false; event.preventDefault(); } offsetLeft = Math.min(Math.max(-dragState.pageWidth + 1, offsetLeft), dragState.pageWidth - 1); var towards = offsetLeft < 0 ? 'next' : 'prev'; if (dragState.prevPage && towards === 'prev') { this.translate(dragState.prevPage, offsetLeft - dragState.pageWidth); } this.translate(dragState.dragPage, offsetLeft); if (dragState.nextPage && towards === 'next') { this.translate(dragState.nextPage, offsetLeft + dragState.pageWidth); } }, doOnTouchEnd: function doOnTouchEnd() { if (this.noDrag) return; var dragState = this.dragState; var dragDuration = new Date() - dragState.startTime; var towards = null; var offsetLeft = dragState.currentLeft - dragState.startLeft; var offsetTop = dragState.currentTop - dragState.startTop; var pageWidth = dragState.pageWidth; var index = this.index; var pageCount = this.pages.length; if (dragDuration < 300) { var fireTap = Math.abs(offsetLeft) < 5 && Math.abs(offsetTop) < 5; if (isNaN(offsetLeft) || isNaN(offsetTop)) { fireTap = true; } if (fireTap) { this.$children[this.index].$emit('tap'); } } if (dragDuration < 300 && dragState.currentLeft === undefined) return; if (dragDuration < 300 || Math.abs(offsetLeft) > pageWidth / 2) { towards = offsetLeft < 0 ? 'next' : 'prev'; } if (!this.continuous) { if ((index === 0 && towards === 'prev') || (index === pageCount - 1 && towards === 'next')) { towards = null; } } if (this.$children.length < 2) { towards = null; } this.doAnimate(towards, { offsetLeft: offsetLeft, pageWidth: dragState.pageWidth, prevPage: dragState.prevPage, currentPage: dragState.dragPage, nextPage: dragState.nextPage }); this.dragState = {}; } }, destroyed: function destroyed() { if (this.timer) { clearInterval(this.timer); this.timer = null; } if (this.reInitTimer) { clearTimeout(this.reInitTimer); this.reInitTimer = null; } }, mounted: function mounted() { var this$1 = this; this.ready = true; if (this.auto > 0) { this.timer = setInterval(function () { if (!this$1.dragging && !this$1.animating) { this$1.next(); } }, this.auto); } this.reInitPages(); var element = this.$el; element.addEventListener('touchstart', function (event) { if (this$1.prevent) { event.preventDefault(); } if (this$1.animating) return; this$1.dragging = true; this$1.userScrolling = false; this$1.doOnTouchStart(event); }); element.addEventListener('touchmove', function (event) { if (!this$1.dragging) return; this$1.doOnTouchMove(event); }); element.addEventListener('touchend', function (event) { if (this$1.userScrolling) { this$1.dragging = false; this$1.dragState = {}; return; } if (!this$1.dragging) return; this$1.doOnTouchEnd(event); this$1.dragging = false; }); } }; /***/ } /******/ });
tinyMCE.addI18n('zh.table_dlg',{ general_tab:"\u4E00\u822C", advanced_tab:"\u9AD8\u7D1A", general_props:"\u4E00\u822C\u5C6C\u6027", advanced_props:"\u9AD8\u7D1A\u5C6C\u6027", rowtype:"\u884C\u6240\u5728\u7684\u8868\u683C\u4F4D\u7F6E", title:"\u63D2\u5165/\u7DE8\u8F2F\u8868\u683C", width:"\u5BEC\u5EA6", height:"\u9AD8\u5EA6", cols:"\u5217\u6578", rows:"\u884C\u6578", cellspacing:"\u55AE\u5143\u683C\u908A\u8DDD", cellpadding:"\u55AE\u5143\u683C\u9593\u8DDD", border:"\u908A\u6846", align:"\u5C0D\u9F4A\u65B9\u5F0F", align_default:"\u9810\u8A2D", align_left:"\u9760\u5DE6", align_right:"\u9760\u53F3", align_middle:"\u7F6E\u4E2D", row_title:"\u884C\u5C6C\u6027", cell_title:"\u55AE\u5143\u683C\u5C6C\u6027", cell_type:"\u55AE\u5143\u683C\u985E\u578B", valign:"\u6C34\u5E73\u5C0D\u9F4A\u65B9\u5F0F", align_top:"\u9760\u4E0A", align_bottom:"\u9760\u4E0B", bordercolor:"\u908A\u6846\u984F\u8272", bgcolor:"\u80CC\u666F\u984F\u8272", merge_cells_title:"\u5408\u4F75\u55AE\u5143\u683C", id:"Id", style:"\u6A23\u5F0F", langdir:"\u66F8\u5BEB\u65B9\u5411", langcode:"\u8A9E\u8A00\u7DE8\u78BC", mime:"\u76EE\u6A19MIME\u985E\u578B", ltr:"\u7531\u5DE6\u5230\u53F3", rtl:"\u7531\u53F3\u5230\u5DE6", bgimage:"\u80CC\u666F\u5716\u7247", summary:"\u6982\u8981", td:"\u55AE\u5143\u683C", th:"\u8868\u982D", cell_cell:"\u66F4\u65B0\u6240\u5728\u7684\u55AE\u5143\u683C", cell_row:"\u66F4\u65B0\u6240\u5728\u884C\u7684\u5168\u90E8\u55AE\u5143\u683C", cell_all:"\u66F4\u65B0\u8868\u683C\u5167\u7684\u5168\u90E8\u55AE\u5143\u683C", row_row:"\u66F4\u65B0\u6240\u5728\u884C", row_odd:"\u66F4\u65B0\u8868\u683C\u5167\u7684\u5947\u6578\u884C", row_even:"\u66F4\u65B0\u8868\u683C\u5167\u7684\u5076\u6578\u884C", row_all:"\u66F4\u65B0\u8868\u683C\u5167\u5168\u90E8\u884C", thead:"\u8868\u982D", tbody:"\u8868\u8EAB", tfoot:"\u8868\u5C3E", scope:"\u7BC4\u570D", rowgroup:"\u884C\u7FA4\u7D44", colgroup:"\u5217\u7FA4\u7D44", col_limit:"\u5DF2\u8D85\u904E\u9650\u5236\uFF0C\u6700\u9AD8\u7684\u5217\u6578\u70BA{$cols}\u5217\u3002", row_limit:"\u5DF2\u8D85\u904E\u9650\u5236\uFF0C\u6700\u9AD8\u7684\u884C\u6578\u70BA{$rows}\u884C\u3002", cell_limit:"\u5DF2\u8D85\u904E\u9650\u5236\uFF0C\u6700\u9AD8\u7684\u55AE\u5143\u683C\u6578\u70BA{$cells}\u683C\u3002", missing_scope:"\u6A19\u984C\u6B04\u907A\u5931\uFF01", caption:"\u8868\u683C\u6279\u6CE8", frame:"\u908A\u6846", frame_none:"\u7121", frame_groups:"\u7FA4\u7D44", frame_rows:"\u884C", frame_cols:"\u5217", frame_all:"\u5168\u90E8", rules:"\u7DDA\u689D", rules_void:"\u7A7A", rules_above:"\u4E0A", rules_below:"\u4E0B", rules_hsides:"\u6C34\u5E73\u908A", rules_lhs:"\u5DE6\u908A", rules_rhs:"\u53F3\u908A", rules_vsides:"\u5782\u76F4\u908A", rules_box:"\u65B9\u6846", rules_border:"\u5916\u6846" });
/* * ___ __ __ * ( ( / \ * ) ) )( () ) * (___(__\__/ * * a library for building user interfaces */ /* eslint-disable */ (function (factory) { if (typeof exports === 'object' && typeof module !== 'undefined') { module.exports = factory(global, typeof __webpack_require__ === 'undefined' ? require : null); } else if (typeof define === 'function' && define.amd) { define(factory(window, null)); } else { window.dio = factory(window, null); } }(function (self, __require__) { 'use strict'; /** * ## Constants */ var browser = self.window === self; var server = browser === false; var body = null; var w3 = 'http://www.w3.org/'; var svg = w3 + '2000/svg'; var xlink = w3 + '1999/xlink'; var math = w3 + '1998/Math/MathML'; var noop = function () {}; var Promise = self.Promise || noop; var requestAnimationFrame = self.requestAnimationFrame || setTimeout; var requestIdleCallback = self.requestIdleCallback || setTimeout; var READY = 0; var PROCESSING = 1; var PROCESSED = 2; var PENDING = 3; var STRING = 0; var FUNCTION = 1; var CLASS = 2; var NOOP = 3; var FORCE = 4; var EMPTY = 0; var TEXT = 1; var ELEMENT = 2; var COMPOSITE = 3; var FRAGMENT = 4; var ERROR = 5; var PORTAL = 6; var CUSTOM = 7; var CHILDREN = []; var ATTRS = {}; var PROPS = {children: CHILDREN}; var SHARED = new Tree(EMPTY); /** * ## Element Shape * * tag: node tag {String} * type: node type {Function|Class|String} * props: node properties {Object?} * attrs: node attributes {Object?} * children: node children {Array<Tree>} * key: node key {Any} * flag: node flag {Number} * xmlns: node xmlns namespace {String?} * owner: node component {Component?} * node: node DOM reference {Node?} * group: node ground {Number} * async: node work state {Number} 0: ready, 1:processing, 2:processed, 3: pending * yield: coroutine {Function?} * host: host component * * ## Component Shape * * this: current tree {Tree?} * async: component async, tracks async lifecycle methods flag {Number} * * _props: previous props {Object} * _state: previous state {Object} * _pending: pending state {Object} * * props: current props {Object} * state: current state {Object} * refs: refs {Object?} * setState: method {Function} * forceUpdate: method {Function} */ /** * Component * * @param {Object?} props */ function Component (props) { var state = this.state; this.refs = null; this.this = null; // props if (this.props === void 0) { this.props = (props !== void 0 && props !== null) ? props : PROPS; } // state if (state === void 0) { state = this.state = {}; } this._state = state; } /** * Prototype * * @type {Object} */ var ComponentPrototype = { setState: {value: setState}, forceUpdate: {value: forceUpdate}, UUID: {value: 2} }; Component.prototype = Object.create(null, ComponentPrototype); ComponentPrototype.UUID.value = 1; /** * Extend * * @param {Function} type * @param {Object} prototype */ function extendClass (type, prototype) { if (prototype.constructor !== type) { Object.defineProperty(prototype, 'constructor', {value: type}); } Object.defineProperties(prototype, ComponentPrototype); } /** * setState * * @param {Object} state * @param {Function?} callback */ function setState (state, callback) { var owner = this; var newState = state !== void 0 && state !== null ? state : {}; var oldState = owner.state; var constructor = newState.constructor; if (constructor === Function) { newState = callbackBoundary(SHARED, owner, newState, oldState, 0); if (newState === void 0 || newState === null) { return; } constructor = newState.constructor; } switch (constructor) { case Promise: { newState.then(function (value) { owner.setState(value, callback); }); break; } case Object: { var older = owner.this; if (older === null) { return; } if (older.async !== READY) { updateState(owner._state, newState); return } else { owner._state = newState; } commitUpdate(callback, this, NOOP) } } } /** * forceUpdate * * @param {Function?} callback */ function forceUpdate (callback) { commitUpdate(callback, this, FORCE); } /** * commitUpdate * * @param {Function?} callback * @param {Component} owner * @param {Number} group */ function commitUpdate (callback, owner, group) { var older = owner.this; if (older === null || older.node === null) { return; } else if (older.async !== READY) { // process this update in the next frame return void requestAnimationFrame(function () { owner.forceUpdate(callback); }); } else { patch(older, older, group); } if (callback !== void 0 && callback !== null && callback.constructor === Function) { if (older.async === READY) { callbackBoundary(older, owner, callback, owner.state, 1); } else { requestAnimationFrame(function () { callbackBoundary(older, owner, callback, owner.state, 1); }); } } } /** * updateState * * @param {Object} oldState * @param {Object} newState */ function updateState (oldState, newState) { for (var name in newState) { oldState[name] = newState[name]; } } /** * initialState * * @param {Tree} older * @param {Object} state */ function getInitialState (older, state) { if (state !== void 0 && state !== null) { switch (state.constructor) { case Promise: { older.async = PENDING; if (browser === true) { state.then(function (value) { older.async = READY; older.owner.setState(value); }); break; } } case Object: { older.owner.state = state; break; } } } } /** * initialStatic * * @param {Function} owner * @param {Function} func * @param {String} type * @param {Object} props * @return {Object?} */ function getInitialStatic (owner, func, type, props) { if (typeof func !== 'function') { return func; } var value = callbackBoundary(SHARED, owner, func, props, 0); if (value !== void 0 && value !== null) { return Object.defineProperty(owner, type, {value: value}); } } /** * PropTypes * * @param {Component} owner * @param {Function} type * @param {Object} props */ function propTypes (owner, type, props) { var display = type.name; var types = type.propTypes; try { for (var name in types) { var valid = types[name]; var result = valid(props, name, display); if (result) { console.error(result); } } } catch (err) { errorBoundary(err, SHARED, owner, 2, valid); } } /** * Element * * @param {String|Function} _type * @param {...} _props * @return {Tree} */ function element (_type, _props) { var type = _type; var props = _props !== void 0 ? _props : null; var attrs = props; var length = arguments.length; var size = 0; var offset = 0; var i = 2; var group = 0; var newer = new Tree(ELEMENT); switch (props) { case null: { props = PROPS; attrs = ATTRS; offset++; break; } default: { switch (props.constructor) { case Object: { if (props.key !== void 0) { newer.key = props.key; } if (props.xmlns !== void 0) { newer.xmlns = props.xmlns; } offset++; newer.props = props; break; } case Array: { size = props.length; } default: { props = PROPS; attrs = ATTRS; i = 1; } } } } switch (type.constructor) { // fragment case Array: { return fragment(type); } // import case Promise: { newer.tag = 'div'; newer.attrs = attrs; newer.flag = FRAGMENT; break; } // node case String: { newer.tag = type; newer.attrs = attrs; break; } // component case Function: { var proto = type.prototype; if (proto !== void 0 && proto.render !== void 0) { // class component group = CLASS; } else if (type.ELEMENT_NODE !== 1) { // function component group = FUNCTION; } else { // custom element group = STRING; newer.flag = CUSTOM; newer.tag = type; newer.attrs = attrs; } newer.group = group; break; } default: { if (type.ELEMENT_NODE === 1) { // portal newer.flag = PORTAL; newer.tag = type; newer.attrs = attrs; } else if (type.flag !== void 0) { // clone if (type.props !== PROPS) { if (props === PROPS) { props = newer.props = {}; attrs = newer.attrs = {}; } merge(type.props, props); merge(type.attrs, attrs); } group = newer.group = type.group; type = type.type; if (group === STRING) { newer.tag = type; } else { props.children = CHILDREN; } } } } newer.type = type; if (length - offset > 1) { var children = newer.children = new Array(size); var index = 0; if (group === 0) { for (; i < length; i++) { index = push(newer, index, arguments[i]); } } else { if (props === PROPS) { props = newer.props = {}; } for (; i < length; i++) { index = pull(newer, index, arguments[i]); } props.children = children; newer.children = CHILDREN; } } return newer; } /** * Push Children * * @param {Tree} newer * @param {Number} index * @param {Any} value * @return {Number} */ function push (newer, index, value) { var children = newer.children; var child; if (value === null || value === void 0) { child = text(' '); } else if (value.group !== void 0) { if (newer.keyed === 0 && value.key !== null) { newer.keyed = 1; } child = value; } else { switch (value.constructor) { case String: { if (value.length === 0) { value = ' '; } } case Number: { child = new Tree(TEXT); child.type = child.tag = '#text'; child.children = value; break; } case Array: { for (var j = 0, i = index, length = value.length; j < length; j++) { i = push(newer, i, value[j]); } return i; } case Promise: case Function: { child = element(value); break; } case Object: { child = stringify(value); break; } case Date: { child = text(value.toString()); break; } default: { child = value.ELEMENT_NODE === 1 ? element(value) : text(' '); break; } } } children[index] = child; return index + 1; } /** * Pull Children * * @param {Tree} newer * @param {Number} index * @param {Any} value * @return {Number} */ function pull (newer, index, value) { var children = newer.children; if (value !== null && value !== void 0 && value.constructor === Array) { for (var j = 0, i = index, length = value.length; j < length; j++) { i = pull(newer, i, value[j]); } return i; } children[index] = value; return index + 1; } /** * Text * * @param {String|Number|Boolean} value * @param {Tree} * @return {Tree} */ function text (value) { var newer = new Tree(TEXT); newer.type = newer.tag = '#text'; newer.children = value; return newer; } /** * Fragment * * @param {Array<Tree>|Tree|Function} children * @return {Tree} */ function fragment (children) { var newer = new Tree(FRAGMENT); newer.tag = newer.type = 'div'; newer.children = children; for (var i = 0, index = 0, length = children.length; i < length; i++) { index = push(newer, index, children[i]); } return newer; } /** * Compose * * @param {Tree} child * @return {Tree} */ function compose (child) { var newer = new Tree(COMPOSITE); newer.children = [child]; return newer; } /** * Stringify * * @param {Object} value * @return {Tree} */ function stringify (value) { try { return element('pre', null, JSON.stringify(value, null, 2)); } catch (err) { return text(' '); } } /** * Assign * * @param {Tree} older * @param {Tree} newer * @param {Boolean} deep */ function assign (older, newer, deep) { older.flag = newer.flag; older.tag = newer.tag; older.ref = newer.ref; older.node = newer.node; older.attrs = newer.attrs; older.xmlns = newer.xmlns; older.async = newer.async; older.keyed = newer.keyed; older.children = newer.children; if (deep === true) { older.parent = newer.parent; older.props = newer.props; older.owner = newer.owner; older.yield = newer.yield; older.type = newer.type; older.host = newer.host; older.key = newer.key; if ((older.group = newer.group) === CLASS) { older.owner.this = older; } } } /** * Clone * * @param {Tree} older * @param {Tree} newer * @param {Boolean} deep * @return {Tree} */ function clone (older, newer, deep) { assign(older, newer, deep); return older; } /** * Tree * * @param {Number} flag */ function Tree (flag) { this.flag = flag; this.tag = null; this.key = null; this.ref = null; this.type = null; this.node = null; this.host = null; this.group = STRING; this.async = READY; this.props = PROPS; this.attrs = ATTRS; this.xmlns = null; this.owner = null; this.yield = null; this.keyed = 0; this.parent = null; this.children = CHILDREN; } /** * Prototype * * @type {Object} */ Tree.prototype = element.prototype = Object.create(null); /** * Data Boundary * * @param {Tree} older * @param {Component} owner * @param {Number} type * @param {Object} props * @return {Object?} */ function dataBoundary (older, owner, type, props) { try { switch (type) { case 0: returnBoundary(older, owner.componentWillReceiveProps(props), owner, null, true); break; case 1: return owner.getInitialState(props); } } catch (err) { errorBoundary(err, older, owner, 0, type); } } /** * Update Boundary * * @param {Tree} older * @param {Component} owner * @param {Number} type * @param {Object} props * @param {Object} state * @return {Boolean?} */ function updateBoundary (older, owner, type, props, state) { try { switch (type) { case 0: return owner.shouldComponentUpdate(props, state); case 1: returnBoundary(older, owner.componentWillUpdate(props, state), owner, null, true); break; case 2: returnBoundary(older, owner.componentDidUpdate(props, state), owner, null, false); break; } } catch (err) { errorBoundary(err, older, owner, 1, type); } } /** * Render Boundary * * @param {Tree} older * @param {Number} group * @return {Tree} */ function renderBoundary (older, group) { try { if (older.yield !== null) { return older.yield(); } switch (group) { case FUNCTION: return older.type(older.props); default: return older.owner.render(older.owner.props, older.owner.state); } } catch (err) { return errorBoundary(err, older, group === CLASS ? older.owner : older.type, 3, group); } } /** * Mount Boundary * * @param {Tree} older * @param {Component} owner * @param {Node} node * @param {Number} type */ function mountBoundary (older, owner, node, type) { try { switch (type) { case 0: returnBoundary(older, owner.componentWillMount(node), owner, null, false); break; case 1: returnBoundary(older, owner.componentDidMount(node), owner, null, true); break; case 2: return owner.componentWillUnmount(node); } } catch (err) { errorBoundary(err, older, owner, 4, type); } } /** * Callback Boundary * * @param {Tree} older * @param {Function} callback * @param {Component} owner * @param {Object|Node} data * @param {Number} type */ function callbackBoundary (older, owner, callback, data, type) { try { if (type === 0) { return callback.call(owner, data); } else { returnBoundary(older, callback.call(owner, data), owner, null, false); } } catch (err) { errorBoundary(err, older, owner, 2, callback); } } /** * Events Boundary * * @param {Event} e */ function eventBoundary (e) { var handlers = this.that; var host = handlers.host; var func = handlers[e.type]; if (func !== null && func !== void 0) { if (host !== void 0) { try { var owner = host.owner; var result = func.call(owner, e); if (result !== void 0) { returnBoundary(host, result, owner, e, true); } } catch (err) { errorBoundary(err, host, owner, 5, func); } } else { func.call(this, e); } } } /** * Return Boundary * * @param {Tree} older * @param {(Object|Promise)?} state * @param {Component} owner * @param {Event?} e * @param {Boolean} sync */ function returnBoundary (older, state, owner, e, sync) { if (state === void 0 || state === null || older.group !== CLASS) { return; } if (sync === true) { owner.setState(state); return; } requestIdleCallback(function () { owner.setState(state); }); } /** * Error Boundary * * @param {Error|String} message * @param {Tree} older * @param {Component} owner * @param {Number} type * @param {Number|Function} from * @return {Tree?} */ function errorBoundary (message, older, owner, type, from) { var unknown = '#unknown'; var component = unknown; var location = unknown; var newer; try { if (typeof from === 'function') { location = from.name; } else { switch (type) { case 0: { switch (from) { case 0: location = 'componentWillReceiveProps'; case 1: location = 'getInitialState'; } break; } case 1: { switch (from) { case 0: location = 'shouldComponentUpdate'; case 1: location = 'componentWillUpdate'; case 2: location = 'componentDidUpdate'; } break; } case 3: { location = 'render'; break; } case 4: { switch (from) { case 0: location = 'componentWillMount'; case 1: location = 'componentDidMount'; case 2: location = 'componentWillUnmount'; } break; } case 5: { location = 'event'; break; } } } if (owner !== null) { if (owner.componentDidThrow !== void 0) { newer = owner.componentDidThrow({location: location, message: message}); } component = typeof owner === 'function' ? owner.name : owner.constructor.name; } } catch (err) { message = err; location = 'componentDidThrow'; } console.error( (message instanceof Error ? message.stack : message) + '\n\n ^^ Error caught in '+'"'+component+'"'+' from "'+location+'" \n' ); if (type === 3) { if (newer === void 0 && older !== SHARED && older.node !== null) { // last non-error state return older; } else { // authored/default error state return shape(newer, older, true); } } } /** * Whitelist * * @param {String} name * @return {Number} */ function whitelist (name) { switch (name) { case 'class': case 'className': return 1; case 'width': case 'height': return 3; case 'xlink:href': return 4; case 'defaultValue': return 5; case 'id': case 'selected': case 'hidden': case 'checked': case 'value': return 6; case 'innerHTML': return 10; case 'style': return 20; case 'ref': return 30; case 'key': case 'children': return 31; default: return name.charCodeAt(0) === 111 && name.charCodeAt(1) === 110 ? 21 : 0; } } /** * Attribute [Mount] * * @param {Tree} newer * @param {String?} xmlns * @param {Boolean} event */ function attribute (newer, xmlns, event) { var attrs = newer.attrs; var node = newer.node; for (var name in attrs) { var type = event === false ? whitelist(name) : 21; if (type < 31) { var value = attrs[name]; if (type === 30) { refs(newer, value, 2); } else if (type < 20) { if (value !== void 0 && value !== null) { setAttribute(type, name, value, xmlns, true, node); } } else if (type > 20) { setEvent(newer, name, value, 1); } else { setStyle(newer, newer, 0); } } } } /** * Attributes [Reconcile] * * @param {Tree} older * @param {Tree} newer */ function attributes (older, newer) { var node = older.node; var previous = older.attrs; var current = newer.attrs; if (previous === current && current === ATTRS) { return; } var xmlns = older.xmlns; var type; var next; var prev; // old attributes for (var name in previous) { type = whitelist(name); if (type < 31) { next = current[name]; if (next === null || next === void 0) { if (type < 20) { setAttribute(type, name, next, xmlns, false, node); } else if (type > 20) { setEvent(older, name, next, 0); } } else if (type === 30 && next !== (prev = previous[name])) { refs(older, prev, 0); } } } // new attributes for (var name in current) { type = whitelist(name); if (type < 31) { next = current[name]; if (type === 30) { refs(older, next, 2); } else { prev = previous[name]; if (next !== prev && next !== null && next !== void 0) { if (type < 20) { setAttribute(type, name, next, xmlns, true, node); } else if (type > 20) { setEvent(older, name, next, 2); } else { setStyle(older, newer, 1); } } } } } older.attrs = current; } /** * Refs * * @param {Tree} older * @param {Function|String} value * @param {Number} type */ function refs (older, value, type) { var host = older.host; var stateful = false; if (host !== null) { var owner = host.owner; if (owner !== null && host.group === CLASS) { stateful = true; } } if (stateful === true && owner.refs === null) { owner.refs = {}; } if ((older.ref = value) !== void 0 && value !== null) { var node = type > 0 ? older.node : null; switch (value.constructor) { case Function: { callbackBoundary(older, owner, value, node, 2); break; } case String: { if (stateful === true) { owner.refs[value] = node; } break; } } } } /** * Merge * * @param {Object} source * @param {Object} props */ function merge (source, props) { for (var name in source) { if (props[name] === void 0) { props[name] = source[name]; } } } /** * Create * * @param {Tree} newer * @param {Tree} parent * @param {Tree} sibling * @param {Number} _action * @param {Tree?} _host * @param {String?} _xmlns */ function create (newer, parent, sibling, _action, _host, _xmlns) { var host = _host; var xmlns = _xmlns; var action = _action; var group = newer.group; var flag = newer.flag; var type = 2; var skip = false; var owner; var node; var temp; // cache host if (host !== SHARED) { newer.host = host; } // component if (group !== STRING) { if (group === CLASS) { host = newer; } extract(newer, true); flag = newer.flag; owner = newer.owner; } switch (flag) { // text case TEXT: { node = newer.node = createTextNode(newer.children); type = 1; break; } // composite case COMPOSITE: { create(temp = newer.children[0], parent, sibling, action, newer, xmlns); node = newer.node = temp.node; type = 0; break; } default: { var children = newer.children; var length = children.length; switch (flag) { case PORTAL: { node = newer.tag; action = 0; break; } case CUSTOM: { node = createCustomElement(newer, host) break; } default: { var tag = newer.tag; // cache namespace if (newer.xmlns !== null) { xmlns = newer.xmlns; } // namespace(implicit) svg/math roots switch (tag) { case 'svg': xmlns = svg; break; case 'math': xmlns = math; break; case '!doctype': tag = 'html'; break; } node = createElement(tag, newer, host, xmlns); } } // error if (newer.flag === ERROR) { create(node, parent, sibling, action, host, xmlns); assign(newer, node, newer.group === 0); return; } newer.node = node; if (length > 0) { for (var i = 0; i < length; i++) { var child = children[i]; // hoisted if (child.node !== null) { child = assign(children[i] = new Tree(child.flag), child, true); } create(child, newer, sibling, 1, host, xmlns); } } } } if (group !== STRING && owner.componentWillMount !== void 0) { mountBoundary(newer, owner, node, 0); } newer.parent = parent; if (type !== 0) { switch (action) { case 1: appendChild(newer, parent); break; case 2: insertBefore(newer, sibling, parent); break; case 3: skip = remove(sibling, newer, parent); break; } if (type !== 1) { attribute(newer, xmlns, false); } } if (group !== STRING && skip !== true && owner.componentDidMount !== void 0) { mountBoundary(newer, owner, node, 1); } } /** * Extract * * @param {Tree} older * @param {Boolean} abstract * @return {Tree} */ function extract (older, abstract) { var type = older.type; var props = older.props; var children = older.children; var group = older.group; var length = children.length; var defaults = type.defaultProps; var types = type.propTypes; var skip = false; var newer; var result; if (props === PROPS) { props = {}; } if (length !== 0) { props.children = children; } if (defaults !== void 0) { merge(getInitialStatic(type, defaults, 'defaultProps', props), props); } if (types !== void 0) { getInitialStatic(type, types, 'propTypes', props); } if (group === CLASS) { var proto = type.prototype; var UUID = proto.UUID; var owner; if (UUID === 2) { if ((owner = new type(props)).props === PROPS) { owner.props = props } } else { if (UUID !== 1) { extendClass(type, proto); } owner = new type(props); Component.call(owner, props); } older.owner = owner; if (owner.getInitialState !== void 0) { getInitialState(older, dataBoundary(SHARED, owner, 1, owner.props)); if (older.async === PENDING) { if (server === true) { return older; } else { skip = true; newer = text(' '); } } } if (skip !== true) { older.async = PROCESSING; newer = renderBoundary(older, group); older.async = READY; } owner.this = older; } else { older.owner = type; newer = renderBoundary(older, group); } result = shape(newer, older, abstract); older.tag = result.tag; older.flag = result.flag; older.attrs = result.attrs; older.xmlns = result.xmlns; older.children = result.children; return result; } /** * Shape * * @param {Any} value * @param {Tree?} older * @param {Boolean} abstract * @return {Tree} */ function shape (value, older, abstract) { var newer = (value !== null && value !== void 0) ? value : text(' '); switch (newer.flag) { case FRAGMENT: { if (newer.type !== null) { switch (newer.type.constructor) { case Array: { return fragment(newer) } case Promise: { return (resolve(older, newer.type), newer) } } } } case void 0: { switch (newer.constructor) { case Function: { newer = element(newer); break; } case String: { if (newer.length === 0) { newer = ' '; } } case Number: { return text(newer); } case Array: { return fragment(newer); } case Date: { return text(newer.toString()); } case Object: { return stringify(newer); } case Promise: { if (older !== null && older.flag !== EMPTY) { return resolve(older, newer, true); } } case Boolean: { return text(' '); } default: { if (older === null || newer.next === void 0) { return newer.ELEMENT_NODE === 1 ? element(newer) : text(' '); } newer = coroutine(older, newer); } } } } if (abstract === true && newer.group !== STRING) { return compose(newer); } else { return newer; } } /** * Resolve * * @param {Tree} older * @param {Promise} value */ function resolve (older, value) { older.async = PENDING; value.then(function (value) { if (older.node === null) { return; } var newer = shape(value, older, true); older.async = READY; if (older.tag !== newer.tag) { exchange(older, newer, false); } else { newer.type = older.type; patch(older, newer, 0); } }); return older.node === null ? text(' ') : older } /** * Coroutine * * @param {Tree} older * @param {Generator} generator * @return {Tree} */ function coroutine (older, generator) { var previous; var current; older.yield = function () { var supply = generator.next(previous); var next = supply.value; if (supply.done === true) { current = shape(next !== void 0 && next !== null ? next : previous, older, true); } else { current = shape(next, older, true); } return previous = current; }; return shape(renderBoundary(older, older.group), older, true); } /** * Fill * * @param {Tree} older * @param {Tree} newer * @param {Number} length */ function fill (older, newer, length) { var children = newer.children; var host = older.host; for (var i = 0, child; i < length; i++) { create(child = children[i], older, SHARED, 1, host, null); } older.children = children; } /** * Animate * * @param {Tree} older * @param {Tree} newer * @param {tree} parent * @param {Promise} pending * @param {Node} node */ function animate (older, newer, parent, pending) { pending.then(function () { if (parent.node === null || older.node === null) { return; } if (newer === SHARED) { removeChild(older, parent); } else if (newer.node !== null) { replaceChild(older, newer, parent); if (newer.group !== STRING && newer.owner.componentDidMount !== void 0) { mountBoundary(newer, newer.owner, newer.node, 1); } } unmount(older); detach(older); }); } /** * Remove * * @param {Tree} older * @param {Tree} newer * @param {Tree} parent * @return {Tree} */ function remove (older, newer, parent) { if (older.group !== STRING && older.owner.componentWillUnmount !== void 0) { var pending = mountBoundary(older, older.owner, older.node, 2); if (pending !== void 0 && pending !== null && pending.constructor === Promise) { animate(older, newer, parent, pending, older.node); return true; } } unmount(older); if (newer === SHARED) { removeChild(older, parent); detach(older); } else { replaceChild(older, newer, parent); } return false; } /** * Unmount * * @param {Tree} older */ function unmount (older) { var children = older.children; var length = children.length; var flag = older.flag; if (flag !== TEXT) { if (length !== 0) { for (var i = 0; i < length; i++) { var child = children[i]; if (child.group !== STRING && child.owner.componentWillUnmount !== void 0) { mountBoundary(child, child.owner, child.node, 2); } unmount(child); detach(child); } } if (older.ref !== null) { refs(older, older.ref, 0); } } } /** * Detach * * @param {Tree} */ function detach (older) { older.parent = null; older.owner = null; older.node = null; older.host = null; } /** * Exchange * * @param {Tree} newer * @param {Tree} older * @param {Boolean} deep */ function exchange (older, newer, deep) { change(older, newer, older.host); assign(older, newer, deep); update(older.host, newer); } /** * Update * * @param {Tree} older * @param {Tree} newer */ function update (older, newer) { if (older !== null && older.flag === COMPOSITE) { older.node = newer.node; older.parent = newer.parent; if (older.host !== older) { update(older.host, newer); } } } /** * Change * * @param {Tree} older * @param {Tree} newer */ function change (older, newer) { create(newer, older.parent, older, 3, older.host, null); } /** * Render * * @param {Any} subject * @param {Node?} container * @param {(Function|Node)?} callback */ function render (subject, container, callback) { var newer = subject; var target = container; if (newer === void 0 || newer === null) { newer = text(' '); } else if (newer.flag === void 0) { newer = shape(newer, null, false); } // browser if (target === void 0 || target === null) { // uses <body> if it exists at this point // else default to the root <html> node if (body === null && (body = documentElement()) === null) { return server === true ? newer.toString() : void 0; } target = body; } var older = target.this; if (older !== void 0) { if (older.key === newer.key) { patch(older, newer, older.group); } else { exchange(older, newer, true); } } else { var parent = new Tree(ELEMENT); target.this = older = newer; parent.node = target; if (callback === void 0 || callback === null || callback.constructor === Function) { create(newer, parent, SHARED, 1, newer, null); } else { hydrate(newer, parent, 0, callback, newer, null); } } if (callback !== void 0 && callback !== null && callback.constructor === Function) { callbackBoundary(older, older.owner, callback, target, 0); } } /** * Patch * * @param {Tree} older * @param {Tree} _newer * @param {Number} group */ function patch (older, _newer, group) { var newer = _newer; var type = older.type; var skip = false; if (type !== newer.type) { exchange(older, newer, true); return; } if (group !== STRING) { var owner = older.owner if (owner === null || older.async !== READY) { return; } older.async = PROCESSING; var newProps = newer.props; var oldProps = older.props; var newState; var oldState; if (group !== FUNCTION) { oldState = owner.state; newState = owner._state; } else { oldState = oldProps; newState = newProps; } if (group < NOOP) { if (type.propTypes !== void 0) { propTypes(owner, type, newProps); } if (owner.componentWillReceiveProps !== void 0) { dataBoundary(older, owner, 0, newProps); } if (type.defaultProps !== void 0) { merge(type.defaultProps, newProps === PROPS ? (newProps = {}) : newProps); } } if ( group !== FORCE && owner.shouldComponentUpdate !== void 0 && updateBoundary(older, owner, 0, newProps, newState) === false ) { older.async = READY; return; } if (group < NOOP) { if (group === CLASS) { owner.props = newProps; } older.props = newProps; } if (owner.componentWillUpdate !== void 0) { updateBoundary(older, owner, 1, newProps, newState); } // update current state if (group !== FUNCTION) { updateState(oldState, newState); } newer = renderBoundary(older, group); newer = newer !== older ? shape(newer, older, true) : newer; if (older.async === PENDING) { return; } older.async = READY; if (newer.tag !== older.tag) { exchange(older, newer, false); skip = true; } else { // composite component if (newer.flag === COMPOSITE) { patch(older.children[0], newer.children[0], group); skip = true; } } } if (skip === false) { switch (older.flag) { // text component case TEXT: { if (older.children !== newer.children) { nodeValue(older, newer); } break } default: { var oldLength = older.children.length; var newLength = newer.children.length; /** * when int * 0 === 0, * if oldLength is not zero then newLength is. */ switch (oldLength * newLength) { case 0: { switch (oldLength) { // fill children case 0: { if (newLength > 0) { fill(older, newer, newLength); older.children = newer.children; } break } // remove children default: { unmount(older); removeChildren(older); older.children = newer.children; } } break; } default: { switch (newer.keyed) { case 0: nonkeyed(older, newer, oldLength, newLength); break; case 1: keyed(older, newer, oldLength, newLength); break; } } } attributes(older, newer); } } } if (group !== STRING && older.owner.componentDidUpdate !== void 0) { older.async = PROCESSED; updateBoundary(older, owner, 2, oldProps, oldState); older.async = READY; } } /** * Non-Keyed Children [Simple] * * @param {Tree} older * @param {Tree} newer * @param {Number} oldLength * @param {Number} newLength */ function nonkeyed (older, newer, oldLength, newLength) { var host = older.host; var oldChildren = older.children; var newChildren = newer.children; var length = newLength > oldLength ? newLength : oldLength; for (var i = 0; i < length; i++) { if (i >= oldLength) { create(oldChildren[i] = newChildren[i], older, SHARED, 1, host, null); } else if (i >= newLength) { remove(oldChildren.pop(), SHARED, older); } else { var newChild = newChildren[i]; var oldChild = oldChildren[i]; if (newChild.flag === TEXT && oldChild.flag === TEXT) { if (newChild.children !== oldChild.children) { nodeValue(oldChild, newChild); } } else { patch(oldChild, newChild, oldChild.group); } } } } /** * Keyed Children [Simple] * * @param {Tree} older * @param {Tree} newer * @param {Number} oldLength * @param {Number} newLength */ function keyed (older, newer, oldLength, newLength) { var host = older.host; var oldChildren = older.children; var newChildren = newer.children; var oldStart = 0; var newStart = 0; var oldEnd = oldLength - 1; var newEnd = newLength - 1; var oldStartNode = oldChildren[oldStart]; var newStartNode = newChildren[newStart]; var oldEndNode = oldChildren[oldEnd]; var newEndNode = newChildren[newEnd]; var nextPos; var nextChild; // step 1, sync leading [a, b ...], trailing [... c, d], opposites [a, b] [b, a] recursively outer: while (true) { // sync leading nodes while (oldStartNode.key === newStartNode.key) { newChildren[newStart] = oldStartNode; patch(oldStartNode, newStartNode, oldStartNode.group); oldStart++; newStart++; if (oldStart > oldEnd || newStart > newEnd) { break outer; } oldStartNode = oldChildren[oldStart]; newStartNode = newChildren[newStart]; } // sync trailing nodes while (oldEndNode.key === newEndNode.key) { newChildren[newEnd] = oldEndNode; patch(oldEndNode, newEndNode, oldEndNode.group); oldEnd--; newEnd--; if (oldStart > oldEnd || newStart > newEnd) { break outer; } oldEndNode = oldChildren[oldEnd]; newEndNode = newChildren[newEnd]; } // move and sync nodes from right to left if (oldEndNode.key === newStartNode.key) { newChildren[newStart] = oldEndNode; oldChildren[oldEnd] = oldStartNode; insertBefore(oldEndNode, oldStartNode, older); patch(oldEndNode, newStartNode, oldEndNode.group); oldEnd--; newStart++; oldEndNode = oldChildren[oldEnd]; newStartNode = newChildren[newStart]; continue; } // move and sync nodes from left to right if (oldStartNode.key === newEndNode.key) { newChildren[newEnd] = oldStartNode; oldChildren[oldStart] = oldEndNode; nextPos = newEnd + 1; if (nextPos < newLength) { insertBefore(oldStartNode, oldChildren[nextPos], older); } else { appendChild(oldStartNode, older); } patch(oldStartNode, newEndNode, oldStartNode.group); oldStart++; newEnd--; oldStartNode = oldChildren[oldStart]; newEndNode = newChildren[newEnd]; continue; } break; } // step 2, remove or insert or both if (oldStart > oldEnd) { // old children is synced, insert the difference if (newStart <= newEnd) { nextPos = newEnd + 1; nextChild = nextPos < newLength ? newChildren[nextPos] : SHARED; do { create(newStartNode = newChildren[newStart++], older, nextChild, 2, host, null); } while (newStart <= newEnd); } } else if (newStart > newEnd) { // new children is synced, remove the difference do { remove(oldStartNode = oldChildren[oldStart++], SHARED, older); } while (oldStart <= oldEnd); } else if (newStart === 0 && newEnd === newLength-1) { // all children are out of sync, remove all, append new set unmount(older); removeChildren(older); fill(older, newer, newLength); } else { // could sync all children, move on the the next phase complex(older, newer, oldStart, newStart, oldEnd + 1, newEnd + 1, oldLength, newLength); } older.children = newChildren; } /** * Keyed Children [Complex] * * @param {Tree} older * @param {Tree} newer * @param {Number} oldStart * @param {Number} newStart * @param {Number} oldEnd * @param {Number} newEnd * @param {Number} oldLength * @param {number} newLength */ function complex (older, newer, oldStart, newStart, oldEnd, newEnd, oldLength, newLength) { var host = older.host; var oldChildren = older.children; var newChildren = newer.children; var oldKeys = {}; var newKeys = {}; var oldIndex = oldStart; var newIndex = newStart; var oldOffset = 0; var newOffset = 0; var oldChild; var newChild; var nextChild; var nextPos; // step 1, build a map of keys while (true) { if (oldIndex < oldEnd) { oldChild = oldChildren[oldIndex]; oldKeys[oldChild.key] = oldIndex++; } if (newIndex < newEnd) { newChild = newChildren[newIndex]; newKeys[newChild.key] = newIndex++; } if (oldIndex === oldEnd && newIndex === newEnd) { break; } } // reset oldIndex = oldStart; newIndex = newStart; // step 2, insert and sync nodes from left to right [a, b, ...] while (newIndex < newEnd) { newChild = newChildren[newIndex]; oldIndex = oldKeys[newChild.key]; // new child doesn't exist in old children, insert if (oldIndex === void 0) { nextPos = newIndex - newOffset; nextChild = nextPos < oldLength ? oldChildren[nextPos] : SHARED; create(newChild, older, nextChild, 2, host, null); newOffset++; } else if (newIndex === oldIndex) { oldChild = oldChildren[oldIndex]; patch(newChildren[newIndex] = oldChild, newChild, oldChild.group); } newIndex++; } // reset oldIndex = oldStart; // step 3, remove and sync nodes from left to right [a, b, ...] while (oldIndex < oldEnd) { oldChild = oldChildren[oldIndex]; newIndex = newKeys[oldChild.key]; // old child doesn't exist in new children, remove if (newIndex === void 0) { remove(oldChild, SHARED, older); oldOffset++; } oldIndex++; } // compute changes oldOffset = (oldEnd - oldStart) - oldOffset; newOffset = (newEnd - newStart) - newOffset; // new and old children positions are in sync if (oldOffset + newOffset === 2) { return; } // reset newIndex = newEnd - 1; // step 4, move and sync nodes from right to left, [..., c, d] while (newIndex >= newStart) { newChild = newChildren[newIndex]; // moved node if (newChild.node === null) { // retreive index oldIndex = oldKeys[newChild.key]; // exists if (oldIndex !== void 0) { oldChild = oldChildren[oldIndex]; // within bounds if ((nextPos = newIndex + 1) < newLength) { insertBefore(oldChild, newChildren[nextPos], older); } else { appendChild(oldChild, older); } patch(newChildren[newIndex] = oldChild, newChild, oldChild.group); } } newIndex--; } } /** * Create * * @param {String} tag * @param {Tree} newer * @param {Tree} host * @param {String?} xmlns * @return {Node} */ function createElement (tag, newer, host, xmlns) { try { if (xmlns === null) { return document.createElement(tag); } else { return document.createElementNS(newer.xmlns = xmlns, tag); } } catch (err) { return errorBoundary(err, host, host.owner, (newer.flag = ERROR, 3), 0); } } /** * Custom * * @param {Tree} newer * @param {Tree} host * @return {Node} */ function createCustomElement (newer, host) { try { return new newer.tag(newer.props); } catch (err) { return errorBoundary(err, host, host.owner, (newer.flag = ERROR, 3), 0); } } /** * Text * * @param {(String|Number)} value * @return {Node} */ function createTextNode (value) { return document.createTextNode(value); } /** * Fragment * * @return {Node} */ function createDocumentFragment () { return document.createDocumentFragment(); } /** * Document * * @return {Node?} */ function documentElement () { return self.document !== void 0 ? (document.body || document.documentElement) : null; } /** * Insert * * @param {Tree} newer * @param {Tree} sibling * @param {Tree} parent */ function insertBefore (newer, sibling, parent) { parent.node.insertBefore(newer.node, sibling.node); } /** * Append * * @param {Tree} newer * @param {Tree} parent */ function appendChild (newer, parent) { parent.node.appendChild(newer.node); } /** * Replace * * @param {Tree} older * @param {Tree} newer * @param {Tree} parent */ function replaceChild (older, newer, parent) { parent.node.replaceChild(newer.node, older.node); } /** * Remove * * @param {Tree} older * @param {Tree} newer * @param {Tree} parent */ function removeChild (older, parent) { parent.node.removeChild(older.node); } /** * Remove All * * @param {Tree} older */ function removeChildren (older) { older.node.textContent = null; } /** * Text * * @param {Tree} older * @param {Tree} newer */ function nodeValue (older, newer) { older.node.nodeValue = older.children = newer.children; } /** * Attribute * * @param {Number} type * @param {String} name * @param {Any} value * @param {String?} xmlns * @param {Boolean} set * @param {Tree} node */ function setAttribute (type, name, value, xmlns, set, node) { switch (type) { case 0: { if (xmlns === null && (name in node) === true) { setUnknown(name, value, node); } else if (set === true) { node.setAttribute(name, value); } else { node.removeAttribute(name); } break; } case 1: { if (xmlns === null) { node.className = value; } else { setAttribute(0, 'class', value, xmlns, set, node); } break; } case 3: { if ((name in node) === false) { node.style.setProperty(name, value); } else if (isNaN(Number(value)) === true) { setAttribute(0, name, value, xmlns, set, node); } else { setAttribute(6, name, value, xmlns, set, node); } break; } case 4: { if (set === true) { node.setAttributeNS(xlink, 'href', value); } else { node.removeAttributeNS(xlink, 'href'); } break; } case 5: case 6: { if (xmlns === null) { node[name] = value; } else { setAttribute(0, name, value, xmlns, set, node); } break; } case 10: { node.innerHTML = value; break; } } } /** * Unknown * * @param {String} name * @param {Any} value * @param {Node} node */ function setUnknown (name, value, node) { try { node[name] = value; } catch (e) {} } /** * Style * * @param {Tree} older * @param {Tree} newer * @param {Number} _type */ function setStyle (older, newer, _type) { var node = older.node.style; var prev = older.attrs.style; var next = newer.attrs.style; switch (next.constructor) { case Object: { // update/assign var type = prev !== void 0 && prev !== null ? _type : 0; for (var name in next) { var value = next[name]; if (type === 1 && value === prev[name]) { continue } if (name.charCodeAt(0) === 45) { node.setProperty(name, value); } else { node[name] = value; } } break; } case String: { // update/assign if (_type === 0 || next !== prev) { node.cssText = next; } break; } default: { node.cssText = ''; } } } /** * Event * * @param {Tree} older * @param {String} type * @param {Function} value * @param {Number} action */ function setEvent (older, type, value, action) { var name = type.toLowerCase().substring(2); var host = older.host; var node = older.node; var handlers = node.that; if (handlers === void 0) { handlers = node.that = {}; } switch (action) { case 0: { node.removeEventListener(name, eventBoundary); if (handlers.host !== void 0) { handlers.host = null; } break; } case 1: { node.addEventListener(name, eventBoundary); } case 2: { if (host !== null && host.group === CLASS) { handlers.host = host; } } } handlers[name] = value; } /** * Hydrate * * @param {Tree} newer * @param {Tree} parent * @param {Number} index * @param {Node} _node * @param {Tree?} _host * @param {String?} _xmlns * @param {Boolean} entry * @return {Number} */ function hydrate (newer, parent, index, _node, _host, _xmlns, entry) { var flag = newer.flag; var group = newer.group; var node = _node; var host = _host; var xmlns = _xmlns; var i = 0; var temp; // link host if (host !== SHARED) { newer.host = host; } // link parent newer.parent = parent; // component if (group !== STRING) { if (group === CLASS) { host = newer; } temp = extract(newer, true); flag = temp.flag; } switch (flag) { // text case TEXT: { var children = parent.children; var length = children.length; if (length > 1 && children[index + 1].flag === TEXT) { var fragment = new Tree(FRAGMENT); var sibling = new Tree(TEXT); fragment.node = createDocumentFragment(); sibling.node = node; for (i = index; i < length; i++) { var child = children[i]; if (child.flag !== TEXT) { replaceChild(sibling, fragment, parent); return i; } child.node = createTextNode(child.children); appendChild(child, fragment); } } else { if (node.nodeValue !== newer.children) { node.nodeValue = newer.children; } newer.node = node; } return 0; } // composite case COMPOSITE: { hydrate(temp = temp.children[0], parent, index, node, host, xmlns); newer.node = temp.node; return 0; } // portal case PORTAL: { create(newer, parent, SHARED, 0, host, xmlns); break; } default: { var children = newer.children; var length = children.length; // cache namespace if (newer.xmlns !== null) { xmlns = newer.xmlns; } else if (xmlns !== null) { newer.xmlns = xmlns; } // namespace(implicit) svg/math roots switch (newer.tag) { case 'svg': xmlns = svg; break; case 'math': xmlns = math; break; } // whitespace if (node.splitText !== void 0 && node.nodeValue.trim().length === 0) { node = node.nextSibling; } newer.node = node; if (length > 0) { node = node.firstChild; while (i < length && node !== null) { var child = children[i]; if (child.node !== null) { child = clone(children[i] = new Tree(child.flag), child, true); } var idx = hydrate(child, newer, i, node, host, xmlns); if (idx !== 0) { node = children[i = idx - 1].node; } node = node.nextSibling; i++; } } } } attribute(newer, xmlns, true); return 0; } /** * Exports * * @type {Object} */ var dio = { version: '7.1.0', h: element, createElement: element, render: render, Component: Component }; self.h = element; /** * Server */ if (server === true && __require__ !== null) { __require__('./dio.server.js')( dio, element, shape, extract, whitelist, render, renderBoundary, CHILDREN, PROPS, ATTRS, READY, PROCESSING, PROCESSED, PENDING, STRING, FUNCTION, CLASS, NOOP, EMPTY, TEXT, ELEMENT, COMPOSITE, FRAGMENT, ERROR, PORTAL ); } return dio; }));
describe('select-multiple', function() { beforeEach(function() { browser().navigateTo(mainUrl); }); it('should show options and submit new value', function() { var s = '[ng-controller="SelectMultipleCtrl"] '; expect(element(s+'a').text()).toMatch('status2'); expect(element(s+'a').text()).toMatch('status4'); element(s+'a').click(); expect(element(s+'a').css('display')).toBe('none'); expect(element(s+'form[editable-form="$form"]').count()).toBe(1); expect(element(s+'form select:visible:enabled').count()).toBe(1); expect(element(s+'form select option').count()).toBe(4); expect(element(s+'form select option:selected').count()).toBe(2); expect(element(s+'form select').val()).toMatch('["1","3"]'); using(s).select('$data').options('1', '2'); element(s+'form button[type="submit"]').click(); expect(element(s+'a').css('display')).not().toBe('none'); expect(element(s+'a').text()).toMatch('status2'); expect(element(s+'a').text()).toMatch('status3'); expect(element(s+'a').text()).not().toMatch('status4'); expect(element(s+'form').count()).toBe(0); }); });
describe("module:ng.input:input[number]", function() { var rootEl; beforeEach(function() { rootEl = browser.rootEl; browser.get("./examples/example-number-input-directive/index-jquery.html"); }); var value = element(by.binding('value')); var valid = element(by.binding('myForm.input.$valid')); var input = element(by.model('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'); }); });
version https://git-lfs.github.com/spec/v1 oid sha256:9aa196a5fac550c5666e19c78ddfc6391c3ff6f512e64e8c847d611d647f24a2 size 2345
version https://git-lfs.github.com/spec/v1 oid sha256:43174f11524ba5affe1bf3c72d91ab9e8610d39f6ae0fa0a80829ec2098a6f2e size 2412
/************************************************************* * * MathJax/jax/output/SVG/fonts/TeX/svg/Main/Bold/LatinExtendedA.js * * Copyright (c) 2011-2014 The MathJax Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ MathJax.Hub.Insert( MathJax.OutputJax.SVG.FONTDATA.FONTS['MathJax_Main-bold'], { // LATIN SMALL LETTER DOTLESS I 0x131: [452,8,394,24,367,'24 296Q24 305 34 328T63 380T115 430T187 452Q205 452 223 448T262 435T295 406T308 360Q308 345 287 290T240 170T207 87Q202 67 202 57Q202 42 215 42Q235 42 257 64Q288 92 302 140Q307 156 310 159T330 162H336H347Q367 162 367 148Q367 140 357 117T329 65T276 14T201 -8Q158 -8 121 15T83 84Q83 104 133 229T184 358Q189 376 189 388Q189 402 177 402Q156 402 134 380Q103 352 89 304Q84 288 81 285T61 282H55H44Q24 282 24 296'] } ); MathJax.Ajax.loadComplete(MathJax.OutputJax.SVG.fontDir+"/Main/Bold/LatinExtendedA.js");
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'pastetext', 'et', { button: 'Asetamine tavalise tekstina', title: 'Asetamine tavalise tekstina' } );
/** * 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 context_1 = require("../context/context"); var utils_1 = require("../utils"); var textCellEditor_1 = require("./cellEditors/textCellEditor"); var selectCellEditor_1 = require("./cellEditors/selectCellEditor"); var popupEditorWrapper_1 = require("./cellEditors/popupEditorWrapper"); var popupTextCellEditor_1 = require("./cellEditors/popupTextCellEditor"); var popupSelectCellEditor_1 = require("./cellEditors/popupSelectCellEditor"); var gridOptionsWrapper_1 = require("../gridOptionsWrapper"); var largeTextCellEditor_1 = require("./cellEditors/largeTextCellEditor"); var CellEditorFactory = CellEditorFactory_1 = (function () { function CellEditorFactory() { this.cellEditorMap = {}; } CellEditorFactory.prototype.init = function () { this.cellEditorMap[CellEditorFactory_1.TEXT] = textCellEditor_1.TextCellEditor; this.cellEditorMap[CellEditorFactory_1.SELECT] = selectCellEditor_1.SelectCellEditor; this.cellEditorMap[CellEditorFactory_1.POPUP_TEXT] = popupTextCellEditor_1.PopupTextCellEditor; this.cellEditorMap[CellEditorFactory_1.POPUP_SELECT] = popupSelectCellEditor_1.PopupSelectCellEditor; this.cellEditorMap[CellEditorFactory_1.LARGE_TEXT] = largeTextCellEditor_1.LargeTextCellEditor; }; CellEditorFactory.prototype.addCellEditor = function (key, cellEditor) { this.cellEditorMap[key] = cellEditor; }; // private registerEditorsFromGridOptions(): void { // var userProvidedCellEditors = this.gridOptionsWrapper.getCellEditors(); // _.iterateObject(userProvidedCellEditors, (key: string, cellEditor: {new(): ICellEditor})=> { // this.addCellEditor(key, cellEditor); // }); // } CellEditorFactory.prototype.createCellEditor = function (key, params) { var CellEditorClass; if (utils_1.Utils.missing(key)) { CellEditorClass = this.cellEditorMap[CellEditorFactory_1.TEXT]; } else if (typeof key === 'string') { CellEditorClass = this.cellEditorMap[key]; if (utils_1.Utils.missing(CellEditorClass)) { console.warn('ag-Grid: unable to find cellEditor for key ' + key); CellEditorClass = this.cellEditorMap[CellEditorFactory_1.TEXT]; } } else { CellEditorClass = key; } var cellEditor = new CellEditorClass(); this.context.wireBean(cellEditor); // we have to call init first, otherwise when using the frameworks, the wrapper // classes won't be set up if (cellEditor.init) { cellEditor.init(params); } if (cellEditor.isPopup && cellEditor.isPopup()) { if (this.gridOptionsWrapper.isFullRowEdit()) { console.warn('ag-Grid: popup cellEditor does not work with fullRowEdit - you cannot use them both ' + '- either turn off fullRowEdit, or stop using popup editors.'); } cellEditor = new popupEditorWrapper_1.PopupEditorWrapper(cellEditor); cellEditor.init(params); } return cellEditor; }; return CellEditorFactory; }()); CellEditorFactory.TEXT = 'text'; CellEditorFactory.SELECT = 'select'; CellEditorFactory.POPUP_TEXT = 'popupText'; CellEditorFactory.POPUP_SELECT = 'popupSelect'; CellEditorFactory.LARGE_TEXT = 'largeText'; __decorate([ context_1.Autowired('context'), __metadata("design:type", context_1.Context) ], CellEditorFactory.prototype, "context", void 0); __decorate([ context_1.Autowired('gridOptionsWrapper'), __metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper) ], CellEditorFactory.prototype, "gridOptionsWrapper", void 0); __decorate([ context_1.PostConstruct, __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", void 0) ], CellEditorFactory.prototype, "init", null); CellEditorFactory = CellEditorFactory_1 = __decorate([ context_1.Bean('cellEditorFactory') ], CellEditorFactory); exports.CellEditorFactory = CellEditorFactory; var CellEditorFactory_1;
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v9.0.2 * @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 expressionService_1 = require("./expressionService"); var columnController_1 = require("./columnController/columnController"); var context_1 = require("./context/context"); var utils_1 = require("./utils"); var events_1 = require("./events"); var eventService_1 = require("./eventService"); var ValueService = (function () { function ValueService() { this.initialised = false; } ValueService.prototype.init = function () { this.cellExpressions = this.gridOptionsWrapper.isEnableCellExpressions(); this.userProvidedTheGroups = utils_1.Utils.exists(this.gridOptionsWrapper.getNodeChildDetailsFunc()); this.suppressUseColIdForGroups = this.gridOptionsWrapper.isSuppressUseColIdForGroups(); this.initialised = true; }; ValueService.prototype.getValue = function (column, node) { return this.getValueUsingSpecificData(column, node.data, node); }; ValueService.prototype.getValueUsingSpecificData = function (column, data, node) { // hack - the grid is getting refreshed before this bean gets initialised, race condition. // really should have a way so they get initialised in the right order??? if (!this.initialised) { this.init(); } var colDef = column.getColDef(); var field = colDef.field; var result; // if there is a value getter, this gets precedence over a field // - need to revisit this, we check 'data' as this is the way for the grid to // not render when on the footer row if (data && node.group && !this.userProvidedTheGroups && !this.suppressUseColIdForGroups) { result = node.data ? node.data[column.getId()] : undefined; } else if (colDef.valueGetter) { result = this.executeValueGetter(colDef.valueGetter, data, column, node); } else if (field && data) { result = utils_1.Utils.getValueUsingField(data, field, column.isFieldContainsDots()); } else { result = undefined; } // the result could be an expression itself, if we are allowing cell values to be expressions if (this.cellExpressions && (typeof result === 'string') && result.indexOf('=') === 0) { var cellValueGetter = result.substring(1); result = this.executeValueGetter(cellValueGetter, data, column, node); } return result; }; ValueService.prototype.setValue = function (rowNode, colKey, newValue) { var column = this.columnController.getPrimaryColumn(colKey); if (!rowNode || !column) { return; } // this will only happen if user is trying to paste into a group row, which doesn't make sense // the user should not be trying to paste into group rows var data = rowNode.data; if (utils_1.Utils.missing(data)) { return; } var field = column.getColDef().field; var newValueHandler = column.getColDef().newValueHandler; // need either a field or a newValueHandler for this to work if (utils_1.Utils.missing(field) && utils_1.Utils.missing(newValueHandler)) { console.warn("ag-Grid: you need either field or newValueHandler set on colDef for editing to work"); return; } var paramsForCallbacks = { node: rowNode, data: rowNode.data, oldValue: this.getValue(column, rowNode), newValue: newValue, colDef: column.getColDef(), api: this.gridOptionsWrapper.getApi(), context: this.gridOptionsWrapper.getContext() }; if (newValueHandler) { newValueHandler(paramsForCallbacks); } else { this.setValueUsingField(data, field, newValue, column.isFieldContainsDots()); } // reset quick filter on this row rowNode.resetQuickFilterAggregateText(); paramsForCallbacks.newValue = this.getValue(column, rowNode); if (typeof column.getColDef().onCellValueChanged === 'function') { column.getColDef().onCellValueChanged(paramsForCallbacks); } this.eventService.dispatchEvent(events_1.Events.EVENT_CELL_VALUE_CHANGED, paramsForCallbacks); }; ValueService.prototype.setValueUsingField = function (data, field, newValue, isFieldContainsDots) { // if no '.', then it's not a deep value if (!isFieldContainsDots) { data[field] = newValue; } else { // otherwise it is a deep value, so need to dig for it var fieldPieces = field.split('.'); var currentObject = data; while (fieldPieces.length > 0 && currentObject) { var fieldPiece = fieldPieces.shift(); if (fieldPieces.length === 0) { currentObject[fieldPiece] = newValue; } else { currentObject = currentObject[fieldPiece]; } } } }; ValueService.prototype.executeValueGetter = function (valueGetter, data, column, node) { var context = this.gridOptionsWrapper.getContext(); var api = this.gridOptionsWrapper.getApi(); var params = { data: data, node: node, colDef: column.getColDef(), api: api, context: context, getValue: this.getValueCallback.bind(this, data, node) }; if (typeof valueGetter === 'function') { // valueGetter is a function, so just call it return valueGetter(params); } else if (typeof valueGetter === 'string') { // valueGetter is an expression, so execute the expression return this.expressionService.evaluate(valueGetter, params); } }; ValueService.prototype.getValueCallback = function (data, node, field) { var otherColumn = this.columnController.getPrimaryColumn(field); if (otherColumn) { return this.getValueUsingSpecificData(otherColumn, data, node); } else { return null; } }; return ValueService; }()); __decorate([ context_1.Autowired('gridOptionsWrapper'), __metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper) ], ValueService.prototype, "gridOptionsWrapper", void 0); __decorate([ context_1.Autowired('expressionService'), __metadata("design:type", expressionService_1.ExpressionService) ], ValueService.prototype, "expressionService", void 0); __decorate([ context_1.Autowired('columnController'), __metadata("design:type", columnController_1.ColumnController) ], ValueService.prototype, "columnController", void 0); __decorate([ context_1.Autowired('eventService'), __metadata("design:type", eventService_1.EventService) ], ValueService.prototype, "eventService", void 0); __decorate([ context_1.PostConstruct, __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", void 0) ], ValueService.prototype, "init", null); ValueService = __decorate([ context_1.Bean('valueService') ], ValueService); exports.ValueService = ValueService;
/*! * Angular-PDF: An Angularjs directive <ng-pdf> to display PDF in the browser with PDFJS. * @version 1.6.0 * @link https://github.com/sayanee/angular-pdf#readme * @license MIT License, http://www.opensource.org/licenses/MIT */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("angular")); else if(typeof define === 'function' && define.amd) define("pdf", ["angular"], factory); else if(typeof exports === 'object') exports["pdf"] = factory(require("angular")); else root["pdf"] = factory(root["angular"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_0__) { 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] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = 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; /******/ /******/ // identity function for calling harmony imports with the correct context /******/ __webpack_require__.i = function(value) { return value; }; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "/"; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = "./src/angular-pdf.module.js"); /******/ }) /************************************************************************/ /******/ ({ /***/ "./src/angular-pdf.directive.js": /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var cov_2fg5t5f49d = function () { var path = '/Users/denny/git/angularjs-pdf/src/angular-pdf.directive.js', hash = 'c1e5fe6dd86903947afef54c11feff53857202dd', global = new Function('return this')(), gcv = '__coverage__', coverageData = { path: '/Users/denny/git/angularjs-pdf/src/angular-pdf.directive.js', statementMap: { '0': { start: { line: 1, column: 21 }, end: { line: 217, column: 1 } }, '1': { start: { line: 4, column: 23 }, end: { line: 14, column: 3 } }, '2': { start: { line: 5, column: 16 }, end: { line: 5, column: 39 } }, '3': { start: { line: 6, column: 16 }, end: { line: 6, column: 45 } }, '4': { start: { line: 7, column: 16 }, end: { line: 11, column: 37 } }, '5': { start: { line: 13, column: 4 }, end: { line: 13, column: 21 } }, '6': { start: { line: 16, column: 30 }, end: { line: 24, column: 3 } }, '7': { start: { line: 17, column: 18 }, end: { line: 17, column: 38 } }, '8': { start: { line: 18, column: 4 }, end: { line: 18, column: 41 } }, '9': { start: { line: 19, column: 4 }, end: { line: 19, column: 42 } }, '10': { start: { line: 20, column: 4 }, end: { line: 20, column: 46 } }, '11': { start: { line: 21, column: 4 }, end: { line: 21, column: 47 } }, '12': { start: { line: 22, column: 4 }, end: { line: 22, column: 67 } }, '13': { start: { line: 23, column: 4 }, end: { line: 23, column: 18 } }, '14': { start: { line: 26, column: 2 }, end: { line: 216, column: 3 } }, '15': { start: { line: 29, column: 6 }, end: { line: 29, column: 74 } }, '16': { start: { line: 32, column: 23 }, end: { line: 32, column: 27 } }, '17': { start: { line: 33, column: 26 }, end: { line: 33, column: 30 } }, '18': { start: { line: 34, column: 18 }, end: { line: 34, column: 23 } }, '19': { start: { line: 35, column: 16 }, end: { line: 35, column: 28 } }, '20': { start: { line: 36, column: 24 }, end: { line: 36, column: 41 } }, '21': { start: { line: 37, column: 19 }, end: { line: 37, column: 23 } }, '22': { start: { line: 38, column: 26 }, end: { line: 38, column: 73 } }, '23': { start: { line: 39, column: 20 }, end: { line: 39, column: 46 } }, '24': { start: { line: 40, column: 18 }, end: { line: 40, column: 51 } }, '25': { start: { line: 41, column: 21 }, end: { line: 41, column: 51 } }, '26': { start: { line: 42, column: 19 }, end: { line: 42, column: 56 } }, '27': { start: { line: 43, column: 18 }, end: { line: 43, column: 38 } }, '28': { start: { line: 44, column: 6 }, end: { line: 44, column: 66 } }, '29': { start: { line: 46, column: 16 }, end: { line: 46, column: 39 } }, '30': { start: { line: 47, column: 21 }, end: { line: 47, column: 45 } }, '31': { start: { line: 49, column: 6 }, end: { line: 49, column: 38 } }, '32': { start: { line: 51, column: 6 }, end: { line: 55, column: 9 } }, '33': { start: { line: 52, column: 8 }, end: { line: 54, column: 11 } }, '34': { start: { line: 53, column: 10 }, end: { line: 53, column: 45 } }, '35': { start: { line: 57, column: 6 }, end: { line: 57, column: 33 } }, '36': { start: { line: 58, column: 6 }, end: { line: 58, column: 36 } }, '37': { start: { line: 60, column: 6 }, end: { line: 94, column: 8 } }, '38': { start: { line: 61, column: 8 }, end: { line: 63, column: 9 } }, '39': { start: { line: 62, column: 10 }, end: { line: 62, column: 50 } }, '40': { start: { line: 65, column: 8 }, end: { line: 93, column: 11 } }, '41': { start: { line: 70, column: 10 }, end: { line: 75, column: 11 } }, '42': { start: { line: 71, column: 12 }, end: { line: 71, column: 43 } }, '43': { start: { line: 72, column: 31 }, end: { line: 72, column: 65 } }, '44': { start: { line: 73, column: 12 }, end: { line: 73, column: 63 } }, '45': { start: { line: 74, column: 12 }, end: { line: 74, column: 35 } }, '46': { start: { line: 76, column: 10 }, end: { line: 76, column: 45 } }, '47': { start: { line: 78, column: 10 }, end: { line: 78, column: 71 } }, '48': { start: { line: 80, column: 10 }, end: { line: 83, column: 12 } }, '49': { start: { line: 85, column: 10 }, end: { line: 85, column: 50 } }, '50': { start: { line: 86, column: 10 }, end: { line: 92, column: 13 } }, '51': { start: { line: 87, column: 12 }, end: { line: 89, column: 13 } }, '52': { start: { line: 88, column: 14 }, end: { line: 88, column: 35 } }, '53': { start: { line: 91, column: 12 }, end: { line: 91, column: 29 } }, '54': { start: { line: 96, column: 6 }, end: { line: 102, column: 8 } }, '55': { start: { line: 97, column: 8 }, end: { line: 99, column: 9 } }, '56': { start: { line: 98, column: 10 }, end: { line: 98, column: 17 } }, '57': { start: { line: 100, column: 8 }, end: { line: 100, column: 64 } }, '58': { start: { line: 101, column: 8 }, end: { line: 101, column: 44 } }, '59': { start: { line: 104, column: 6 }, end: { line: 110, column: 8 } }, '60': { start: { line: 105, column: 8 }, end: { line: 107, column: 9 } }, '61': { start: { line: 106, column: 10 }, end: { line: 106, column: 17 } }, '62': { start: { line: 108, column: 8 }, end: { line: 108, column: 64 } }, '63': { start: { line: 109, column: 8 }, end: { line: 109, column: 44 } }, '64': { start: { line: 112, column: 6 }, end: { line: 117, column: 8 } }, '65': { start: { line: 113, column: 8 }, end: { line: 113, column: 24 } }, '66': { start: { line: 114, column: 8 }, end: { line: 114, column: 40 } }, '67': { start: { line: 115, column: 8 }, end: { line: 115, column: 46 } }, '68': { start: { line: 116, column: 8 }, end: { line: 116, column: 21 } }, '69': { start: { line: 119, column: 6 }, end: { line: 124, column: 8 } }, '70': { start: { line: 120, column: 8 }, end: { line: 120, column: 24 } }, '71': { start: { line: 121, column: 8 }, end: { line: 121, column: 40 } }, '72': { start: { line: 122, column: 8 }, end: { line: 122, column: 46 } }, '73': { start: { line: 123, column: 8 }, end: { line: 123, column: 21 } }, '74': { start: { line: 126, column: 6 }, end: { line: 129, column: 7 } }, '75': { start: { line: 127, column: 8 }, end: { line: 127, column: 23 } }, '76': { start: { line: 128, column: 8 }, end: { line: 128, column: 46 } }, '77': { start: { line: 131, column: 6 }, end: { line: 133, column: 8 } }, '78': { start: { line: 132, column: 8 }, end: { line: 132, column: 46 } }, '79': { start: { line: 135, column: 6 }, end: { line: 145, column: 8 } }, '80': { start: { line: 136, column: 8 }, end: { line: 144, column: 9 } }, '81': { start: { line: 137, column: 10 }, end: { line: 137, column: 51 } }, '82': { start: { line: 138, column: 15 }, end: { line: 144, column: 9 } }, '83': { start: { line: 139, column: 10 }, end: { line: 139, column: 52 } }, '84': { start: { line: 140, column: 15 }, end: { line: 144, column: 9 } }, '85': { start: { line: 141, column: 10 }, end: { line: 141, column: 52 } }, '86': { start: { line: 143, column: 10 }, end: { line: 143, column: 50 } }, '87': { start: { line: 148, column: 8 }, end: { line: 150, column: 9 } }, '88': { start: { line: 149, column: 10 }, end: { line: 149, column: 59 } }, '89': { start: { line: 154, column: 8 }, end: { line: 154, column: 22 } }, '90': { start: { line: 156, column: 21 }, end: { line: 159, column: 9 } }, '91': { start: { line: 161, column: 8 }, end: { line: 163, column: 9 } }, '92': { start: { line: 162, column: 10 }, end: { line: 162, column: 43 } }, '93': { start: { line: 165, column: 8 }, end: { line: 189, column: 9 } }, '94': { start: { line: 166, column: 10 }, end: { line: 166, column: 52 } }, '95': { start: { line: 167, column: 10 }, end: { line: 167, column: 54 } }, '96': { start: { line: 168, column: 10 }, end: { line: 168, column: 54 } }, '97': { start: { line: 169, column: 10 }, end: { line: 188, column: 12 } }, '98': { start: { line: 171, column: 14 }, end: { line: 173, column: 15 } }, '99': { start: { line: 172, column: 16 }, end: { line: 172, column: 31 } }, '100': { start: { line: 175, column: 14 }, end: { line: 175, column: 31 } }, '101': { start: { line: 176, column: 14 }, end: { line: 176, column: 52 } }, '102': { start: { line: 178, column: 14 }, end: { line: 180, column: 17 } }, '103': { start: { line: 179, column: 16 }, end: { line: 179, column: 51 } }, '104': { start: { line: 182, column: 14 }, end: { line: 186, column: 15 } }, '105': { start: { line: 183, column: 16 }, end: { line: 185, column: 17 } }, '106': { start: { line: 184, column: 18 }, end: { line: 184, column: 39 } }, '107': { start: { line: 192, column: 6 }, end: { line: 197, column: 9 } }, '108': { start: { line: 193, column: 8 }, end: { line: 193, column: 47 } }, '109': { start: { line: 194, column: 8 }, end: { line: 196, column: 9 } }, '110': { start: { line: 195, column: 10 }, end: { line: 195, column: 48 } }, '111': { start: { line: 199, column: 6 }, end: { line: 214, column: 9 } }, '112': { start: { line: 200, column: 8 }, end: { line: 213, column: 9 } }, '113': { start: { line: 201, column: 10 }, end: { line: 203, column: 11 } }, '114': { start: { line: 202, column: 12 }, end: { line: 202, column: 69 } }, '115': { start: { line: 204, column: 10 }, end: { line: 204, column: 23 } }, '116': { start: { line: 205, column: 10 }, end: { line: 205, column: 62 } }, '117': { start: { line: 206, column: 10 }, end: { line: 212, column: 11 } }, '118': { start: { line: 207, column: 12 }, end: { line: 209, column: 15 } }, '119': { start: { line: 208, column: 14 }, end: { line: 208, column: 26 } }, '120': { start: { line: 211, column: 12 }, end: { line: 211, column: 24 } } }, fnMap: { '0': { name: '(anonymous_0)', decl: { start: { line: 1, column: 21 }, end: { line: 1, column: 22 } }, loc: { start: { line: 1, column: 51 }, end: { line: 217, column: 1 } }, line: 1 }, '1': { name: '(anonymous_1)', decl: { start: { line: 4, column: 23 }, end: { line: 4, column: 24 } }, loc: { start: { line: 4, column: 33 }, end: { line: 14, column: 3 } }, line: 4 }, '2': { name: '(anonymous_2)', decl: { start: { line: 16, column: 30 }, end: { line: 16, column: 31 } }, loc: { start: { line: 16, column: 48 }, end: { line: 24, column: 3 } }, line: 16 }, '3': { name: '(anonymous_3)', decl: { start: { line: 51, column: 28 }, end: { line: 51, column: 29 } }, loc: { start: { line: 51, column: 34 }, end: { line: 55, column: 7 } }, line: 51 }, '4': { name: '(anonymous_4)', decl: { start: { line: 52, column: 21 }, end: { line: 52, column: 22 } }, loc: { start: { line: 52, column: 27 }, end: { line: 54, column: 9 } }, line: 52 }, '5': { name: '(anonymous_5)', decl: { start: { line: 60, column: 25 }, end: { line: 60, column: 26 } }, loc: { start: { line: 60, column: 32 }, end: { line: 94, column: 7 } }, line: 60 }, '6': { name: '(anonymous_6)', decl: { start: { line: 65, column: 33 }, end: { line: 65, column: 34 } }, loc: { start: { line: 65, column: 41 }, end: { line: 93, column: 9 } }, line: 65 }, '7': { name: '(anonymous_7)', decl: { start: { line: 86, column: 34 }, end: { line: 86, column: 35 } }, loc: { start: { line: 86, column: 40 }, end: { line: 90, column: 11 } }, line: 86 }, '8': { name: '(anonymous_8)', decl: { start: { line: 90, column: 19 }, end: { line: 90, column: 20 } }, loc: { start: { line: 90, column: 29 }, end: { line: 92, column: 11 } }, line: 90 }, '9': { name: '(anonymous_9)', decl: { start: { line: 96, column: 25 }, end: { line: 96, column: 26 } }, loc: { start: { line: 96, column: 31 }, end: { line: 102, column: 7 } }, line: 96 }, '10': { name: '(anonymous_10)', decl: { start: { line: 104, column: 21 }, end: { line: 104, column: 22 } }, loc: { start: { line: 104, column: 27 }, end: { line: 110, column: 7 } }, line: 104 }, '11': { name: '(anonymous_11)', decl: { start: { line: 112, column: 21 }, end: { line: 112, column: 22 } }, loc: { start: { line: 112, column: 27 }, end: { line: 117, column: 7 } }, line: 112 }, '12': { name: '(anonymous_12)', decl: { start: { line: 119, column: 22 }, end: { line: 119, column: 23 } }, loc: { start: { line: 119, column: 28 }, end: { line: 124, column: 7 } }, line: 119 }, '13': { name: '(anonymous_13)', decl: { start: { line: 126, column: 18 }, end: { line: 126, column: 19 } }, loc: { start: { line: 126, column: 24 }, end: { line: 129, column: 7 } }, line: 126 }, '14': { name: '(anonymous_14)', decl: { start: { line: 131, column: 25 }, end: { line: 131, column: 26 } }, loc: { start: { line: 131, column: 31 }, end: { line: 133, column: 7 } }, line: 131 }, '15': { name: '(anonymous_15)', decl: { start: { line: 135, column: 21 }, end: { line: 135, column: 22 } }, loc: { start: { line: 135, column: 27 }, end: { line: 145, column: 7 } }, line: 135 }, '16': { name: 'clearCanvas', decl: { start: { line: 147, column: 15 }, end: { line: 147, column: 26 } }, loc: { start: { line: 147, column: 29 }, end: { line: 151, column: 7 } }, line: 147 }, '17': { name: 'renderPDF', decl: { start: { line: 153, column: 15 }, end: { line: 153, column: 24 } }, loc: { start: { line: 153, column: 27 }, end: { line: 190, column: 7 } }, line: 153 }, '18': { name: '(anonymous_18)', decl: { start: { line: 170, column: 12 }, end: { line: 170, column: 13 } }, loc: { start: { line: 170, column: 23 }, end: { line: 181, column: 13 } }, line: 170 }, '19': { name: '(anonymous_19)', decl: { start: { line: 178, column: 27 }, end: { line: 178, column: 28 } }, loc: { start: { line: 178, column: 33 }, end: { line: 180, column: 15 } }, line: 178 }, '20': { name: '(anonymous_20)', decl: { start: { line: 181, column: 15 }, end: { line: 181, column: 16 } }, loc: { start: { line: 181, column: 24 }, end: { line: 187, column: 13 } }, line: 181 }, '21': { name: '(anonymous_21)', decl: { start: { line: 192, column: 30 }, end: { line: 192, column: 31 } }, loc: { start: { line: 192, column: 40 }, end: { line: 197, column: 7 } }, line: 192 }, '22': { name: '(anonymous_22)', decl: { start: { line: 199, column: 29 }, end: { line: 199, column: 30 } }, loc: { start: { line: 199, column: 39 }, end: { line: 214, column: 7 } }, line: 199 }, '23': { name: '(anonymous_23)', decl: { start: { line: 207, column: 41 }, end: { line: 207, column: 42 } }, loc: { start: { line: 207, column: 47 }, end: { line: 209, column: 13 } }, line: 207 } }, branchMap: { '0': { loc: { start: { line: 6, column: 16 }, end: { line: 6, column: 45 } }, type: 'binary-expr', locations: [{ start: { line: 6, column: 16 }, end: { line: 6, column: 40 } }, { start: { line: 6, column: 44 }, end: { line: 6, column: 45 } }], line: 6 }, '1': { loc: { start: { line: 7, column: 16 }, end: { line: 11, column: 37 } }, type: 'binary-expr', locations: [{ start: { line: 7, column: 16 }, end: { line: 7, column: 48 } }, { start: { line: 8, column: 6 }, end: { line: 8, column: 35 } }, { start: { line: 9, column: 6 }, end: { line: 9, column: 34 } }, { start: { line: 10, column: 6 }, end: { line: 10, column: 33 } }, { start: { line: 11, column: 6 }, end: { line: 11, column: 32 } }, { start: { line: 11, column: 36 }, end: { line: 11, column: 37 } }], line: 7 }, '2': { loc: { start: { line: 29, column: 13 }, end: { line: 29, column: 73 } }, type: 'cond-expr', locations: [{ start: { line: 29, column: 32 }, end: { line: 29, column: 48 } }, { start: { line: 29, column: 51 }, end: { line: 29, column: 73 } }], line: 29 }, '3': { loc: { start: { line: 38, column: 26 }, end: { line: 38, column: 73 } }, type: 'cond-expr', locations: [{ start: { line: 38, column: 49 }, end: { line: 38, column: 69 } }, { start: { line: 38, column: 72 }, end: { line: 38, column: 73 } }], line: 38 }, '4': { loc: { start: { line: 40, column: 18 }, end: { line: 40, column: 51 } }, type: 'cond-expr', locations: [{ start: { line: 40, column: 36 }, end: { line: 40, column: 47 } }, { start: { line: 40, column: 50 }, end: { line: 40, column: 51 } }], line: 40 }, '5': { loc: { start: { line: 41, column: 21 }, end: { line: 41, column: 51 } }, type: 'binary-expr', locations: [{ start: { line: 41, column: 21 }, end: { line: 41, column: 35 } }, { start: { line: 41, column: 39 }, end: { line: 41, column: 51 } }], line: 41 }, '6': { loc: { start: { line: 44, column: 14 }, end: { line: 44, column: 65 } }, type: 'cond-expr', locations: [{ start: { line: 44, column: 46 }, end: { line: 44, column: 57 } }, { start: { line: 44, column: 60 }, end: { line: 44, column: 65 } }], line: 44 }, '7': { loc: { start: { line: 61, column: 8 }, end: { line: 63, column: 9 } }, type: 'if', locations: [{ start: { line: 61, column: 8 }, end: { line: 63, column: 9 } }, { start: { line: 61, column: 8 }, end: { line: 63, column: 9 } }], line: 61 }, '8': { loc: { start: { line: 70, column: 10 }, end: { line: 75, column: 11 } }, type: 'if', locations: [{ start: { line: 70, column: 10 }, end: { line: 75, column: 11 } }, { start: { line: 70, column: 10 }, end: { line: 75, column: 11 } }], line: 70 }, '9': { loc: { start: { line: 87, column: 12 }, end: { line: 89, column: 13 } }, type: 'if', locations: [{ start: { line: 87, column: 12 }, end: { line: 89, column: 13 } }, { start: { line: 87, column: 12 }, end: { line: 89, column: 13 } }], line: 87 }, '10': { loc: { start: { line: 97, column: 8 }, end: { line: 99, column: 9 } }, type: 'if', locations: [{ start: { line: 97, column: 8 }, end: { line: 99, column: 9 } }, { start: { line: 97, column: 8 }, end: { line: 99, column: 9 } }], line: 97 }, '11': { loc: { start: { line: 105, column: 8 }, end: { line: 107, column: 9 } }, type: 'if', locations: [{ start: { line: 105, column: 8 }, end: { line: 107, column: 9 } }, { start: { line: 105, column: 8 }, end: { line: 107, column: 9 } }], line: 105 }, '12': { loc: { start: { line: 136, column: 8 }, end: { line: 144, column: 9 } }, type: 'if', locations: [{ start: { line: 136, column: 8 }, end: { line: 144, column: 9 } }, { start: { line: 136, column: 8 }, end: { line: 144, column: 9 } }], line: 136 }, '13': { loc: { start: { line: 138, column: 15 }, end: { line: 144, column: 9 } }, type: 'if', locations: [{ start: { line: 138, column: 15 }, end: { line: 144, column: 9 } }, { start: { line: 138, column: 15 }, end: { line: 144, column: 9 } }], line: 138 }, '14': { loc: { start: { line: 140, column: 15 }, end: { line: 144, column: 9 } }, type: 'if', locations: [{ start: { line: 140, column: 15 }, end: { line: 144, column: 9 } }, { start: { line: 140, column: 15 }, end: { line: 144, column: 9 } }], line: 140 }, '15': { loc: { start: { line: 148, column: 8 }, end: { line: 150, column: 9 } }, type: 'if', locations: [{ start: { line: 148, column: 8 }, end: { line: 150, column: 9 } }, { start: { line: 148, column: 8 }, end: { line: 150, column: 9 } }], line: 148 }, '16': { loc: { start: { line: 161, column: 8 }, end: { line: 163, column: 9 } }, type: 'if', locations: [{ start: { line: 161, column: 8 }, end: { line: 163, column: 9 } }, { start: { line: 161, column: 8 }, end: { line: 163, column: 9 } }], line: 161 }, '17': { loc: { start: { line: 165, column: 8 }, end: { line: 189, column: 9 } }, type: 'if', locations: [{ start: { line: 165, column: 8 }, end: { line: 189, column: 9 } }, { start: { line: 165, column: 8 }, end: { line: 189, column: 9 } }], line: 165 }, '18': { loc: { start: { line: 165, column: 12 }, end: { line: 165, column: 29 } }, type: 'binary-expr', locations: [{ start: { line: 165, column: 12 }, end: { line: 165, column: 15 } }, { start: { line: 165, column: 19 }, end: { line: 165, column: 29 } }], line: 165 }, '19': { loc: { start: { line: 171, column: 14 }, end: { line: 173, column: 15 } }, type: 'if', locations: [{ start: { line: 171, column: 14 }, end: { line: 173, column: 15 } }, { start: { line: 171, column: 14 }, end: { line: 173, column: 15 } }], line: 171 }, '20': { loc: { start: { line: 182, column: 14 }, end: { line: 186, column: 15 } }, type: 'if', locations: [{ start: { line: 182, column: 14 }, end: { line: 186, column: 15 } }, { start: { line: 182, column: 14 }, end: { line: 186, column: 15 } }], line: 182 }, '21': { loc: { start: { line: 183, column: 16 }, end: { line: 185, column: 17 } }, type: 'if', locations: [{ start: { line: 183, column: 16 }, end: { line: 185, column: 17 } }, { start: { line: 183, column: 16 }, end: { line: 185, column: 17 } }], line: 183 }, '22': { loc: { start: { line: 194, column: 8 }, end: { line: 196, column: 9 } }, type: 'if', locations: [{ start: { line: 194, column: 8 }, end: { line: 196, column: 9 } }, { start: { line: 194, column: 8 }, end: { line: 196, column: 9 } }], line: 194 }, '23': { loc: { start: { line: 200, column: 8 }, end: { line: 213, column: 9 } }, type: 'if', locations: [{ start: { line: 200, column: 8 }, end: { line: 213, column: 9 } }, { start: { line: 200, column: 8 }, end: { line: 213, column: 9 } }], line: 200 }, '24': { loc: { start: { line: 201, column: 10 }, end: { line: 203, column: 11 } }, type: 'if', locations: [{ start: { line: 201, column: 10 }, end: { line: 203, column: 11 } }, { start: { line: 201, column: 10 }, end: { line: 203, column: 11 } }], line: 201 }, '25': { loc: { start: { line: 206, column: 10 }, end: { line: 212, column: 11 } }, type: 'if', locations: [{ start: { line: 206, column: 10 }, end: { line: 212, column: 11 } }, { start: { line: 206, column: 10 }, end: { line: 212, column: 11 } }], line: 206 } }, s: { '0': 0, '1': 0, '2': 0, '3': 0, '4': 0, '5': 0, '6': 0, '7': 0, '8': 0, '9': 0, '10': 0, '11': 0, '12': 0, '13': 0, '14': 0, '15': 0, '16': 0, '17': 0, '18': 0, '19': 0, '20': 0, '21': 0, '22': 0, '23': 0, '24': 0, '25': 0, '26': 0, '27': 0, '28': 0, '29': 0, '30': 0, '31': 0, '32': 0, '33': 0, '34': 0, '35': 0, '36': 0, '37': 0, '38': 0, '39': 0, '40': 0, '41': 0, '42': 0, '43': 0, '44': 0, '45': 0, '46': 0, '47': 0, '48': 0, '49': 0, '50': 0, '51': 0, '52': 0, '53': 0, '54': 0, '55': 0, '56': 0, '57': 0, '58': 0, '59': 0, '60': 0, '61': 0, '62': 0, '63': 0, '64': 0, '65': 0, '66': 0, '67': 0, '68': 0, '69': 0, '70': 0, '71': 0, '72': 0, '73': 0, '74': 0, '75': 0, '76': 0, '77': 0, '78': 0, '79': 0, '80': 0, '81': 0, '82': 0, '83': 0, '84': 0, '85': 0, '86': 0, '87': 0, '88': 0, '89': 0, '90': 0, '91': 0, '92': 0, '93': 0, '94': 0, '95': 0, '96': 0, '97': 0, '98': 0, '99': 0, '100': 0, '101': 0, '102': 0, '103': 0, '104': 0, '105': 0, '106': 0, '107': 0, '108': 0, '109': 0, '110': 0, '111': 0, '112': 0, '113': 0, '114': 0, '115': 0, '116': 0, '117': 0, '118': 0, '119': 0, '120': 0 }, f: { '0': 0, '1': 0, '2': 0, '3': 0, '4': 0, '5': 0, '6': 0, '7': 0, '8': 0, '9': 0, '10': 0, '11': 0, '12': 0, '13': 0, '14': 0, '15': 0, '16': 0, '17': 0, '18': 0, '19': 0, '20': 0, '21': 0, '22': 0, '23': 0 }, b: { '0': [0, 0], '1': [0, 0, 0, 0, 0, 0], '2': [0, 0], '3': [0, 0], '4': [0, 0], '5': [0, 0], '6': [0, 0], '7': [0, 0], '8': [0, 0], '9': [0, 0], '10': [0, 0], '11': [0, 0], '12': [0, 0], '13': [0, 0], '14': [0, 0], '15': [0, 0], '16': [0, 0], '17': [0, 0], '18': [0, 0], '19': [0, 0], '20': [0, 0], '21': [0, 0], '22': [0, 0], '23': [0, 0], '24': [0, 0], '25': [0, 0] }, _coverageSchema: '332fd63041d2c1bcb487cc26dd0d5f7d97098a6c' }, coverage = global[gcv] || (global[gcv] = {}); if (coverage[path] && coverage[path].hash === hash) { return coverage[path]; } coverageData.hash = hash; return coverage[path] = coverageData; }(); var NgPdf = exports.NgPdf = (++cov_2fg5t5f49d.s[0], ["$window", "$document", "$log", function ($window, $document, $log) { 'ngInject'; ++cov_2fg5t5f49d.f[0]; ++cov_2fg5t5f49d.s[1]; var backingScale = function backingScale(canvas) { ++cov_2fg5t5f49d.f[1]; var ctx = (++cov_2fg5t5f49d.s[2], canvas.getContext('2d')); var dpr = (++cov_2fg5t5f49d.s[3], (++cov_2fg5t5f49d.b[0][0], $window.devicePixelRatio) || (++cov_2fg5t5f49d.b[0][1], 1)); var bsr = (++cov_2fg5t5f49d.s[4], (++cov_2fg5t5f49d.b[1][0], ctx.webkitBackingStorePixelRatio) || (++cov_2fg5t5f49d.b[1][1], ctx.mozBackingStorePixelRatio) || (++cov_2fg5t5f49d.b[1][2], ctx.msBackingStorePixelRatio) || (++cov_2fg5t5f49d.b[1][3], ctx.oBackingStorePixelRatio) || (++cov_2fg5t5f49d.b[1][4], ctx.backingStorePixelRatio) || (++cov_2fg5t5f49d.b[1][5], 1)); ++cov_2fg5t5f49d.s[5]; return dpr / bsr; }; ++cov_2fg5t5f49d.s[6]; var setCanvasDimensions = function setCanvasDimensions(canvas, w, h) { ++cov_2fg5t5f49d.f[2]; var ratio = (++cov_2fg5t5f49d.s[7], backingScale(canvas)); ++cov_2fg5t5f49d.s[8]; canvas.width = Math.floor(w * ratio); ++cov_2fg5t5f49d.s[9]; canvas.height = Math.floor(h * ratio); ++cov_2fg5t5f49d.s[10]; canvas.style.width = Math.floor(w) + 'px'; ++cov_2fg5t5f49d.s[11]; canvas.style.height = Math.floor(h) + 'px'; ++cov_2fg5t5f49d.s[12]; canvas.getContext('2d').setTransform(ratio, 0, 0, ratio, 0, 0); ++cov_2fg5t5f49d.s[13]; return canvas; }; ++cov_2fg5t5f49d.s[14]; return { restrict: 'E', templateUrl: function templateUrl(element, attr) { ++cov_2fg5t5f49d.s[15]; return attr.templateUrl ? (++cov_2fg5t5f49d.b[2][0], attr.templateUrl) : (++cov_2fg5t5f49d.b[2][1], 'partials/viewer.html'); }, link: function link(scope, element, attrs) { var renderTask = (++cov_2fg5t5f49d.s[16], null); var pdfLoaderTask = (++cov_2fg5t5f49d.s[17], null); var debug = (++cov_2fg5t5f49d.s[18], false); var url = (++cov_2fg5t5f49d.s[19], scope.pdfUrl); var httpHeaders = (++cov_2fg5t5f49d.s[20], scope.httpHeaders); var pdfDoc = (++cov_2fg5t5f49d.s[21], null); var pageToDisplay = (++cov_2fg5t5f49d.s[22], isFinite(attrs.page) ? (++cov_2fg5t5f49d.b[3][0], parseInt(attrs.page)) : (++cov_2fg5t5f49d.b[3][1], 1)); var pageFit = (++cov_2fg5t5f49d.s[23], attrs.scale === 'page-fit'); var scale = (++cov_2fg5t5f49d.s[24], attrs.scale > 0 ? (++cov_2fg5t5f49d.b[4][0], attrs.scale) : (++cov_2fg5t5f49d.b[4][1], 1)); var canvasid = (++cov_2fg5t5f49d.s[25], (++cov_2fg5t5f49d.b[5][0], attrs.canvasid) || (++cov_2fg5t5f49d.b[5][1], 'pdf-canvas')); var canvas = (++cov_2fg5t5f49d.s[26], $document[0].getElementById(canvasid)); var creds = (++cov_2fg5t5f49d.s[27], attrs.usecredentials); ++cov_2fg5t5f49d.s[28]; debug = attrs.hasOwnProperty('debug') ? (++cov_2fg5t5f49d.b[6][0], attrs.debug) : (++cov_2fg5t5f49d.b[6][1], false); var ctx = (++cov_2fg5t5f49d.s[29], canvas.getContext('2d')); var windowEl = (++cov_2fg5t5f49d.s[30], angular.element($window)); ++cov_2fg5t5f49d.s[31]; element.css('display', 'block'); ++cov_2fg5t5f49d.s[32]; windowEl.on('scroll', function () { ++cov_2fg5t5f49d.f[3]; ++cov_2fg5t5f49d.s[33]; scope.$apply(function () { ++cov_2fg5t5f49d.f[4]; ++cov_2fg5t5f49d.s[34]; scope.scroll = windowEl[0].scrollY; }); }); ++cov_2fg5t5f49d.s[35]; PDFJS.disableWorker = true; ++cov_2fg5t5f49d.s[36]; scope.pageNum = pageToDisplay; ++cov_2fg5t5f49d.s[37]; scope.renderPage = function (num) { ++cov_2fg5t5f49d.f[5]; ++cov_2fg5t5f49d.s[38]; if (renderTask) { ++cov_2fg5t5f49d.b[7][0]; ++cov_2fg5t5f49d.s[39]; renderTask._internalRenderTask.cancel(); } else { ++cov_2fg5t5f49d.b[7][1]; } ++cov_2fg5t5f49d.s[40]; pdfDoc.getPage(num).then(function (page) { ++cov_2fg5t5f49d.f[6]; var viewport = void 0; var pageWidthScale = void 0; var renderContext = void 0; ++cov_2fg5t5f49d.s[41]; if (pageFit) { ++cov_2fg5t5f49d.b[8][0]; ++cov_2fg5t5f49d.s[42]; viewport = page.getViewport(1); var clientRect = (++cov_2fg5t5f49d.s[43], element[0].getBoundingClientRect()); ++cov_2fg5t5f49d.s[44]; pageWidthScale = clientRect.width / viewport.width; ++cov_2fg5t5f49d.s[45]; scale = pageWidthScale; } else { ++cov_2fg5t5f49d.b[8][1]; } ++cov_2fg5t5f49d.s[46]; viewport = page.getViewport(scale); ++cov_2fg5t5f49d.s[47]; setCanvasDimensions(canvas, viewport.width, viewport.height); ++cov_2fg5t5f49d.s[48]; renderContext = { canvasContext: ctx, viewport: viewport }; ++cov_2fg5t5f49d.s[49]; renderTask = page.render(renderContext); ++cov_2fg5t5f49d.s[50]; renderTask.promise.then(function () { ++cov_2fg5t5f49d.f[7]; ++cov_2fg5t5f49d.s[51]; if (angular.isFunction(scope.onPageRender)) { ++cov_2fg5t5f49d.b[9][0]; ++cov_2fg5t5f49d.s[52]; scope.onPageRender(); } else { ++cov_2fg5t5f49d.b[9][1]; } }).catch(function (reason) { ++cov_2fg5t5f49d.f[8]; ++cov_2fg5t5f49d.s[53]; $log.log(reason); }); }); }; ++cov_2fg5t5f49d.s[54]; scope.goPrevious = function () { ++cov_2fg5t5f49d.f[9]; ++cov_2fg5t5f49d.s[55]; if (scope.pageToDisplay <= 1) { ++cov_2fg5t5f49d.b[10][0]; ++cov_2fg5t5f49d.s[56]; return; } else { ++cov_2fg5t5f49d.b[10][1]; } ++cov_2fg5t5f49d.s[57]; scope.pageToDisplay = parseInt(scope.pageToDisplay) - 1; ++cov_2fg5t5f49d.s[58]; scope.pageNum = scope.pageToDisplay; }; ++cov_2fg5t5f49d.s[59]; scope.goNext = function () { ++cov_2fg5t5f49d.f[10]; ++cov_2fg5t5f49d.s[60]; if (scope.pageToDisplay >= pdfDoc.numPages) { ++cov_2fg5t5f49d.b[11][0]; ++cov_2fg5t5f49d.s[61]; return; } else { ++cov_2fg5t5f49d.b[11][1]; } ++cov_2fg5t5f49d.s[62]; scope.pageToDisplay = parseInt(scope.pageToDisplay) + 1; ++cov_2fg5t5f49d.s[63]; scope.pageNum = scope.pageToDisplay; }; ++cov_2fg5t5f49d.s[64]; scope.zoomIn = function () { ++cov_2fg5t5f49d.f[11]; ++cov_2fg5t5f49d.s[65]; pageFit = false; ++cov_2fg5t5f49d.s[66]; scale = parseFloat(scale) + 0.2; ++cov_2fg5t5f49d.s[67]; scope.renderPage(scope.pageToDisplay); ++cov_2fg5t5f49d.s[68]; return scale; }; ++cov_2fg5t5f49d.s[69]; scope.zoomOut = function () { ++cov_2fg5t5f49d.f[12]; ++cov_2fg5t5f49d.s[70]; pageFit = false; ++cov_2fg5t5f49d.s[71]; scale = parseFloat(scale) - 0.2; ++cov_2fg5t5f49d.s[72]; scope.renderPage(scope.pageToDisplay); ++cov_2fg5t5f49d.s[73]; return scale; }; ++cov_2fg5t5f49d.s[74]; scope.fit = function () { ++cov_2fg5t5f49d.f[13]; ++cov_2fg5t5f49d.s[75]; pageFit = true; ++cov_2fg5t5f49d.s[76]; scope.renderPage(scope.pageToDisplay); }; ++cov_2fg5t5f49d.s[77]; scope.changePage = function () { ++cov_2fg5t5f49d.f[14]; ++cov_2fg5t5f49d.s[78]; scope.renderPage(scope.pageToDisplay); }; ++cov_2fg5t5f49d.s[79]; scope.rotate = function () { ++cov_2fg5t5f49d.f[15]; ++cov_2fg5t5f49d.s[80]; if (canvas.getAttribute('class') === 'rotate0') { ++cov_2fg5t5f49d.b[12][0]; ++cov_2fg5t5f49d.s[81]; canvas.setAttribute('class', 'rotate90'); } else { ++cov_2fg5t5f49d.b[12][1]; ++cov_2fg5t5f49d.s[82]; if (canvas.getAttribute('class') === 'rotate90') { ++cov_2fg5t5f49d.b[13][0]; ++cov_2fg5t5f49d.s[83]; canvas.setAttribute('class', 'rotate180'); } else { ++cov_2fg5t5f49d.b[13][1]; ++cov_2fg5t5f49d.s[84]; if (canvas.getAttribute('class') === 'rotate180') { ++cov_2fg5t5f49d.b[14][0]; ++cov_2fg5t5f49d.s[85]; canvas.setAttribute('class', 'rotate270'); } else { ++cov_2fg5t5f49d.b[14][1]; ++cov_2fg5t5f49d.s[86]; canvas.setAttribute('class', 'rotate0'); } } } }; function clearCanvas() { ++cov_2fg5t5f49d.f[16]; ++cov_2fg5t5f49d.s[87]; if (ctx) { ++cov_2fg5t5f49d.b[15][0]; ++cov_2fg5t5f49d.s[88]; ctx.clearRect(0, 0, canvas.width, canvas.height); } else { ++cov_2fg5t5f49d.b[15][1]; } } function renderPDF() { ++cov_2fg5t5f49d.f[17]; ++cov_2fg5t5f49d.s[89]; clearCanvas(); var params = (++cov_2fg5t5f49d.s[90], { 'url': url, 'withCredentials': creds }); ++cov_2fg5t5f49d.s[91]; if (httpHeaders) { ++cov_2fg5t5f49d.b[16][0]; ++cov_2fg5t5f49d.s[92]; params.httpHeaders = httpHeaders; } else { ++cov_2fg5t5f49d.b[16][1]; } ++cov_2fg5t5f49d.s[93]; if ((++cov_2fg5t5f49d.b[18][0], url) && (++cov_2fg5t5f49d.b[18][1], url.length)) { ++cov_2fg5t5f49d.b[17][0]; ++cov_2fg5t5f49d.s[94]; pdfLoaderTask = PDFJS.getDocument(params); ++cov_2fg5t5f49d.s[95]; pdfLoaderTask.onProgress = scope.onProgress; ++cov_2fg5t5f49d.s[96]; pdfLoaderTask.onPassword = scope.onPassword; ++cov_2fg5t5f49d.s[97]; pdfLoaderTask.then(function (_pdfDoc) { ++cov_2fg5t5f49d.f[18]; ++cov_2fg5t5f49d.s[98]; if (angular.isFunction(scope.onLoad)) { ++cov_2fg5t5f49d.b[19][0]; ++cov_2fg5t5f49d.s[99]; scope.onLoad(); } else { ++cov_2fg5t5f49d.b[19][1]; } ++cov_2fg5t5f49d.s[100]; pdfDoc = _pdfDoc; ++cov_2fg5t5f49d.s[101]; scope.renderPage(scope.pageToDisplay); ++cov_2fg5t5f49d.s[102]; scope.$apply(function () { ++cov_2fg5t5f49d.f[19]; ++cov_2fg5t5f49d.s[103]; scope.pageCount = _pdfDoc.numPages; }); }, function (error) { ++cov_2fg5t5f49d.f[20]; ++cov_2fg5t5f49d.s[104]; if (error) { ++cov_2fg5t5f49d.b[20][0]; ++cov_2fg5t5f49d.s[105]; if (angular.isFunction(scope.onError)) { ++cov_2fg5t5f49d.b[21][0]; ++cov_2fg5t5f49d.s[106]; scope.onError(error); } else { ++cov_2fg5t5f49d.b[21][1]; } } else { ++cov_2fg5t5f49d.b[20][1]; } }); } else { ++cov_2fg5t5f49d.b[17][1]; } } ++cov_2fg5t5f49d.s[107]; scope.$watch('pageNum', function (newVal) { ++cov_2fg5t5f49d.f[21]; ++cov_2fg5t5f49d.s[108]; scope.pageToDisplay = parseInt(newVal); ++cov_2fg5t5f49d.s[109]; if (pdfDoc !== null) { ++cov_2fg5t5f49d.b[22][0]; ++cov_2fg5t5f49d.s[110]; scope.renderPage(scope.pageToDisplay); } else { ++cov_2fg5t5f49d.b[22][1]; } }); ++cov_2fg5t5f49d.s[111]; scope.$watch('pdfUrl', function (newVal) { ++cov_2fg5t5f49d.f[22]; ++cov_2fg5t5f49d.s[112]; if (newVal !== '') { ++cov_2fg5t5f49d.b[23][0]; ++cov_2fg5t5f49d.s[113]; if (debug) { ++cov_2fg5t5f49d.b[24][0]; ++cov_2fg5t5f49d.s[114]; $log.log('pdfUrl value change detected: ', scope.pdfUrl); } else { ++cov_2fg5t5f49d.b[24][1]; } ++cov_2fg5t5f49d.s[115]; url = newVal; ++cov_2fg5t5f49d.s[116]; scope.pageNum = scope.pageToDisplay = pageToDisplay; ++cov_2fg5t5f49d.s[117]; if (pdfLoaderTask) { ++cov_2fg5t5f49d.b[25][0]; ++cov_2fg5t5f49d.s[118]; pdfLoaderTask.destroy().then(function () { ++cov_2fg5t5f49d.f[23]; ++cov_2fg5t5f49d.s[119]; renderPDF(); }); } else { ++cov_2fg5t5f49d.b[25][1]; ++cov_2fg5t5f49d.s[120]; renderPDF(); } } else { ++cov_2fg5t5f49d.b[23][1]; } }); } }; }]); /***/ }), /***/ "./src/angular-pdf.module.js": /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Pdf = undefined; var cov_1rmvbbu9ah = function () { var path = '/Users/denny/git/angularjs-pdf/src/angular-pdf.module.js', hash = '0e2d9432ed38b7f829d9e27ba392ee3abb9e801f', global = new Function('return this')(), gcv = '__coverage__', coverageData = { path: '/Users/denny/git/angularjs-pdf/src/angular-pdf.module.js', statementMap: { '0': { start: { line: 4, column: 19 }, end: { line: 7, column: 7 } } }, fnMap: {}, branchMap: {}, s: { '0': 0 }, f: {}, b: {}, _coverageSchema: '332fd63041d2c1bcb487cc26dd0d5f7d97098a6c' }, coverage = global[gcv] || (global[gcv] = {}); if (coverage[path] && coverage[path].hash === hash) { return coverage[path]; } coverageData.hash = hash; return coverage[path] = coverageData; }(); var _angular = __webpack_require__(0); var _angular2 = _interopRequireDefault(_angular); var _angularPdf = __webpack_require__("./src/angular-pdf.directive.js"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Pdf = exports.Pdf = (++cov_1rmvbbu9ah.s[0], _angular2.default.module('pdf', []).directive('ngPdf', _angularPdf.NgPdf).name); /***/ }), /***/ 0: /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_0__; /***/ }) /******/ }); }); //# sourceMappingURL=angular-pdf.js.map
var List = require('../../utils/list.js'); module.exports = function disjoin(node, item, list) { var selectors = node.selector.selectors; // generate new rule sets: // .a, .b { color: red; } // -> // .a { color: red; } // .b { color: red; } // while there are more than 1 simple selector split for rulesets while (selectors.head !== selectors.tail) { var newSelectors = new List(); newSelectors.insert(selectors.remove(selectors.head)); list.insert(list.createItem({ type: 'Ruleset', info: node.info, pseudoSignature: node.pseudoSignature, selector: { type: 'Selector', info: node.selector.info, selectors: newSelectors }, block: { type: 'Block', info: node.block.info, declarations: node.block.declarations.copy() } }), item); } };
var MockServer = require('mockserver'); module.exports = { setUp: function (callback) { this.client = require('../../nightwatch.js').init(); callback(); }, testCommand : function(test) { MockServer.addMock({ url : "/wd/hub/session/1352110219202/screenshot", method:'GET', response : JSON.stringify({ sessionId: "1352110219202", status:0, value:'screendata' }) }); this.client.saveScreenshotToFile = function(fileName, data) { test.equal(fileName, 'screenshot.png'); test.equal(data, 'screendata'); test.done(); }; this.client.api.saveScreenshot('screenshot.png', function(result) { test.equal(result.value, 'screendata'); }); }, tearDown : function(callback) { this.client = null; callback(); } }
function xdiff_file_diff(old_file, new_file, dest, context, minimal) { // http://kevin.vanzonneveld.net // + original by: Brett Zamir (http://brett-zamir.me) // % note 1: Depends on file_put_contents which is not yet implemented // - depends on: xdiff_string_diff // - depends on: file_get_contents // - depends on: file_put_contents old_file = this.file_get_contents(old_file); new_file = this.file_get_contents(new_file); return this.file_put_contents(dest, this.xdiff_string_diff(old_file, new_file, context)); }
/* @flow */ ("hi": Iterable<string>); ("hi": Iterable<*>); ("hi": Iterable<number>); // Error - string is a Iterable<string>
#pragma strict @script ExecuteInEditMode @script RequireComponent (Camera) @script AddComponentMenu ("Image Effects/Camera/Camera Motion Blur") public class CameraMotionBlur extends PostEffectsBase { // make sure to match this to MAX_RADIUS in shader ('k' in paper) static var MAX_RADIUS : int = 10.0f; public enum MotionBlurFilter { CameraMotion = 0, // global screen blur based on cam motion LocalBlur = 1, // cheap blur, no dilation or scattering Reconstruction = 2, // advanced filter (simulates scattering) as in plausible motion blur paper ReconstructionDX11 = 3, // advanced filter (simulates scattering) as in plausible motion blur paper ReconstructionDisc = 4, // advanced filter using scaled poisson disc sampling } // settings public var filterType : MotionBlurFilter = MotionBlurFilter.Reconstruction; public var preview : boolean = false; // show how blur would look like in action ... public var previewScale : Vector3 = Vector3.one; // ... given this movement vector // params public var movementScale : float = 0.0f; public var rotationScale : float = 1.0f; public var maxVelocity : float = 8.0f; // maximum velocity in pixels public var minVelocity : float = 0.1f; // minimum velocity in pixels public var velocityScale : float = 0.375f; // global velocity scale public var softZDistance : float = 0.005f; // for z overlap check softness (reconstruction filter only) public var velocityDownsample : int = 1; // low resolution velocity buffer? (optimization) public var excludeLayers : LayerMask = 0; //public var dynamicLayers : LayerMask = 0; private var tmpCam : GameObject = null; // resources public var shader : Shader; public var dx11MotionBlurShader : Shader; public var replacementClear : Shader; //public var replacementDynamics : Shader; private var motionBlurMaterial : Material = null; private var dx11MotionBlurMaterial : Material = null; public var noiseTexture : Texture2D = null; public var jitter : float = 0.05f; // (internal) debug public var showVelocity : boolean = false; public var showVelocityScale : float = 1.0f; // camera transforms private var currentViewProjMat : Matrix4x4; private var prevViewProjMat : Matrix4x4; private var prevFrameCount : int; private var wasActive : boolean; // shortcuts to calculate global blur direction when using 'CameraMotion' private var prevFrameForward : Vector3 = Vector3.forward; private var prevFrameRight : Vector3 = Vector3.right; private var prevFrameUp : Vector3 = Vector3.up; private var prevFramePos : Vector3 = Vector3.zero; private function CalculateViewProjection() { var viewMat : Matrix4x4 = GetComponent.<Camera>().worldToCameraMatrix; var projMat : Matrix4x4 = GL.GetGPUProjectionMatrix (GetComponent.<Camera>().projectionMatrix, true); currentViewProjMat = projMat * viewMat; } function Start () { CheckResources (); wasActive = gameObject.activeInHierarchy; CalculateViewProjection (); Remember (); wasActive = false; // hack to fake position/rotation update and prevent bad blurs } function OnEnable () { GetComponent.<Camera>().depthTextureMode |= DepthTextureMode.Depth; } function OnDisable () { if (null != motionBlurMaterial) { DestroyImmediate (motionBlurMaterial); motionBlurMaterial = null; } if (null != dx11MotionBlurMaterial) { DestroyImmediate (dx11MotionBlurMaterial); dx11MotionBlurMaterial = null; } if (null != tmpCam) { DestroyImmediate (tmpCam); tmpCam = null; } } function CheckResources () : boolean { CheckSupport (true, true); // depth & hdr needed motionBlurMaterial = CheckShaderAndCreateMaterial (shader, motionBlurMaterial); if (supportDX11 && filterType == MotionBlurFilter.ReconstructionDX11) { dx11MotionBlurMaterial = CheckShaderAndCreateMaterial (dx11MotionBlurShader, dx11MotionBlurMaterial); } if (!isSupported) ReportAutoDisable (); return isSupported; } function OnRenderImage (source : RenderTexture, destination : RenderTexture) { if (false == CheckResources ()) { Graphics.Blit (source, destination); return; } if (filterType == MotionBlurFilter.CameraMotion) StartFrame (); // use if possible new RG format ... fallback to half otherwise var rtFormat = SystemInfo.SupportsRenderTextureFormat (RenderTextureFormat.RGHalf) ? RenderTextureFormat.RGHalf : RenderTextureFormat.ARGBHalf; // get temp textures var velBuffer : RenderTexture = RenderTexture.GetTemporary (divRoundUp (source.width, velocityDownsample), divRoundUp (source.height, velocityDownsample), 0, rtFormat); var tileWidth : int = 1; var tileHeight : int = 1; maxVelocity = Mathf.Max (2.0f, maxVelocity); var _maxVelocity : float = maxVelocity; // calculate 'k' // note: 's' is hardcoded in shaders except for DX11 path // auto DX11 fallback! var fallbackFromDX11 : boolean = false; if (filterType == MotionBlurFilter.ReconstructionDX11 && dx11MotionBlurMaterial == null) { fallbackFromDX11 = true; } if (filterType == MotionBlurFilter.Reconstruction || fallbackFromDX11 || filterType == MotionBlurFilter.ReconstructionDisc) { maxVelocity = Mathf.Min (maxVelocity, MAX_RADIUS); tileWidth = divRoundUp (velBuffer.width, maxVelocity); tileHeight = divRoundUp (velBuffer.height, maxVelocity); _maxVelocity = velBuffer.width/tileWidth; } else { tileWidth = divRoundUp (velBuffer.width, maxVelocity); tileHeight = divRoundUp (velBuffer.height, maxVelocity); _maxVelocity = velBuffer.width/tileWidth; } var tileMax : RenderTexture = RenderTexture.GetTemporary (tileWidth, tileHeight, 0, rtFormat); var neighbourMax : RenderTexture = RenderTexture.GetTemporary (tileWidth, tileHeight, 0, rtFormat); velBuffer.filterMode = FilterMode.Point; tileMax.filterMode = FilterMode.Point; neighbourMax.filterMode = FilterMode.Point; if(noiseTexture) noiseTexture.filterMode = FilterMode.Point; source.wrapMode = TextureWrapMode.Clamp; velBuffer.wrapMode = TextureWrapMode.Clamp; neighbourMax.wrapMode = TextureWrapMode.Clamp; tileMax.wrapMode = TextureWrapMode.Clamp; // calc correct viewprj matrix CalculateViewProjection (); // just started up? if (gameObject.activeInHierarchy && !wasActive) { Remember (); } wasActive = gameObject.activeInHierarchy; // matrices var invViewPrj : Matrix4x4 = Matrix4x4.Inverse (currentViewProjMat); motionBlurMaterial.SetMatrix ("_InvViewProj", invViewPrj); motionBlurMaterial.SetMatrix ("_PrevViewProj", prevViewProjMat); motionBlurMaterial.SetMatrix ("_ToPrevViewProjCombined", prevViewProjMat * invViewPrj); motionBlurMaterial.SetFloat ("_MaxVelocity", _maxVelocity); motionBlurMaterial.SetFloat ("_MaxRadiusOrKInPaper", _maxVelocity); motionBlurMaterial.SetFloat ("_MinVelocity", minVelocity); motionBlurMaterial.SetFloat ("_VelocityScale", velocityScale); motionBlurMaterial.SetFloat ("_Jitter", jitter); // texture samplers motionBlurMaterial.SetTexture ("_NoiseTex", noiseTexture); motionBlurMaterial.SetTexture ("_VelTex", velBuffer); motionBlurMaterial.SetTexture ("_NeighbourMaxTex", neighbourMax); motionBlurMaterial.SetTexture ("_TileTexDebug", tileMax); if (preview) { // generate an artifical 'previous' matrix to simulate blur look var viewMat : Matrix4x4 = GetComponent.<Camera>().worldToCameraMatrix; var offset : Matrix4x4 = Matrix4x4.identity; offset.SetTRS(previewScale * 0.3333f, Quaternion.identity, Vector3.one); // using only translation var projMat : Matrix4x4 = GL.GetGPUProjectionMatrix (GetComponent.<Camera>().projectionMatrix, true); prevViewProjMat = projMat * offset * viewMat; motionBlurMaterial.SetMatrix ("_PrevViewProj", prevViewProjMat); motionBlurMaterial.SetMatrix ("_ToPrevViewProjCombined", prevViewProjMat * invViewPrj); } if (filterType == MotionBlurFilter.CameraMotion) { // build blur vector to be used in shader to create a global blur direction var blurVector : Vector4 = Vector4.zero; var lookUpDown : float = Vector3.Dot (transform.up, Vector3.up); var distanceVector : Vector3 = prevFramePos-transform.position; var distMag : float = distanceVector.magnitude; var farHeur : float = 1.0f; // pitch (vertical) farHeur = (Vector3.Angle (transform.up, prevFrameUp) / GetComponent.<Camera>().fieldOfView) * (source.width * 0.75f); blurVector.x = rotationScale * farHeur;//Mathf.Clamp01((1.0f-Vector3.Dot(transform.up, prevFrameUp))); // yaw #1 (horizontal, faded by pitch) farHeur = (Vector3.Angle (transform.forward, prevFrameForward) / GetComponent.<Camera>().fieldOfView) * (source.width * 0.75f); blurVector.y = rotationScale * lookUpDown * farHeur;//Mathf.Clamp01((1.0f-Vector3.Dot(transform.forward, prevFrameForward))); // yaw #2 (when looking down, faded by 1-pitch) farHeur = (Vector3.Angle (transform.forward, prevFrameForward) / GetComponent.<Camera>().fieldOfView) * (source.width * 0.75f); blurVector.z = rotationScale * (1.0f- lookUpDown) * farHeur;//Mathf.Clamp01((1.0f-Vector3.Dot(transform.forward, prevFrameForward))); if (distMag > Mathf.Epsilon && movementScale > Mathf.Epsilon) { // forward (probably most important) blurVector.w = movementScale * (Vector3.Dot (transform.forward, distanceVector) ) * (source.width * 0.5f); // jump (maybe scale down further) blurVector.x += movementScale * (Vector3.Dot (transform.up, distanceVector) ) * (source.width * 0.5f); // strafe (maybe scale down further) blurVector.y += movementScale * (Vector3.Dot (transform.right, distanceVector) ) * (source.width * 0.5f); } if (preview) // crude approximation motionBlurMaterial.SetVector ("_BlurDirectionPacked", Vector4 (previewScale.y, previewScale.x, 0.0f, previewScale.z) * 0.5f * GetComponent.<Camera>().fieldOfView); else motionBlurMaterial.SetVector ("_BlurDirectionPacked", blurVector); } else { // generate velocity buffer Graphics.Blit (source, velBuffer, motionBlurMaterial, 0); // patch up velocity buffer: // exclude certain layers (e.g. skinned objects as we cant really support that atm) var cam : Camera = null; if (excludeLayers.value)// || dynamicLayers.value) cam = GetTmpCam (); if (cam && excludeLayers.value != 0 && replacementClear && replacementClear.isSupported) { cam.targetTexture = velBuffer; cam.cullingMask = excludeLayers; cam.RenderWithShader (replacementClear, ""); } // dynamic layers (e.g. rigid bodies) // no worky in 4.0, but let's fix for 4.x /* if (cam && dynamicLayers.value != 0 && replacementDynamics && replacementDynamics.isSupported) { Shader.SetGlobalFloat ("_MaxVelocity", maxVelocity); Shader.SetGlobalFloat ("_VelocityScale", velocityScale); Shader.SetGlobalVector ("_VelBufferSize", Vector4 (velBuffer.width, velBuffer.height, 0, 0)); Shader.SetGlobalMatrix ("_PrevViewProj", prevViewProjMat); Shader.SetGlobalMatrix ("_ViewProj", currentViewProjMat); cam.targetTexture = velBuffer; cam.cullingMask = dynamicLayers; cam.RenderWithShader (replacementDynamics, ""); } */ } if (!preview && Time.frameCount != prevFrameCount) { // remember current transformation data for next frame prevFrameCount = Time.frameCount; Remember (); } source.filterMode = FilterMode.Bilinear; // debug vel buffer: if (showVelocity) { // generate tile max and neighbour max //Graphics.Blit (velBuffer, tileMax, motionBlurMaterial, 2); //Graphics.Blit (tileMax, neighbourMax, motionBlurMaterial, 3); motionBlurMaterial.SetFloat ("_DisplayVelocityScale", showVelocityScale); Graphics.Blit (velBuffer, destination, motionBlurMaterial, 1); } else { if (filterType == MotionBlurFilter.ReconstructionDX11 && !fallbackFromDX11) { // need to reset some parameters for dx11 shader dx11MotionBlurMaterial.SetFloat ("_MinVelocity", minVelocity); dx11MotionBlurMaterial.SetFloat ("_VelocityScale", velocityScale); dx11MotionBlurMaterial.SetFloat ("_Jitter", jitter); // texture samplers dx11MotionBlurMaterial.SetTexture ("_NoiseTex", noiseTexture); dx11MotionBlurMaterial.SetTexture ("_VelTex", velBuffer); dx11MotionBlurMaterial.SetTexture ("_NeighbourMaxTex", neighbourMax); dx11MotionBlurMaterial.SetFloat ("_SoftZDistance", Mathf.Max(0.00025f, softZDistance) ); dx11MotionBlurMaterial.SetFloat ("_MaxRadiusOrKInPaper", _maxVelocity); // generate tile max and neighbour max Graphics.Blit (velBuffer, tileMax, dx11MotionBlurMaterial, 0); Graphics.Blit (tileMax, neighbourMax, dx11MotionBlurMaterial, 1); // final blur Graphics.Blit (source, destination, dx11MotionBlurMaterial, 2); } else if (filterType == MotionBlurFilter.Reconstruction || fallbackFromDX11) { // 'reconstructing' properly integrated color motionBlurMaterial.SetFloat ("_SoftZDistance", Mathf.Max(0.00025f, softZDistance) ); // generate tile max and neighbour max Graphics.Blit (velBuffer, tileMax, motionBlurMaterial, 2); Graphics.Blit (tileMax, neighbourMax, motionBlurMaterial, 3); // final blur Graphics.Blit (source, destination, motionBlurMaterial, 4); } else if (filterType == MotionBlurFilter.CameraMotion) { // orange box style motion blur Graphics.Blit (source, destination, motionBlurMaterial, 6); } else if (filterType == MotionBlurFilter.ReconstructionDisc) { // dof style motion blur defocuing and ellipse around the princical blur direction // 'reconstructing' properly integrated color motionBlurMaterial.SetFloat ("_SoftZDistance", Mathf.Max(0.00025f, softZDistance) ); // generate tile max and neighbour max Graphics.Blit (velBuffer, tileMax, motionBlurMaterial, 2); Graphics.Blit (tileMax, neighbourMax, motionBlurMaterial, 3); Graphics.Blit (source, destination, motionBlurMaterial, 7); } else { // simple & fast blur (low quality): just blurring along velocity Graphics.Blit (source, destination, motionBlurMaterial, 5); } } // cleanup RenderTexture.ReleaseTemporary (velBuffer); RenderTexture.ReleaseTemporary (tileMax); RenderTexture.ReleaseTemporary (neighbourMax); } function Remember () { prevViewProjMat = currentViewProjMat; prevFrameForward = transform.forward; prevFrameRight = transform.right; prevFrameUp = transform.up; prevFramePos = transform.position; } function GetTmpCam () : Camera { if (tmpCam == null) { var name : String = "_" + GetComponent.<Camera>().name + "_MotionBlurTmpCam"; var go : GameObject = GameObject.Find (name); if (null == go) // couldn't find, recreate tmpCam = new GameObject (name, typeof (Camera)); else tmpCam = go; } tmpCam.hideFlags = HideFlags.DontSave; tmpCam.transform.position = GetComponent.<Camera>().transform.position; tmpCam.transform.rotation = GetComponent.<Camera>().transform.rotation; tmpCam.transform.localScale = GetComponent.<Camera>().transform.localScale; tmpCam.GetComponent.<Camera>().CopyFrom (GetComponent.<Camera>()); tmpCam.GetComponent.<Camera>().enabled = false; tmpCam.GetComponent.<Camera>().depthTextureMode = DepthTextureMode.None; tmpCam.GetComponent.<Camera>().clearFlags = CameraClearFlags.Nothing; return tmpCam.GetComponent.<Camera>(); } function StartFrame () { // take only x% of positional changes into account (camera motion) // TODO: possibly do the same for rotational part prevFramePos = Vector3.Slerp(prevFramePos, transform.position, 0.75f); } function divRoundUp (x : int, d : int) : int { return (x + d - 1) / d; } }
var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); import { Resource } from './Resource'; import { Promise } from '../Promises'; import { Texture } from './Texture'; import { Color } from '../Drawing/Color'; import { SpriteSheet } from '../Drawing/SpriteSheet'; /** * The [[Texture]] object allows games built in Excalibur to load image resources. * [[Texture]] is an [[Loadable]] which means it can be passed to a [[Loader]] * to pre-load before starting a level or game. * * [[include:Textures.md]] */ var Gif = /** @class */ (function (_super) { __extends(Gif, _super); /** * @param path Path to the image resource * @param color Optionally set the color to treat as transparent the gif, by default [[Color.Magenta]] * @param bustCache Optionally load texture with cache busting */ function Gif(path, color, bustCache) { if (color === void 0) { color = Color.Magenta; } if (bustCache === void 0) { bustCache = true; } var _this = _super.call(this, path, 'arraybuffer', bustCache) || this; _this.path = path; _this.color = color; _this.bustCache = bustCache; /** * A [[Promise]] that resolves when the Texture is loaded. */ _this.loaded = new Promise(); _this._isLoaded = false; _this._stream = null; _this._gif = null; _this._texture = []; _this._animation = null; _this._transparentColor = null; _this._transparentColor = color; return _this; } /** * Returns true if the Texture is completely loaded and is ready * to be drawn. */ Gif.prototype.isLoaded = function () { return this._isLoaded; }; /** * Begins loading the texture and returns a promise to be resolved on completion */ Gif.prototype.load = function () { var _this = this; var complete = new Promise(); var loaded = _super.prototype.load.call(this); loaded.then(function () { _this._stream = new Stream(_this.getData()); _this._gif = new ParseGif(_this._stream, _this._transparentColor); var promises = []; for (var imageIndex = 0; imageIndex < _this._gif.images.length; imageIndex++) { var texture = new Texture(_this._gif.images[imageIndex].src, false); _this._texture.push(texture); promises.push(texture.load()); } Promise.join(promises).then(function () { _this._isLoaded = true; complete.resolve(_this._texture); }); }, function () { complete.reject('Error loading texture.'); }); return complete; }; Gif.prototype.asSprite = function (id) { if (id === void 0) { id = 0; } var sprite = this._texture[id].asSprite(); return sprite; }; Gif.prototype.asSpriteSheet = function () { var spriteArray = this._texture.map(function (texture) { return texture.asSprite(); }); return new SpriteSheet(spriteArray); }; Gif.prototype.asAnimation = function (engine, speed) { var spriteSheet = this.asSpriteSheet(); this._animation = spriteSheet.getAnimationForAll(engine, speed); return this._animation; }; Object.defineProperty(Gif.prototype, "readCheckBytes", { get: function () { return this._gif.checkBytes; }, enumerable: false, configurable: true }); return Gif; }(Resource)); export { Gif }; var bitsToNum = function (ba) { return ba.reduce(function (s, n) { return s * 2 + n; }, 0); }; var byteToBitArr = function (bite) { var a = []; for (var i = 7; i >= 0; i--) { a.push(!!(bite & (1 << i))); } return a; }; var Stream = /** @class */ (function () { function Stream(dataArray) { var _this = this; this.data = null; this.len = 0; this.position = 0; this.readByte = function () { if (_this.position >= _this.data.byteLength) { throw new Error('Attempted to read past end of stream.'); } return _this.data[_this.position++]; }; this.readBytes = function (n) { var bytes = []; for (var i = 0; i < n; i++) { bytes.push(_this.readByte()); } return bytes; }; this.read = function (n) { var s = ''; for (var i = 0; i < n; i++) { s += String.fromCharCode(_this.readByte()); } return s; }; this.readUnsigned = function () { // Little-endian. var a = _this.readBytes(2); return (a[1] << 8) + a[0]; }; this.data = new Uint8Array(dataArray); this.len = this.data.byteLength; if (this.len === 0) { throw new Error('No data loaded from file'); } } return Stream; }()); export { Stream }; var lzwDecode = function (minCodeSize, data) { // TODO: Now that the GIF parser is a bit different, maybe this should get an array of bytes instead of a String? var pos = 0; // Maybe this streaming thing should be merged with the Stream? var readCode = function (size) { var code = 0; for (var i = 0; i < size; i++) { if (data.charCodeAt(pos >> 3) & (1 << (pos & 7))) { code |= 1 << i; } pos++; } return code; }; var output = []; var clearCode = 1 << minCodeSize; var eoiCode = clearCode + 1; var codeSize = minCodeSize + 1; var dict = []; var clear = function () { dict = []; codeSize = minCodeSize + 1; for (var i = 0; i < clearCode; i++) { dict[i] = [i]; } dict[clearCode] = []; dict[eoiCode] = null; }; var code; var last; while (true) { last = code; code = readCode(codeSize); if (code === clearCode) { clear(); continue; } if (code === eoiCode) { break; } if (code < dict.length) { if (last !== clearCode) { dict.push(dict[last].concat(dict[code][0])); } } else { if (code !== dict.length) { throw new Error('Invalid LZW code.'); } dict.push(dict[last].concat(dict[last][0])); } output.push.apply(output, dict[code]); if (dict.length === 1 << codeSize && codeSize < 12) { // If we're at the last code and codeSize is 12, the next code will be a clearCode, and it'll be 12 bits long. codeSize++; } } // I don't know if this is technically an error, but some GIFs do it. //if (Math.ceil(pos / 8) !== data.length) throw new Error('Extraneous LZW bytes.'); return output; }; // The actual parsing; returns an object with properties. var ParseGif = /** @class */ (function () { function ParseGif(stream, color) { var _this = this; if (color === void 0) { color = Color.Magenta; } this._st = null; this._handler = {}; this._transparentColor = null; this.frames = []; this.images = []; this.globalColorTable = []; this.checkBytes = []; // LZW (GIF-specific) this.parseColorTable = function (entries) { // Each entry is 3 bytes, for RGB. var ct = []; for (var i = 0; i < entries; i++) { var rgb = _this._st.readBytes(3); var rgba = '#' + rgb .map(function (x) { var hex = x.toString(16); return hex.length === 1 ? '0' + hex : hex; }) .join(''); ct.push(rgba); } return ct; }; this.readSubBlocks = function () { var size, data; data = ''; do { size = _this._st.readByte(); data += _this._st.read(size); } while (size !== 0); return data; }; this.parseHeader = function () { var hdr = { sig: null, ver: null, width: null, height: null, colorRes: null, globalColorTableSize: null, gctFlag: null, sorted: null, globalColorTable: [], bgColor: null, pixelAspectRatio: null // if not 0, aspectRatio = (pixelAspectRatio + 15) / 64 }; hdr.sig = _this._st.read(3); hdr.ver = _this._st.read(3); if (hdr.sig !== 'GIF') { throw new Error('Not a GIF file.'); // XXX: This should probably be handled more nicely. } hdr.width = _this._st.readUnsigned(); hdr.height = _this._st.readUnsigned(); var bits = byteToBitArr(_this._st.readByte()); hdr.gctFlag = bits.shift(); hdr.colorRes = bitsToNum(bits.splice(0, 3)); hdr.sorted = bits.shift(); hdr.globalColorTableSize = bitsToNum(bits.splice(0, 3)); hdr.bgColor = _this._st.readByte(); hdr.pixelAspectRatio = _this._st.readByte(); // if not 0, aspectRatio = (pixelAspectRatio + 15) / 64 if (hdr.gctFlag) { hdr.globalColorTable = _this.parseColorTable(1 << (hdr.globalColorTableSize + 1)); _this.globalColorTable = hdr.globalColorTable; } if (_this._handler.hdr && _this._handler.hdr(hdr)) { _this.checkBytes.push(_this._handler.hdr); } }; this.parseExt = function (block) { var parseGCExt = function (block) { _this.checkBytes.push(_this._st.readByte()); // Always 4 var bits = byteToBitArr(_this._st.readByte()); block.reserved = bits.splice(0, 3); // Reserved; should be 000. block.disposalMethod = bitsToNum(bits.splice(0, 3)); block.userInput = bits.shift(); block.transparencyGiven = bits.shift(); block.delayTime = _this._st.readUnsigned(); block.transparencyIndex = _this._st.readByte(); block.terminator = _this._st.readByte(); if (_this._handler.gce && _this._handler.gce(block)) { _this.checkBytes.push(_this._handler.gce); } }; var parseComExt = function (block) { block.comment = _this.readSubBlocks(); if (_this._handler.com && _this._handler.com(block)) { _this.checkBytes.push(_this._handler.com); } }; var parsePTExt = function (block) { _this.checkBytes.push(_this._st.readByte()); // Always 12 block.ptHeader = _this._st.readBytes(12); block.ptData = _this.readSubBlocks(); if (_this._handler.pte && _this._handler.pte(block)) { _this.checkBytes.push(_this._handler.pte); } }; var parseAppExt = function (block) { var parseNetscapeExt = function (block) { _this.checkBytes.push(_this._st.readByte()); // Always 3 block.unknown = _this._st.readByte(); // ??? Always 1? What is this? block.iterations = _this._st.readUnsigned(); block.terminator = _this._st.readByte(); if (_this._handler.app && _this._handler.app.NETSCAPE && _this._handler.app.NETSCAPE(block)) { _this.checkBytes.push(_this._handler.app); } }; var parseUnknownAppExt = function (block) { block.appData = _this.readSubBlocks(); // FIXME: This won't work if a handler wants to match on any identifier. if (_this._handler.app && _this._handler.app[block.identifier] && _this._handler.app[block.identifier](block)) { _this.checkBytes.push(_this._handler.app[block.identifier]); } }; _this.checkBytes.push(_this._st.readByte()); // Always 11 block.identifier = _this._st.read(8); block.authCode = _this._st.read(3); switch (block.identifier) { case 'NETSCAPE': parseNetscapeExt(block); break; default: parseUnknownAppExt(block); break; } }; var parseUnknownExt = function (block) { block.data = _this.readSubBlocks(); if (_this._handler.unknown && _this._handler.unknown(block)) { _this.checkBytes.push(_this._handler.unknown); } }; block.label = _this._st.readByte(); switch (block.label) { case 0xf9: block.extType = 'gce'; parseGCExt(block); break; case 0xfe: block.extType = 'com'; parseComExt(block); break; case 0x01: block.extType = 'pte'; parsePTExt(block); break; case 0xff: block.extType = 'app'; parseAppExt(block); break; default: block.extType = 'unknown'; parseUnknownExt(block); break; } }; this.parseImg = function (img) { var deinterlace = function (pixels, width) { // Of course this defeats the purpose of interlacing. And it's *probably* // the least efficient way it's ever been implemented. But nevertheless... var newPixels = new Array(pixels.length); var rows = pixels.length / width; var cpRow = function (toRow, fromRow) { var fromPixels = pixels.slice(fromRow * width, (fromRow + 1) * width); newPixels.splice.apply(newPixels, [toRow * width, width].concat(fromPixels)); }; var offsets = [0, 4, 2, 1]; var steps = [8, 8, 4, 2]; var fromRow = 0; for (var pass = 0; pass < 4; pass++) { for (var toRow = offsets[pass]; toRow < rows; toRow += steps[pass]) { cpRow(toRow, fromRow); fromRow++; } } return newPixels; }; img.leftPos = _this._st.readUnsigned(); img.topPos = _this._st.readUnsigned(); img.width = _this._st.readUnsigned(); img.height = _this._st.readUnsigned(); var bits = byteToBitArr(_this._st.readByte()); img.lctFlag = bits.shift(); img.interlaced = bits.shift(); img.sorted = bits.shift(); img.reserved = bits.splice(0, 2); img.lctSize = bitsToNum(bits.splice(0, 3)); if (img.lctFlag) { img.lct = _this.parseColorTable(1 << (img.lctSize + 1)); } img.lzwMinCodeSize = _this._st.readByte(); var lzwData = _this.readSubBlocks(); img.pixels = lzwDecode(img.lzwMinCodeSize, lzwData); if (img.interlaced) { // Move img.pixels = deinterlace(img.pixels, img.width); } _this.frames.push(img); _this.arrayToImage(img); if (_this._handler.img && _this._handler.img(img)) { _this.checkBytes.push(_this._handler); } }; this.parseBlock = function () { var block = { sentinel: _this._st.readByte(), type: '' }; var blockChar = String.fromCharCode(block.sentinel); switch (blockChar) { case '!': block.type = 'ext'; _this.parseExt(block); break; case ',': block.type = 'img'; _this.parseImg(block); break; case ';': block.type = 'eof'; if (_this._handler.eof && _this._handler.eof(block)) { _this.checkBytes.push(_this._handler.eof); } break; default: throw new Error('Unknown block: 0x' + block.sentinel.toString(16)); } if (block.type !== 'eof') { _this.parseBlock(); } }; this.arrayToImage = function (frame) { var count = 0; var c = document.createElement('canvas'); c.id = count.toString(); c.width = frame.width; c.height = frame.height; count++; var context = c.getContext('2d'); var pixSize = 1; var y = 0; var x = 0; for (var i = 0; i < frame.pixels.length; i++) { if (x % frame.width === 0) { y++; x = 0; } if (_this.globalColorTable[frame.pixels[i]] === _this._transparentColor.toHex()) { context.fillStyle = "rgba(0, 0, 0, 0)"; } else { context.fillStyle = _this.globalColorTable[frame.pixels[i]]; } context.fillRect(x, y, pixSize, pixSize); x++; } var img = new Image(); img.src = c.toDataURL(); _this.images.push(img); }; this._st = stream; this._handler = {}; this._transparentColor = color; this.parseHeader(); this.parseBlock(); } return ParseGif; }()); export { ParseGif }; //# sourceMappingURL=Gif.js.map
module.exports = function(grunt) { grunt.config.set('watch', { // Watch assets to detect changes and launch `SyncAssets` task assets: { files: ['source/_*/**/*'], tasks: ['syncAssets'] } }); grunt.loadNpmTasks('grunt-contrib-watch'); };
'use strict'; // Load modules const Any = require('./any'); const Ref = require('./ref'); const Hoek = require('hoek'); // Declare internals const internals = { precisionRx: /(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/ }; internals.Number = class extends Any { constructor() { super(); this._type = 'number'; this._invalids.add(Infinity); this._invalids.add(-Infinity); } _base(value, state, options) { const result = { errors: null, value }; if (typeof value === 'string' && options.convert) { const number = parseFloat(value); result.value = (isNaN(number) || !isFinite(value)) ? NaN : number; } const isNumber = typeof result.value === 'number' && !isNaN(result.value); if (options.convert && 'precision' in this._flags && isNumber) { // This is conceptually equivalent to using toFixed but it should be much faster const precision = Math.pow(10, this._flags.precision); result.value = Math.round(result.value * precision) / precision; } result.errors = isNumber ? null : this.createError('number.base', null, state, options); return result; } multiple(base) { const isRef = Ref.isRef(base); if (!isRef) { Hoek.assert(typeof base === 'number' && isFinite(base), 'multiple must be a number'); Hoek.assert(base > 0, 'multiple must be greater than 0'); } return this._test('multiple', base, function (value, state, options) { const divisor = isRef ? base(state.reference || state.parent, options) : base; if (isRef && (typeof divisor !== 'number' || !isFinite(divisor))) { return this.createError('number.ref', { ref: base.key }, state, options); } if (value % divisor === 0) { return value; } return this.createError('number.multiple', { multiple: base, value }, state, options); }); } integer() { return this._test('integer', undefined, function (value, state, options) { return Hoek.isInteger(value) ? value : this.createError('number.integer', { value }, state, options); }); } negative() { return this._test('negative', undefined, function (value, state, options) { if (value < 0) { return value; } return this.createError('number.negative', { value }, state, options); }); } positive() { return this._test('positive', undefined, function (value, state, options) { if (value > 0) { return value; } return this.createError('number.positive', { value }, state, options); }); } precision(limit) { Hoek.assert(Hoek.isInteger(limit), 'limit must be an integer'); Hoek.assert(!('precision' in this._flags), 'precision already set'); const obj = this._test('precision', limit, function (value, state, options) { const places = value.toString().match(internals.precisionRx); const decimals = Math.max((places[1] ? places[1].length : 0) - (places[2] ? parseInt(places[2], 10) : 0), 0); if (decimals <= limit) { return value; } return this.createError('number.precision', { limit, value }, state, options); }); obj._flags.precision = limit; return obj; } }; internals.compare = function (type, compare) { return function (limit) { const isRef = Ref.isRef(limit); const isNumber = typeof limit === 'number' && !isNaN(limit); Hoek.assert(isNumber || isRef, 'limit must be a number or reference'); return this._test(type, limit, function (value, state, options) { let compareTo; if (isRef) { compareTo = limit(state.reference || state.parent, options); if (!(typeof compareTo === 'number' && !isNaN(compareTo))) { return this.createError('number.ref', { ref: limit.key }, state, options); } } else { compareTo = limit; } if (compare(value, compareTo)) { return value; } return this.createError('number.' + type, { limit: compareTo, value }, state, options); }); }; }; internals.Number.prototype.min = internals.compare('min', (value, limit) => value >= limit); internals.Number.prototype.max = internals.compare('max', (value, limit) => value <= limit); internals.Number.prototype.greater = internals.compare('greater', (value, limit) => value > limit); internals.Number.prototype.less = internals.compare('less', (value, limit) => value < limit); module.exports = new internals.Number();
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'toolbar', 'it', { toolbarCollapse: 'Minimizza Toolbar', toolbarExpand: 'Espandi Toolbar', toolbarGroups: { document: 'Documento', clipboard: 'Copia negli appunti/Annulla', editing: 'Modifica', forms: 'Form', basicstyles: 'Stili di base', paragraph: 'Paragrafo', links: 'Link', insert: 'Inserisci', styles: 'Stili', colors: 'Colori', tools: 'Strumenti' }, toolbars: 'Editor toolbar' } );
module.exports = /******/ (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] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.l = 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; /******/ // identity function for calling harmony imports with the correct context /******/ __webpack_require__.i = function(value) { return value; }; /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 219); /******/ }) /************************************************************************/ /******/ ({ /***/ 104: /***/ function(module, exports) { // removed by extract-text-webpack-plugin /***/ }, /***/ 139: /***/ function(module, exports, __webpack_require__) { var __vue_exports__, __vue_options__ var __vue_styles__ = {} /* styles */ __webpack_require__(104) /* script */ __vue_exports__ = __webpack_require__(61) /* template */ var __vue_template__ = __webpack_require__(174) __vue_options__ = __vue_exports__ = __vue_exports__ || {} if ( typeof __vue_exports__.default === "object" || typeof __vue_exports__.default === "function" ) { __vue_options__ = __vue_exports__ = __vue_exports__.default } if (typeof __vue_options__ === "function") { __vue_options__ = __vue_options__.options } __vue_options__.render = __vue_template__.render __vue_options__.staticRenderFns = __vue_template__.staticRenderFns module.exports = __vue_exports__ /***/ }, /***/ 174: /***/ function(module, exports) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h; return _c('li', { staticClass: "mint-indexsection" }, [_c('p', { staticClass: "mint-indexsection-index" }, [_vm._v(_vm._s(_vm.index))]), _vm._v(" "), _c('ul', [_vm._t("default")], 2)]) },staticRenderFns: []} /***/ }, /***/ 219: /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(27); /***/ }, /***/ 27: /***/ function(module, exports, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__src_index_section_vue__ = __webpack_require__(139); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__src_index_section_vue___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0__src_index_section_vue__); Object.defineProperty(exports, "__esModule", { value: true }); /* harmony reexport (default from non-hamory) */ __webpack_require__.d(exports, "default", function() { return __WEBPACK_IMPORTED_MODULE_0__src_index_section_vue___default.a; }); /***/ }, /***/ 61: /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // // // // // // // // // // // // // // // // // // // // // // // // // // // // /* harmony default export */ exports["default"] = { name: 'mt-index-section', props: { index: { type: String, required: true } }, mounted: function mounted() { this.$parent.sections.push(this); }, beforeDestroy: function beforeDestroy() { var index = this.$parent.sections.indexOf(this); if (index > -1) { this.$parent.sections.splice(index, 1); } } }; /***/ } /******/ });
(function (global, factory) { if (typeof define === "function" && define.amd) { define('element/locale/fi', ['module', 'exports'], factory); } else if (typeof exports !== "undefined") { factory(module, exports); } else { var mod = { exports: {} }; factory(mod, mod.exports); global.ELEMENT.lang = global.ELEMENT.lang || {}; global.ELEMENT.lang.fi = mod.exports; } })(this, function (module, exports) { 'use strict'; exports.__esModule = true; exports.default = { el: { colorpicker: { confirm: 'OK', clear: 'Tyhjennä' }, datepicker: { now: 'Nyt', today: 'Tänään', cancel: 'Peruuta', clear: 'Tyhjennä', confirm: 'OK', selectDate: 'Valitse päivä', selectTime: 'Valitse aika', startDate: 'Aloituspäivä', startTime: 'Aloitusaika', endDate: 'Lopetuspäivä', endTime: 'Lopetusaika', prevYear: 'Previous Year', // to be translated nextYear: 'Next Year', // to be translated prevMonth: 'Previous Month', // to be translated nextMonth: 'Next Month', // to be translated year: '', month1: 'tammikuu', month2: 'helmikuu', month3: 'maaliskuu', month4: 'huhtikuu', month5: 'toukokuu', month6: 'kesäkuu', month7: 'heinäkuu', month8: 'elokuu', month9: 'syyskuu', month10: 'lokakuu', month11: 'marraskuu', month12: 'joulukuu', // week: 'week', weeks: { sun: 'su', mon: 'ma', tue: 'ti', wed: 'ke', thu: 'to', fri: 'pe', sat: 'la' }, months: { jan: 'tam', feb: 'hel', mar: 'maa', apr: 'huh', may: 'tou', jun: 'kes', jul: 'hei', aug: 'elo', sep: 'syy', oct: 'lok', nov: 'mar', dec: 'jou' } }, select: { loading: 'Lataa', noMatch: 'Ei vastaavia tietoja', noData: 'Ei tietoja', placeholder: 'Valitse' }, cascader: { noMatch: 'Ei vastaavia tietoja', loading: 'Lataa', placeholder: 'Valitse' }, pagination: { goto: 'Mene', pagesize: '/sivu', total: 'Yhteensä {total}', pageClassifier: '' }, messagebox: { title: 'Viesti', confirm: 'OK', cancel: 'Peruuta', error: 'Virheellinen syöte' }, upload: { deleteTip: 'press delete to remove', // to be translated delete: 'Poista', preview: 'Esikatsele', continue: 'Jatka' }, table: { emptyText: 'Ei tietoja', confirmFilter: 'Vahvista', resetFilter: 'Tyhjennä', clearFilter: 'Kaikki', sumText: 'Sum' // to be translated }, tree: { emptyText: 'Ei tietoja' }, transfer: { noMatch: 'Ei vastaavia tietoja', noData: 'Ei tietoja', titles: ['List 1', 'List 2'], // to be translated filterPlaceholder: 'Enter keyword', // to be translated noCheckedFormat: '{total} items', // to be translated hasCheckedFormat: '{checked}/{total} checked' // to be translated } } }; module.exports = exports['default']; });
/* Lightbox for Bootstrap 3 by @ashleydw https://github.com/ashleydw/lightbox License: https://github.com/ashleydw/lightbox/blob/master/LICENSE */ (function() { "use strict"; var $, EkkoLightbox; $ = jQuery; EkkoLightbox = function(element, options) { var content, footer, header, _this = this; this.options = $.extend({ title: null, footer: null, remote: null }, $.fn.ekkoLightbox.defaults, options || {}); this.$element = $(element); content = ''; this.modal_id = this.options.modal_id ? this.options.modal_id : 'ekkoLightbox-' + Math.floor((Math.random() * 1000) + 1); header = '<div class="modal-header"' + (this.options.title || this.options.always_show_close ? '' : ' style="display:none"') + '><button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button><h4 class="modal-title">' + (this.options.title || "&nbsp;") + '</h4></div>'; footer = '<div class="modal-footer"' + (this.options.footer ? '' : ' style="display:none"') + '>' + this.options.footer + '</div>'; $(document.body).append('<div id="' + this.modal_id + '" class="ekko-lightbox modal fade" tabindex="-1"><div class="modal-dialog"><div class="modal-content">' + header + '<div class="modal-body"><div class="ekko-lightbox-container"><div></div></div></div>' + footer + '</div></div></div>'); this.modal = $('#' + this.modal_id); this.modal_dialog = this.modal.find('.modal-dialog').first(); this.modal_content = this.modal.find('.modal-content').first(); this.modal_body = this.modal.find('.modal-body').first(); this.lightbox_container = this.modal_body.find('.ekko-lightbox-container').first(); this.lightbox_body = this.lightbox_container.find('> div:first-child').first(); this.showLoading(); this.modal_arrows = null; this.border = { top: parseFloat(this.modal_dialog.css('border-top-width')) + parseFloat(this.modal_content.css('border-top-width')) + parseFloat(this.modal_body.css('border-top-width')), right: parseFloat(this.modal_dialog.css('border-right-width')) + parseFloat(this.modal_content.css('border-right-width')) + parseFloat(this.modal_body.css('border-right-width')), bottom: parseFloat(this.modal_dialog.css('border-bottom-width')) + parseFloat(this.modal_content.css('border-bottom-width')) + parseFloat(this.modal_body.css('border-bottom-width')), left: parseFloat(this.modal_dialog.css('border-left-width')) + parseFloat(this.modal_content.css('border-left-width')) + parseFloat(this.modal_body.css('border-left-width')) }; this.padding = { top: parseFloat(this.modal_dialog.css('padding-top')) + parseFloat(this.modal_content.css('padding-top')) + parseFloat(this.modal_body.css('padding-top')), right: parseFloat(this.modal_dialog.css('padding-right')) + parseFloat(this.modal_content.css('padding-right')) + parseFloat(this.modal_body.css('padding-right')), bottom: parseFloat(this.modal_dialog.css('padding-bottom')) + parseFloat(this.modal_content.css('padding-bottom')) + parseFloat(this.modal_body.css('padding-bottom')), left: parseFloat(this.modal_dialog.css('padding-left')) + parseFloat(this.modal_content.css('padding-left')) + parseFloat(this.modal_body.css('padding-left')) }; this.modal.on('show.bs.modal', this.options.onShow.bind(this)).on('shown.bs.modal', function() { _this.modal_shown(); return _this.options.onShown.call(_this); }).on('hide.bs.modal', this.options.onHide.bind(this)).on('hidden.bs.modal', function() { if (_this.gallery) { $(document).off('keydown.ekkoLightbox'); } _this.modal.remove(); return _this.options.onHidden.call(_this); }).modal('show', options); return this.modal; }; EkkoLightbox.prototype = { modal_shown: function() { var video_id, _this = this; if (!this.options.remote) { return this.error('No remote target given'); } else { this.gallery = this.$element.data('gallery'); if (this.gallery) { if (this.options.gallery_parent_selector === 'document.body' || this.options.gallery_parent_selector === '') { this.gallery_items = $(document.body).find('*[data-toggle="lightbox"][data-gallery="' + this.gallery + '"]'); } else { this.gallery_items = this.$element.parents(this.options.gallery_parent_selector).first().find('*[data-toggle="lightbox"][data-gallery="' + this.gallery + '"]'); } this.gallery_index = this.gallery_items.index(this.$element); $(document).on('keydown.ekkoLightbox', this.navigate.bind(this)); if (this.options.directional_arrows && this.gallery_items.length > 1) { this.lightbox_container.prepend('<div class="ekko-lightbox-nav-overlay"><a href="#" class="' + this.strip_stops(this.options.left_arrow_class) + '"></a><a href="#" class="' + this.strip_stops(this.options.right_arrow_class) + '"></a></div>'); this.modal_arrows = this.lightbox_container.find('div.ekko-lightbox-nav-overlay').first(); this.lightbox_container.find('a' + this.strip_spaces(this.options.left_arrow_class)).on('click', function(event) { event.preventDefault(); return _this.navigate_left(); }); this.lightbox_container.find('a' + this.strip_spaces(this.options.right_arrow_class)).on('click', function(event) { event.preventDefault(); return _this.navigate_right(); }); } } if (this.options.type) { if (this.options.type === 'image') { return this.preloadImage(this.options.remote, true); } else if (this.options.type === 'youtube' && (video_id = this.getYoutubeId(this.options.remote))) { return this.showYoutubeVideo(video_id); } else if (this.options.type === 'vimeo') { return this.showVimeoVideo(this.options.remote); } else if (this.options.type === 'instagram') { return this.showInstagramVideo(this.options.remote); } else if (this.options.type === 'url') { return this.showInstagramVideo(this.options.remote); } else { return this.error("Could not detect remote target type. Force the type using data-type=\"image|youtube|vimeo|url\""); } } else { return this.detectRemoteType(this.options.remote); } } }, strip_stops: function(str) { return str.replace(/\./g, ''); }, strip_spaces: function(str) { return str.replace(/\s/g, ''); }, isImage: function(str) { return str.match(/(^data:image\/.*,)|(\.(jp(e|g|eg)|gif|png|bmp|webp|svg)((\?|#).*)?$)/i); }, isSwf: function(str) { return str.match(/\.(swf)((\?|#).*)?$/i); }, getYoutubeId: function(str) { var match; match = str.match(/^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/); if (match && match[2].length === 11) { return match[2]; } else { return false; } }, getVimeoId: function(str) { if (str.indexOf('vimeo') > 0) { return str; } else { return false; } }, getInstagramId: function(str) { if (str.indexOf('instagram') > 0) { return str; } else { return false; } }, navigate: function(event) { event = event || window.event; if (event.keyCode === 39 || event.keyCode === 37) { if (event.keyCode === 39) { return this.navigate_right(); } else if (event.keyCode === 37) { return this.navigate_left(); } } }, navigateTo: function(index) { var next, src; if (index < 0 || index > this.gallery_items.length - 1) { return this; } this.showLoading(); this.gallery_index = index; this.options.onNavigate.call(this, this.gallery_index); this.$element = $(this.gallery_items.get(this.gallery_index)); this.updateTitleAndFooter(); src = this.$element.attr('data-remote') || this.$element.attr('href'); this.detectRemoteType(src, this.$element.attr('data-type') || false); if (this.gallery_index + 1 < this.gallery_items.length) { next = $(this.gallery_items.get(this.gallery_index + 1), false); src = next.attr('data-remote') || next.attr('href'); if (next.attr('data-type') === 'image' || this.isImage(src)) { return this.preloadImage(src, false); } } }, navigate_left: function() { if (this.gallery_items.length === 1) { return; } if (this.gallery_index === 0) { this.gallery_index = this.gallery_items.length - 1; } else { this.gallery_index--; } this.options.onNavigate.call(this, 'left', this.gallery_index); return this.navigateTo(this.gallery_index); }, navigate_right: function() { if (this.gallery_items.length === 1) { return; } if (this.gallery_index === this.gallery_items.length - 1) { this.gallery_index = 0; } else { this.gallery_index++; } this.options.onNavigate.call(this, 'right', this.gallery_index); return this.navigateTo(this.gallery_index); }, detectRemoteType: function(src, type) { var video_id; if (type === 'image' || this.isImage(src)) { this.options.type = 'image'; return this.preloadImage(src, true); } else if (type === 'youtube' || (video_id = this.getYoutubeId(src))) { this.options.type = 'youtube'; return this.showYoutubeVideo(video_id); } else if (type === 'vimeo' || (video_id = this.getVimeoId(src))) { this.options.type = 'vimeo'; return this.showVimeoVideo(video_id); } else if (type === 'instagram' || (video_id = this.getInstagramId(src))) { this.options.type = 'instagram'; return this.showInstagramVideo(video_id); } else if (type === 'url' || (video_id = this.getInstagramId(src))) { this.options.type = 'instagram'; return this.showInstagramVideo(video_id); } else { this.options.type = 'url'; return this.loadRemoteContent(src); } }, updateTitleAndFooter: function() { var caption, footer, header, title; header = this.modal_content.find('.modal-header'); footer = this.modal_content.find('.modal-footer'); title = this.$element.data('title') || ""; caption = this.$element.data('footer') || ""; if (title || this.options.always_show_close) { header.css('display', '').find('.modal-title').html(title || "&nbsp;"); } else { header.css('display', 'none'); } if (caption) { footer.css('display', '').html(caption); } else { footer.css('display', 'none'); } return this; }, showLoading: function() { this.lightbox_body.html('<div class="modal-loading">Loading..</div>'); return this; }, showYoutubeVideo: function(id) { var aspectRatio, height, width; aspectRatio = 560 / 315; width = this.$element.data('width') || 560; width = this.checkDimensions(width); height = width / aspectRatio; this.resize(width); this.lightbox_body.html('<iframe width="' + width + '" height="' + height + '" src="//www.youtube.com/embed/' + id + '?badge=0&autoplay=1&html5=1" frameborder="0" allowfullscreen></iframe>'); this.options.onContentLoaded.call(this); if (this.modal_arrows) { return this.modal_arrows.css('display', 'none'); } }, showVimeoVideo: function(id) { var aspectRatio, height, width; aspectRatio = 500 / 281; width = this.$element.data('width') || 560; width = this.checkDimensions(width); height = width / aspectRatio; this.resize(width); this.lightbox_body.html('<iframe width="' + width + '" height="' + height + '" src="' + id + '?autoplay=1" frameborder="0" allowfullscreen></iframe>'); this.options.onContentLoaded.call(this); if (this.modal_arrows) { return this.modal_arrows.css('display', 'none'); } }, showInstagramVideo: function(id) { var width; width = this.$element.data('width') || 612; width = this.checkDimensions(width); this.resize(width); this.lightbox_body.html('<iframe width="' + width + '" height="' + width + '" src="' + this.addTrailingSlash(id) + 'embed/" frameborder="0" allowfullscreen></iframe>'); this.options.onContentLoaded.call(this); if (this.modal_arrows) { return this.modal_arrows.css('display', 'none'); } }, loadRemoteContent: function(url) { var disableExternalCheck, width, _this = this; width = this.$element.data('width') || 560; this.resize(width); disableExternalCheck = this.$element.data('disableExternalCheck') || false; if (!disableExternalCheck && !this.isExternal(url)) { this.lightbox_body.load(url, $.proxy(function() { return _this.$element.trigger('loaded.bs.modal'); })); } else { this.lightbox_body.html('<iframe width="' + width + '" height="' + width + '" src="' + url + '" frameborder="0" allowfullscreen></iframe>'); this.options.onContentLoaded.call(this); } if (this.modal_arrows) { return this.modal_arrows.css('display', 'block'); } }, isExternal: function(url) { var match; match = url.match(/^([^:\/?#]+:)?(?:\/\/([^\/?#]*))?([^?#]+)?(\?[^#]*)?(#.*)?/); if (typeof match[1] === "string" && match[1].length > 0 && match[1].toLowerCase() !== location.protocol) { return true; } if (typeof match[2] === "string" && match[2].length > 0 && match[2].replace(new RegExp(":(" + { "http:": 80, "https:": 443 }[location.protocol] + ")?$"), "") !== location.host) { return true; } return false; }, error: function(message) { this.lightbox_body.html(message); return this; }, preloadImage: function(src, onLoadShowImage) { var img, _this = this; img = new Image(); if ((onLoadShowImage == null) || onLoadShowImage === true) { img.onload = function() { var image; image = $('<img />'); image.attr('src', img.src); image.addClass('img-responsive'); _this.lightbox_body.html(image); if (_this.modal_arrows) { _this.modal_arrows.css('display', 'block'); } _this.resize(img.width); return _this.options.onContentLoaded.call(_this); }; img.onerror = function() { return _this.error('Failed to load image: ' + src); }; } img.src = src; return img; }, resize: function(width) { var width_total; width_total = width + this.border.left + this.padding.left + this.padding.right + this.border.right; this.modal_dialog.css('width', 'auto').css('max-width', width_total); this.lightbox_container.find('a').css('line-height', function() { return $(this).parent().height() + 'px'; }); return this; }, checkDimensions: function(width) { var body_width, width_total; width_total = width + this.border.left + this.padding.left + this.padding.right + this.border.right; body_width = document.body.clientWidth; if (width_total > body_width) { width = this.modal_body.width(); } return width; }, close: function() { return this.modal.modal('hide'); }, addTrailingSlash: function(url) { if (url.substr(-1) !== '/') { url += '/'; } return url; } }; $.fn.ekkoLightbox = function(options) { return this.each(function() { var $this; $this = $(this); options = $.extend({ remote: $this.attr('data-remote') || $this.attr('href'), gallery_parent_selector: $this.attr('data-parent'), type: $this.attr('data-type') }, options, $this.data()); new EkkoLightbox(this, options); return this; }); }; $.fn.ekkoLightbox.defaults = { gallery_parent_selector: '*:not(.row)', left_arrow_class: '.glyphicon .glyphicon-chevron-left', right_arrow_class: '.glyphicon .glyphicon-chevron-right', directional_arrows: true, type: null, always_show_close: true, onShow: function() {}, onShown: function() {}, onHide: function() {}, onHidden: function() {}, onNavigate: function() {}, onContentLoaded: function() {} }; }).call(this);
// Copyright 2012 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 Utilities for detecting, adding and removing classes. Prefer * this over goog.dom.classes for new code since it attempts to use classList * (DOMTokenList: http://dom.spec.whatwg.org/#domtokenlist) which is faster * and requires less code. * * Note: these utilities are meant to operate on HTMLElements and * will not work on elements with differing interfaces (such as SVGElements). */ goog.provide('goog.dom.classlist'); goog.require('goog.array'); goog.require('goog.asserts'); /** * Override this define at build-time if you know your target supports it. * @define {boolean} Whether to use the classList property (DOMTokenList). */ goog.dom.classlist.ALWAYS_USE_DOM_TOKEN_LIST = false; /** * Enables use of the native DOMTokenList methods. See the spec at * {@link http://dom.spec.whatwg.org/#domtokenlist}. * @type {boolean} * @private */ goog.dom.classlist.NATIVE_DOM_TOKEN_LIST_ = goog.dom.classlist.ALWAYS_USE_DOM_TOKEN_LIST || !!window['DOMTokenList']; /** * Gets an array-like object of class names on an element. * @param {Element} element DOM node to get the classes of. * @return {!goog.array.ArrayLike} Class names on {@code element}. */ goog.dom.classlist.get = goog.dom.classlist.NATIVE_DOM_TOKEN_LIST_ ? function(element) { return element.classList; } : function(element) { var className = element.className; // Some types of elements don't have a className in IE (e.g. iframes). // Furthermore, in Firefox, className is not a string when the element is // an SVG element. return goog.isString(className) && className.match(/\S+/g) || []; }; /** * Sets the entire class name of an element. * @param {Element} element DOM node to set class of. * @param {string} className Class name(s) to apply to element. */ goog.dom.classlist.set = function(element, className) { element.className = className; }; /** * Returns true if an element has a class. This method may throw a DOM * exception for an invalid or empty class name if DOMTokenList is used. * @param {Element} element DOM node to test. * @param {string} className Class name to test for. * @return {boolean} Whether element has the class. */ goog.dom.classlist.contains = goog.dom.classlist.NATIVE_DOM_TOKEN_LIST_ ? function(element, className) { goog.asserts.assert(!!element.classList); return element.classList.contains(className); } : function(element, className) { return goog.array.contains(goog.dom.classlist.get(element), className); }; /** * Adds a class to an element. Does not add multiples of class names. This * method may throw a DOM exception for an invalid or empty class name if * DOMTokenList is used. * @param {Element} element DOM node to add class to. * @param {string} className Class name to add. */ goog.dom.classlist.add = goog.dom.classlist.NATIVE_DOM_TOKEN_LIST_ ? function(element, className) { element.classList.add(className); } : function(element, className) { if (!goog.dom.classlist.contains(element, className)) { // Ensure we add a space if this is not the first class name added. element.className += element.className.length > 0 ? (' ' + className) : className; } }; /** * Removes a class from an element. This method may throw a DOM exception * for an invalid or empty class name if DOMTokenList is used. * @param {Element} element DOM node to remove class from. * @param {string} className Class name to remove. */ goog.dom.classlist.remove = goog.dom.classlist.NATIVE_DOM_TOKEN_LIST_ ? function(element, className) { element.classList.remove(className); } : function(element, className) { if (goog.dom.classlist.contains(element, className)) { // Filter out the class name. element.className = goog.array.filter( goog.dom.classlist.get(element), function(c) { return c != className; }).join(' '); } }; /** * Removes a set of classes from an element. Prefer this call to * repeatedly calling {@code goog.dom.classlist.remove} if you want to remove * a large set of class names at once. * @param {Element} element The element from which to remove classes. * @param {goog.array.ArrayLike.<string>} classesToRemove An array-like object * containing a collection of class names to remove from the element. * This method may throw a DOM exception if classNames contains invalid * or empty class names. */ goog.dom.classlist.removeAll = goog.dom.classlist.NATIVE_DOM_TOKEN_LIST_ ? function(element, classesToRemove) { goog.array.forEach(classesToRemove, function(className) { goog.dom.classlist.remove(element, className); }); } : function(element, classesToRemove) { // Filter out those classes in classesToRemove. element.className = goog.array.filter( goog.dom.classlist.get(element), function(className) { // If this class is not one we are trying to remove, // add it to the array of new class names. return !goog.array.contains(classesToRemove, className); }).join(' '); }; /** * Adds or removes a class depending on the enabled argument. This method * may throw a DOM exception for an invalid or empty class name if DOMTokenList * is used. * @param {Element} element DOM node to add or remove the class on. * @param {string} className Class name to add or remove. * @param {boolean} enabled Whether to add or remove the class (true adds, * false removes). */ goog.dom.classlist.enable = function(element, className, enabled) { if (enabled) { goog.dom.classlist.add(element, className); } else { goog.dom.classlist.remove(element, className); } }; /** * Switches a class on an element from one to another without disturbing other * classes. If the fromClass isn't removed, the toClass won't be added. This * method may throw a DOM exception if the class names are empty or invalid. * @param {Element} element DOM node to swap classes on. * @param {string} fromClass Class to remove. * @param {string} toClass Class to add. * @return {boolean} Whether classes were switched. */ goog.dom.classlist.swap = function(element, fromClass, toClass) { if (goog.dom.classlist.contains(element, fromClass)) { goog.dom.classlist.remove(element, fromClass); goog.dom.classlist.add(element, toClass); return true; } return false; }; /** * Removes a class if an element has it, and adds it the element doesn't have * it. Won't affect other classes on the node. This method may throw a DOM * exception if the class name is empty or invalid. * @param {Element} element DOM node to toggle class on. * @param {string} className Class to toggle. * @return {boolean} True if class was added, false if it was removed * (in other words, whether element has the class after this function has * been called). */ goog.dom.classlist.toggle = function(element, className) { var add = !goog.dom.classlist.contains(element, className); goog.dom.classlist.enable(element, className, add); return add; }; /** * Adds and removes a class of an element. Unlike * {@link goog.dom.classlist.swap}, this method adds the classToAdd regardless * of whether the classToRemove was present and had been removed. This method * may throw a DOM exception if the class names are empty or invalid. * * @param {Element} element DOM node to swap classes on. * @param {string} classToRemove Class to remove. * @param {string} classToAdd Class to add. */ goog.dom.classlist.addRemove = function(element, classToRemove, classToAdd) { goog.dom.classlist.remove(element, classToRemove); goog.dom.classlist.add(element, classToAdd); };
YUI.add('datatable-sort-deprecated', function(Y) { // API Doc comments disabled to avoid deprecated class leakage into // non-deprecated class API docs. See the 3.4.1 datatable API doc files in the // download at http://yui.zenfs.com/releases/yui3/yui_3.4.1.zip for reference. /** Plugs DataTable with sorting functionality. DEPRECATED. As of YUI 3.5.0, DataTable has been rebuilt. This module is designed to work with `datatable-base-deprecated` (effectively the 3.4.1 version of DataTable) and will be removed from the library in a future version. See http://yuilibrary.com/yui/docs/migration.html for help upgrading to the latest version. For complete API docs for the classes in this and other deprecated DataTable-related modules, refer to the static API doc files in the 3.4.1 download at http://yui.zenfs.com/releases/yui3/yui_3.4.1.zip @module datatable-deprecated @submodule datatable-sort-deprecated @deprecated **/ /* * Adds column sorting to DataTable. * @class DataTableSort * @extends Plugin.Base */ var YgetClassName = Y.ClassNameManager.getClassName, DATATABLE = "datatable", COLUMN = "column", ASC = "asc", DESC = "desc", //TODO: Don't use hrefs - use tab/arrow/enter TEMPLATE = '<a class="{link_class}" title="{link_title}" href="{link_href}">{value}</a>'; function DataTableSort() { DataTableSort.superclass.constructor.apply(this, arguments); } ///////////////////////////////////////////////////////////////////////////// // // STATIC PROPERTIES // ///////////////////////////////////////////////////////////////////////////// Y.mix(DataTableSort, { /* * The namespace for the plugin. This will be the property on the host which * references the plugin instance. * * @property NS * @type String * @static * @final * @value "sort" */ NS: "sort", /* * Class name. * * @property NAME * @type String * @static * @final * @value "dataTableSort" */ NAME: "dataTableSort", ///////////////////////////////////////////////////////////////////////////// // // ATTRIBUTES // ///////////////////////////////////////////////////////////////////////////// ATTRS: { /* * @attribute trigger * @description Defines the trigger that causes a column to be sorted: * {event, selector}, where "event" is an event type and "selector" is * is a node query selector. * @type Object * @default {event:"click", selector:"th"} * @writeOnce "initOnly" */ trigger: { value: {event:"click", selector:"th"}, writeOnce: "initOnly" }, /* * @attribute lastSortedBy * @description Describes last known sort state: {key,dir}, where * "key" is column key and "dir" is either "asc" or "desc". * @type Object */ lastSortedBy: { setter: "_setLastSortedBy", lazyAdd: false }, /* * @attribute template * @description Tokenized markup template for TH sort element. * @type String * @default '<a class="{link_class}" title="{link_title}" href="{link_href}">{value}</a>' */ template: { value: TEMPLATE }, /* * Strings used in the UI elements. * * The strings used are defaulted from the datatable-sort language pack * for the language identified in the YUI "lang" configuration (which * defaults to "en"). * * Configurable strings are "sortBy" and "reverseSortBy", which are * assigned to the sort link's title attribute. * * @attribute strings * @type {Object} */ strings: { valueFn: function () { return Y.Intl.get('datatable-sort-deprecated'); } } } }); ///////////////////////////////////////////////////////////////////////////// // // PROTOTYPE // ///////////////////////////////////////////////////////////////////////////// Y.extend(DataTableSort, Y.Plugin.Base, { ///////////////////////////////////////////////////////////////////////////// // // METHODS // ///////////////////////////////////////////////////////////////////////////// /* * Initializer. * * @method initializer * @param config {Object} Config object. * @private */ initializer: function(config) { var dt = this.get("host"), trigger = this.get("trigger"); dt.get("recordset").plug(Y.Plugin.RecordsetSort, {dt: dt}); dt.get("recordset").sort.addTarget(dt); // Wrap link around TH value this.doBefore("_createTheadThNode", this._beforeCreateTheadThNode); // Add class this.doBefore("_attachTheadThNode", this._beforeAttachTheadThNode); this.doBefore("_attachTbodyTdNode", this._beforeAttachTbodyTdNode); // Attach trigger handlers dt.delegate(trigger.event, Y.bind(this._onEventSortColumn,this), trigger.selector); // Attach UI hooks dt.after("recordsetSort:sort", function() { this._uiSetRecordset(this.get("recordset")); }); this.on("lastSortedByChange", function(e) { this._uiSetLastSortedBy(e.prevVal, e.newVal, dt); }); //TODO //dt.after("recordset:mutation", function() {//reset lastSortedBy}); //TODO //add Column sortFn ATTR // Update UI after the fact (render-then-plug case) if(dt.get("rendered")) { dt._uiSetColumnset(dt.get("columnset")); this._uiSetLastSortedBy(null, this.get("lastSortedBy"), dt); } }, /* * @method _setLastSortedBy * @description Normalizes lastSortedBy * @param val {String | Object} {key, dir} or "key" * @return {key, dir, notdir} * @private */ _setLastSortedBy: function(val) { if (Y.Lang.isString(val)) { val = { key: val, dir: "desc" }; } if (val) { return (val.dir === "desc") ? { key: val.key, dir: "desc", notdir: "asc" } : { key: val.key, dir: "asc", notdir:"desc" }; } else { return null; } }, /* * Updates sort UI. * * @method _uiSetLastSortedBy * @param val {Object} New lastSortedBy object {key,dir}. * @param dt {Y.DataTable.Base} Host. * @protected */ _uiSetLastSortedBy: function(prevVal, newVal, dt) { var strings = this.get('strings'), columnset = dt.get("columnset"), prevKey = prevVal && prevVal.key, newKey = newVal && newVal.key, prevClass = prevVal && dt.getClassName(prevVal.dir), newClass = newVal && dt.getClassName(newVal.dir), prevColumn = columnset.keyHash[prevKey], newColumn = columnset.keyHash[newKey], tbodyNode = dt._tbodyNode, fromTemplate = Y.Lang.sub, th, sortArrow, sortLabel; // Clear previous UI if (prevColumn && prevClass) { th = prevColumn.thNode; sortArrow = th.one('a'); if (sortArrow) { sortArrow.set('title', fromTemplate(strings.sortBy, { column: prevColumn.get('label') })); } th.removeClass(prevClass); tbodyNode.all("." + YgetClassName(COLUMN, prevColumn.get("id"))) .removeClass(prevClass); } // Add new sort UI if (newColumn && newClass) { th = newColumn.thNode; sortArrow = th.one('a'); if (sortArrow) { sortLabel = (newVal.dir === ASC) ? "reverseSortBy" : "sortBy"; sortArrow.set('title', fromTemplate(strings[sortLabel], { column: newColumn.get('label') })); } th.addClass(newClass); tbodyNode.all("." + YgetClassName(COLUMN, newColumn.get("id"))) .addClass(newClass); } }, /* * Before header cell element is created, inserts link markup around {value}. * * @method _beforeCreateTheadThNode * @param o {Object} {value, column, tr}. * @protected */ _beforeCreateTheadThNode: function(o) { var sortedBy, sortLabel; if (o.column.get("sortable")) { sortedBy = this.get('lastSortedBy'); sortLabel = (sortedBy && sortedBy.dir === ASC && sortedBy.key === o.column.get('key')) ? "reverseSortBy" : "sortBy"; o.value = Y.Lang.sub(this.get("template"), { link_class: o.link_class || "", link_title: Y.Lang.sub(this.get('strings.' + sortLabel), { column: o.column.get('label') }), link_href: "#", value: o.value }); } }, /* * Before header cell element is attached, sets applicable class names. * * @method _beforeAttachTheadThNode * @param o {Object} {value, column, tr}. * @protected */ _beforeAttachTheadThNode: function(o) { var lastSortedBy = this.get("lastSortedBy"), key = lastSortedBy && lastSortedBy.key, dir = lastSortedBy && lastSortedBy.dir, notdir = lastSortedBy && lastSortedBy.notdir; // This Column is sortable if(o.column.get("sortable")) { o.th.addClass(YgetClassName(DATATABLE, "sortable")); } // This Column is currently sorted if(key && (key === o.column.get("key"))) { o.th.replaceClass(YgetClassName(DATATABLE, notdir), YgetClassName(DATATABLE, dir)); } }, /* * Before header cell element is attached, sets applicable class names. * * @method _beforeAttachTbodyTdNode * @param o {Object} {record, column, tr, headers, classnames, value}. * @protected */ _beforeAttachTbodyTdNode: function(o) { var lastSortedBy = this.get("lastSortedBy"), key = lastSortedBy && lastSortedBy.key, dir = lastSortedBy && lastSortedBy.dir, notdir = lastSortedBy && lastSortedBy.notdir; // This Column is sortable if(o.column.get("sortable")) { o.td.addClass(YgetClassName(DATATABLE, "sortable")); } // This Column is currently sorted if(key && (key === o.column.get("key"))) { o.td.replaceClass(YgetClassName(DATATABLE, notdir), YgetClassName(DATATABLE, dir)); } }, /* * In response to the "trigger" event, sorts the underlying Recordset and * updates the lastSortedBy attribute. * * @method _onEventSortColumn * @param o {Object} {value, column, tr}. * @protected */ _onEventSortColumn: function(e) { e.halt(); //TODO: normalize e.currentTarget to TH var table = this.get("host"), column = table.get("columnset").idHash[e.currentTarget.get("id")], key, field, lastSort, desc, sorter; if (column.get("sortable")) { key = column.get("key"); field = column.get("field"); lastSort = this.get("lastSortedBy") || {}; desc = (lastSort.key === key && lastSort.dir === ASC); sorter = column.get("sortFn"); table.get("recordset").sort.sort(field, desc, sorter); this.set("lastSortedBy", { key: key, dir: (desc) ? DESC : ASC }); } } }); Y.namespace("Plugin").DataTableSort = DataTableSort; }, '@VERSION@' ,{requires:['datatable-base-deprecated','plugin','recordset-sort'], lang:['en']});
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v5.2.0 * @link http://www.ag-grid.com/ * @license MIT */ var utils_1 = require('../utils'); var TabbedLayout = (function () { function TabbedLayout(params) { var _this = this; this.items = []; this.params = params; this.eGui = document.createElement('div'); this.eGui.innerHTML = TabbedLayout.TEMPLATE; this.eHeader = this.eGui.querySelector('#tabHeader'); this.eBody = this.eGui.querySelector('#tabBody'); utils_1.Utils.addCssClass(this.eGui, params.cssClass); if (params.items) { params.items.forEach(function (item) { return _this.addItem(item); }); } } TabbedLayout.prototype.setAfterAttachedParams = function (params) { this.afterAttachedParams = params; }; TabbedLayout.prototype.getMinWidth = function () { var eDummyContainer = document.createElement('span'); // position fixed, so it isn't restricted to the boundaries of the parent eDummyContainer.style.position = 'fixed'; // we put the dummy into the body container, so it will inherit all the // css styles that the real cells are inheriting this.eGui.appendChild(eDummyContainer); var minWidth = 0; this.items.forEach(function (itemWrapper) { utils_1.Utils.removeAllChildren(eDummyContainer); var eClone = itemWrapper.tabbedItem.body.cloneNode(true); eDummyContainer.appendChild(eClone); if (minWidth < eDummyContainer.offsetWidth) { minWidth = eDummyContainer.offsetWidth; } }); this.eGui.removeChild(eDummyContainer); return minWidth; }; TabbedLayout.prototype.showFirstItem = function () { if (this.items.length > 0) { this.showItemWrapper(this.items[0]); } }; TabbedLayout.prototype.addItem = function (item) { var eHeaderButton = document.createElement('span'); eHeaderButton.appendChild(item.title); utils_1.Utils.addCssClass(eHeaderButton, 'ag-tab'); this.eHeader.appendChild(eHeaderButton); var wrapper = { tabbedItem: item, eHeaderButton: eHeaderButton }; this.items.push(wrapper); eHeaderButton.addEventListener('click', this.showItemWrapper.bind(this, wrapper)); }; TabbedLayout.prototype.showItem = function (tabbedItem) { var itemWrapper = utils_1.Utils.find(this.items, function (itemWrapper) { return itemWrapper.tabbedItem === tabbedItem; }); if (itemWrapper) { this.showItemWrapper(itemWrapper); } }; TabbedLayout.prototype.showItemWrapper = function (wrapper) { if (this.params.onItemClicked) { this.params.onItemClicked({ item: wrapper.tabbedItem }); } if (this.activeItem === wrapper) { utils_1.Utils.callIfPresent(this.params.onActiveItemClicked); return; } utils_1.Utils.removeAllChildren(this.eBody); this.eBody.appendChild(wrapper.tabbedItem.body); if (this.activeItem) { utils_1.Utils.removeCssClass(this.activeItem.eHeaderButton, 'ag-tab-selected'); } utils_1.Utils.addCssClass(wrapper.eHeaderButton, 'ag-tab-selected'); this.activeItem = wrapper; if (wrapper.tabbedItem.afterAttachedCallback) { wrapper.tabbedItem.afterAttachedCallback(this.afterAttachedParams); } }; TabbedLayout.prototype.getGui = function () { return this.eGui; }; TabbedLayout.TEMPLATE = '<div>' + '<div id="tabHeader" class="ag-tab-header"></div>' + '<div id="tabBody" class="ag-tab-body"></div>' + '</div>'; return TabbedLayout; })(); exports.TabbedLayout = TabbedLayout;
version https://git-lfs.github.com/spec/v1 oid sha256:595a5981ebcb57d8a2c48a230e0a63ec714396ece9ea5dbbcd1009d7582705a7 size 2931
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ 'use strict'; function appendSaveAsDialog (index, output) { var div; var menu; function closeMenu(e) { var left = parseInt(menu.style.left, 10); var top = parseInt(menu.style.top, 10); if ( e.x < left || e.x > (left + menu.offsetWidth) || e.y < top || e.y > (top + menu.offsetHeight) ) { menu.parentNode.removeChild(menu); document.body.removeEventListener('mousedown', closeMenu, false); } } div = document.getElementById(output + index); div.childNodes[0].addEventListener('contextmenu', function (e) { var list, savePng, saveSvg; menu = document.createElement('div'); menu.className = 'wavedromMenu'; menu.style.top = e.y + 'px'; menu.style.left = e.x + 'px'; list = document.createElement('ul'); savePng = document.createElement('li'); savePng.innerHTML = 'Save as PNG'; list.appendChild(savePng); saveSvg = document.createElement('li'); saveSvg.innerHTML = 'Save as SVG'; list.appendChild(saveSvg); //var saveJson = document.createElement('li'); //saveJson.innerHTML = 'Save as JSON'; //list.appendChild(saveJson); menu.appendChild(list); document.body.appendChild(menu); savePng.addEventListener('click', function () { var html, firstDiv, svgdata, img, canvas, context, pngdata, a; html = ''; if (index !== 0) { firstDiv = document.getElementById(output + 0); html += firstDiv.innerHTML.substring(166, firstDiv.innerHTML.indexOf('<g id="waves_0">')); } html = [div.innerHTML.slice(0, 166), html, div.innerHTML.slice(166)].join(''); svgdata = 'data:image/svg+xml;base64,' + btoa(html); img = new Image(); img.src = svgdata; canvas = document.createElement('canvas'); canvas.width = img.width; canvas.height = img.height; context = canvas.getContext('2d'); context.drawImage(img, 0, 0); pngdata = canvas.toDataURL('image/png'); a = document.createElement('a'); a.href = pngdata; a.download = 'wavedrom.png'; a.click(); menu.parentNode.removeChild(menu); document.body.removeEventListener('mousedown', closeMenu, false); }, false ); saveSvg.addEventListener('click', function () { var html, firstDiv, svgdata, a; html = ''; if (index !== 0) { firstDiv = document.getElementById(output + 0); html += firstDiv.innerHTML.substring(166, firstDiv.innerHTML.indexOf('<g id="waves_0">')); } html = [div.innerHTML.slice(0, 166), html, div.innerHTML.slice(166)].join(''); svgdata = 'data:image/svg+xml;base64,' + btoa(html); a = document.createElement('a'); a.href = svgdata; a.download = 'wavedrom.svg'; a.click(); menu.parentNode.removeChild(menu); document.body.removeEventListener('mousedown', closeMenu, false); }, false ); menu.addEventListener('contextmenu', function (ee) { ee.preventDefault(); }, false ); document.body.addEventListener('mousedown', closeMenu, false); e.preventDefault(); }, false ); } module.exports = appendSaveAsDialog; /* eslint-env browser */ },{}],2:[function(require,module,exports){ 'use strict'; var // obj2ml = require('./obj2ml'), jsonmlParse = require('./jsonml-parse'); // function createElement (obj) { // var el; // // el = document.createElement('g'); // el.innerHTML = obj2ml(obj); // return el.firstChild; // } module.exports = jsonmlParse; // module.exports = createElement; /* eslint-env browser */ },{"./jsonml-parse":15}],3:[function(require,module,exports){ 'use strict'; var eva = require('./eva'), renderWaveForm = require('./render-wave-form'); function editorRefresh () { // var svg, // ser, // ssvg, // asvg, // sjson, // ajson; renderWaveForm(0, eva('InputJSON_0'), 'WaveDrom_Display_'); /* svg = document.getElementById('svgcontent_0'); ser = new XMLSerializer(); ssvg = '<?xml version='1.0' standalone='no'?>\n' + '<!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'>\n' + '<!-- Created with WaveDrom -->\n' + ser.serializeToString(svg); asvg = document.getElementById('download_svg'); asvg.href = 'data:image/svg+xml;base64,' + window.btoa(ssvg); sjson = localStorage.waveform; ajson = document.getElementById('download_json'); ajson.href = 'data:text/json;base64,' + window.btoa(sjson); */ } module.exports = editorRefresh; },{"./eva":4,"./render-wave-form":28}],4:[function(require,module,exports){ 'use strict'; function eva (id) { var TheTextBox, source; function erra (e) { return { signal: [{ name: ['tspan', ['tspan', {class:'error h5'}, 'Error: '], e.message] }]}; } TheTextBox = document.getElementById(id); /* eslint-disable no-eval */ if (TheTextBox.type && TheTextBox.type === 'textarea') { try { source = eval('(' + TheTextBox.value + ')'); } catch (e) { return erra(e); } } else { try { source = eval('(' + TheTextBox.innerHTML + ')'); } catch (e) { return erra(e); } } /* eslint-enable no-eval */ if (Object.prototype.toString.call(source) !== '[object Object]') { return erra({ message: '[Semantic]: The root has to be an Object: "{signal:[...]}"'}); } if (source.signal) { if (Object.prototype.toString.call(source.signal) !== '[object Array]') { return erra({ message: '[Semantic]: "signal" object has to be an Array "signal:[]"'}); } } else if (source.assign) { if (Object.prototype.toString.call(source.assign) !== '[object Array]') { return erra({ message: '[Semantic]: "assign" object hasto be an Array "assign:[]"'}); } } else { return erra({ message: '[Semantic]: "signal:[...]" or "assign:[...]" property is missing inside the root Object'}); } return source; } module.exports = eva; /* eslint-env browser */ },{}],5:[function(require,module,exports){ 'use strict'; function findLaneMarkers (lanetext) { var gcount = 0, lcount = 0, ret = []; lanetext.forEach(function (e) { if ( (e === 'vvv-2') || (e === 'vvv-3') || (e === 'vvv-4') || (e === 'vvv-5') ) { lcount += 1; } else { if (lcount !== 0) { ret.push(gcount - ((lcount + 1) / 2)); lcount = 0; } } gcount += 1; }); if (lcount !== 0) { ret.push(gcount - ((lcount + 1) / 2)); } return ret; } module.exports = findLaneMarkers; },{}],6:[function(require,module,exports){ 'use strict'; function genBrick (texts, extra, times) { var i, j, R = []; if (texts.length === 4) { for (j = 0; j < times; j += 1) { R.push(texts[0]); for (i = 0; i < extra; i += 1) { R.push(texts[1]); } R.push(texts[2]); for (i = 0; i < extra; i += 1) { R.push(texts[3]); } } return R; } if (texts.length === 1) { texts.push(texts[0]); } R.push(texts[0]); for (i = 0; i < (times * (2 * (extra + 1)) - 1); i += 1) { R.push(texts[1]); } return R; } module.exports = genBrick; },{}],7:[function(require,module,exports){ 'use strict'; var genBrick = require('./gen-brick'); function genFirstWaveBrick (text, extra, times) { var tmp; tmp = []; switch (text) { case 'p': tmp = genBrick(['pclk', '111', 'nclk', '000'], extra, times); break; case 'n': tmp = genBrick(['nclk', '000', 'pclk', '111'], extra, times); break; case 'P': tmp = genBrick(['Pclk', '111', 'nclk', '000'], extra, times); break; case 'N': tmp = genBrick(['Nclk', '000', 'pclk', '111'], extra, times); break; case 'l': case 'L': case '0': tmp = genBrick(['000'], extra, times); break; case 'h': case 'H': case '1': tmp = genBrick(['111'], extra, times); break; case '=': tmp = genBrick(['vvv-2'], extra, times); break; case '2': tmp = genBrick(['vvv-2'], extra, times); break; case '3': tmp = genBrick(['vvv-3'], extra, times); break; case '4': tmp = genBrick(['vvv-4'], extra, times); break; case '5': tmp = genBrick(['vvv-5'], extra, times); break; case 'd': tmp = genBrick(['ddd'], extra, times); break; case 'u': tmp = genBrick(['uuu'], extra, times); break; case 'z': tmp = genBrick(['zzz'], extra, times); break; default: tmp = genBrick(['xxx'], extra, times); break; } return tmp; } module.exports = genFirstWaveBrick; },{"./gen-brick":6}],8:[function(require,module,exports){ 'use strict'; var genBrick = require('./gen-brick'); function genWaveBrick (text, extra, times) { var x1, x2, x3, y1, y2, x4, x5, x6, xclude, atext, tmp0, tmp1, tmp2, tmp3, tmp4; x1 = {p:'pclk', n:'nclk', P:'Pclk', N:'Nclk', h:'pclk', l:'nclk', H:'Pclk', L:'Nclk'}; x2 = { '0':'0', '1':'1', 'x':'x', 'd':'d', 'u':'u', 'z':'z', '=':'v', '2':'v', '3':'v', '4':'v', '5':'v' }; x3 = { '0': '', '1': '', 'x': '', 'd': '', 'u': '', 'z': '', '=':'-2', '2':'-2', '3':'-3', '4':'-4', '5':'-5' }; y1 = { 'p':'0', 'n':'1', 'P':'0', 'N':'1', 'h':'1', 'l':'0', 'H':'1', 'L':'0', '0':'0', '1':'1', 'x':'x', 'd':'d', 'u':'u', 'z':'z', '=':'v', '2':'v', '3':'v', '4':'v', '5':'v' }; y2 = { 'p': '', 'n': '', 'P': '', 'N': '', 'h': '', 'l': '', 'H': '', 'L': '', '0': '', '1': '', 'x': '', 'd': '', 'u': '', 'z': '', '=':'-2', '2':'-2', '3':'-3', '4':'-4', '5':'-5' }; x4 = { 'p': '111', 'n': '000', 'P': '111', 'N': '000', 'h': '111', 'l': '000', 'H': '111', 'L': '000', '0': '000', '1': '111', 'x': 'xxx', 'd': 'ddd', 'u': 'uuu', 'z': 'zzz', '=': 'vvv-2', '2': 'vvv-2', '3': 'vvv-3', '4': 'vvv-4', '5': 'vvv-5' }; x5 = { p:'nclk', n:'pclk', P:'nclk', N:'pclk' }; x6 = { p: '000', n: '111', P: '000', N: '111' }; xclude = { 'hp':'111', 'Hp':'111', 'ln': '000', 'Ln': '000', 'nh':'111', 'Nh':'111', 'pl': '000', 'Pl':'000' }; atext = text.split(''); //if (atext.length !== 2) { return genBrick(['xxx'], extra, times); } tmp0 = x4[atext[1]]; tmp1 = x1[atext[1]]; if (tmp1 === undefined) { tmp2 = x2[atext[1]]; if (tmp2 === undefined) { // unknown return genBrick(['xxx'], extra, times); } else { tmp3 = y1[atext[0]]; if (tmp3 === undefined) { // unknown return genBrick(['xxx'], extra, times); } // soft curves return genBrick([tmp3 + 'm' + tmp2 + y2[atext[0]] + x3[atext[1]], tmp0], extra, times); } } else { tmp4 = xclude[text]; if (tmp4 !== undefined) { tmp1 = tmp4; } // sharp curves tmp2 = x5[atext[1]]; if (tmp2 === undefined) { // hlHL return genBrick([tmp1, tmp0], extra, times); } else { // pnPN return genBrick([tmp1, tmp0, tmp2, x6[atext[1]]], extra, times); } } } module.exports = genWaveBrick; },{"./gen-brick":6}],9:[function(require,module,exports){ 'use strict'; var processAll = require('./process-all'), eva = require('./eva'), renderWaveForm = require('./render-wave-form'), editorRefresh = require('./editor-refresh'); module.exports = { processAll: processAll, eva: eva, renderWaveForm: renderWaveForm, editorRefresh: editorRefresh }; },{"./editor-refresh":3,"./eva":4,"./process-all":21,"./render-wave-form":28}],10:[function(require,module,exports){ 'use strict'; var jsonmlParse = require('./create-element'), w3 = require('./w3'); function insertSVGTemplateAssign (index, parent) { var node, e; // cleanup while (parent.childNodes.length) { parent.removeChild(parent.childNodes[0]); } e = ['svg', {id: 'svgcontent_' + index, xmlns: w3.svg, 'xmlns:xlink': w3.xlink, overflow:'hidden'}, ['style', '.pinname {font-size:12px; font-style:normal; font-variant:normal; font-weight:500; font-stretch:normal; text-align:center; text-anchor:end; font-family:Helvetica} .wirename {font-size:12px; font-style:normal; font-variant:normal; font-weight:500; font-stretch:normal; text-align:center; text-anchor:start; font-family:Helvetica} .wirename:hover {fill:blue} .gate {color:#000; fill:#ffc; fill-opacity: 1;stroke:#000; stroke-width:1; stroke-opacity:1} .gate:hover {fill:red !important; } .wire {fill:none; stroke:#000; stroke-width:1; stroke-opacity:1} .grid {fill:#fff; fill-opacity:1; stroke:none}'] ]; node = jsonmlParse(e); parent.insertBefore(node, null); } module.exports = insertSVGTemplateAssign; /* eslint-env browser */ },{"./create-element":2,"./w3":30}],11:[function(require,module,exports){ 'use strict'; var jsonmlParse = require('./create-element'), w3 = require('./w3'), waveSkin = require('./wave-skin'); function insertSVGTemplate (index, parent, source, lane) { var node, first, e; // cleanup while (parent.childNodes.length) { parent.removeChild(parent.childNodes[0]); } for (first in waveSkin) { break; } e = waveSkin.default || waveSkin[first]; if (source && source.config && source.config.skin && waveSkin[source.config.skin]) { e = waveSkin[source.config.skin]; } if (index === 0) { lane.xs = Number(e[3][1][2][1].width); lane.ys = Number(e[3][1][2][1].height); lane.xlabel = Number(e[3][1][2][1].x); lane.ym = Number(e[3][1][2][1].y); } else { e = ['svg', { id: 'svg', xmlns: w3.svg, 'xmlns:xlink': w3.xlink, height: '0' }, ['g', { id: 'waves' }, ['g', {id: 'lanes'}], ['g', {id: 'groups'}] ] ]; } e[e.length - 1][1].id = 'waves_' + index; e[e.length - 1][2][1].id = 'lanes_' + index; e[e.length - 1][3][1].id = 'groups_' + index; e[1].id = 'svgcontent_' + index; e[1].height = 0; node = jsonmlParse(e); parent.insertBefore(node, null); } module.exports = insertSVGTemplate; /* eslint-env browser */ },{"./create-element":2,"./w3":30,"./wave-skin":32}],12:[function(require,module,exports){ 'use strict'; //attribute name mapping var ATTRMAP = { rowspan : 'rowSpan', colspan : 'colSpan', cellpadding : 'cellPadding', cellspacing : 'cellSpacing', tabindex : 'tabIndex', accesskey : 'accessKey', hidefocus : 'hideFocus', usemap : 'useMap', maxlength : 'maxLength', readonly : 'readOnly', contenteditable : 'contentEditable' // can add more attributes here as needed }, // attribute duplicates ATTRDUP = { enctype : 'encoding', onscroll : 'DOMMouseScroll' // can add more attributes here as needed }, // event names EVTS = (function (/*string[]*/ names) { var evts = {}, evt; while (names.length) { evt = names.shift(); evts['on' + evt.toLowerCase()] = evt; } return evts; })('blur,change,click,dblclick,error,focus,keydown,keypress,keyup,load,mousedown,mouseenter,mouseleave,mousemove,mouseout,mouseover,mouseup,resize,scroll,select,submit,unload'.split(',')); /*void*/ function addHandler(/*DOM*/ elem, /*string*/ name, /*function*/ handler) { if (typeof handler === 'string') { handler = new Function('event', handler); } if (typeof handler !== 'function') { return; } elem[name] = handler; } /*DOM*/ function addAttributes(/*DOM*/ elem, /*object*/ attr) { if (attr.name && document.attachEvent) { try { // IE fix for not being able to programatically change the name attribute var alt = document.createElement('<' + elem.tagName + ' name=\'' + attr.name + '\'>'); // fix for Opera 8.5 and Netscape 7.1 creating malformed elements if (elem.tagName === alt.tagName) { elem = alt; } } catch (ex) { console.log(ex); } } // for each attributeName for (var name in attr) { if (attr.hasOwnProperty(name)) { // attributeValue var value = attr[name]; if ( name && value !== null && typeof value !== 'undefined' ) { name = ATTRMAP[name.toLowerCase()] || name; if (name === 'style') { if (typeof elem.style.cssText !== 'undefined') { elem.style.cssText = value; } else { elem.style = value; } // } else if (name === 'class') { // elem.className = value; // // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // elem.setAttribute(name, value); // // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! } else if (EVTS[name]) { addHandler(elem, name, value); // also set duplicated events if (ATTRDUP[name]) { addHandler(elem, ATTRDUP[name], value); } } else if ( typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' ) { elem.setAttribute(name, value); // also set duplicated attributes if (ATTRDUP[name]) { elem.setAttribute(ATTRDUP[name], value); } } else { // allow direct setting of complex properties elem[name] = value; // also set duplicated attributes if (ATTRDUP[name]) { elem[ATTRDUP[name]] = value; } } } } } return elem; } module.exports = addAttributes; /* eslint-env browser */ /* eslint no-new-func:0 */ },{}],13:[function(require,module,exports){ 'use strict'; /*void*/ function appendChild(/*DOM*/ elem, /*DOM*/ child) { if (child) { // if ( // elem.tagName && // elem.tagName.toLowerCase() === 'table' && // elem.tBodies // ) { // if (!child.tagName) { // // must unwrap documentFragment for tables // if (child.nodeType === 11) { // while (child.firstChild) { // appendChild(elem, child.removeChild(child.firstChild)); // } // } // return; // } // // in IE must explicitly nest TRs in TBODY // var childTag = child.tagName.toLowerCase();// child tagName // if (childTag && childTag !== "tbody" && childTag !== "thead") { // // insert in last tbody // var tBody = elem.tBodies.length > 0 ? elem.tBodies[elem.tBodies.length - 1] : null; // if (!tBody) { // tBody = document.createElement(childTag === "th" ? "thead" : "tbody"); // elem.appendChild(tBody); // } // tBody.appendChild(child); // } else if (elem.canHaveChildren !== false) { // elem.appendChild(child); // } // } else if ( elem.tagName && elem.tagName.toLowerCase() === 'style' && document.createStyleSheet ) { // IE requires this interface for styles elem.cssText = child; } else if (elem.canHaveChildren !== false) { elem.appendChild(child); } // else if ( // elem.tagName && // elem.tagName.toLowerCase() === 'object' && // child.tagName && // child.tagName.toLowerCase() === 'param' // ) { // // IE-only path // try { // elem.appendChild(child); // } catch (ex1) { // // } // try { // if (elem.object) { // elem.object[child.name] = child.value; // } // } catch (ex2) {} // } } } module.exports = appendChild; /* eslint-env browser */ },{}],14:[function(require,module,exports){ 'use strict'; var trimWhitespace = require('./jsonml-trim-whitespace'); /*DOM*/ function hydrate(/*string*/ value) { var wrapper = document.createElement('div'); wrapper.innerHTML = value; // trim extraneous whitespace trimWhitespace(wrapper); // eliminate wrapper for single nodes if (wrapper.childNodes.length === 1) { return wrapper.firstChild; } // create a document fragment to hold elements var frag = document.createDocumentFragment ? document.createDocumentFragment() : document.createElement(''); while (wrapper.firstChild) { frag.appendChild(wrapper.firstChild); } return frag; } module.exports = hydrate; /* eslint-env browser */ },{"./jsonml-trim-whitespace":16}],15:[function(require,module,exports){ 'use strict'; var hydrate = require('./jsonml-hydrate'), w3 = require('./w3'), appendChild = require('./jsonml-append-child'), addAttributes = require('./jsonml-add-attributes'), trimWhitespace = require('./jsonml-trim-whitespace'); var patch, parse, onerror = null; /*bool*/ function isElement (/*JsonML*/ jml) { return (jml instanceof Array) && (typeof jml[0] === 'string'); } /*DOM*/ function onError (/*Error*/ ex, /*JsonML*/ jml, /*function*/ filter) { return document.createTextNode('[' + ex + '-' + filter + ']'); } patch = /*DOM*/ function (/*DOM*/ elem, /*JsonML*/ jml, /*function*/ filter) { for (var i = 1; i < jml.length; i++) { if ( (jml[i] instanceof Array) || (typeof jml[i] === 'string') ) { // append children appendChild(elem, parse(jml[i], filter)); // } else if (jml[i] instanceof Unparsed) { } else if ( jml[i] && jml[i].value ) { appendChild(elem, hydrate(jml[i].value)); } else if ( (typeof jml[i] === 'object') && (jml[i] !== null) && elem.nodeType === 1 ) { // add attributes elem = addAttributes(elem, jml[i]); } } return elem; }; parse = /*DOM*/ function (/*JsonML*/ jml, /*function*/ filter) { var elem; try { if (!jml) { return null; } if (typeof jml === 'string') { return document.createTextNode(jml); } // if (jml instanceof Unparsed) { if (jml && jml.value) { return hydrate(jml.value); } if (!isElement(jml)) { throw new SyntaxError('invalid JsonML'); } var tagName = jml[0]; // tagName if (!tagName) { // correctly handle a list of JsonML trees // create a document fragment to hold elements var frag = document.createDocumentFragment ? document.createDocumentFragment() : document.createElement(''); for (var i = 2; i < jml.length; i++) { appendChild(frag, parse(jml[i], filter)); } // trim extraneous whitespace trimWhitespace(frag); // eliminate wrapper for single nodes if (frag.childNodes.length === 1) { return frag.firstChild; } return frag; } if ( tagName.toLowerCase() === 'style' && document.createStyleSheet ) { // IE requires this interface for styles patch(document.createStyleSheet(), jml, filter); // in IE styles are effective immediately return null; } elem = patch(document.createElementNS(w3.svg, tagName), jml, filter); // trim extraneous whitespace trimWhitespace(elem); // return (elem && (typeof filter === 'function')) ? filter(elem) : elem; return elem; } catch (ex) { try { // handle error with complete context var err = (typeof onerror === 'function') ? onerror : onError; return err(ex, jml, filter); } catch (ex2) { return document.createTextNode('[' + ex2 + ']'); } } }; module.exports = parse; /* eslint-env browser */ /* eslint yoda:1 */ },{"./jsonml-add-attributes":12,"./jsonml-append-child":13,"./jsonml-hydrate":14,"./jsonml-trim-whitespace":16,"./w3":30}],16:[function(require,module,exports){ 'use strict'; /*bool*/ function isWhitespace(/*DOM*/ node) { return node && (node.nodeType === 3) && (!node.nodeValue || !/\S/.exec(node.nodeValue)); } /*void*/ function trimWhitespace(/*DOM*/ elem) { if (elem) { while (isWhitespace(elem.firstChild)) { // trim leading whitespace text nodes elem.removeChild(elem.firstChild); } while (isWhitespace(elem.lastChild)) { // trim trailing whitespace text nodes elem.removeChild(elem.lastChild); } } } module.exports = trimWhitespace; /* eslint-env browser */ },{}],17:[function(require,module,exports){ 'use strict'; var lane = { xs : 20, // tmpgraphlane0.width ys : 20, // tmpgraphlane0.height xg : 120, // tmpgraphlane0.x // yg : 0, // head gap yh0 : 0, // head gap title yh1 : 0, // head gap yf0 : 0, // foot gap yf1 : 0, // foot gap y0 : 5, // tmpgraphlane0.y yo : 30, // tmpgraphlane1.y - y0; tgo : -10, // tmptextlane0.x - xg; ym : 15, // tmptextlane0.y - y0 xlabel : 6, // tmptextlabel.x - xg; xmax : 1, scale : 1, head : {}, foot : {} }; module.exports = lane; },{}],18:[function(require,module,exports){ 'use strict'; function parseConfig (source, lane) { var hscale; function tonumber (x) { return x > 0 ? Math.round(x) : 1; } lane.hscale = 1; if (lane.hscale0) { lane.hscale = lane.hscale0; } if (source && source.config && source.config.hscale) { hscale = Math.round(tonumber(source.config.hscale)); if (hscale > 0) { if (hscale > 100) { hscale = 100; } lane.hscale = hscale; } } lane.yh0 = 0; lane.yh1 = 0; lane.head = source.head; lane.xmin_cfg = 0; lane.xmax_cfg = 1e12; // essentially infinity if (source && source.config && source.config.hbounds && source.config.hbounds.length==2) { source.config.hbounds[0] = Math.floor(source.config.hbounds[0]); source.config.hbounds[1] = Math.ceil(source.config.hbounds[1]); if ( source.config.hbounds[0] < source.config.hbounds[1] ) { // convert hbounds ticks min, max to bricks min, max // TODO: do we want to base this on ticks or tocks in // head or foot? All 4 can be different... or just 0 reference? lane.xmin_cfg = 2 * Math.floor(source.config.hbounds[0]); lane.xmax_cfg = 2 * Math.floor(source.config.hbounds[1]); } } if (source && source.head) { if ( source.head.tick || source.head.tick === 0 || source.head.tock || source.head.tock === 0 ) { lane.yh0 = 20; } // if tick defined, modify start tick by lane.xmin_cfg if ( source.head.tick || source.head.tick === 0 ) { source.head.tick = source.head.tick + lane.xmin_cfg/2; } // if tock defined, modify start tick by lane.xmin_cfg if ( source.head.tock || source.head.tock === 0 ) { source.head.tock = source.head.tock + lane.xmin_cfg/2; } if (source.head.text) { lane.yh1 = 46; lane.head.text = source.head.text; } } lane.yf0 = 0; lane.yf1 = 0; lane.foot = source.foot; if (source && source.foot) { if ( source.foot.tick || source.foot.tick === 0 || source.foot.tock || source.foot.tock === 0 ) { lane.yf0 = 20; } // if tick defined, modify start tick by lane.xmin_cfg if ( source.foot.tick || source.foot.tick === 0 ) { source.foot.tick = source.foot.tick + lane.xmin_cfg/2; } // if tock defined, modify start tick by lane.xmin_cfg if ( source.foot.tock || source.foot.tock === 0 ) { source.foot.tock = source.foot.tock + lane.xmin_cfg/2; } if (source.foot.text) { lane.yf1 = 46; lane.foot.text = source.foot.text; } } } module.exports = parseConfig; },{}],19:[function(require,module,exports){ 'use strict'; var genFirstWaveBrick = require('./gen-first-wave-brick'), genWaveBrick = require('./gen-wave-brick'), findLaneMarkers = require('./find-lane-markers'); // text is the wave member of the signal object // extra = hscale-1 ( padding ) // lane is an object containing all properties for this waveform function parseWaveLane (text, extra, lane) { var Repeats, Top, Next, Stack = [], R = [], i; var unseen_bricks = [], num_unseen_markers; Stack = text.split(''); Next = Stack.shift(); Repeats = 1; while (Stack[0] === '.' || Stack[0] === '|') { // repeaters parser Stack.shift(); Repeats += 1; } R = R.concat(genFirstWaveBrick(Next, extra, Repeats)); while (Stack.length) { Top = Next; Next = Stack.shift(); Repeats = 1; while (Stack[0] === '.' || Stack[0] === '|') { // repeaters parser Stack.shift(); Repeats += 1; } R = R.concat(genWaveBrick((Top + Next), extra, Repeats)); } // shift out unseen bricks due to phase shift, and save them in // unseen_bricks array for (i = 0; i < lane.phase; i += 1) { unseen_bricks.push(R.shift()); } if (unseen_bricks.length > 0) { num_unseen_markers = findLaneMarkers( unseen_bricks ).length; // if end of unseen_bricks and start of R both have a marker, // then one less unseen marker if ( findLaneMarkers( [unseen_bricks[unseen_bricks.length-1]] ).length == 1 && findLaneMarkers( [R[0]] ).length == 1 ) { num_unseen_markers -= 1; } } else { num_unseen_markers = 0; } // R is array of half brick types, each is item is string // num_unseen_markers is how many markers are now unseen due to phase return [R, num_unseen_markers]; } module.exports = parseWaveLane; },{"./find-lane-markers":5,"./gen-first-wave-brick":7,"./gen-wave-brick":8}],20:[function(require,module,exports){ 'use strict'; var parseWaveLane = require('./parse-wave-lane'); function data_extract (e, num_unseen_markers) { var ret_data; ret_data = e.data; if (ret_data === undefined) { return null; } if (typeof (ret_data) === 'string') { ret_data= ret_data.split(' '); } // slice data array after unseen markers ret_data = ret_data.slice( num_unseen_markers ); return ret_data; } function parseWaveLanes (sig, lane) { var x, sigx, content = [], content_wave, parsed_wave_lane, num_unseen_markers, tmp0 = []; for (x in sig) { // sigx is each signal in the array of signals being iterated over sigx = sig[x]; lane.period = sigx.period ? sigx.period : 1; // xmin_cfg is min. brick of hbounds, add to lane.phase of all signals lane.phase = (sigx.phase ? sigx.phase * 2 : 0) + lane.xmin_cfg; content.push([]); tmp0[0] = sigx.name || ' '; // xmin_cfg is min. brick of hbounds, add 1/2 to sigx.phase of all sigs tmp0[1] = (sigx.phase || 0) + lane.xmin_cfg/2; if ( sigx.wave ) { parsed_wave_lane = parseWaveLane(sigx.wave, lane.period * lane.hscale - 1, lane); content_wave = parsed_wave_lane[0] ; num_unseen_markers = parsed_wave_lane[1]; } else { content_wave = null; } content[content.length - 1][0] = tmp0.slice(0); content[content.length - 1][1] = content_wave; content[content.length - 1][2] = data_extract(sigx,num_unseen_markers); } // content is an array of arrays, representing the list of signals using // the same order: // content[0] = [ [name,phase], parsedwavelaneobj, dataextracted ] return content; } module.exports = parseWaveLanes; },{"./parse-wave-lane":19}],21:[function(require,module,exports){ 'use strict'; var eva = require('./eva'), appendSaveAsDialog = require('./append-save-as-dialog'), renderWaveForm = require('./render-wave-form'); function processAll () { var points, i, index, node0; // node1; // first pass index = 0; // actual number of valid anchor points = document.querySelectorAll('*'); for (i = 0; i < points.length; i++) { if (points.item(i).type && points.item(i).type === 'WaveDrom') { points.item(i).setAttribute('id', 'InputJSON_' + index); node0 = document.createElement('div'); // node0.className += 'WaveDrom_Display_' + index; node0.id = 'WaveDrom_Display_' + index; points.item(i).parentNode.insertBefore(node0, points.item(i)); // WaveDrom.InsertSVGTemplate(i, node0); index += 1; } } // second pass for (i = 0; i < index; i += 1) { renderWaveForm(i, eva('InputJSON_' + i), 'WaveDrom_Display_'); appendSaveAsDialog(i, 'WaveDrom_Display_'); } // add styles document.head.innerHTML += '<style type="text/css">div.wavedromMenu{position:fixed;border:solid 1pt#CCCCCC;background-color:white;box-shadow:0px 10px 20px #808080;cursor:default;margin:0px;padding:0px;}div.wavedromMenu>ul{margin:0px;padding:0px;}div.wavedromMenu>ul>li{padding:2px 10px;list-style:none;}div.wavedromMenu>ul>li:hover{background-color:#b5d5ff;}</style>'; } module.exports = processAll; /* eslint-env browser */ },{"./append-save-as-dialog":1,"./eva":4,"./render-wave-form":28}],22:[function(require,module,exports){ 'use strict'; function rec (tmp, state) { var i, name, old = {}, delta = {'x':10}; if (typeof tmp[0] === 'string' || typeof tmp[0] === 'number') { name = tmp[0]; delta.x = 25; } state.x += delta.x; for (i = 0; i < tmp.length; i++) { if (typeof tmp[i] === 'object') { if (Object.prototype.toString.call(tmp[i]) === '[object Array]') { old.y = state.y; state = rec(tmp[i], state); state.groups.push({'x':state.xx, 'y':old.y, 'height':(state.y - old.y), 'name':state.name}); } else { state.lanes.push(tmp[i]); state.width.push(state.x); state.y += 1; } } } state.xx = state.x; state.x -= delta.x; state.name = name; return state; } module.exports = rec; },{}],23:[function(require,module,exports){ 'use strict'; var tspan = require('tspan'), jsonmlParse = require('./create-element'), w3 = require('./w3'); function renderArcs (root, source, index, top, lane) { var gg, i, k, text, Stack = [], Edge = {words: [], from: 0, shape: '', to: 0, label: ''}, Events = {}, pos, eventname, // labeltext, label, underlabel, from, to, dx, dy, lx, ly, gmark, lwidth; function t1 () { if (from && to) { gmark = document.createElementNS(w3.svg, 'path'); gmark.id = ('gmark_' + Edge.from + '_' + Edge.to); gmark.setAttribute('d', 'M ' + from.x + ',' + from.y + ' ' + to.x + ',' + to.y); gmark.setAttribute('style', 'fill:none;stroke:#00F;stroke-width:1'); gg.insertBefore(gmark, null); } } if (source) { for (i in source) { lane.period = source[i].period ? source[i].period : 1; lane.phase = (source[i].phase ? source[i].phase * 2 : 0) + lane.xmin_cfg; text = source[i].node; if (text) { Stack = text.split(''); pos = 0; while (Stack.length) { eventname = Stack.shift(); if (eventname !== '.') { Events[eventname] = { 'x' : lane.xs * (2 * pos * lane.period * lane.hscale - lane.phase) + lane.xlabel, 'y' : i * lane.yo + lane.y0 + lane.ys * 0.5 }; } pos += 1; } } } gg = document.createElementNS(w3.svg, 'g'); gg.id = 'wavearcs_' + index; root.insertBefore(gg, null); if (top.edge) { for (i in top.edge) { Edge.words = top.edge[i].split(' '); Edge.label = top.edge[i].substring(Edge.words[0].length); Edge.label = Edge.label.substring(1); Edge.from = Edge.words[0].substr(0, 1); Edge.to = Edge.words[0].substr(-1, 1); Edge.shape = Edge.words[0].slice(1, -1); from = Events[Edge.from]; to = Events[Edge.to]; t1(); if (from && to) { if (Edge.label) { label = tspan.parse(Edge.label); label.unshift( 'text', { style: 'font-size:10px;', 'text-anchor': 'middle', 'xml:space': 'preserve' } ); label = jsonmlParse(label); underlabel = jsonmlParse(['rect', { height: 9, style: 'fill:#FFF;' } ]); gg.insertBefore(underlabel, null); gg.insertBefore(label, null); lwidth = label.getBBox().width; underlabel.setAttribute('width', lwidth); } dx = to.x - from.x; dy = to.y - from.y; lx = ((from.x + to.x) / 2); ly = ((from.y + to.y) / 2); switch (Edge.shape) { case '-' : { break; } case '~' : { gmark.setAttribute('d', 'M ' + from.x + ',' + from.y + ' c ' + (0.7 * dx) + ', 0 ' + (0.3 * dx) + ', ' + dy + ' ' + dx + ', ' + dy); break; } case '-~' : { gmark.setAttribute('d', 'M ' + from.x + ',' + from.y + ' c ' + (0.7 * dx) + ', 0 ' + dx + ', ' + dy + ' ' + dx + ', ' + dy); if (Edge.label) { lx = (from.x + (to.x - from.x) * 0.75); } break; } case '~-' : { gmark.setAttribute('d', 'M ' + from.x + ',' + from.y + ' c ' + 0 + ', 0 ' + (0.3 * dx) + ', ' + dy + ' ' + dx + ', ' + dy); if (Edge.label) { lx = (from.x + (to.x - from.x) * 0.25); } break; } case '-|' : { gmark.setAttribute('d', 'm ' + from.x + ',' + from.y + ' ' + dx + ',0 0,' + dy); if (Edge.label) { lx = to.x; } break; } case '|-' : { gmark.setAttribute('d', 'm ' + from.x + ',' + from.y + ' 0,' + dy + ' ' + dx + ',0'); if (Edge.label) { lx = from.x; } break; } case '-|-': { gmark.setAttribute('d', 'm ' + from.x + ',' + from.y + ' ' + (dx / 2) + ',0 0,' + dy + ' ' + (dx / 2) + ',0'); break; } case '->' : { gmark.setAttribute('style', 'marker-end:url(#arrowhead);stroke:#0041c4;stroke-width:1;fill:none'); break; } case '~>' : { gmark.setAttribute('style', 'marker-end:url(#arrowhead);stroke:#0041c4;stroke-width:1;fill:none'); gmark.setAttribute('d', 'M ' + from.x + ',' + from.y + ' ' + 'c ' + (0.7 * dx) + ', 0 ' + 0.3 * dx + ', ' + dy + ' ' + dx + ', ' + dy); break; } case '-~>': { gmark.setAttribute('style', 'marker-end:url(#arrowhead);stroke:#0041c4;stroke-width:1;fill:none'); gmark.setAttribute('d', 'M ' + from.x + ',' + from.y + ' ' + 'c ' + (0.7 * dx) + ', 0 ' + dx + ', ' + dy + ' ' + dx + ', ' + dy); if (Edge.label) { lx = (from.x + (to.x - from.x) * 0.75); } break; } case '~->': { gmark.setAttribute('style', 'marker-end:url(#arrowhead);stroke:#0041c4;stroke-width:1;fill:none'); gmark.setAttribute('d', 'M ' + from.x + ',' + from.y + ' ' + 'c ' + 0 + ', 0 ' + (0.3 * dx) + ', ' + dy + ' ' + dx + ', ' + dy); if (Edge.label) { lx = (from.x + (to.x - from.x) * 0.25); } break; } case '-|>' : { gmark.setAttribute('style', 'marker-end:url(#arrowhead);stroke:#0041c4;stroke-width:1;fill:none'); gmark.setAttribute('d', 'm ' + from.x + ',' + from.y + ' ' + dx + ',0 0,' + dy); if (Edge.label) { lx = to.x; } break; } case '|->' : { gmark.setAttribute('style', 'marker-end:url(#arrowhead);stroke:#0041c4;stroke-width:1;fill:none'); gmark.setAttribute('d', 'm ' + from.x + ',' + from.y + ' 0,' + dy + ' ' + dx + ',0'); if (Edge.label) { lx = from.x; } break; } case '-|->': { gmark.setAttribute('style', 'marker-end:url(#arrowhead);stroke:#0041c4;stroke-width:1;fill:none'); gmark.setAttribute('d', 'm ' + from.x + ',' + from.y + ' ' + (dx / 2) + ',0 0,' + dy + ' ' + (dx / 2) + ',0'); break; } case '<->' : { gmark.setAttribute('style', 'marker-end:url(#arrowhead);marker-start:url(#arrowtail);stroke:#0041c4;stroke-width:1;fill:none'); break; } case '<~>' : { gmark.setAttribute('style', 'marker-end:url(#arrowhead);marker-start:url(#arrowtail);stroke:#0041c4;stroke-width:1;fill:none'); gmark.setAttribute('d', 'M ' + from.x + ',' + from.y + ' ' + 'c ' + (0.7 * dx) + ', 0 ' + (0.3 * dx) + ', ' + dy + ' ' + dx + ', ' + dy); break; } case '<-~>': { gmark.setAttribute('style', 'marker-end:url(#arrowhead);marker-start:url(#arrowtail);stroke:#0041c4;stroke-width:1;fill:none'); gmark.setAttribute('d', 'M ' + from.x + ',' + from.y + ' ' + 'c ' + (0.7 * dx) + ', 0 ' + dx + ', ' + dy + ' ' + dx + ', ' + dy); if (Edge.label) { lx = (from.x + (to.x - from.x) * 0.75); } break; } case '<-|>' : { gmark.setAttribute('style', 'marker-end:url(#arrowhead);marker-start:url(#arrowtail);stroke:#0041c4;stroke-width:1;fill:none'); gmark.setAttribute('d', 'm ' + from.x + ',' + from.y + ' ' + dx + ',0 0,' + dy); if (Edge.label) { lx = to.x; } break; } case '<-|->': { gmark.setAttribute('style', 'marker-end:url(#arrowhead);marker-start:url(#arrowtail);stroke:#0041c4;stroke-width:1;fill:none'); gmark.setAttribute('d', 'm ' + from.x + ',' + from.y + ' ' + (dx / 2) + ',0 0,' + dy + ' ' + (dx / 2) + ',0'); break; } default : { gmark.setAttribute('style', 'fill:none;stroke:#F00;stroke-width:1'); } } if (Edge.label) { label.setAttribute('x', lx); label.setAttribute('y', ly + 3); underlabel.setAttribute('x', lx - lwidth / 2); underlabel.setAttribute('y', ly - 5); } } } } for (k in Events) { if (k === k.toLowerCase()) { if (Events[k].x > 0) { underlabel = jsonmlParse(['rect', { y: Events[k].y - 4, height: 8, style: 'fill:#FFF;' } ]); label = jsonmlParse(['text', { style: 'font-size:8px;', x: Events[k].x, y: Events[k].y + 2, 'text-anchor': 'middle' }, (k + '') ]); gg.insertBefore(underlabel, null); gg.insertBefore(label, null); lwidth = label.getBBox().width + 2; underlabel.setAttribute('x', Events[k].x - lwidth / 2); underlabel.setAttribute('width', lwidth); } } } } } module.exports = renderArcs; /* eslint-env browser */ },{"./create-element":2,"./w3":30,"tspan":33}],24:[function(require,module,exports){ 'use strict'; var jsonmlParse = require('./create-element'); function render (tree, state) { var y, i, ilen; state.xmax = Math.max(state.xmax, state.x); y = state.y; ilen = tree.length; for (i = 1; i < ilen; i++) { if (Object.prototype.toString.call(tree[i]) === '[object Array]') { state = render(tree[i], {x: (state.x + 1), y: state.y, xmax: state.xmax}); } else { tree[i] = {name:tree[i], x: (state.x + 1), y: state.y}; state.y += 2; } } tree[0] = {name: tree[0], x: state.x, y: Math.round((y + (state.y - 2)) / 2)}; state.x--; return state; } function draw_body (type, ymin, ymax) { var e, iecs, circle = ' M 4,0 C 4,1.1 3.1,2 2,2 0.9,2 0,1.1 0,0 c 0,-1.1 0.9,-2 2,-2 1.1,0 2,0.9 2,2 z', gates = { '~': 'M -11,-6 -11,6 0,0 z m -5,6 5,0' + circle, '=': 'M -11,-6 -11,6 0,0 z m -5,6 5,0', '&': 'm -16,-10 5,0 c 6,0 11,4 11,10 0,6 -5,10 -11,10 l -5,0 z', '~&': 'm -16,-10 5,0 c 6,0 11,4 11,10 0,6 -5,10 -11,10 l -5,0 z' + circle, '|': 'm -18,-10 4,0 c 6,0 12,5 14,10 -2,5 -8,10 -14,10 l -4,0 c 2.5,-5 2.5,-15 0,-20 z', '~|': 'm -18,-10 4,0 c 6,0 12,5 14,10 -2,5 -8,10 -14,10 l -4,0 c 2.5,-5 2.5,-15 0,-20 z' + circle, '^': 'm -21,-10 c 1,3 2,6 2,10 m 0,0 c 0,4 -1,7 -2,10 m 3,-20 4,0 c 6,0 12,5 14,10 -2,5 -8,10 -14,10 l -4,0 c 1,-3 2,-6 2,-10 0,-4 -1,-7 -2,-10 z', '~^': 'm -21,-10 c 1,3 2,6 2,10 m 0,0 c 0,4 -1,7 -2,10 m 3,-20 4,0 c 6,0 12,5 14,10 -2,5 -8,10 -14,10 l -4,0 c 1,-3 2,-6 2,-10 0,-4 -1,-7 -2,-10 z' + circle, '+': 'm -8,5 0,-10 m -5,5 10,0 m 3,0 c 0,4.418278 -3.581722,8 -8,8 -4.418278,0 -8,-3.581722 -8,-8 0,-4.418278 3.581722,-8 8,-8 4.418278,0 8,3.581722 8,8 z', '*': 'm -4,4 -8,-8 m 0,8 8,-8 m 4,4 c 0,4.418278 -3.581722,8 -8,8 -4.418278,0 -8,-3.581722 -8,-8 0,-4.418278 3.581722,-8 8,-8 4.418278,0 8,3.581722 8,8 z' }, iec = { BUF: 1, INV: 1, AND: '&', NAND: '&', OR: '\u22651', NOR: '\u22651', XOR: '=1', XNOR: '=1', box: '' }, circled = { INV: 1, NAND: 1, NOR: 1, XNOR: 1 }; if (ymax === ymin) { ymax = 4; ymin = -4; } e = gates[type]; iecs = iec[type]; if (e) { return ['path', {class:'gate', d: e}]; } else { if (iecs) { return [ 'g', [ 'path', { class:'gate', d: 'm -16,' + (ymin - 3) + ' 16,0 0,' + (ymax - ymin + 6) + ' -16,0 z' + (circled[type] ? circle : '') }], [ 'text', [ 'tspan', {x: '-14', y: '4', class: 'wirename'}, iecs + '' ] ] ]; } else { return ['text', ['tspan', {x: '-14', y: '4', class: 'wirename'}, type + '']]; } } } function draw_gate (spec) { // ['type', [x,y], [x,y] ... ] var i, ret = ['g'], ys = [], ymin, ymax, ilen = spec.length; for (i = 2; i < ilen; i++) { ys.push(spec[i][1]); } ymin = Math.min.apply(null, ys); ymax = Math.max.apply(null, ys); ret.push( ['g', {transform:'translate(16,0)'}, ['path', { d: 'M ' + spec[2][0] + ',' + ymin + ' ' + spec[2][0] + ',' + ymax, class: 'wire' }] ] ); for (i = 2; i < ilen; i++) { ret.push( ['g', ['path', { d: 'm ' + spec[i][0] + ',' + spec[i][1] + ' 16,0', class: 'wire' } ] ] ); } ret.push( ['g', { transform: 'translate(' + spec[1][0] + ',' + spec[1][1] + ')' }, ['title', spec[0]], draw_body(spec[0], ymin - spec[1][1], ymax - spec[1][1]) ] ); return ret; } function draw_boxes (tree, xmax) { var ret = ['g'], i, ilen, fx, fy, fname, spec = []; if (Object.prototype.toString.call(tree) === '[object Array]') { ilen = tree.length; spec.push(tree[0].name); spec.push([32 * (xmax - tree[0].x), 8 * tree[0].y]); for (i = 1; i < ilen; i++) { if (Object.prototype.toString.call(tree[i]) === '[object Array]') { spec.push([32 * (xmax - tree[i][0].x), 8 * tree[i][0].y]); } else { spec.push([32 * (xmax - tree[i].x), 8 * tree[i].y]); } } ret.push(draw_gate(spec)); for (i = 1; i < ilen; i++) { ret.push(draw_boxes(tree[i], xmax)); } } else { fname = tree.name; fx = 32 * (xmax - tree.x); fy = 8 * tree.y; ret.push( ['g', { transform: 'translate(' + fx + ',' + fy + ')'}, ['title', fname], ['path', {d:'M 2,0 a 2,2 0 1 1 -4,0 2,2 0 1 1 4,0 z'}], ['text', ['tspan', { x:'-4', y:'4', class:'pinname'}, fname ] ] ] ); } return ret; } function renderAssign (index, source) { var tree, state, xmax, svg = ['g'], grid = ['g'], svgcontent, width, height, i, ilen, j, jlen; ilen = source.assign.length; state = { x: 0, y: 2, xmax: 0 }; tree = source.assign; for (i = 0; i < ilen; i++) { state = render(tree[i], state); state.x++; } xmax = state.xmax + 3; for (i = 0; i < ilen; i++) { svg.push(draw_boxes(tree[i], xmax)); } width = 32 * (xmax + 1) + 1; height = 8 * (state.y + 1) - 7; ilen = 4 * (xmax + 1); jlen = state.y + 1; for (i = 0; i <= ilen; i++) { for (j = 0; j <= jlen; j++) { grid.push(['rect', { height: 1, width: 1, x: (i * 8 - 0.5), y: (j * 8 - 0.5), class: 'grid' }]); } } svgcontent = document.getElementById('svgcontent_' + index); svgcontent.setAttribute('viewBox', '0 0 ' + width + ' ' + height); svgcontent.setAttribute('width', width); svgcontent.setAttribute('height', height); svgcontent.insertBefore(jsonmlParse(['g', {transform:'translate(0.5, 0.5)'}, grid, svg]), null); } module.exports = renderAssign; /* eslint-env browser */ },{"./create-element":2}],25:[function(require,module,exports){ 'use strict'; var w3 = require('./w3'); function renderGaps (root, source, index, lane) { var i, gg, g, b, pos, Stack = [], text; if (source) { gg = document.createElementNS(w3.svg, 'g'); gg.id = 'wavegaps_' + index; root.insertBefore(gg, null); for (i in source) { lane.period = source[i].period ? source[i].period : 1; lane.phase = (source[i].phase ? source[i].phase * 2 : 0) + lane.xmin_cfg; g = document.createElementNS(w3.svg, 'g'); g.id = 'wavegap_' + i + '_' + index; g.setAttribute('transform', 'translate(0,' + (lane.y0 + i * lane.yo) + ')'); gg.insertBefore(g, null); text = source[i].wave; if (text) { Stack = text.split(''); pos = 0; while (Stack.length) { if (Stack.shift() === '|') { b = document.createElementNS(w3.svg, 'use'); // b.id = 'guse_' + pos + '_' + i + '_' + index; b.setAttributeNS(w3.xlink, 'xlink:href', '#gap'); b.setAttribute('transform', 'translate(' + (lane.xs * ((2 * pos + 1) * lane.period * lane.hscale - lane.phase)) + ')'); g.insertBefore(b, null); } pos += 1; } } } } } module.exports = renderGaps; /* eslint-env browser */ },{"./w3":30}],26:[function(require,module,exports){ 'use strict'; var tspan = require('tspan'); function renderGroups (groups, index, lane) { var x, y, res = ['g'], ts; groups.forEach(function (e, i) { res.push(['path', { id: 'group_' + i + '_' + index, d: ('m ' + (e.x + 0.5) + ',' + (e.y * lane.yo + 3.5 + lane.yh0 + lane.yh1) + ' c -3,0 -5,2 -5,5 l 0,' + (e.height * lane.yo - 16) + ' c 0,3 2,5 5,5'), style: 'stroke:#0041c4;stroke-width:1;fill:none' } ]); if (e.name === undefined) { return; } x = (e.x - 10); y = (lane.yo * (e.y + (e.height / 2)) + lane.yh0 + lane.yh1); ts = tspan.parse(e.name); ts.unshift( 'text', { 'text-anchor': 'middle', class: 'info', 'xml:space': 'preserve' } ); res.push(['g', {transform: 'translate(' + x + ',' + y + ')'}, ['g', {transform: 'rotate(270)'}, ts]]); }); return res; } module.exports = renderGroups; /* eslint-env browser */ },{"tspan":33}],27:[function(require,module,exports){ 'use strict'; var tspan = require('tspan'), jsonmlParse = require('./create-element'); // w3 = require('./w3'); function renderMarks (root, content, index, lane) { var i, g, marks, mstep, mmstep, gy; // svgns function captext (cxt, anchor, y) { var tmark; if (cxt[anchor] && cxt[anchor].text) { tmark = tspan.parse(cxt[anchor].text); tmark.unshift( 'text', { x: cxt.xmax * cxt.xs / 2, y: y, 'text-anchor': 'middle', fill: '#000', 'xml:space': 'preserve' } ); tmark = jsonmlParse(tmark); g.insertBefore(tmark, null); } } function ticktock (cxt, ref1, ref2, x, dx, y, len) { var tmark, step = 1, offset, dp = 0, val, L = [], tmp; if (cxt[ref1] === undefined || cxt[ref1][ref2] === undefined) { return; } val = cxt[ref1][ref2]; if (typeof val === 'string') { val = val.split(' '); } else if (typeof val === 'number' || typeof val === 'boolean') { offset = Number(val); val = []; for (i = 0; i < len; i += 1) { val.push(i + offset); } } if (Object.prototype.toString.call(val) === '[object Array]') { if (val.length === 0) { return; } else if (val.length === 1) { offset = Number(val[0]); if (isNaN(offset)) { L = val; } else { for (i = 0; i < len; i += 1) { L[i] = i + offset; } } } else if (val.length === 2) { offset = Number(val[0]); step = Number(val[1]); tmp = val[1].split('.'); if ( tmp.length === 2 ) { dp = tmp[1].length; } if (isNaN(offset) || isNaN(step)) { L = val; } else { offset = step * offset; for (i = 0; i < len; i += 1) { L[i] = (step * i + offset).toFixed(dp); } } } else { L = val; } } else { return; } for (i = 0; i < len; i += 1) { tmp = L[i]; // if (typeof tmp === 'number') { tmp += ''; } tmark = tspan.parse(tmp); tmark.unshift( 'text', { x: i * dx + x, y: y, 'text-anchor': 'middle', class: 'muted', 'xml:space': 'preserve' } ); tmark = jsonmlParse(tmark); g.insertBefore(tmark, null); } } mstep = 2 * (lane.hscale); mmstep = mstep * lane.xs; marks = lane.xmax / mstep; gy = content.length * lane.yo; g = jsonmlParse(['g', {id: ('gmarks_' + index)}]); root.insertBefore(g, root.firstChild); for (i = 0; i < (marks + 1); i += 1) { g.insertBefore( jsonmlParse([ 'path', { id: 'gmark_' + i + '_' + index, d: 'm ' + (i * mmstep) + ',' + 0 + ' 0,' + gy, style: 'stroke:#888;stroke-width:0.5;stroke-dasharray:1,3' } ]), null ); } captext(lane, 'head', (lane.yh0 ? -33 : -13)); captext(lane, 'foot', gy + (lane.yf0 ? 45 : 25)); ticktock(lane, 'head', 'tick', 0, mmstep, -5, marks + 1); ticktock(lane, 'head', 'tock', mmstep / 2, mmstep, -5, marks); ticktock(lane, 'foot', 'tick', 0, mmstep, gy + 15, marks + 1); ticktock(lane, 'foot', 'tock', mmstep / 2, mmstep, gy + 15, marks); } module.exports = renderMarks; /* eslint-env browser */ },{"./create-element":2,"tspan":33}],28:[function(require,module,exports){ 'use strict'; var rec = require('./rec'), lane = require('./lane'), jsonmlParse = require('./create-element'), parseConfig = require('./parse-config'), parseWaveLanes = require('./parse-wave-lanes'), renderMarks = require('./render-marks'), renderGaps = require('./render-gaps'), renderGroups = require('./render-groups'), renderWaveLane = require('./render-wave-lane'), renderAssign = require('./render-assign'), renderArcs = require('./render-arcs'), insertSVGTemplate = require('./insert-svg-template'), insertSVGTemplateAssign = require('./insert-svg-template-assign'); function renderWaveForm (index, source, output) { var ret, root, groups, svgcontent, content, width, height, glengths, xmax = 0, i; if (source.signal) { insertSVGTemplate(index, document.getElementById(output + index), source, lane); parseConfig(source, lane); ret = rec(source.signal, {'x':0, 'y':0, 'xmax':0, 'width':[], 'lanes':[], 'groups':[]}); root = document.getElementById('lanes_' + index); groups = document.getElementById('groups_' + index); content = parseWaveLanes(ret.lanes, lane); glengths = renderWaveLane(root, content, index, lane); for (i in glengths) { xmax = Math.max(xmax, (glengths[i] + ret.width[i])); } renderMarks(root, content, index, lane); renderArcs(root, ret.lanes, index, source, lane); renderGaps(root, ret.lanes, index, lane); groups.insertBefore(jsonmlParse(renderGroups(ret.groups, index, lane)), null); lane.xg = Math.ceil((xmax - lane.tgo) / lane.xs) * lane.xs; width = (lane.xg + (lane.xs * (lane.xmax + 1))); height = (content.length * lane.yo + lane.yh0 + lane.yh1 + lane.yf0 + lane.yf1); svgcontent = document.getElementById('svgcontent_' + index); svgcontent.setAttribute('viewBox', '0 0 ' + width + ' ' + height); svgcontent.setAttribute('width', width); svgcontent.setAttribute('height', height); svgcontent.setAttribute('overflow', 'hidden'); root.setAttribute('transform', 'translate(' + (lane.xg + 0.5) + ', ' + ((lane.yh0 + lane.yh1) + 0.5) + ')'); } else if (source.assign) { insertSVGTemplateAssign(index, document.getElementById(output + index), source); renderAssign(index, source); } } module.exports = renderWaveForm; /* eslint-env browser */ },{"./create-element":2,"./insert-svg-template":11,"./insert-svg-template-assign":10,"./lane":17,"./parse-config":18,"./parse-wave-lanes":20,"./rec":22,"./render-arcs":23,"./render-assign":24,"./render-gaps":25,"./render-groups":26,"./render-marks":27,"./render-wave-lane":29}],29:[function(require,module,exports){ 'use strict'; var tspan = require('tspan'), jsonmlParse = require('./create-element'), w3 = require('./w3'), findLaneMarkers = require('./find-lane-markers'); function renderWaveLane (root, content, index, lane) { var i, j, k, g, gg, title, b, labels = [1], name, xoffset, xmax = 0, xgmax = 0, glengths = []; for (j = 0; j < content.length; j += 1) { name = content[j][0][0]; if (name) { // check name g = jsonmlParse(['g', { id: 'wavelane_' + j + '_' + index, transform: 'translate(0,' + ((lane.y0) + j * lane.yo) + ')' } ]); root.insertBefore(g, null); title = tspan.parse(name); title.unshift( 'text', { x: lane.tgo, y: lane.ym, class: 'info', 'text-anchor': 'end', 'xml:space': 'preserve' } ); title = jsonmlParse(title); g.insertBefore(title, null); // scale = lane.xs * (lane.hscale) * 2; glengths.push(title.getBBox().width); xoffset = content[j][0][1]; xoffset = (xoffset > 0) ? (Math.ceil(2 * xoffset) - 2 * xoffset) : (-2 * xoffset); gg = jsonmlParse(['g', { id: 'wavelane_draw_' + j + '_' + index, transform: 'translate(' + (xoffset * lane.xs) + ', 0)' } ]); g.insertBefore(gg, null); if (content[j][1]) { for (i = 0; i < content[j][1].length; i += 1) { b = document.createElementNS(w3.svg, 'use'); // b.id = 'use_' + i + '_' + j + '_' + index; b.setAttributeNS(w3.xlink, 'xlink:href', '#' + content[j][1][i]); // b.setAttribute('transform', 'translate(' + (i * lane.xs) + ')'); b.setAttribute('transform', 'translate(' + (i * lane.xs) + ')'); gg.insertBefore(b, null); } if (content[j][2] && content[j][2].length) { labels = findLaneMarkers(content[j][1]); if (labels.length !== 0) { for (k in labels) { if (content[j][2] && (typeof content[j][2][k] !== 'undefined')) { title = tspan.parse(content[j][2][k]); title.unshift( 'text', { x: labels[k] * lane.xs + lane.xlabel, y: lane.ym, 'text-anchor': 'middle', 'xml:space': 'preserve' } ); title = jsonmlParse(title); gg.insertBefore(title, null); } } } } if (content[j][1].length > xmax) { xmax = content[j][1].length; } } } } // xmax if no xmax_cfg,xmin_cfg, else set to config lane.xmax = Math.min(xmax, lane.xmax_cfg - lane.xmin_cfg); lane.xg = xgmax + 20; return glengths; } module.exports = renderWaveLane; /* eslint-env browser */ },{"./create-element":2,"./find-lane-markers":5,"./w3":30,"tspan":33}],30:[function(require,module,exports){ 'use strict'; module.exports = { svg: 'http://www.w3.org/2000/svg', xlink: 'http://www.w3.org/1999/xlink', xmlns: 'http://www.w3.org/XML/1998/namespace' }; },{}],31:[function(require,module,exports){ 'use strict'; window.WaveDrom = window.WaveDrom || {}; var index = require('./'); window.WaveDrom.ProcessAll = index.processAll; window.WaveDrom.RenderWaveForm = index.renderWaveForm; window.WaveDrom.EditorRefresh = index.editorRefresh; window.WaveDrom.eva = index.eva; /* eslint-env browser */ },{"./":9}],32:[function(require,module,exports){ 'use strict'; module.exports = window.WaveSkin; /* eslint-env browser */ },{}],33:[function(require,module,exports){ 'use strict'; var token = /<o>|<ins>|<s>|<sub>|<sup>|<b>|<i>|<tt>|<\/o>|<\/ins>|<\/s>|<\/sub>|<\/sup>|<\/b>|<\/i>|<\/tt>/; function update (s, cmd) { if (cmd.add) { cmd.add.split(';').forEach(function (e) { var arr = e.split(' '); s[arr[0]][arr[1]] = true; }); } if (cmd.del) { cmd.del.split(';').forEach(function (e) { var arr = e.split(' '); delete s[arr[0]][arr[1]]; }); } } var trans = { '<o>' : { add: 'text-decoration overline' }, '</o>' : { del: 'text-decoration overline' }, '<ins>' : { add: 'text-decoration underline' }, '</ins>' : { del: 'text-decoration underline' }, '<s>' : { add: 'text-decoration line-through' }, '</s>' : { del: 'text-decoration line-through' }, '<b>' : { add: 'font-weight bold' }, '</b>' : { del: 'font-weight bold' }, '<i>' : { add: 'font-style italic' }, '</i>' : { del: 'font-style italic' }, '<sub>' : { add: 'baseline-shift sub;font-size .7em' }, '</sub>' : { del: 'baseline-shift sub;font-size .7em' }, '<sup>' : { add: 'baseline-shift super;font-size .7em' }, '</sup>' : { del: 'baseline-shift super;font-size .7em' }, '<tt>' : { add: 'font-family monospace' }, '</tt>' : { del: 'font-family monospace' } }; function dump (s) { return Object.keys(s).reduce(function (pre, cur) { var keys = Object.keys(s[cur]); if (keys.length > 0) { pre[cur] = keys.join(' '); } return pre; }, {}); } function parse (str) { var state, res, i, m, a; if (str === undefined) { return []; } if (typeof str === 'number') { return [str + '']; } if (typeof str !== 'string') { return [str]; } res = []; state = { 'text-decoration': {}, 'font-weight': {}, 'font-style': {}, 'baseline-shift': {}, 'font-size': {}, 'font-family': {} }; while (true) { i = str.search(token); if (i === -1) { res.push(['tspan', dump(state), str]); return res; } if (i > 0) { a = str.slice(0, i); res.push(['tspan', dump(state), a]); } m = str.match(token)[0]; update(state, trans[m]); str = str.slice(i + m.length); if (str.length === 0) { return res; } } } exports.parse = parse; },{}]},{},[31]);
Package.describe({ name: 'rocketchat:crowd', version: '1.0.0', summary: 'Accounts login handler for crowd using atlassian-crowd-client from npm', git: '' }); Package.onUse(function(api) { api.use('rocketchat:logger'); api.use('rocketchat:lib'); api.use('ecmascript'); api.use('sha'); api.use('templating', 'client'); api.use('accounts-base', 'server'); api.use('accounts-password', 'server'); api.addFiles('client/loginHelper.js', 'client'); api.addFiles('server/crowd.js', 'server'); api.addFiles('server/settings.js', 'server'); api.export('CROWD', 'server'); }); Npm.depends({ 'atlassian-crowd': '0.5.0' });
/* Author: Geraint Luff and others Year: 2013 This code is released into the "public domain" by its author(s). Anybody may use, alter and distribute the code without restriction. The author makes no guarantees, and takes no liability of any kind for use of this code. If you find a bug or make an improvement, it would be courteous to let the author know, but it is not compulsory. */ (function (global) { 'use strict'; // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FObject%2Fkeys if (!Object.keys) { Object.keys = (function () { var hasOwnProperty = Object.prototype.hasOwnProperty, hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'), dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ], dontEnumsLength = dontEnums.length; return function (obj) { if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) { throw new TypeError('Object.keys called on non-object'); } var result = []; for (var prop in obj) { if (hasOwnProperty.call(obj, prop)) { result.push(prop); } } if (hasDontEnumBug) { for (var i=0; i < dontEnumsLength; i++) { if (hasOwnProperty.call(obj, dontEnums[i])) { result.push(dontEnums[i]); } } } return result; }; })(); } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create if (!Object.create) { Object.create = (function(){ function F(){} return function(o){ if (arguments.length !== 1) { throw new Error('Object.create implementation only accepts one parameter.'); } F.prototype = o; return new F(); }; })(); } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FArray%2FisArray if(!Array.isArray) { Array.isArray = function (vArg) { return Object.prototype.toString.call(vArg) === "[object Array]"; }; } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FArray%2FindexOf if (!Array.prototype.indexOf) { Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) { if (this === null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; if (len === 0) { return -1; } var n = 0; if (arguments.length > 1) { n = Number(arguments[1]); if (n !== n) { // shortcut for verifying if it's NaN n = 0; } else if (n !== 0 && n !== Infinity && n !== -Infinity) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } } if (n >= len) { return -1; } var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); for (; k < len; k++) { if (k in t && t[k] === searchElement) { return k; } } return -1; }; } // Grungey Object.isFrozen hack if (!Object.isFrozen) { Object.isFrozen = function (obj) { var key = "tv4_test_frozen_key"; while (obj.hasOwnProperty(key)) { key += Math.random(); } try { obj[key] = true; delete obj[key]; return false; } catch (e) { return true; } }; } var ValidatorContext = function ValidatorContext(parent, collectMultiple, errorMessages, checkRecursive, trackUnknownProperties) { this.missing = []; this.missingMap = {}; this.formatValidators = parent ? Object.create(parent.formatValidators) : {}; this.schemas = parent ? Object.create(parent.schemas) : {}; this.collectMultiple = collectMultiple; this.errors = []; this.handleError = collectMultiple ? this.collectError : this.returnError; if (checkRecursive) { this.checkRecursive = true; this.scanned = []; this.scannedFrozen = []; this.scannedFrozenSchemas = []; this.key = 'tv4_validation_id'; } if (trackUnknownProperties) { this.trackUnknownProperties = true; this.knownPropertyPaths = {}; this.unknownPropertyPaths = {}; } this.errorMessages = errorMessages; }; ValidatorContext.prototype.createError = function (code, messageParams, dataPath, schemaPath, subErrors) { var messageTemplate = this.errorMessages[code] || ErrorMessagesDefault[code]; if (typeof messageTemplate !== 'string') { return new ValidationError(code, "Unknown error code " + code + ": " + JSON.stringify(messageParams), dataPath, schemaPath, subErrors); } // Adapted from Crockford's supplant() var message = messageTemplate.replace(/\{([^{}]*)\}/g, function (whole, varName) { var subValue = messageParams[varName]; return typeof subValue === 'string' || typeof subValue === 'number' ? subValue : whole; }); return new ValidationError(code, message, dataPath, schemaPath, subErrors); }; ValidatorContext.prototype.returnError = function (error) { return error; }; ValidatorContext.prototype.collectError = function (error) { if (error) { this.errors.push(error); } return null; }; ValidatorContext.prototype.prefixErrors = function (startIndex, dataPath, schemaPath) { for (var i = startIndex; i < this.errors.length; i++) { this.errors[i] = this.errors[i].prefixWith(dataPath, schemaPath); } return this; }; ValidatorContext.prototype.banUnknownProperties = function () { for (var unknownPath in this.unknownPropertyPaths) { var error = this.createError(ErrorCodes.UNKNOWN_PROPERTY, {path: unknownPath}, unknownPath, ""); var result = this.handleError(error); if (result) { return result; } } return null; }; ValidatorContext.prototype.addFormat = function (format, validator) { if (typeof format === 'object') { for (var key in format) { this.addFormat(key, format[key]); } return this; } this.formatValidators[format] = validator; }; ValidatorContext.prototype.getSchema = function (url) { var schema; if (this.schemas[url] !== undefined) { schema = this.schemas[url]; return schema; } var baseUrl = url; var fragment = ""; if (url.indexOf('#') !== -1) { fragment = url.substring(url.indexOf("#") + 1); baseUrl = url.substring(0, url.indexOf("#")); } if (typeof this.schemas[baseUrl] === 'object') { schema = this.schemas[baseUrl]; var pointerPath = decodeURIComponent(fragment); if (pointerPath === "") { return schema; } else if (pointerPath.charAt(0) !== "/") { return undefined; } var parts = pointerPath.split("/").slice(1); for (var i = 0; i < parts.length; i++) { var component = parts[i].replace(/~1/g, "/").replace(/~0/g, "~"); if (schema[component] === undefined) { schema = undefined; break; } schema = schema[component]; } if (schema !== undefined) { return schema; } } if (this.missing[baseUrl] === undefined) { this.missing.push(baseUrl); this.missing[baseUrl] = baseUrl; this.missingMap[baseUrl] = baseUrl; } }; ValidatorContext.prototype.searchSchemas = function (schema, url) { if (typeof schema.id === "string") { if (isTrustedUrl(url, schema.id)) { if (this.schemas[schema.id] === undefined) { this.schemas[schema.id] = schema; } } } if (typeof schema === "object") { for (var key in schema) { if (key !== "enum") { if (typeof schema[key] === "object") { this.searchSchemas(schema[key], url); } else if (key === "$ref") { var uri = getDocumentUri(schema[key]); if (uri && this.schemas[uri] === undefined && this.missingMap[uri] === undefined) { this.missingMap[uri] = uri; } } } } } }; ValidatorContext.prototype.addSchema = function (url, schema) { //overload if (typeof schema === 'undefined') { if (typeof url === 'object' && typeof url.id === 'string') { schema = url; url = schema.id; } else { return; } } if (url = getDocumentUri(url) + "#") { // Remove empty fragment url = getDocumentUri(url); } this.schemas[url] = schema; delete this.missingMap[url]; normSchema(schema, url); this.searchSchemas(schema, url); }; ValidatorContext.prototype.getSchemaMap = function () { var map = {}; for (var key in this.schemas) { map[key] = this.schemas[key]; } return map; }; ValidatorContext.prototype.getSchemaUris = function (filterRegExp) { var list = []; for (var key in this.schemas) { if (!filterRegExp || filterRegExp.test(key)) { list.push(key); } } return list; }; ValidatorContext.prototype.getMissingUris = function (filterRegExp) { var list = []; for (var key in this.missingMap) { if (!filterRegExp || filterRegExp.test(key)) { list.push(key); } } return list; }; ValidatorContext.prototype.dropSchemas = function () { this.schemas = {}; this.reset(); }; ValidatorContext.prototype.reset = function () { this.missing = []; this.missingMap = {}; this.errors = []; }; ValidatorContext.prototype.validateAll = function (data, schema, dataPathParts, schemaPathParts, dataPointerPath) { var topLevel; if (schema['$ref'] !== undefined) { schema = this.getSchema(schema['$ref']); if (!schema) { return null; } } if (this.checkRecursive && (typeof data) === 'object') { topLevel = !this.scanned.length; if (data[this.key] && data[this.key].indexOf(schema) !== -1) { return null; } var frozenIndex; if (Object.isFrozen(data)) { frozenIndex = this.scannedFrozen.indexOf(data); if (frozenIndex !== -1 && this.scannedFrozenSchemas[frozenIndex].indexOf(schema) !== -1) { return null; } } this.scanned.push(data); if (Object.isFrozen(data)) { if (frozenIndex === -1) { frozenIndex = this.scannedFrozen.length; this.scannedFrozen.push(data); this.scannedFrozenSchemas.push([]); } this.scannedFrozenSchemas[frozenIndex].push(schema); } else { if (!data[this.key]) { try { Object.defineProperty(data, this.key, { value: [], configurable: true }); } catch (e) { //IE 7/8 workaround data[this.key] = []; } } data[this.key].push(schema); } } var errorCount = this.errors.length; var error = this.validateBasic(data, schema, dataPointerPath) || this.validateNumeric(data, schema, dataPointerPath) || this.validateString(data, schema, dataPointerPath) || this.validateArray(data, schema, dataPointerPath) || this.validateObject(data, schema, dataPointerPath) || this.validateCombinations(data, schema, dataPointerPath) || this.validateFormat(data, schema, dataPointerPath) || null; if (topLevel) { while (this.scanned.length) { var item = this.scanned.pop(); delete item[this.key]; } this.scannedFrozen = []; this.scannedFrozenSchemas = []; } if (error || errorCount !== this.errors.length) { while ((dataPathParts && dataPathParts.length) || (schemaPathParts && schemaPathParts.length)) { var dataPart = (dataPathParts && dataPathParts.length) ? "" + dataPathParts.pop() : null; var schemaPart = (schemaPathParts && schemaPathParts.length) ? "" + schemaPathParts.pop() : null; if (error) { error = error.prefixWith(dataPart, schemaPart); } this.prefixErrors(errorCount, dataPart, schemaPart); } } return this.handleError(error); }; ValidatorContext.prototype.validateFormat = function (data, schema) { if (typeof schema.format !== 'string' || !this.formatValidators[schema.format]) { return null; } var errorMessage = this.formatValidators[schema.format].call(null, data, schema); if (typeof errorMessage === 'string' || typeof errorMessage === 'number') { return this.createError(ErrorCodes.FORMAT_CUSTOM, {message: errorMessage}).prefixWith(null, "format"); } else if (errorMessage && typeof errorMessage === 'object') { return this.createError(ErrorCodes.FORMAT_CUSTOM, {message: errorMessage.message || "?"}, errorMessage.dataPath || null, errorMessage.schemaPath || "/format"); } return null; }; function recursiveCompare(A, B) { if (A === B) { return true; } if (typeof A === "object" && typeof B === "object") { if (Array.isArray(A) !== Array.isArray(B)) { return false; } else if (Array.isArray(A)) { if (A.length !== B.length) { return false; } for (var i = 0; i < A.length; i++) { if (!recursiveCompare(A[i], B[i])) { return false; } } } else { var key; for (key in A) { if (B[key] === undefined && A[key] !== undefined) { return false; } } for (key in B) { if (A[key] === undefined && B[key] !== undefined) { return false; } } for (key in A) { if (!recursiveCompare(A[key], B[key])) { return false; } } } return true; } return false; } ValidatorContext.prototype.validateBasic = function validateBasic(data, schema, dataPointerPath) { var error; if (error = this.validateType(data, schema, dataPointerPath)) { return error.prefixWith(null, "type"); } if (error = this.validateEnum(data, schema, dataPointerPath)) { return error.prefixWith(null, "type"); } return null; }; ValidatorContext.prototype.validateType = function validateType(data, schema) { if (schema.type === undefined) { return null; } var dataType = typeof data; if (data === null) { dataType = "null"; } else if (Array.isArray(data)) { dataType = "array"; } var allowedTypes = schema.type; if (typeof allowedTypes !== "object") { allowedTypes = [allowedTypes]; } for (var i = 0; i < allowedTypes.length; i++) { var type = allowedTypes[i]; if (type === dataType || (type === "integer" && dataType === "number" && (data % 1 === 0))) { return null; } } return this.createError(ErrorCodes.INVALID_TYPE, {type: dataType, expected: allowedTypes.join("/")}); }; ValidatorContext.prototype.validateEnum = function validateEnum(data, schema) { if (schema["enum"] === undefined) { return null; } for (var i = 0; i < schema["enum"].length; i++) { var enumVal = schema["enum"][i]; if (recursiveCompare(data, enumVal)) { return null; } } return this.createError(ErrorCodes.ENUM_MISMATCH, {value: (typeof JSON !== 'undefined') ? JSON.stringify(data) : data}); }; ValidatorContext.prototype.validateNumeric = function validateNumeric(data, schema, dataPointerPath) { return this.validateMultipleOf(data, schema, dataPointerPath) || this.validateMinMax(data, schema, dataPointerPath) || null; }; ValidatorContext.prototype.validateMultipleOf = function validateMultipleOf(data, schema) { var multipleOf = schema.multipleOf || schema.divisibleBy; if (multipleOf === undefined) { return null; } if (typeof data === "number") { if (data % multipleOf !== 0) { return this.createError(ErrorCodes.NUMBER_MULTIPLE_OF, {value: data, multipleOf: multipleOf}); } } return null; }; ValidatorContext.prototype.validateMinMax = function validateMinMax(data, schema) { if (typeof data !== "number") { return null; } if (schema.minimum !== undefined) { if (data < schema.minimum) { return this.createError(ErrorCodes.NUMBER_MINIMUM, {value: data, minimum: schema.minimum}).prefixWith(null, "minimum"); } if (schema.exclusiveMinimum && data === schema.minimum) { return this.createError(ErrorCodes.NUMBER_MINIMUM_EXCLUSIVE, {value: data, minimum: schema.minimum}).prefixWith(null, "exclusiveMinimum"); } } if (schema.maximum !== undefined) { if (data > schema.maximum) { return this.createError(ErrorCodes.NUMBER_MAXIMUM, {value: data, maximum: schema.maximum}).prefixWith(null, "maximum"); } if (schema.exclusiveMaximum && data === schema.maximum) { return this.createError(ErrorCodes.NUMBER_MAXIMUM_EXCLUSIVE, {value: data, maximum: schema.maximum}).prefixWith(null, "exclusiveMaximum"); } } return null; }; ValidatorContext.prototype.validateString = function validateString(data, schema, dataPointerPath) { return this.validateStringLength(data, schema, dataPointerPath) || this.validateStringPattern(data, schema, dataPointerPath) || null; }; ValidatorContext.prototype.validateStringLength = function validateStringLength(data, schema) { if (typeof data !== "string") { return null; } if (schema.minLength !== undefined) { if (data.length < schema.minLength) { return this.createError(ErrorCodes.STRING_LENGTH_SHORT, {length: data.length, minimum: schema.minLength}).prefixWith(null, "minLength"); } } if (schema.maxLength !== undefined) { if (data.length > schema.maxLength) { return this.createError(ErrorCodes.STRING_LENGTH_LONG, {length: data.length, maximum: schema.maxLength}).prefixWith(null, "maxLength"); } } return null; }; ValidatorContext.prototype.validateStringPattern = function validateStringPattern(data, schema) { if (typeof data !== "string" || schema.pattern === undefined) { return null; } var regexp = new RegExp(schema.pattern); if (!regexp.test(data)) { return this.createError(ErrorCodes.STRING_PATTERN, {pattern: schema.pattern}).prefixWith(null, "pattern"); } return null; }; ValidatorContext.prototype.validateArray = function validateArray(data, schema, dataPointerPath) { if (!Array.isArray(data)) { return null; } return this.validateArrayLength(data, schema, dataPointerPath) || this.validateArrayUniqueItems(data, schema, dataPointerPath) || this.validateArrayItems(data, schema, dataPointerPath) || null; }; ValidatorContext.prototype.validateArrayLength = function validateArrayLength(data, schema) { var error; if (schema.minItems !== undefined) { if (data.length < schema.minItems) { error = (this.createError(ErrorCodes.ARRAY_LENGTH_SHORT, {length: data.length, minimum: schema.minItems})).prefixWith(null, "minItems"); if (this.handleError(error)) { return error; } } } if (schema.maxItems !== undefined) { if (data.length > schema.maxItems) { error = (this.createError(ErrorCodes.ARRAY_LENGTH_LONG, {length: data.length, maximum: schema.maxItems})).prefixWith(null, "maxItems"); if (this.handleError(error)) { return error; } } } return null; }; ValidatorContext.prototype.validateArrayUniqueItems = function validateArrayUniqueItems(data, schema) { if (schema.uniqueItems) { for (var i = 0; i < data.length; i++) { for (var j = i + 1; j < data.length; j++) { if (recursiveCompare(data[i], data[j])) { var error = (this.createError(ErrorCodes.ARRAY_UNIQUE, {match1: i, match2: j})).prefixWith(null, "uniqueItems"); if (this.handleError(error)) { return error; } } } } } return null; }; ValidatorContext.prototype.validateArrayItems = function validateArrayItems(data, schema, dataPointerPath) { if (schema.items === undefined) { return null; } var error, i; if (Array.isArray(schema.items)) { for (i = 0; i < data.length; i++) { if (i < schema.items.length) { if (error = this.validateAll(data[i], schema.items[i], [i], ["items", i], dataPointerPath + "/" + i)) { return error; } } else if (schema.additionalItems !== undefined) { if (typeof schema.additionalItems === "boolean") { if (!schema.additionalItems) { error = (this.createError(ErrorCodes.ARRAY_ADDITIONAL_ITEMS, {})).prefixWith("" + i, "additionalItems"); if (this.handleError(error)) { return error; } } } else if (error = this.validateAll(data[i], schema.additionalItems, [i], ["additionalItems"], dataPointerPath + "/" + i)) { return error; } } } } else { for (i = 0; i < data.length; i++) { if (error = this.validateAll(data[i], schema.items, [i], ["items"], dataPointerPath + "/" + i)) { return error; } } } return null; }; ValidatorContext.prototype.validateObject = function validateObject(data, schema, dataPointerPath) { if (typeof data !== "object" || data === null || Array.isArray(data)) { return null; } return this.validateObjectMinMaxProperties(data, schema, dataPointerPath) || this.validateObjectRequiredProperties(data, schema, dataPointerPath) || this.validateObjectProperties(data, schema, dataPointerPath) || this.validateObjectDependencies(data, schema, dataPointerPath) || null; }; ValidatorContext.prototype.validateObjectMinMaxProperties = function validateObjectMinMaxProperties(data, schema) { var keys = Object.keys(data); var error; if (schema.minProperties !== undefined) { if (keys.length < schema.minProperties) { error = this.createError(ErrorCodes.OBJECT_PROPERTIES_MINIMUM, {propertyCount: keys.length, minimum: schema.minProperties}).prefixWith(null, "minProperties"); if (this.handleError(error)) { return error; } } } if (schema.maxProperties !== undefined) { if (keys.length > schema.maxProperties) { error = this.createError(ErrorCodes.OBJECT_PROPERTIES_MAXIMUM, {propertyCount: keys.length, maximum: schema.maxProperties}).prefixWith(null, "maxProperties"); if (this.handleError(error)) { return error; } } } return null; }; ValidatorContext.prototype.validateObjectRequiredProperties = function validateObjectRequiredProperties(data, schema) { if (schema.required !== undefined) { for (var i = 0; i < schema.required.length; i++) { var key = schema.required[i]; if (data[key] === undefined) { var error = this.createError(ErrorCodes.OBJECT_REQUIRED, {key: key}).prefixWith(null, "" + i).prefixWith(null, "required"); if (this.handleError(error)) { return error; } } } } return null; }; ValidatorContext.prototype.validateObjectProperties = function validateObjectProperties(data, schema, dataPointerPath) { var error; for (var key in data) { var keyPointerPath = dataPointerPath + "/" + key.replace(/~/g, '~0').replace(/\//g, '~1'); var foundMatch = false; if (schema.properties !== undefined && schema.properties[key] !== undefined) { foundMatch = true; if (error = this.validateAll(data[key], schema.properties[key], [key], ["properties", key], keyPointerPath)) { return error; } } if (schema.patternProperties !== undefined) { for (var patternKey in schema.patternProperties) { var regexp = new RegExp(patternKey); if (regexp.test(key)) { foundMatch = true; if (error = this.validateAll(data[key], schema.patternProperties[patternKey], [key], ["patternProperties", patternKey], keyPointerPath)) { return error; } } } } if (!foundMatch) { if (schema.additionalProperties !== undefined) { if (this.trackUnknownProperties) { this.knownPropertyPaths[keyPointerPath] = true; delete this.unknownPropertyPaths[keyPointerPath]; } if (typeof schema.additionalProperties === "boolean") { if (!schema.additionalProperties) { error = this.createError(ErrorCodes.OBJECT_ADDITIONAL_PROPERTIES, {}).prefixWith(key, "additionalProperties"); if (this.handleError(error)) { return error; } } } else { if (error = this.validateAll(data[key], schema.additionalProperties, [key], ["additionalProperties"], keyPointerPath)) { return error; } } } else if (this.trackUnknownProperties && !this.knownPropertyPaths[keyPointerPath]) { this.unknownPropertyPaths[keyPointerPath] = true; } } else if (this.trackUnknownProperties) { this.knownPropertyPaths[keyPointerPath] = true; delete this.unknownPropertyPaths[keyPointerPath]; } } return null; }; ValidatorContext.prototype.validateObjectDependencies = function validateObjectDependencies(data, schema, dataPointerPath) { var error; if (schema.dependencies !== undefined) { for (var depKey in schema.dependencies) { if (data[depKey] !== undefined) { var dep = schema.dependencies[depKey]; if (typeof dep === "string") { if (data[dep] === undefined) { error = this.createError(ErrorCodes.OBJECT_DEPENDENCY_KEY, {key: depKey, missing: dep}).prefixWith(null, depKey).prefixWith(null, "dependencies"); if (this.handleError(error)) { return error; } } } else if (Array.isArray(dep)) { for (var i = 0; i < dep.length; i++) { var requiredKey = dep[i]; if (data[requiredKey] === undefined) { error = this.createError(ErrorCodes.OBJECT_DEPENDENCY_KEY, {key: depKey, missing: requiredKey}).prefixWith(null, "" + i).prefixWith(null, depKey).prefixWith(null, "dependencies"); if (this.handleError(error)) { return error; } } } } else { if (error = this.validateAll(data, dep, [], ["dependencies", depKey], dataPointerPath)) { return error; } } } } } return null; }; ValidatorContext.prototype.validateCombinations = function validateCombinations(data, schema, dataPointerPath) { return this.validateAllOf(data, schema, dataPointerPath) || this.validateAnyOf(data, schema, dataPointerPath) || this.validateOneOf(data, schema, dataPointerPath) || this.validateNot(data, schema, dataPointerPath) || null; }; ValidatorContext.prototype.validateAllOf = function validateAllOf(data, schema, dataPointerPath) { if (schema.allOf === undefined) { return null; } var error; for (var i = 0; i < schema.allOf.length; i++) { var subSchema = schema.allOf[i]; if (error = this.validateAll(data, subSchema, [], ["allOf", i], dataPointerPath)) { return error; } } return null; }; ValidatorContext.prototype.validateAnyOf = function validateAnyOf(data, schema, dataPointerPath) { if (schema.anyOf === undefined) { return null; } var errors = []; var startErrorCount = this.errors.length; var oldUnknownPropertyPaths, oldKnownPropertyPaths; if (this.trackUnknownProperties) { oldUnknownPropertyPaths = this.unknownPropertyPaths; oldKnownPropertyPaths = this.knownPropertyPaths; } var errorAtEnd = true; for (var i = 0; i < schema.anyOf.length; i++) { if (this.trackUnknownProperties) { this.unknownPropertyPaths = {}; this.knownPropertyPaths = {}; } var subSchema = schema.anyOf[i]; var errorCount = this.errors.length; var error = this.validateAll(data, subSchema, [], ["anyOf", i], dataPointerPath); if (error === null && errorCount === this.errors.length) { this.errors = this.errors.slice(0, startErrorCount); if (this.trackUnknownProperties) { for (var knownKey in this.knownPropertyPaths) { oldKnownPropertyPaths[knownKey] = true; delete oldUnknownPropertyPaths[knownKey]; } for (var unknownKey in this.unknownPropertyPaths) { if (!oldKnownPropertyPaths[unknownKey]) { oldUnknownPropertyPaths[unknownKey] = true; } } console.log("Continuing"); // We need to continue looping so we catch all the property definitions, but we don't want to return an error errorAtEnd = false; continue; } return null; } if (error) { errors.push(error.prefixWith(null, "" + i).prefixWith(null, "anyOf")); } } if (this.trackUnknownProperties) { this.unknownPropertyPaths = oldUnknownPropertyPaths; this.knownPropertyPaths = oldKnownPropertyPaths; } if (errorAtEnd) { errors = errors.concat(this.errors.slice(startErrorCount)); this.errors = this.errors.slice(0, startErrorCount); return this.createError(ErrorCodes.ANY_OF_MISSING, {}, "", "/anyOf", errors); } }; ValidatorContext.prototype.validateOneOf = function validateOneOf(data, schema, dataPointerPath) { if (schema.oneOf === undefined) { return null; } var validIndex = null; var errors = []; var startErrorCount = this.errors.length; var oldUnknownPropertyPaths, oldKnownPropertyPaths; if (this.trackUnknownProperties) { oldUnknownPropertyPaths = this.unknownPropertyPaths; oldKnownPropertyPaths = this.knownPropertyPaths; } for (var i = 0; i < schema.oneOf.length; i++) { if (this.trackUnknownProperties) { this.unknownPropertyPaths = {}; this.knownPropertyPaths = {}; } var subSchema = schema.oneOf[i]; var errorCount = this.errors.length; var error = this.validateAll(data, subSchema, [], ["oneOf", i], dataPointerPath); if (error === null && errorCount === this.errors.length) { if (validIndex === null) { validIndex = i; } else { this.errors = this.errors.slice(0, startErrorCount); return this.createError(ErrorCodes.ONE_OF_MULTIPLE, {index1: validIndex, index2: i}, "", "/oneOf"); } if (this.trackUnknownProperties) { for (var knownKey in this.knownPropertyPaths) { oldKnownPropertyPaths[knownKey] = true; delete oldUnknownPropertyPaths[knownKey]; } for (var unknownKey in this.unknownPropertyPaths) { if (!oldKnownPropertyPaths[unknownKey]) { oldUnknownPropertyPaths[unknownKey] = true; } } } } else if (error) { errors.push(error.prefixWith(null, "" + i).prefixWith(null, "oneOf")); } } if (this.trackUnknownProperties) { this.unknownPropertyPaths = oldUnknownPropertyPaths; this.knownPropertyPaths = oldKnownPropertyPaths; } if (validIndex === null) { errors = errors.concat(this.errors.slice(startErrorCount)); this.errors = this.errors.slice(0, startErrorCount); return this.createError(ErrorCodes.ONE_OF_MISSING, {}, "", "/oneOf", errors); } else { this.errors = this.errors.slice(0, startErrorCount); } return null; }; ValidatorContext.prototype.validateNot = function validateNot(data, schema, dataPointerPath) { if (schema.not === undefined) { return null; } var oldErrorCount = this.errors.length; var oldUnknownPropertyPaths, oldKnownPropertyPaths; if (this.trackUnknownProperties) { oldUnknownPropertyPaths = this.unknownPropertyPaths; oldKnownPropertyPaths = this.knownPropertyPaths; this.unknownPropertyPaths = {}; this.knownPropertyPaths = {}; } var error = this.validateAll(data, schema.not, null, null, dataPointerPath); var notErrors = this.errors.slice(oldErrorCount); this.errors = this.errors.slice(0, oldErrorCount); if (this.trackUnknownProperties) { this.unknownPropertyPaths = oldUnknownPropertyPaths; this.knownPropertyPaths = oldKnownPropertyPaths; } if (error === null && notErrors.length === 0) { return this.createError(ErrorCodes.NOT_PASSED, {}, "", "/not"); } return null; }; // parseURI() and resolveUrl() are from https://gist.github.com/1088850 // - released as public domain by author ("Yaffle") - see comments on gist function parseURI(url) { var m = String(url).replace(/^\s+|\s+$/g, '').match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/); // authority = '//' + user + ':' + pass '@' + hostname + ':' port return (m ? { href : m[0] || '', protocol : m[1] || '', authority: m[2] || '', host : m[3] || '', hostname : m[4] || '', port : m[5] || '', pathname : m[6] || '', search : m[7] || '', hash : m[8] || '' } : null); } function resolveUrl(base, href) {// RFC 3986 function removeDotSegments(input) { var output = []; input.replace(/^(\.\.?(\/|$))+/, '') .replace(/\/(\.(\/|$))+/g, '/') .replace(/\/\.\.$/, '/../') .replace(/\/?[^\/]*/g, function (p) { if (p === '/..') { output.pop(); } else { output.push(p); } }); return output.join('').replace(/^\//, input.charAt(0) === '/' ? '/' : ''); } href = parseURI(href || ''); base = parseURI(base || ''); return !href || !base ? null : (href.protocol || base.protocol) + (href.protocol || href.authority ? href.authority : base.authority) + removeDotSegments(href.protocol || href.authority || href.pathname.charAt(0) === '/' ? href.pathname : (href.pathname ? ((base.authority && !base.pathname ? '/' : '') + base.pathname.slice(0, base.pathname.lastIndexOf('/') + 1) + href.pathname) : base.pathname)) + (href.protocol || href.authority || href.pathname ? href.search : (href.search || base.search)) + href.hash; } function getDocumentUri(uri) { return uri.split('#')[0]; } function normSchema(schema, baseUri) { if (baseUri === undefined) { baseUri = schema.id; } else if (typeof schema.id === "string") { baseUri = resolveUrl(baseUri, schema.id); schema.id = baseUri; } if (typeof schema === "object") { if (Array.isArray(schema)) { for (var i = 0; i < schema.length; i++) { normSchema(schema[i], baseUri); } } else if (typeof schema['$ref'] === "string") { schema['$ref'] = resolveUrl(baseUri, schema['$ref']); } else { for (var key in schema) { if (key !== "enum") { normSchema(schema[key], baseUri); } } } } } var ErrorCodes = { INVALID_TYPE: 0, ENUM_MISMATCH: 1, ANY_OF_MISSING: 10, ONE_OF_MISSING: 11, ONE_OF_MULTIPLE: 12, NOT_PASSED: 13, // Numeric errors NUMBER_MULTIPLE_OF: 100, NUMBER_MINIMUM: 101, NUMBER_MINIMUM_EXCLUSIVE: 102, NUMBER_MAXIMUM: 103, NUMBER_MAXIMUM_EXCLUSIVE: 104, // String errors STRING_LENGTH_SHORT: 200, STRING_LENGTH_LONG: 201, STRING_PATTERN: 202, // Object errors OBJECT_PROPERTIES_MINIMUM: 300, OBJECT_PROPERTIES_MAXIMUM: 301, OBJECT_REQUIRED: 302, OBJECT_ADDITIONAL_PROPERTIES: 303, OBJECT_DEPENDENCY_KEY: 304, // Array errors ARRAY_LENGTH_SHORT: 400, ARRAY_LENGTH_LONG: 401, ARRAY_UNIQUE: 402, ARRAY_ADDITIONAL_ITEMS: 403, // Format errors FORMAT_CUSTOM: 500, // Non-standard validation options UNKNOWN_PROPERTY: 1000 }; var ErrorMessagesDefault = { INVALID_TYPE: "invalid type: {type} (expected {expected})", ENUM_MISMATCH: "No enum match for: {value}", ANY_OF_MISSING: "Data does not match any schemas from \"anyOf\"", ONE_OF_MISSING: "Data does not match any schemas from \"oneOf\"", ONE_OF_MULTIPLE: "Data is valid against more than one schema from \"oneOf\": indices {index1} and {index2}", NOT_PASSED: "Data matches schema from \"not\"", // Numeric errors NUMBER_MULTIPLE_OF: "Value {value} is not a multiple of {multipleOf}", NUMBER_MINIMUM: "Value {value} is less than minimum {minimum}", NUMBER_MINIMUM_EXCLUSIVE: "Value {value} is equal to exclusive minimum {minimum}", NUMBER_MAXIMUM: "Value {value} is greater than maximum {maximum}", NUMBER_MAXIMUM_EXCLUSIVE: "Value {value} is equal to exclusive maximum {maximum}", // String errors STRING_LENGTH_SHORT: "String is too short ({length} chars), minimum {minimum}", STRING_LENGTH_LONG: "String is too long ({length} chars), maximum {maximum}", STRING_PATTERN: "String does not match pattern: {pattern}", // Object errors OBJECT_PROPERTIES_MINIMUM: "Too few properties defined ({propertyCount}), minimum {minimum}", OBJECT_PROPERTIES_MAXIMUM: "Too many properties defined ({propertyCount}), maximum {maximum}", OBJECT_REQUIRED: "Missing required property: {key}", OBJECT_ADDITIONAL_PROPERTIES: "Additional properties not allowed", OBJECT_DEPENDENCY_KEY: "Dependency failed - key must exist: {missing} (due to key: {key})", // Array errors ARRAY_LENGTH_SHORT: "Array is too short ({length}), minimum {minimum}", ARRAY_LENGTH_LONG: "Array is too long ({length}), maximum {maximum}", ARRAY_UNIQUE: "Array items are not unique (indices {match1} and {match2})", ARRAY_ADDITIONAL_ITEMS: "Additional items not allowed", // Format errors FORMAT_CUSTOM: "Format validation failed ({message})", UNKNOWN_PROPERTY: "Unknown property (not in schema)" }; function ValidationError(code, message, dataPath, schemaPath, subErrors) { if (code === undefined) { throw new Error ("No code supplied for error: "+ message); } this.code = code; this.message = message; this.dataPath = dataPath || ""; this.schemaPath = schemaPath || ""; this.subErrors = subErrors || null; } ValidationError.prototype = new Error(); ValidationError.prototype.prefixWith = function (dataPrefix, schemaPrefix) { if (dataPrefix !== null) { dataPrefix = dataPrefix.replace(/~/g, "~0").replace(/\//g, "~1"); this.dataPath = "/" + dataPrefix + this.dataPath; } if (schemaPrefix !== null) { schemaPrefix = schemaPrefix.replace(/~/g, "~0").replace(/\//g, "~1"); this.schemaPath = "/" + schemaPrefix + this.schemaPath; } if (this.subErrors !== null) { for (var i = 0; i < this.subErrors.length; i++) { this.subErrors[i].prefixWith(dataPrefix, schemaPrefix); } } return this; }; function isTrustedUrl(baseUrl, testUrl) { if(testUrl.substring(0, baseUrl.length) === baseUrl){ var remainder = testUrl.substring(baseUrl.length); if ((testUrl.length > 0 && testUrl.charAt(baseUrl.length - 1) === "/") || remainder.charAt(0) === "#" || remainder.charAt(0) === "?") { return true; } } return false; } var languages = {}; function createApi(language) { var globalContext = new ValidatorContext(); var currentLanguage = language || 'en'; var api = { addFormat: function () { globalContext.addFormat.apply(globalContext, arguments); }, language: function (code) { if (!code) { return currentLanguage; } if (!languages[code]) { code = code.split('-')[0]; // fall back to base language } if (languages[code]) { currentLanguage = code; return code; // so you can tell if fall-back has happened } return false; }, addLanguage: function (code, messageMap) { var key; for (key in ErrorCodes) { if (messageMap[key] && !messageMap[ErrorCodes[key]]) { messageMap[ErrorCodes[key]] = messageMap[key]; } } var rootCode = code.split('-')[0]; if (!languages[rootCode]) { // use for base language if not yet defined languages[code] = messageMap; languages[rootCode] = messageMap; } else { languages[code] = Object.create(languages[rootCode]); for (key in messageMap) { if (typeof languages[rootCode][key] === 'undefined') { languages[rootCode][key] = messageMap[key]; } languages[code][key] = messageMap[key]; } } return this; }, freshApi: function (language) { var result = createApi(); if (language) { result.language(language); } return result; }, validate: function (data, schema, checkRecursive, banUnknownProperties) { var context = new ValidatorContext(globalContext, false, languages[currentLanguage], checkRecursive, banUnknownProperties); if (typeof schema === "string") { schema = {"$ref": schema}; } context.addSchema("", schema); var error = context.validateAll(data, schema, null, null, ""); if (!error && banUnknownProperties) { error = context.banUnknownProperties(); } this.error = error; this.missing = context.missing; this.valid = (error === null); return this.valid; }, validateResult: function () { var result = {}; this.validate.apply(result, arguments); return result; }, validateMultiple: function (data, schema, checkRecursive, banUnknownProperties) { var context = new ValidatorContext(globalContext, true, languages[currentLanguage], checkRecursive, banUnknownProperties); if (typeof schema === "string") { schema = {"$ref": schema}; } context.addSchema("", schema); context.validateAll(data, schema, null, null, ""); if (banUnknownProperties) { context.banUnknownProperties(); } var result = {}; result.errors = context.errors; result.missing = context.missing; result.valid = (result.errors.length === 0); return result; }, addSchema: function () { return globalContext.addSchema.apply(globalContext, arguments); }, getSchema: function () { return globalContext.getSchema.apply(globalContext, arguments); }, getSchemaMap: function () { return globalContext.getSchemaMap.apply(globalContext, arguments); }, getSchemaUris: function () { return globalContext.getSchemaUris.apply(globalContext, arguments); }, getMissingUris: function () { return globalContext.getMissingUris.apply(globalContext, arguments); }, dropSchemas: function () { globalContext.dropSchemas.apply(globalContext, arguments); }, reset: function () { globalContext.reset(); this.error = null; this.missing = []; this.valid = true; }, missing: [], error: null, valid: true, normSchema: normSchema, resolveUrl: resolveUrl, getDocumentUri: getDocumentUri, errorCodes: ErrorCodes }; return api; } var tv4 = createApi(); tv4.addLanguage('en-gb', ErrorMessagesDefault); //legacy property tv4.tv4 = tv4; if (typeof module !== 'undefined' && module.exports){ module.exports = tv4; } else { global.tv4 = tv4; } })(this); //@ sourceMappingURL=tv4.js.map
(function(global) { Ember.libraries.register('Ember Simple Auth Torii', '0.6.7'); var define, requireModule; (function() { var registry = {}, seen = {}; define = function(name, deps, callback) { registry[name] = { deps: deps, callback: callback }; }; requireModule = function(name) { if (seen.hasOwnProperty(name)) { return seen[name]; } seen[name] = {}; if (!registry[name]) { throw new Error("Could not find module " + name); } var mod = registry[name], deps = mod.deps, callback = mod.callback, reified = [], exports; for (var i=0, l=deps.length; i<l; i++) { if (deps[i] === 'exports') { reified.push(exports = {}); } else { reified.push(requireModule(resolve(deps[i]))); } } var value = callback.apply(this, reified); return seen[name] = exports || value; function resolve(child) { if (child.charAt(0) !== '.') { return child; } var parts = child.split("/"); var parentBase = name.split("/").slice(0, -1); for (var i=0, l=parts.length; i<l; i++) { var part = parts[i]; if (part === '..') { parentBase.pop(); } else if (part === '.') { continue; } else { parentBase.push(part); } } return parentBase.join("/"); } }; requireModule.registry = registry; })(); define("simple-auth-torii/authenticators/torii", ["simple-auth/authenticators/base","exports"], function(__dependency1__, __exports__) { "use strict"; var Base = __dependency1__["default"]; /** Authenticator that wraps the [Torii library](https://github.com/Vestorly/torii). _The factory for this authenticator is registered as `'simple-auth-authenticator:torii'` in Ember's container._ @class Torii @namespace SimpleAuth.Authenticators @module simple-auth-torii/authenticators/torii @extends Base */ __exports__["default"] = Base.extend({ /** @property torii @private */ torii: null, /** @property provider @private */ provider: null, /** Restores the session by calling the torii provider's `fetch` method. @method restore @param {Object} data The data to restore the session from @return {Ember.RSVP.Promise} A promise that when it resolves results in the session being authenticated */ restore: function(data) { var _this = this; data = data || {}; return new Ember.RSVP.Promise(function(resolve, reject) { if (!Ember.isEmpty(data.provider)) { var provider = data.provider; _this.torii.fetch(data.provider, data).then(function(data) { _this.resolveWith(provider, data, resolve); }, function() { delete _this.provider; reject(); }); } else { delete _this.provider; reject(); } }); }, /** Authenticates the session by opening the torii provider. For more documentation on torii, see the [project's README](https://github.com/Vestorly/torii#readme). @method authenticate @param {String} provider The provider to authenticate the session with @return {Ember.RSVP.Promise} A promise that resolves when the provider successfully authenticates a user and rejects otherwise */ authenticate: function(provider) { var _this = this; return new Ember.RSVP.Promise(function(resolve, reject) { _this.torii.open(provider).then(function(data) { _this.resolveWith(provider, data, resolve); }, reject); }); }, /** Closes the torii provider. @method invalidate @param {Object} data The data that's stored in the session @return {Ember.RSVP.Promise} A promise that resolves when the provider successfully closes and rejects otherwise */ invalidate: function(data) { var _this = this; return new Ember.RSVP.Promise(function(resolve, reject) { _this.torii.close(_this.provider).then(function() { delete _this.provider; resolve(); }, reject); }); }, /** @method resolveWith @private */ resolveWith: function(provider, data, resolve) { data.provider = provider; this.provider = data.provider; resolve(data); } }); }); define("simple-auth-torii/ember", ["./initializer"], function(__dependency1__) { "use strict"; var initializer = __dependency1__["default"]; Ember.onLoad('Ember.Application', function(Application) { Application.initializer(initializer); }); }); define("simple-auth-torii/initializer", ["simple-auth-torii/authenticators/torii","exports"], function(__dependency1__, __exports__) { "use strict"; var Authenticator = __dependency1__["default"]; __exports__["default"] = { name: 'simple-auth-torii', before: 'simple-auth', after: 'torii', initialize: function(container, application) { var torii = container.lookup('torii:main'); var authenticator = Authenticator.create({ torii: torii }); container.register('simple-auth-authenticator:torii', authenticator, { instantiate: false }); } }; }); define('simple-auth/authenticators/base', ['exports'], function(__exports__) { __exports__['default'] = global.SimpleAuth.Authenticators.Base; }); var Authenticator = requireModule('simple-auth-torii/authenticators/torii')['default']; global.SimpleAuth.Authenticators.Torii = Authenticator; requireModule('simple-auth-torii/ember'); })((typeof global !== 'undefined') ? global : window);
/*! * inferno-component v1.0.2 * (c) 2016 Dominic Gannaway * Released under the MIT License. */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('./inferno')) : typeof define === 'function' && define.amd ? define(['inferno'], factory) : (global.Inferno = global.Inferno || {}, global.Inferno.Component = factory(global.Inferno)); }(this, (function (inferno) { 'use strict'; var ERROR_MSG = 'a runtime error occured! Use Inferno in development environment to find the error.'; var isBrowser = typeof window !== 'undefined' && window.document; // this is MUCH faster than .constructor === Array and instanceof Array // in Node 7 and the later versions of V8, slower in older versions though var isArray = Array.isArray; function isStringOrNumber(obj) { return isString(obj) || isNumber(obj); } function isNullOrUndef(obj) { return isUndefined(obj) || isNull(obj); } function isInvalid(obj) { return isNull(obj) || obj === false || isTrue(obj) || isUndefined(obj); } function isFunction(obj) { return typeof obj === 'function'; } function isString(obj) { return typeof obj === 'string'; } function isNumber(obj) { return typeof obj === 'number'; } function isNull(obj) { return obj === null; } function isTrue(obj) { return obj === true; } function isUndefined(obj) { return obj === undefined; } function throwError(message) { if (!message) { message = ERROR_MSG; } throw new Error(("Inferno Error: " + message)); } var Lifecycle = function Lifecycle() { this.listeners = []; this.fastUnmount = true; }; Lifecycle.prototype.addListener = function addListener (callback) { this.listeners.push(callback); }; Lifecycle.prototype.trigger = function trigger () { var this$1 = this; for (var i = 0; i < this.listeners.length; i++) { this$1.listeners[i](); } }; var noOp = ERROR_MSG; if (process.env.NODE_ENV !== 'production') { noOp = 'Inferno Error: Can only update a mounted or mounting component. This usually means you called setState() or forceUpdate() on an unmounted component. This is a no-op.'; } var componentCallbackQueue = new Map(); // when a components root VNode is also a component, we can run into issues // this will recursively look for vNode.parentNode if the VNode is a component function updateParentComponentVNodes(vNode, dom) { if (vNode.flags & 28 /* Component */) { var parentVNode = vNode.parentVNode; if (parentVNode) { parentVNode.dom = dom; updateParentComponentVNodes(parentVNode, dom); } } } // this is in shapes too, but we don't want to import from shapes as it will pull in a duplicate of createVNode function createVoidVNode() { return inferno.createVNode(4096 /* Void */); } function createTextVNode(text) { return inferno.createVNode(1 /* Text */, null, null, text); } function addToQueue(component, force, callback) { // TODO this function needs to be revised and improved on var queue = componentCallbackQueue.get(component); if (!queue) { queue = []; componentCallbackQueue.set(component, queue); Promise.resolve().then(function () { applyState(component, force, function () { for (var i = 0; i < queue.length; i++) { queue[i](); } }); componentCallbackQueue.delete(component); }); } if (callback) { queue.push(callback); } } function queueStateChanges(component, newState, callback, sync) { if (isFunction(newState)) { newState = newState(component.state); } for (var stateKey in newState) { component._pendingState[stateKey] = newState[stateKey]; } if (!component._pendingSetState && isBrowser) { if (sync || component._blockRender) { component._pendingSetState = true; applyState(component, false, callback); } else { addToQueue(component, false, callback); } } else { component.state = Object.assign({}, component.state, component._pendingState); component._pendingState = {}; } } function applyState(component, force, callback) { if ((!component._deferSetState || force) && !component._blockRender && !component._unmounted) { component._pendingSetState = false; var pendingState = component._pendingState; var prevState = component.state; var nextState = Object.assign({}, prevState, pendingState); var props = component.props; var context = component.context; component._pendingState = {}; var nextInput = component._updateComponent(prevState, nextState, props, props, context, force, true); var didUpdate = true; if (isInvalid(nextInput)) { nextInput = createVoidVNode(); } else if (nextInput === inferno.NO_OP) { nextInput = component._lastInput; didUpdate = false; } else if (isStringOrNumber(nextInput)) { nextInput = createTextVNode(nextInput); } else if (isArray(nextInput)) { if (process.env.NODE_ENV !== 'production') { throwError('a valid Inferno VNode (or null) must be returned from a component render. You may have returned an array or an invalid object.'); } throwError(); } var lastInput = component._lastInput; var vNode = component._vNode; var parentDom = (lastInput.dom && lastInput.dom.parentNode) || (lastInput.dom = vNode.dom); component._lastInput = nextInput; if (didUpdate) { var subLifecycle = component._lifecycle; if (!subLifecycle) { subLifecycle = new Lifecycle(); } else { subLifecycle.listeners = []; } component._lifecycle = subLifecycle; var childContext = component.getChildContext(); if (!isNullOrUndef(childContext)) { childContext = Object.assign({}, context, component._childContext, childContext); } else { childContext = Object.assign({}, context, component._childContext); } component._patch(lastInput, nextInput, parentDom, subLifecycle, childContext, component._isSVG, false); subLifecycle.trigger(); component.componentDidUpdate(props, prevState); inferno.options.afterUpdate && inferno.options.afterUpdate(vNode); } var dom = vNode.dom = nextInput.dom; var componentToDOMNodeMap = component._componentToDOMNodeMap; componentToDOMNodeMap && componentToDOMNodeMap.set(component, nextInput.dom); updateParentComponentVNodes(vNode, dom); if (!isNullOrUndef(callback)) { callback(); } } } var Component$1 = function Component(props, context) { this.state = {}; this.refs = {}; this._blockRender = false; this._ignoreSetState = false; this._blockSetState = false; this._deferSetState = false; this._pendingSetState = false; this._pendingState = {}; this._lastInput = null; this._vNode = null; this._unmounted = true; this._lifecycle = null; this._childContext = null; this._patch = null; this._isSVG = false; this._componentToDOMNodeMap = null; /** @type {object} */ this.props = props || inferno.EMPTY_OBJ; /** @type {object} */ this.context = context || {}; }; Component$1.prototype.render = function render (nextProps, nextState, nextContext) { }; Component$1.prototype.forceUpdate = function forceUpdate (callback) { if (this._unmounted) { return; } isBrowser && applyState(this, true, callback); }; Component$1.prototype.setState = function setState (newState, callback) { if (this._unmounted) { return; } if (!this._blockSetState) { if (!this._ignoreSetState) { queueStateChanges(this, newState, callback, false); } } else { if (process.env.NODE_ENV !== 'production') { throwError('cannot update state via setState() in componentWillUpdate().'); } throwError(); } }; Component$1.prototype.setStateSync = function setStateSync (newState) { if (this._unmounted) { return; } if (!this._blockSetState) { if (!this._ignoreSetState) { queueStateChanges(this, newState, null, true); } } else { if (process.env.NODE_ENV !== 'production') { throwError('cannot update state via setState() in componentWillUpdate().'); } throwError(); } }; Component$1.prototype.componentWillMount = function componentWillMount () { }; Component$1.prototype.componentDidUpdate = function componentDidUpdate (prevProps, prevState, prevContext) { }; Component$1.prototype.shouldComponentUpdate = function shouldComponentUpdate (nextProps, nextState, context) { return true; }; Component$1.prototype.componentWillReceiveProps = function componentWillReceiveProps (nextProps, context) { }; Component$1.prototype.componentWillUpdate = function componentWillUpdate (nextProps, nextState, nextContext) { }; Component$1.prototype.getChildContext = function getChildContext () { }; Component$1.prototype._updateComponent = function _updateComponent (prevState, nextState, prevProps, nextProps, context, force, fromSetState) { if (this._unmounted === true) { if (process.env.NODE_ENV !== 'production') { throwError(noOp); } throwError(); } if ((prevProps !== nextProps || nextProps === inferno.EMPTY_OBJ) || prevState !== nextState || force) { if (prevProps !== nextProps || nextProps === inferno.EMPTY_OBJ) { if (!fromSetState) { this._blockRender = true; this.componentWillReceiveProps(nextProps, context); this._blockRender = false; } if (this._pendingSetState) { nextState = Object.assign({}, nextState, this._pendingState); this._pendingSetState = false; this._pendingState = {}; } } var shouldUpdate = this.shouldComponentUpdate(nextProps, nextState, context); if (shouldUpdate !== false || force) { this._blockSetState = true; this.componentWillUpdate(nextProps, nextState, context); this._blockSetState = false; this.props = nextProps; var state = this.state = nextState; this.context = context; inferno.options.beforeRender && inferno.options.beforeRender(this); var render = this.render(nextProps, state, context); inferno.options.afterRender && inferno.options.afterRender(this); return render; } } return inferno.NO_OP; }; return Component$1; })));
// (c) ammap.com | SVG (in JSON format) map of Libya - Low // areas: {id:"LY-WD"},{id:"LY-BU"},{id:"LY-QB"},{id:"LY-SR"},{id:"LY-BA"},{id:"LY-WA"},{id:"LY-JA"},{id:"LY-HZ"},{id:"LY-TN"},{id:"LY-MZ"},{id:"LY-ZA"},{id:"LY-NQ"},{id:"LY-JI"},{id:"LY-SB"},{id:"LY-MI"},{id:"LY-MQ"},{id:"LY-GT"},{id:"LY-SH"},{id:"LY-MB"},{id:"LY-KF"},{id:"LY-JU"},{id:"LY-GD"} AmCharts.maps.libyaLow={ "svg": { "defs": { "amcharts:ammap": { "projection":"mercator", "leftLongitude":"9.391466", "topLatitude":"33.1679793", "rightLongitude":"25.146954", "bottomLatitude":"19.5008125" } }, "g":{ "path":[ { "id":"LY-WD", "title":"Wadi al Hayaa", "d":"M236.97,352.67L188.1,345.8L105.65,404.02L106.9,441.29L145.18,439.93L234.51,402.37L245.18,378.51L236.97,352.67z" }, { "id":"LY-BU", "title":"Al Butnan", "d":"M790.67,297.68L790.32,232.14L775.94,177.43L791.36,142.24L784.01,109.12L799.48,90.55L790.69,72.49L703.58,57.71L689.36,141.4L694.05,295.25L790.67,297.68z" }, { "id":"LY-QB", "title":"Al Qubbah", "d":"M703.58,57.71L696.27,32.47L639.88,16.11L636.44,113.04L646.24,122.59L689.36,141.4L703.58,57.71z" }, { "id":"LY-SR", "title":"Surt", "d":"M478.97,166.48L407.27,124.54L345.42,114.27L365.25,209.36L359.58,222.33L405.66,229.62L418.06,223.15L438.3,261.26L464.33,274.5L478.97,166.48z" }, { "id":"LY-BA", "title":"Benghazi", "d":"M606.3,127.57L601.08,97.76L567.51,95.48L557.53,74.82L568.89,37.08L536.87,73.09L547.02,116.47L569.78,129.22L606.3,127.57z" }, { "id":"LY-WA", "title":"Al Wahat", "d":"M606.3,127.57L569.78,129.22L547.02,116.47L541.73,140.25L520.58,163.52L496.89,172.65L478.97,166.48L464.33,274.5L498.21,283.36L498.09,359.23L790.67,357.18L790.67,297.68L694.05,295.25L689.36,141.4L646.24,122.59L626.34,125.78L606.3,127.57z" }, { "id":"LY-JA", "title":"Al Jabal al Akhdar", "d":"M639.88,16.11L608.21,24.06L626.34,125.78L646.24,122.59L636.44,113.04L639.88,16.11z" }, { "id":"LY-HZ", "title":"Al Marj", "d":"M608.21,24.06L568.89,37.08L557.53,74.82L567.51,95.48L601.08,97.76L606.3,127.57L626.34,125.78L608.21,24.06z" }, { "id":"LY-TN", "title":"Tajura' wa an Nawahi al Arba", "d":"M235.52,25.39L192.67,18.24L191.32,27.6L199.38,50.74L235.52,25.39z" }, { "id":"LY-MZ", "title":"Mizdah", "d":"M207.49,67.57L200.1,51.71L178.39,55.12L130.21,52.3L135.27,124.88L116.48,156.44L123.5,240.9L134.7,269.17L171.79,278.61L233.31,213.15L258.95,233.86L275.7,222.53L280.82,196.08L285.65,164.23L248.47,145.99L207.49,67.57z" }, { "id":"LY-ZA", "title":"Az Zawiyah", "d":"M191.32,27.6L192.67,18.24L165.98,22.13L130.21,52.3L178.39,55.12L191.32,27.6z" }, { "id":"LY-NQ", "title":"An Nuqat al Khams", "d":"M112.21,0L113.27,45.72L130.21,52.3L165.98,22.13L112.21,0z" }, { "id":"LY-JI", "title":"Al Jifarah", "d":"M199.38,50.74L191.32,27.6L178.39,55.12L200.1,51.71L199.38,50.74z" }, { "id":"LY-SB", "title":"Sabha", "d":"M328.23,319.08L291.61,324.15L259.02,350.19L236.97,352.67L245.18,378.51L234.51,402.37L259.18,395.1L279.48,373.62L352.59,355.71L328.23,319.08z" }, { "id":"LY-MI", "title":"Misratah", "d":"M345.42,114.27L314.06,92.6L301.74,51.03L275.87,43.83L271.38,72.5L243.96,62.12L207.49,67.57L248.47,145.99L285.65,164.23L280.82,196.08L325.45,223.19L359.58,222.33L365.25,209.36L345.42,114.27z" }, { "id":"LY-MQ", "title":"Murzuq", "d":"M498,416L449.47,395.09L409.49,413.29L385.86,407.05L352.53,368.64L352.59,355.71L279.48,373.62L259.18,395.1L234.51,402.37L145.18,439.93L106.9,441.29L110.31,509.32L135.56,553.87L211.75,572.39L248.7,603.18L337.76,557.86L498.9,644.09L498,416z" }, { "id":"LY-GT", "title":"Ghat", "d":"M105.65,404.02L92.16,335.26L32.98,313.53L22.41,343.44L31.22,379.55L6.29,409.86L36.84,453.56L38.05,479.97L49.54,495.47L110.31,509.32L106.9,441.29L105.65,404.02z" }, { "id":"LY-SH", "title":"Ash Shati'", "d":"M258.95,233.86L233.31,213.15L171.79,278.61L134.7,269.17L103.09,272.05L82.24,254.85L58.63,267.48L27.74,267.82L32.98,313.53L92.16,335.26L105.65,404.02L188.1,345.8L236.97,352.67L259.02,350.19L291.61,324.15L328.23,319.08L332.41,298.68L317.85,290.94L289.05,294.93L286.08,279.91L259.09,252.9L258.95,233.86z" }, { "id":"LY-MB", "title":"Al Marqab", "d":"M275.87,43.83L235.52,25.39L199.38,50.74L200.1,51.71L207.49,67.57L243.96,62.12L271.38,72.5L275.87,43.83z" }, { "id":"LY-KF", "title":"Al Kufrah", "d":"M740.33,771.53L740.33,744.82L790.45,744.79L790.67,357.18L498.09,359.23L498,416L498.9,644.09L740.33,771.53z" }, { "id":"LY-JU", "title":"Al Jufrah", "d":"M359.58,222.33L325.45,223.19L280.82,196.08L275.7,222.53L258.95,233.86L259.09,252.9L286.08,279.91L289.05,294.93L317.85,290.94L332.41,298.68L328.23,319.08L352.59,355.71L352.53,368.64L385.86,407.05L409.49,413.29L449.47,395.09L498,416L498.09,359.23L498.21,283.36L464.33,274.5L438.3,261.26L418.06,223.15L405.66,229.62L359.58,222.33z" }, { "id":"LY-GD", "title":"Ghadamis", "d":"M130.21,52.3L113.27,45.72L49.73,89.52L41.79,104.37L46.11,145.4L29.96,167.38L0.52,181.25L19.71,210.79L27.74,267.82L58.63,267.48L82.24,254.85L103.09,272.05L134.7,269.17L123.5,240.9L116.48,156.44L135.27,124.88L130.21,52.3z" } ] } } };
/* Language: XL Author: Christophe de Dinechin <christophe@taodyne.com> Description: An extensible programming language, based on parse tree rewriting (http://xlr.sf.net) */ function(hljs) { var BUILTIN_MODULES = 'ObjectLoader Animate MovieCredits Slides Filters Shading Materials LensFlare Mapping VLCAudioVideo ' + 'StereoDecoder PointCloud NetworkAccess RemoteControl RegExp ChromaKey Snowfall NodeJS Speech Charts'; var XL_KEYWORDS = { keyword: 'if then else do while until for loop import with is as where when by data constant', literal: 'true false nil', type: 'integer real text name boolean symbol infix prefix postfix block tree', built_in: 'in mod rem and or xor not abs sign floor ceil sqrt sin cos tan asin acos atan exp expm1 log log2 log10 log1p pi at', module: BUILTIN_MODULES, id: 'text_length text_range text_find text_replace contains page slide basic_slide title_slide title subtitle ' + 'fade_in fade_out fade_at clear_color color line_color line_width texture_wrap texture_transform texture ' + 'scale_?x scale_?y scale_?z? translate_?x translate_?y translate_?z? rotate_?x rotate_?y rotate_?z? rectangle ' + 'circle ellipse sphere path line_to move_to quad_to curve_to theme background contents locally time mouse_?x ' + 'mouse_?y mouse_buttons' }; var XL_CONSTANT = { className: 'constant', begin: '[A-Z][A-Z_0-9]+', relevance: 0 }; var XL_VARIABLE = { className: 'variable', begin: '([A-Z][a-z_0-9]+)+', relevance: 0 }; var XL_ID = { className: 'id', begin: '[a-z][a-z_0-9]+', relevance: 0 }; var DOUBLE_QUOTE_TEXT = { className: 'string', begin: '"', end: '"', illegal: '\\n' }; var SINGLE_QUOTE_TEXT = { className: 'string', begin: '\'', end: '\'', illegal: '\\n' }; var LONG_TEXT = { className: 'string', begin: '<<', end: '>>' }; var BASED_NUMBER = { className: 'number', begin: '[0-9]+#[0-9A-Z_]+(\\.[0-9-A-Z_]+)?#?([Ee][+-]?[0-9]+)?', relevance: 10 }; var IMPORT = { className: 'import', beginKeywords: 'import', end: '$', keywords: { keyword: 'import', module: BUILTIN_MODULES }, relevance: 0, contains: [DOUBLE_QUOTE_TEXT] }; var FUNCTION_DEFINITION = { className: 'function', begin: '[a-z].*->' }; return { aliases: ['tao'], lexemes: /[a-zA-Z][a-zA-Z0-9_?]*/, keywords: XL_KEYWORDS, contains: [ hljs.C_LINE_COMMENT_MODE, hljs.C_BLOCK_COMMENT_MODE, DOUBLE_QUOTE_TEXT, SINGLE_QUOTE_TEXT, LONG_TEXT, FUNCTION_DEFINITION, IMPORT, XL_CONSTANT, XL_VARIABLE, XL_ID, BASED_NUMBER, hljs.NUMBER_MODE ] }; }
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ var Infinilist = _dereq_('../lib/Infinilist'); module.exports = Infinilist; },{"../lib/Infinilist":2}],2:[function(_dereq_,module,exports){ "use strict"; /** * Provides scrolling lists with large data sets that behave in a very * performance-optimised fashion by controlling the DOM elements currently * on screen to ensure that only the visible elements are rendered and * all other elements are simulated by variable height divs at the top * and bottom of the scrolling list. * * This module requires that the AutoBind module is loaded before it * will work. * * Infinilists work from views and those views cannot have an $orderBy * clause in them because that would slow down rendering. Instead if you * wish to have your data ordered you have to create a temporary collection * from which your view feeds from and pre-order the data before inserting * it into the temporary collection. * @class Infinilist * @requires AutoBind */ var Shared = window.ForerunnerDB.shared, View = Shared.modules.View; /** * Creates an infinilist instance. * @param {Selector} selector A jQuery selector targeting the element that * will contain the list items. * @param {Selector} template jQuery selector of the template to use when * rendering an individual list item. * @param {Object} options The options object. * @param {View} view The view to read data from. * @constructor */ var Infinilist = function (selector, template, options, view) { var self = this; selector = $(selector); options = options || {}; self.options = options.infinilist || {}; delete options.infinilist; self.skip = 0; self.limit = 0; self.ignoreScroll = false; self.previousScrollTop = 0; self.selector = selector; self.template = template; self.view = view; self.itemTopMargin = $("<div class='il_topMargin'></div>"); self.itemContainer = $("<div class='il_items'></div>"); self.itemBottomMargin = $("<div class='il_bottomMargin'></div>"); self.total = self.view.from().count(self.options.countQuery); self.itemHeight(self.options.itemHeight); self.___fromChangeFunc = function () { // View data changed, recalculate total items count and check // that the currently displayed view data is correct by forcing // a scroll event after a height recalculation self.recalcHeight(); self.scroll(true); }; self.view.from().on('change', self.___fromChangeFunc); selector.append(self.itemTopMargin); selector.append(self.itemContainer); selector.append(self.itemBottomMargin); self.resize(); view.link(self.itemContainer, template, options); selector.on('scroll', function () { // Debounce scroll event if (!self.scrollDebouceTimeout) { self.scrollDebouceTimeout = setTimeout(function () { self.scroll(); self.scrollDebouceTimeout = 0; }, 16); } }); $(window).on('resize', function () { // Debounce resize event if (self.resizeDebouceTimeout) { clearTimeout(self.resizeDebouceTimeout); } self.resizeDebouceTimeout = setTimeout(function () { self.resize(); }, 16); }); }; Shared.addModule('Infinilist', Infinilist); Shared.mixin(Infinilist.prototype, 'Mixin.Events'); Shared.synthesize(Infinilist.prototype, 'itemHeight', function (val) { var self = this; if (val !== undefined) { self._itemHeight = val; self.virtualHeight = self.total * self._itemHeight; self.resize(); } return this.$super.apply(this, arguments); }); Infinilist.prototype.recalcHeight = function () { var self = this; self.total = self.view.from().count(self.options.countQuery); self.virtualHeight = self.total * self._itemHeight; self.resize(); }; /** * Handle screen resizing. */ Infinilist.prototype.resize = function () { var self = this, newHeight = self.selector.height(), skipCount, scrollTop = self.selector.scrollTop(); if (self.oldHeight !== newHeight) { self.oldHeight = newHeight; // Calculate number of visible items self.maxItemCount = Math.ceil(newHeight / self._itemHeight); skipCount = Math.floor(scrollTop / self._itemHeight); self.skip = skipCount; self.limit = self.maxItemCount + 1; // Check if current range is different from existing range self.view.queryOptions(self.currentRange()); self.itemBottomMargin.height(self.virtualHeight - (skipCount * self._itemHeight)- (self.maxItemCount * self._itemHeight)); } }; Infinilist.prototype.currentRange = function () { return { $skip: this.skip, $limit: this.limit }; }; Infinilist.prototype.scroll = function (force) { var self = this, delta, skipCount, scrollTop = self.selector.scrollTop(); // Get the current scroll position delta = scrollTop - self.previousScrollTop; self.previousScrollTop = scrollTop; // Check if a scroll change occurred if (force || delta !== 0) { // Determine the new item range skipCount = Math.floor(scrollTop / self._itemHeight); self.skip = skipCount; self.view.queryOptions(self.currentRange()); self.itemTopMargin.height(skipCount * self._itemHeight); self.itemBottomMargin.height(self.virtualHeight - (skipCount * self._itemHeight)- (self.maxItemCount * self._itemHeight)); } self.emit('scroll'); }; Infinilist.prototype.scrollToQuery = function (query, options, callback) { var self = this, result, index, orderOp = { $orderBy: self.view.queryOptions().$orderBy }, tmpColl, scrollPos; if (typeof options === 'function') { callback = options; options = undefined; } // Ensure options has properties we expect options = options || {}; options.$inc = options.$inc !== undefined ? options.$inc : 0; options.$incItem = options.$incItem !== undefined ? options.$incItem : 0; // Run query and get first matching record (with current sort) result = self.view.from().findOne(query, orderOp); // Find the position of the element inside the current view // based on the sort order tmpColl = self.view.db().collection('tmpSortCollection'); tmpColl.setData(self.view.from().find(self.view.query())); index = tmpColl.indexOf(result, orderOp); tmpColl.drop(); if (index > -1) { scrollPos = ((index + options.$incItem) * self._itemHeight) + options.$inc; scrollPos = scrollPos > 0 ? scrollPos : 0; if (self.selector.scrollTop() !== scrollPos) { if (callback) { self.once('scroll', function () { callback(); }); } // Scroll the main element to the position of the item self.selector.scrollTop(scrollPos); } else { if (callback) { callback(); } } return true; } return false; }; Infinilist.prototype.drop = function (callback) { var self = this; // Unlink the view from the dom self.view.unlink(self.itemContainer, self.template); // Stop listening for changes self.view.from().off('change', self.___fromChangeFunc); // Set state to dropped self._state = 'dropped'; // Kill listeners self.selector.off('scroll'); $(window).off('resize'); // Remove references delete self.ignoreScroll; delete self.previousScrollTop; delete self._itemHeight; delete self.selector; delete self.template; delete self.view; delete self.itemTopMargin; delete self.itemContainer; delete self.itemBottomMargin; delete self.___fromChangeFunc; this.emit('drop', this); if (callback) { callback(false, true); } delete self._listeners; }; View.prototype.infinilist = function (targetSelector, templateSelector, options) { var target = window.jQuery(targetSelector); if (templateSelector === undefined) { return target.data('infinilist'); } target.data('infinilist', new Infinilist(targetSelector, templateSelector, options, this)); }; View.prototype.unInfinilist = function (targetSelector) { var target = window.jQuery(targetSelector); if (target.data('infinilist')) { target.data('infinilist').drop(); target.removeData('infinilist'); return true; } return false; }; Shared.moduleFinished('AutoBind', function () { Shared.finishModule('Infinilist'); }); module.exports = Infinilist; },{}]},{},[1]);
L.KML = L.FeatureGroup.extend({ options: { async: true }, initialize: function(kml, options) { L.Util.setOptions(this, options); this._kml = kml; this._layers = {}; if (kml) { this.addKML(kml, options, this.options.async); } }, loadXML: function(url, cb, options, async) { if (async === undefined) async = this.options.async; if (options === undefined) options = this.options; var req = new window.XMLHttpRequest(); req.open('GET', url, async); try { req.overrideMimeType('text/xml'); // unsupported by IE } catch(e) {} req.onreadystatechange = function() { if (req.readyState !== 4) return; if (req.status === 200) cb(req.responseXML, options); }; req.send(null); }, addKML: function(url, options, async) { var _this = this; var cb = function(gpx, options) { _this._addKML(gpx, options); }; this.loadXML(url, cb, options, async); }, _addKML: function(xml, options) { var layers = L.KML.parseKML(xml); if (!layers || !layers.length) return; for (var i = 0; i < layers.length; i++) { this.fire('addlayer', { layer: layers[i] }); this.addLayer(layers[i]); } this.latLngs = L.KML.getLatLngs(xml); this.fire('loaded'); }, latLngs: [] }); L.Util.extend(L.KML, { parseKML: function (xml) { var style = this.parseStyle(xml); this.parseStyleMap(xml, style); var el = xml.getElementsByTagName('Folder'); var layers = [], l; for (var i = 0; i < el.length; i++) { if (!this._check_folder(el[i])) { continue; } l = this.parseFolder(el[i], style); if (l) { layers.push(l); } } el = xml.getElementsByTagName('Placemark'); for (var j = 0; j < el.length; j++) { if (!this._check_folder(el[j])) { continue; } l = this.parsePlacemark(el[j], xml, style); if (l) { layers.push(l); } } return layers; }, // Return false if e's first parent Folder is not [folder] // - returns true if no parent Folders _check_folder: function (e, folder) { e = e.parentElement; while (e && e.tagName !== 'Folder') { e = e.parentElement; } return !e || e === folder; }, parseStyle: function (xml) { var style = {}; var sl = xml.getElementsByTagName('Style'); //for (var i = 0; i < sl.length; i++) { var attributes = {color: true, width: true, Icon: true, href: true, hotSpot: true}; function _parse(xml) { var options = {}; for (var i = 0; i < xml.childNodes.length; i++) { var e = xml.childNodes[i]; var key = e.tagName; if (!attributes[key]) { continue; } if (key === 'hotSpot') { for (var j = 0; j < e.attributes.length; j++) { options[e.attributes[j].name] = e.attributes[j].nodeValue; } } else { var value = e.childNodes[0].nodeValue; if (key === 'color') { options.opacity = parseInt(value.substring(0, 2), 16) / 255.0; options.color = '#' + value.substring(6, 8) + value.substring(4, 6) + value.substring(2, 4); } else if (key === 'width') { options.weight = value; } else if (key === 'Icon') { ioptions = _parse(e); if (ioptions.href) { options.href = ioptions.href; } } else if (key === 'href') { options.href = value; } } } return options; } for (var i = 0; i < sl.length; i++) { var e = sl[i], el; var options = {}, poptions = {}, ioptions = {}; el = e.getElementsByTagName('LineStyle'); if (el && el[0]) { options = _parse(el[0]); } el = e.getElementsByTagName('PolyStyle'); if (el && el[0]) { poptions = _parse(el[0]); } if (poptions.color) { options.fillColor = poptions.color; } if (poptions.opacity) { options.fillOpacity = poptions.opacity; } el = e.getElementsByTagName('IconStyle'); if (el && el[0]) { ioptions = _parse(el[0]); } if (ioptions.href) { // save anchor info until the image is loaded options.icon = new L.KMLIcon({ iconUrl: ioptions.href, shadowUrl: null, iconAnchorRef: {x: ioptions.x, y: ioptions.y}, iconAnchorType: {x: ioptions.xunits, y: ioptions.yunits} }); } style['#' + e.getAttribute('id')] = options; } return style; }, parseStyleMap: function (xml, existingStyles) { var sl = xml.getElementsByTagName('StyleMap'); for (var i = 0; i < sl.length; i++) { var e = sl[i], el; var smKey, smStyleUrl; el = e.getElementsByTagName('key'); if (el && el[0]) { smKey = el[0].textContent; } el = e.getElementsByTagName('styleUrl'); if (el && el[0]) { smStyleUrl = el[0].textContent; } if (smKey === 'normal') { existingStyles['#' + e.getAttribute('id')] = existingStyles[smStyleUrl]; } } return; }, parseFolder: function (xml, style) { var el, layers = [], l; el = xml.getElementsByTagName('Folder'); for (var i = 0; i < el.length; i++) { if (!this._check_folder(el[i], xml)) { continue; } l = this.parseFolder(el[i], style); if (l) { layers.push(l); } } el = xml.getElementsByTagName('Placemark'); for (var j = 0; j < el.length; j++) { if (!this._check_folder(el[j], xml)) { continue; } l = this.parsePlacemark(el[j], xml, style); if (l) { layers.push(l); } } if (!layers.length) { return; } if (layers.length === 1) { return layers[0]; } return new L.FeatureGroup(layers); }, parsePlacemark: function (place, xml, style) { var i, j, el, options = {}; el = place.getElementsByTagName('styleUrl'); for (i = 0; i < el.length; i++) { var url = el[i].childNodes[0].nodeValue; for (var a in style[url]) { options[a] = style[url][a]; } } var layers = []; var parse = ['LineString', 'Polygon', 'Point']; for (j in parse) { // for jshint if (true) { var tag = parse[j]; el = place.getElementsByTagName(tag); for (i = 0; i < el.length; i++) { var l = this['parse' + tag](el[i], xml, options); if (l) { layers.push(l); } } } } if (!layers.length) { return; } var layer = layers[0]; if (layers.length > 1) { layer = new L.FeatureGroup(layers); } var name, descr = ''; el = place.getElementsByTagName('name'); if (el.length && el[0].childNodes.length) { name = el[0].childNodes[0].nodeValue; } el = place.getElementsByTagName('description'); for (i = 0; i < el.length; i++) { for (j = 0; j < el[i].childNodes.length; j++) { descr = descr + el[i].childNodes[j].nodeValue; } } if (name) { layer.bindPopup('<h2>' + name + '</h2>' + descr); } return layer; }, parseCoords: function (xml) { var el = xml.getElementsByTagName('coordinates'); return this._read_coords(el[0]); }, parseLineString: function (line, xml, options) { var coords = this.parseCoords(line); if (!coords.length) { return; } return new L.Polyline(coords, options); }, parsePoint: function (line, xml, options) { var el = line.getElementsByTagName('coordinates'); if (!el.length) { return; } var ll = el[0].childNodes[0].nodeValue.split(','); return new L.KMLMarker(new L.LatLng(ll[1], ll[0]), options); }, parsePolygon: function (line, xml, options) { var el, polys = [], inner = [], i, coords; el = line.getElementsByTagName('outerBoundaryIs'); for (i = 0; i < el.length; i++) { coords = this.parseCoords(el[i]); if (coords) { polys.push(coords); } } el = line.getElementsByTagName('innerBoundaryIs'); for (i = 0; i < el.length; i++) { coords = this.parseCoords(el[i]); if (coords) { inner.push(coords); } } if (!polys.length) { return; } if (options.fillColor) { options.fill = true; } if (polys.length === 1) { return new L.Polygon(polys.concat(inner), options); } return new L.MultiPolygon(polys, options); }, getLatLngs: function (xml) { var el = xml.getElementsByTagName('coordinates'); var coords = []; for (var j = 0; j < el.length; j++) { // text might span many childNodes coords = coords.concat(this._read_coords(el[j])); } return coords; }, _read_coords: function (el) { var text = '', coords = [], i; for (i = 0; i < el.childNodes.length; i++) { text = text + el.childNodes[i].nodeValue; } text = text.split(/[\s\n]+/); for (i = 0; i < text.length; i++) { var ll = text[i].split(','); if (ll.length < 2) { continue; } coords.push(new L.LatLng(ll[1], ll[0])); } return coords; } }); L.KMLIcon = L.Icon.extend({ createIcon: function () { var img = this._createIcon('icon'); img.onload = function () { var i = img; this.style.width = i.width + 'px'; this.style.height = i.height + 'px'; if (this.anchorType.x === 'UNITS_FRACTION' || this.anchorType.x === 'fraction') { img.style.marginLeft = (-this.anchor.x * i.width) + 'px'; } if (this.anchorType.y === 'UNITS_FRACTION' || this.anchorType.x === 'fraction') { img.style.marginTop = (-(1 - this.anchor.y) * i.height) + 'px'; } this.style.display = ''; }; return img; }, _setIconStyles: function (img, name) { L.Icon.prototype._setIconStyles.apply(this, [img, name]); // save anchor information to the image img.anchor = this.options.iconAnchorRef; img.anchorType = this.options.iconAnchorType; } }); L.KMLMarker = L.Marker.extend({ options: { icon: new L.KMLIcon.Default() } });
'use strict'; module.exports = function (t, a) { var fn = function (raz, dwa) { return raz + dwa; }; a(t('undefined'), undefined, "Undefined"); a(t('null'), null, "Null"); a(t('"raz"'), 'raz', "String"); a(t('"raz\\"ddwa\\ntrzy"'), 'raz"ddwa\ntrzy', "String with escape"); a(t('false'), false, "Booelean"); a(String(t(String(fn))), String(fn), "Function"); a.deep(t('/raz-dwa/g'), /raz-dwa/g, "RegExp"); a.deep(t('new Date(1234567)'), new Date(1234567), "Date"); a.deep(t('[]'), [], "Empty array"); a.deep(t('[undefined,false,null,"raz\\"ddwa\\ntrzy",/raz/g,new Date(1234567),["foo"]]'), [undefined, false, null, 'raz"ddwa\ntrzy', /raz/g, new Date(1234567), ['foo']], "Rich Array"); a.deep(t('{}'), {}, "Empty object"); a.deep(t('{"raz":undefined,"dwa":false,"trzy":null,"cztery":"raz\\"ddwa\\ntrzy",' + '"szesc":/raz/g,"siedem":new Date(1234567),"osiem":["foo",32],' + '"dziewiec":{"foo":"bar","dwa":343}}'), { raz: undefined, dwa: false, trzy: null, cztery: 'raz"ddwa\ntrzy', szesc: /raz/g, siedem: new Date(1234567), osiem: ['foo', 32], dziewiec: { foo: 'bar', dwa: 343 } }, "Rich object"); };
import { configure } from '@storybook/react'; function loadStories() { require('../stories'); } configure(loadStories, module);
'use strict'; // Use Applicaion configuration module to register a new module ApplicationConfiguration.registerModule('articles');
this.workbox = this.workbox || {}; this.workbox.core = (function (exports) { 'use strict'; try { self['workbox:core:4.3.1'] && _(); } catch (e) {} // eslint-disable-line /* Copyright 2019 Google LLC Use of this source code is governed by an MIT-style license that can be found in the LICENSE file or at https://opensource.org/licenses/MIT. */ const logger = (() => { let inGroup = false; const methodToColorMap = { debug: `#7f8c8d`, // Gray log: `#2ecc71`, // Green warn: `#f39c12`, // Yellow error: `#c0392b`, // Red groupCollapsed: `#3498db`, // Blue groupEnd: null // No colored prefix on groupEnd }; const print = function (method, args) { if (method === 'groupCollapsed') { // Safari doesn't print all console.groupCollapsed() arguments: // https://bugs.webkit.org/show_bug.cgi?id=182754 if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) { console[method](...args); return; } } const styles = [`background: ${methodToColorMap[method]}`, `border-radius: 0.5em`, `color: white`, `font-weight: bold`, `padding: 2px 0.5em`]; // When in a group, the workbox prefix is not displayed. const logPrefix = inGroup ? [] : ['%cworkbox', styles.join(';')]; console[method](...logPrefix, ...args); if (method === 'groupCollapsed') { inGroup = true; } if (method === 'groupEnd') { inGroup = false; } }; const api = {}; for (const method of Object.keys(methodToColorMap)) { api[method] = (...args) => { print(method, args); }; } return api; })(); /* Copyright 2018 Google LLC Use of this source code is governed by an MIT-style license that can be found in the LICENSE file or at https://opensource.org/licenses/MIT. */ const messages = { 'invalid-value': ({ paramName, validValueDescription, value }) => { if (!paramName || !validValueDescription) { throw new Error(`Unexpected input to 'invalid-value' error.`); } return `The '${paramName}' parameter was given a value with an ` + `unexpected value. ${validValueDescription} Received a value of ` + `${JSON.stringify(value)}.`; }, 'not-in-sw': ({ moduleName }) => { if (!moduleName) { throw new Error(`Unexpected input to 'not-in-sw' error.`); } return `The '${moduleName}' must be used in a service worker.`; }, 'not-an-array': ({ moduleName, className, funcName, paramName }) => { if (!moduleName || !className || !funcName || !paramName) { throw new Error(`Unexpected input to 'not-an-array' error.`); } return `The parameter '${paramName}' passed into ` + `'${moduleName}.${className}.${funcName}()' must be an array.`; }, 'incorrect-type': ({ expectedType, paramName, moduleName, className, funcName }) => { if (!expectedType || !paramName || !moduleName || !funcName) { throw new Error(`Unexpected input to 'incorrect-type' error.`); } return `The parameter '${paramName}' passed into ` + `'${moduleName}.${className ? className + '.' : ''}` + `${funcName}()' must be of type ${expectedType}.`; }, 'incorrect-class': ({ expectedClass, paramName, moduleName, className, funcName, isReturnValueProblem }) => { if (!expectedClass || !moduleName || !funcName) { throw new Error(`Unexpected input to 'incorrect-class' error.`); } if (isReturnValueProblem) { return `The return value from ` + `'${moduleName}.${className ? className + '.' : ''}${funcName}()' ` + `must be an instance of class ${expectedClass.name}.`; } return `The parameter '${paramName}' passed into ` + `'${moduleName}.${className ? className + '.' : ''}${funcName}()' ` + `must be an instance of class ${expectedClass.name}.`; }, 'missing-a-method': ({ expectedMethod, paramName, moduleName, className, funcName }) => { if (!expectedMethod || !paramName || !moduleName || !className || !funcName) { throw new Error(`Unexpected input to 'missing-a-method' error.`); } return `${moduleName}.${className}.${funcName}() expected the ` + `'${paramName}' parameter to expose a '${expectedMethod}' method.`; }, 'add-to-cache-list-unexpected-type': ({ entry }) => { return `An unexpected entry was passed to ` + `'workbox-precaching.PrecacheController.addToCacheList()' The entry ` + `'${JSON.stringify(entry)}' isn't supported. You must supply an array of ` + `strings with one or more characters, objects with a url property or ` + `Request objects.`; }, 'add-to-cache-list-conflicting-entries': ({ firstEntry, secondEntry }) => { if (!firstEntry || !secondEntry) { throw new Error(`Unexpected input to ` + `'add-to-cache-list-duplicate-entries' error.`); } return `Two of the entries passed to ` + `'workbox-precaching.PrecacheController.addToCacheList()' had the URL ` + `${firstEntry._entryId} but different revision details. Workbox is ` + `is unable to cache and version the asset correctly. Please remove one ` + `of the entries.`; }, 'plugin-error-request-will-fetch': ({ thrownError }) => { if (!thrownError) { throw new Error(`Unexpected input to ` + `'plugin-error-request-will-fetch', error.`); } return `An error was thrown by a plugins 'requestWillFetch()' method. ` + `The thrown error message was: '${thrownError.message}'.`; }, 'invalid-cache-name': ({ cacheNameId, value }) => { if (!cacheNameId) { throw new Error(`Expected a 'cacheNameId' for error 'invalid-cache-name'`); } return `You must provide a name containing at least one character for ` + `setCacheDeatils({${cacheNameId}: '...'}). Received a value of ` + `'${JSON.stringify(value)}'`; }, 'unregister-route-but-not-found-with-method': ({ method }) => { if (!method) { throw new Error(`Unexpected input to ` + `'unregister-route-but-not-found-with-method' error.`); } return `The route you're trying to unregister was not previously ` + `registered for the method type '${method}'.`; }, 'unregister-route-route-not-registered': () => { return `The route you're trying to unregister was not previously ` + `registered.`; }, 'queue-replay-failed': ({ name }) => { return `Replaying the background sync queue '${name}' failed.`; }, 'duplicate-queue-name': ({ name }) => { return `The Queue name '${name}' is already being used. ` + `All instances of backgroundSync.Queue must be given unique names.`; }, 'expired-test-without-max-age': ({ methodName, paramName }) => { return `The '${methodName}()' method can only be used when the ` + `'${paramName}' is used in the constructor.`; }, 'unsupported-route-type': ({ moduleName, className, funcName, paramName }) => { return `The supplied '${paramName}' parameter was an unsupported type. ` + `Please check the docs for ${moduleName}.${className}.${funcName} for ` + `valid input types.`; }, 'not-array-of-class': ({ value, expectedClass, moduleName, className, funcName, paramName }) => { return `The supplied '${paramName}' parameter must be an array of ` + `'${expectedClass}' objects. Received '${JSON.stringify(value)},'. ` + `Please check the call to ${moduleName}.${className}.${funcName}() ` + `to fix the issue.`; }, 'max-entries-or-age-required': ({ moduleName, className, funcName }) => { return `You must define either config.maxEntries or config.maxAgeSeconds` + `in ${moduleName}.${className}.${funcName}`; }, 'statuses-or-headers-required': ({ moduleName, className, funcName }) => { return `You must define either config.statuses or config.headers` + `in ${moduleName}.${className}.${funcName}`; }, 'invalid-string': ({ moduleName, className, funcName, paramName }) => { if (!paramName || !moduleName || !funcName) { throw new Error(`Unexpected input to 'invalid-string' error.`); } return `When using strings, the '${paramName}' parameter must start with ` + `'http' (for cross-origin matches) or '/' (for same-origin matches). ` + `Please see the docs for ${moduleName}.${funcName}() for ` + `more info.`; }, 'channel-name-required': () => { return `You must provide a channelName to construct a ` + `BroadcastCacheUpdate instance.`; }, 'invalid-responses-are-same-args': () => { return `The arguments passed into responsesAreSame() appear to be ` + `invalid. Please ensure valid Responses are used.`; }, 'expire-custom-caches-only': () => { return `You must provide a 'cacheName' property when using the ` + `expiration plugin with a runtime caching strategy.`; }, 'unit-must-be-bytes': ({ normalizedRangeHeader }) => { if (!normalizedRangeHeader) { throw new Error(`Unexpected input to 'unit-must-be-bytes' error.`); } return `The 'unit' portion of the Range header must be set to 'bytes'. ` + `The Range header provided was "${normalizedRangeHeader}"`; }, 'single-range-only': ({ normalizedRangeHeader }) => { if (!normalizedRangeHeader) { throw new Error(`Unexpected input to 'single-range-only' error.`); } return `Multiple ranges are not supported. Please use a single start ` + `value, and optional end value. The Range header provided was ` + `"${normalizedRangeHeader}"`; }, 'invalid-range-values': ({ normalizedRangeHeader }) => { if (!normalizedRangeHeader) { throw new Error(`Unexpected input to 'invalid-range-values' error.`); } return `The Range header is missing both start and end values. At least ` + `one of those values is needed. The Range header provided was ` + `"${normalizedRangeHeader}"`; }, 'no-range-header': () => { return `No Range header was found in the Request provided.`; }, 'range-not-satisfiable': ({ size, start, end }) => { return `The start (${start}) and end (${end}) values in the Range are ` + `not satisfiable by the cached response, which is ${size} bytes.`; }, 'attempt-to-cache-non-get-request': ({ url, method }) => { return `Unable to cache '${url}' because it is a '${method}' request and ` + `only 'GET' requests can be cached.`; }, 'cache-put-with-no-response': ({ url }) => { return `There was an attempt to cache '${url}' but the response was not ` + `defined.`; }, 'no-response': ({ url, error }) => { let message = `The strategy could not generate a response for '${url}'.`; if (error) { message += ` The underlying error is ${error}.`; } return message; }, 'bad-precaching-response': ({ url, status }) => { return `The precaching request for '${url}' failed with an HTTP ` + `status of ${status}.`; } }; /* Copyright 2018 Google LLC Use of this source code is governed by an MIT-style license that can be found in the LICENSE file or at https://opensource.org/licenses/MIT. */ const generatorFunction = (code, ...args) => { const message = messages[code]; if (!message) { throw new Error(`Unable to find message for code '${code}'.`); } return message(...args); }; const messageGenerator = generatorFunction; /* Copyright 2018 Google LLC Use of this source code is governed by an MIT-style license that can be found in the LICENSE file or at https://opensource.org/licenses/MIT. */ /** * Workbox errors should be thrown with this class. * This allows use to ensure the type easily in tests, * helps developers identify errors from workbox * easily and allows use to optimise error * messages correctly. * * @private */ class WorkboxError extends Error { /** * * @param {string} errorCode The error code that * identifies this particular error. * @param {Object=} details Any relevant arguments * that will help developers identify issues should * be added as a key on the context object. */ constructor(errorCode, details) { let message = messageGenerator(errorCode, details); super(message); this.name = errorCode; this.details = details; } } /* Copyright 2018 Google LLC Use of this source code is governed by an MIT-style license that can be found in the LICENSE file or at https://opensource.org/licenses/MIT. */ /* * This method returns true if the current context is a service worker. */ const isSWEnv = moduleName => { if (!('ServiceWorkerGlobalScope' in self)) { throw new WorkboxError('not-in-sw', { moduleName }); } }; /* * This method throws if the supplied value is not an array. * The destructed values are required to produce a meaningful error for users. * The destructed and restructured object is so it's clear what is * needed. */ const isArray = (value, { moduleName, className, funcName, paramName }) => { if (!Array.isArray(value)) { throw new WorkboxError('not-an-array', { moduleName, className, funcName, paramName }); } }; const hasMethod = (object, expectedMethod, { moduleName, className, funcName, paramName }) => { const type = typeof object[expectedMethod]; if (type !== 'function') { throw new WorkboxError('missing-a-method', { paramName, expectedMethod, moduleName, className, funcName }); } }; const isType = (object, expectedType, { moduleName, className, funcName, paramName }) => { if (typeof object !== expectedType) { throw new WorkboxError('incorrect-type', { paramName, expectedType, moduleName, className, funcName }); } }; const isInstance = (object, expectedClass, { moduleName, className, funcName, paramName, isReturnValueProblem }) => { if (!(object instanceof expectedClass)) { throw new WorkboxError('incorrect-class', { paramName, expectedClass, moduleName, className, funcName, isReturnValueProblem }); } }; const isOneOf = (value, validValues, { paramName }) => { if (!validValues.includes(value)) { throw new WorkboxError('invalid-value', { paramName, value, validValueDescription: `Valid values are ${JSON.stringify(validValues)}.` }); } }; const isArrayOfClass = (value, expectedClass, { moduleName, className, funcName, paramName }) => { const error = new WorkboxError('not-array-of-class', { value, expectedClass, moduleName, className, funcName, paramName }); if (!Array.isArray(value)) { throw error; } for (let item of value) { if (!(item instanceof expectedClass)) { throw error; } } }; const finalAssertExports = { hasMethod, isArray, isInstance, isOneOf, isSWEnv, isType, isArrayOfClass }; /* Copyright 2018 Google LLC Use of this source code is governed by an MIT-style license that can be found in the LICENSE file or at https://opensource.org/licenses/MIT. */ const quotaErrorCallbacks = new Set(); /* Copyright 2019 Google LLC Use of this source code is governed by an MIT-style license that can be found in the LICENSE file or at https://opensource.org/licenses/MIT. */ /** * Adds a function to the set of quotaErrorCallbacks that will be executed if * there's a quota error. * * @param {Function} callback * @memberof workbox.core */ function registerQuotaErrorCallback(callback) { { finalAssertExports.isType(callback, 'function', { moduleName: 'workbox-core', funcName: 'register', paramName: 'callback' }); } quotaErrorCallbacks.add(callback); { logger.log('Registered a callback to respond to quota errors.', callback); } } /* Copyright 2018 Google LLC Use of this source code is governed by an MIT-style license that can be found in the LICENSE file or at https://opensource.org/licenses/MIT. */ const _cacheNameDetails = { googleAnalytics: 'googleAnalytics', precache: 'precache-v2', prefix: 'workbox', runtime: 'runtime', suffix: self.registration.scope }; const _createCacheName = cacheName => { return [_cacheNameDetails.prefix, cacheName, _cacheNameDetails.suffix].filter(value => value.length > 0).join('-'); }; const cacheNames = { updateDetails: details => { Object.keys(_cacheNameDetails).forEach(key => { if (typeof details[key] !== 'undefined') { _cacheNameDetails[key] = details[key]; } }); }, getGoogleAnalyticsName: userCacheName => { return userCacheName || _createCacheName(_cacheNameDetails.googleAnalytics); }, getPrecacheName: userCacheName => { return userCacheName || _createCacheName(_cacheNameDetails.precache); }, getPrefix: () => { return _cacheNameDetails.prefix; }, getRuntimeName: userCacheName => { return userCacheName || _createCacheName(_cacheNameDetails.runtime); }, getSuffix: () => { return _cacheNameDetails.suffix; } }; /* Copyright 2018 Google LLC Use of this source code is governed by an MIT-style license that can be found in the LICENSE file or at https://opensource.org/licenses/MIT. */ const getFriendlyURL = url => { const urlObj = new URL(url, location); if (urlObj.origin === location.origin) { return urlObj.pathname; } return urlObj.href; }; /* Copyright 2018 Google LLC Use of this source code is governed by an MIT-style license that can be found in the LICENSE file or at https://opensource.org/licenses/MIT. */ /** * Runs all of the callback functions, one at a time sequentially, in the order * in which they were registered. * * @memberof workbox.core * @private */ async function executeQuotaErrorCallbacks() { { logger.log(`About to run ${quotaErrorCallbacks.size} ` + `callbacks to clean up caches.`); } for (const callback of quotaErrorCallbacks) { await callback(); { logger.log(callback, 'is complete.'); } } { logger.log('Finished running callbacks.'); } } /* Copyright 2018 Google LLC Use of this source code is governed by an MIT-style license that can be found in the LICENSE file or at https://opensource.org/licenses/MIT. */ const pluginEvents = { CACHE_DID_UPDATE: 'cacheDidUpdate', CACHE_KEY_WILL_BE_USED: 'cacheKeyWillBeUsed', CACHE_WILL_UPDATE: 'cacheWillUpdate', CACHED_RESPONSE_WILL_BE_USED: 'cachedResponseWillBeUsed', FETCH_DID_FAIL: 'fetchDidFail', FETCH_DID_SUCCEED: 'fetchDidSucceed', REQUEST_WILL_FETCH: 'requestWillFetch' }; /* Copyright 2018 Google LLC Use of this source code is governed by an MIT-style license that can be found in the LICENSE file or at https://opensource.org/licenses/MIT. */ const pluginUtils = { filter: (plugins, callbackName) => { return plugins.filter(plugin => callbackName in plugin); } }; /* Copyright 2018 Google LLC Use of this source code is governed by an MIT-style license that can be found in the LICENSE file or at https://opensource.org/licenses/MIT. */ /** * Wrapper around cache.put(). * * Will call `cacheDidUpdate` on plugins if the cache was updated, using * `matchOptions` when determining what the old entry is. * * @param {Object} options * @param {string} options.cacheName * @param {Request} options.request * @param {Response} options.response * @param {Event} [options.event] * @param {Array<Object>} [options.plugins=[]] * @param {Object} [options.matchOptions] * * @private * @memberof module:workbox-core */ const putWrapper = async ({ cacheName, request, response, event, plugins = [], matchOptions } = {}) => { { if (request.method && request.method !== 'GET') { throw new WorkboxError('attempt-to-cache-non-get-request', { url: getFriendlyURL(request.url), method: request.method }); } } const effectiveRequest = await _getEffectiveRequest({ plugins, request, mode: 'write' }); if (!response) { { logger.error(`Cannot cache non-existent response for ` + `'${getFriendlyURL(effectiveRequest.url)}'.`); } throw new WorkboxError('cache-put-with-no-response', { url: getFriendlyURL(effectiveRequest.url) }); } let responseToCache = await _isResponseSafeToCache({ event, plugins, response, request: effectiveRequest }); if (!responseToCache) { { logger.debug(`Response '${getFriendlyURL(effectiveRequest.url)}' will ` + `not be cached.`, responseToCache); } return; } const cache = await caches.open(cacheName); const updatePlugins = pluginUtils.filter(plugins, pluginEvents.CACHE_DID_UPDATE); let oldResponse = updatePlugins.length > 0 ? await matchWrapper({ cacheName, matchOptions, request: effectiveRequest }) : null; { logger.debug(`Updating the '${cacheName}' cache with a new Response for ` + `${getFriendlyURL(effectiveRequest.url)}.`); } try { await cache.put(effectiveRequest, responseToCache); } catch (error) { // See https://developer.mozilla.org/en-US/docs/Web/API/DOMException#exception-QuotaExceededError if (error.name === 'QuotaExceededError') { await executeQuotaErrorCallbacks(); } throw error; } for (let plugin of updatePlugins) { await plugin[pluginEvents.CACHE_DID_UPDATE].call(plugin, { cacheName, event, oldResponse, newResponse: responseToCache, request: effectiveRequest }); } }; /** * This is a wrapper around cache.match(). * * @param {Object} options * @param {string} options.cacheName Name of the cache to match against. * @param {Request} options.request The Request that will be used to look up * cache entries. * @param {Event} [options.event] The event that propted the action. * @param {Object} [options.matchOptions] Options passed to cache.match(). * @param {Array<Object>} [options.plugins=[]] Array of plugins. * @return {Response} A cached response if available. * * @private * @memberof module:workbox-core */ const matchWrapper = async ({ cacheName, request, event, matchOptions, plugins = [] }) => { const cache = await caches.open(cacheName); const effectiveRequest = await _getEffectiveRequest({ plugins, request, mode: 'read' }); let cachedResponse = await cache.match(effectiveRequest, matchOptions); { if (cachedResponse) { logger.debug(`Found a cached response in '${cacheName}'.`); } else { logger.debug(`No cached response found in '${cacheName}'.`); } } for (const plugin of plugins) { if (pluginEvents.CACHED_RESPONSE_WILL_BE_USED in plugin) { cachedResponse = await plugin[pluginEvents.CACHED_RESPONSE_WILL_BE_USED].call(plugin, { cacheName, event, matchOptions, cachedResponse, request: effectiveRequest }); { if (cachedResponse) { finalAssertExports.isInstance(cachedResponse, Response, { moduleName: 'Plugin', funcName: pluginEvents.CACHED_RESPONSE_WILL_BE_USED, isReturnValueProblem: true }); } } } } return cachedResponse; }; /** * This method will call cacheWillUpdate on the available plugins (or use * status === 200) to determine if the Response is safe and valid to cache. * * @param {Object} options * @param {Request} options.request * @param {Response} options.response * @param {Event} [options.event] * @param {Array<Object>} [options.plugins=[]] * @return {Promise<Response>} * * @private * @memberof module:workbox-core */ const _isResponseSafeToCache = async ({ request, response, event, plugins }) => { let responseToCache = response; let pluginsUsed = false; for (let plugin of plugins) { if (pluginEvents.CACHE_WILL_UPDATE in plugin) { pluginsUsed = true; responseToCache = await plugin[pluginEvents.CACHE_WILL_UPDATE].call(plugin, { request, response: responseToCache, event }); { if (responseToCache) { finalAssertExports.isInstance(responseToCache, Response, { moduleName: 'Plugin', funcName: pluginEvents.CACHE_WILL_UPDATE, isReturnValueProblem: true }); } } if (!responseToCache) { break; } } } if (!pluginsUsed) { { if (!responseToCache.status === 200) { if (responseToCache.status === 0) { logger.warn(`The response for '${request.url}' is an opaque ` + `response. The caching strategy that you're using will not ` + `cache opaque responses by default.`); } else { logger.debug(`The response for '${request.url}' returned ` + `a status code of '${response.status}' and won't be cached as a ` + `result.`); } } } responseToCache = responseToCache.status === 200 ? responseToCache : null; } return responseToCache ? responseToCache : null; }; /** * Checks the list of plugins for the cacheKeyWillBeUsed callback, and * executes any of those callbacks found in sequence. The final `Request` object * returned by the last plugin is treated as the cache key for cache reads * and/or writes. * * @param {Object} options * @param {Request} options.request * @param {string} options.mode * @param {Array<Object>} [options.plugins=[]] * @return {Promise<Request>} * * @private * @memberof module:workbox-core */ const _getEffectiveRequest = async ({ request, mode, plugins }) => { const cacheKeyWillBeUsedPlugins = pluginUtils.filter(plugins, pluginEvents.CACHE_KEY_WILL_BE_USED); let effectiveRequest = request; for (const plugin of cacheKeyWillBeUsedPlugins) { effectiveRequest = await plugin[pluginEvents.CACHE_KEY_WILL_BE_USED].call(plugin, { mode, request: effectiveRequest }); if (typeof effectiveRequest === 'string') { effectiveRequest = new Request(effectiveRequest); } { finalAssertExports.isInstance(effectiveRequest, Request, { moduleName: 'Plugin', funcName: pluginEvents.CACHE_KEY_WILL_BE_USED, isReturnValueProblem: true }); } } return effectiveRequest; }; const cacheWrapper = { put: putWrapper, match: matchWrapper }; /* Copyright 2018 Google LLC Use of this source code is governed by an MIT-style license that can be found in the LICENSE file or at https://opensource.org/licenses/MIT. */ /** * A class that wraps common IndexedDB functionality in a promise-based API. * It exposes all the underlying power and functionality of IndexedDB, but * wraps the most commonly used features in a way that's much simpler to use. * * @private */ class DBWrapper { /** * @param {string} name * @param {number} version * @param {Object=} [callback] * @param {!Function} [callbacks.onupgradeneeded] * @param {!Function} [callbacks.onversionchange] Defaults to * DBWrapper.prototype._onversionchange when not specified. * @private */ constructor(name, version, { onupgradeneeded, onversionchange = this._onversionchange } = {}) { this._name = name; this._version = version; this._onupgradeneeded = onupgradeneeded; this._onversionchange = onversionchange; // If this is null, it means the database isn't open. this._db = null; } /** * Returns the IDBDatabase instance (not normally needed). * * @private */ get db() { return this._db; } /** * Opens a connected to an IDBDatabase, invokes any onupgradedneeded * callback, and added an onversionchange callback to the database. * * @return {IDBDatabase} * @private */ async open() { if (this._db) return; this._db = await new Promise((resolve, reject) => { // This flag is flipped to true if the timeout callback runs prior // to the request failing or succeeding. Note: we use a timeout instead // of an onblocked handler since there are cases where onblocked will // never never run. A timeout better handles all possible scenarios: // https://github.com/w3c/IndexedDB/issues/223 let openRequestTimedOut = false; setTimeout(() => { openRequestTimedOut = true; reject(new Error('The open request was blocked and timed out')); }, this.OPEN_TIMEOUT); const openRequest = indexedDB.open(this._name, this._version); openRequest.onerror = () => reject(openRequest.error); openRequest.onupgradeneeded = evt => { if (openRequestTimedOut) { openRequest.transaction.abort(); evt.target.result.close(); } else if (this._onupgradeneeded) { this._onupgradeneeded(evt); } }; openRequest.onsuccess = ({ target }) => { const db = target.result; if (openRequestTimedOut) { db.close(); } else { db.onversionchange = this._onversionchange.bind(this); resolve(db); } }; }); return this; } /** * Polyfills the native `getKey()` method. Note, this is overridden at * runtime if the browser supports the native method. * * @param {string} storeName * @param {*} query * @return {Array} * @private */ async getKey(storeName, query) { return (await this.getAllKeys(storeName, query, 1))[0]; } /** * Polyfills the native `getAll()` method. Note, this is overridden at * runtime if the browser supports the native method. * * @param {string} storeName * @param {*} query * @param {number} count * @return {Array} * @private */ async getAll(storeName, query, count) { return await this.getAllMatching(storeName, { query, count }); } /** * Polyfills the native `getAllKeys()` method. Note, this is overridden at * runtime if the browser supports the native method. * * @param {string} storeName * @param {*} query * @param {number} count * @return {Array} * @private */ async getAllKeys(storeName, query, count) { return (await this.getAllMatching(storeName, { query, count, includeKeys: true })).map(({ key }) => key); } /** * Supports flexible lookup in an object store by specifying an index, * query, direction, and count. This method returns an array of objects * with the signature . * * @param {string} storeName * @param {Object} [opts] * @param {string} [opts.index] The index to use (if specified). * @param {*} [opts.query] * @param {IDBCursorDirection} [opts.direction] * @param {number} [opts.count] The max number of results to return. * @param {boolean} [opts.includeKeys] When true, the structure of the * returned objects is changed from an array of values to an array of * objects in the form {key, primaryKey, value}. * @return {Array} * @private */ async getAllMatching(storeName, { index, query = null, // IE errors if query === `undefined`. direction = 'next', count, includeKeys } = {}) { return await this.transaction([storeName], 'readonly', (txn, done) => { const store = txn.objectStore(storeName); const target = index ? store.index(index) : store; const results = []; target.openCursor(query, direction).onsuccess = ({ target }) => { const cursor = target.result; if (cursor) { const { primaryKey, key, value } = cursor; results.push(includeKeys ? { primaryKey, key, value } : value); if (count && results.length >= count) { done(results); } else { cursor.continue(); } } else { done(results); } }; }); } /** * Accepts a list of stores, a transaction type, and a callback and * performs a transaction. A promise is returned that resolves to whatever * value the callback chooses. The callback holds all the transaction logic * and is invoked with two arguments: * 1. The IDBTransaction object * 2. A `done` function, that's used to resolve the promise when * when the transaction is done, if passed a value, the promise is * resolved to that value. * * @param {Array<string>} storeNames An array of object store names * involved in the transaction. * @param {string} type Can be `readonly` or `readwrite`. * @param {!Function} callback * @return {*} The result of the transaction ran by the callback. * @private */ async transaction(storeNames, type, callback) { await this.open(); return await new Promise((resolve, reject) => { const txn = this._db.transaction(storeNames, type); txn.onabort = ({ target }) => reject(target.error); txn.oncomplete = () => resolve(); callback(txn, value => resolve(value)); }); } /** * Delegates async to a native IDBObjectStore method. * * @param {string} method The method name. * @param {string} storeName The object store name. * @param {string} type Can be `readonly` or `readwrite`. * @param {...*} args The list of args to pass to the native method. * @return {*} The result of the transaction. * @private */ async _call(method, storeName, type, ...args) { const callback = (txn, done) => { txn.objectStore(storeName)[method](...args).onsuccess = ({ target }) => { done(target.result); }; }; return await this.transaction([storeName], type, callback); } /** * The default onversionchange handler, which closes the database so other * connections can open without being blocked. * * @private */ _onversionchange() { this.close(); } /** * Closes the connection opened by `DBWrapper.open()`. Generally this method * doesn't need to be called since: * 1. It's usually better to keep a connection open since opening * a new connection is somewhat slow. * 2. Connections are automatically closed when the reference is * garbage collected. * The primary use case for needing to close a connection is when another * reference (typically in another tab) needs to upgrade it and would be * blocked by the current, open connection. * * @private */ close() { if (this._db) { this._db.close(); this._db = null; } } } // Exposed to let users modify the default timeout on a per-instance // or global basis. DBWrapper.prototype.OPEN_TIMEOUT = 2000; // Wrap native IDBObjectStore methods according to their mode. const methodsToWrap = { 'readonly': ['get', 'count', 'getKey', 'getAll', 'getAllKeys'], 'readwrite': ['add', 'put', 'clear', 'delete'] }; for (const [mode, methods] of Object.entries(methodsToWrap)) { for (const method of methods) { if (method in IDBObjectStore.prototype) { // Don't use arrow functions here since we're outside of the class. DBWrapper.prototype[method] = async function (storeName, ...args) { return await this._call(method, storeName, mode, ...args); }; } } } /* Copyright 2018 Google LLC Use of this source code is governed by an MIT-style license that can be found in the LICENSE file or at https://opensource.org/licenses/MIT. */ /** * The Deferred class composes Promises in a way that allows for them to be * resolved or rejected from outside the constructor. In most cases promises * should be used directly, but Deferreds can be necessary when the logic to * resolve a promise must be separate. * * @private */ class Deferred { /** * Creates a promise and exposes its resolve and reject functions as methods. */ constructor() { this.promise = new Promise((resolve, reject) => { this.resolve = resolve; this.reject = reject; }); } } /* Copyright 2018 Google LLC Use of this source code is governed by an MIT-style license that can be found in the LICENSE file or at https://opensource.org/licenses/MIT. */ /** * Deletes the database. * Note: this is exported separately from the DBWrapper module because most * usages of IndexedDB in workbox dont need deleting, and this way it can be * reused in tests to delete databases without creating DBWrapper instances. * * @param {string} name The database name. * @private */ const deleteDatabase = async name => { await new Promise((resolve, reject) => { const request = indexedDB.deleteDatabase(name); request.onerror = ({ target }) => { reject(target.error); }; request.onblocked = () => { reject(new Error('Delete blocked')); }; request.onsuccess = () => { resolve(); }; }); }; /* Copyright 2018 Google LLC Use of this source code is governed by an MIT-style license that can be found in the LICENSE file or at https://opensource.org/licenses/MIT. */ /** * Wrapper around the fetch API. * * Will call requestWillFetch on available plugins. * * @param {Object} options * @param {Request|string} options.request * @param {Object} [options.fetchOptions] * @param {Event} [options.event] * @param {Array<Object>} [options.plugins=[]] * @return {Promise<Response>} * * @private * @memberof module:workbox-core */ const wrappedFetch = async ({ request, fetchOptions, event, plugins = [] }) => { // We *should* be able to call `await event.preloadResponse` even if it's // undefined, but for some reason, doing so leads to errors in our Node unit // tests. To work around that, explicitly check preloadResponse's value first. if (event && event.preloadResponse) { const possiblePreloadResponse = await event.preloadResponse; if (possiblePreloadResponse) { { logger.log(`Using a preloaded navigation response for ` + `'${getFriendlyURL(request.url)}'`); } return possiblePreloadResponse; } } if (typeof request === 'string') { request = new Request(request); } { finalAssertExports.isInstance(request, Request, { paramName: request, expectedClass: 'Request', moduleName: 'workbox-core', className: 'fetchWrapper', funcName: 'wrappedFetch' }); } const failedFetchPlugins = pluginUtils.filter(plugins, pluginEvents.FETCH_DID_FAIL); // If there is a fetchDidFail plugin, we need to save a clone of the // original request before it's either modified by a requestWillFetch // plugin or before the original request's body is consumed via fetch(). const originalRequest = failedFetchPlugins.length > 0 ? request.clone() : null; try { for (let plugin of plugins) { if (pluginEvents.REQUEST_WILL_FETCH in plugin) { request = await plugin[pluginEvents.REQUEST_WILL_FETCH].call(plugin, { request: request.clone(), event }); { if (request) { finalAssertExports.isInstance(request, Request, { moduleName: 'Plugin', funcName: pluginEvents.CACHED_RESPONSE_WILL_BE_USED, isReturnValueProblem: true }); } } } } } catch (err) { throw new WorkboxError('plugin-error-request-will-fetch', { thrownError: err }); } // The request can be altered by plugins with `requestWillFetch` making // the original request (Most likely from a `fetch` event) to be different // to the Request we make. Pass both to `fetchDidFail` to aid debugging. let pluginFilteredRequest = request.clone(); try { let fetchResponse; // See https://github.com/GoogleChrome/workbox/issues/1796 if (request.mode === 'navigate') { fetchResponse = await fetch(request); } else { fetchResponse = await fetch(request, fetchOptions); } { logger.debug(`Network request for ` + `'${getFriendlyURL(request.url)}' returned a response with ` + `status '${fetchResponse.status}'.`); } for (const plugin of plugins) { if (pluginEvents.FETCH_DID_SUCCEED in plugin) { fetchResponse = await plugin[pluginEvents.FETCH_DID_SUCCEED].call(plugin, { event, request: pluginFilteredRequest, response: fetchResponse }); { if (fetchResponse) { finalAssertExports.isInstance(fetchResponse, Response, { moduleName: 'Plugin', funcName: pluginEvents.FETCH_DID_SUCCEED, isReturnValueProblem: true }); } } } } return fetchResponse; } catch (error) { { logger.error(`Network request for ` + `'${getFriendlyURL(request.url)}' threw an error.`, error); } for (const plugin of failedFetchPlugins) { await plugin[pluginEvents.FETCH_DID_FAIL].call(plugin, { error, event, originalRequest: originalRequest.clone(), request: pluginFilteredRequest.clone() }); } throw error; } }; const fetchWrapper = { fetch: wrappedFetch }; /* Copyright 2018 Google LLC Use of this source code is governed by an MIT-style license that can be found in the LICENSE file or at https://opensource.org/licenses/MIT. */ var _private = /*#__PURE__*/Object.freeze({ assert: finalAssertExports, cacheNames: cacheNames, cacheWrapper: cacheWrapper, DBWrapper: DBWrapper, Deferred: Deferred, deleteDatabase: deleteDatabase, executeQuotaErrorCallbacks: executeQuotaErrorCallbacks, fetchWrapper: fetchWrapper, getFriendlyURL: getFriendlyURL, logger: logger, WorkboxError: WorkboxError }); /* Copyright 2019 Google LLC Use of this source code is governed by an MIT-style license that can be found in the LICENSE file or at https://opensource.org/licenses/MIT. */ /** * Claim any currently available clients once the service worker * becomes active. This is normally used in conjunction with `skipWaiting()`. * * @alias workbox.core.clientsClaim */ const clientsClaim = () => { addEventListener('activate', () => clients.claim()); }; /* Copyright 2019 Google LLC Use of this source code is governed by an MIT-style license that can be found in the LICENSE file or at https://opensource.org/licenses/MIT. */ /** * Get the current cache names and prefix/suffix used by Workbox. * * `cacheNames.precache` is used for precached assets, * `cacheNames.googleAnalytics` is used by `workbox-google-analytics` to * store `analytics.js`, and `cacheNames.runtime` is used for everything else. * * `cacheNames.prefix` can be used to retrieve just the current prefix value. * `cacheNames.suffix` can be used to retrieve just the current suffix value. * * @return {Object} An object with `precache`, `runtime`, `prefix`, and * `googleAnalytics` properties. * * @alias workbox.core.cacheNames */ const cacheNames$1 = { get googleAnalytics() { return cacheNames.getGoogleAnalyticsName(); }, get precache() { return cacheNames.getPrecacheName(); }, get prefix() { return cacheNames.getPrefix(); }, get runtime() { return cacheNames.getRuntimeName(); }, get suffix() { return cacheNames.getSuffix(); } }; /* Copyright 2019 Google LLC Use of this source code is governed by an MIT-style license that can be found in the LICENSE file or at https://opensource.org/licenses/MIT. */ /** * Modifies the default cache names used by the Workbox packages. * Cache names are generated as `<prefix>-<Cache Name>-<suffix>`. * * @param {Object} details * @param {Object} [details.prefix] The string to add to the beginning of * the precache and runtime cache names. * @param {Object} [details.suffix] The string to add to the end of * the precache and runtime cache names. * @param {Object} [details.precache] The cache name to use for precache * caching. * @param {Object} [details.runtime] The cache name to use for runtime caching. * @param {Object} [details.googleAnalytics] The cache name to use for * `workbox-google-analytics` caching. * * @alias workbox.core.setCacheNameDetails */ const setCacheNameDetails = details => { { Object.keys(details).forEach(key => { finalAssertExports.isType(details[key], 'string', { moduleName: 'workbox-core', funcName: 'setCacheNameDetails', paramName: `details.${key}` }); }); if ('precache' in details && details.precache.length === 0) { throw new WorkboxError('invalid-cache-name', { cacheNameId: 'precache', value: details.precache }); } if ('runtime' in details && details.runtime.length === 0) { throw new WorkboxError('invalid-cache-name', { cacheNameId: 'runtime', value: details.runtime }); } if ('googleAnalytics' in details && details.googleAnalytics.length === 0) { throw new WorkboxError('invalid-cache-name', { cacheNameId: 'googleAnalytics', value: details.googleAnalytics }); } } cacheNames.updateDetails(details); }; /* Copyright 2019 Google LLC Use of this source code is governed by an MIT-style license that can be found in the LICENSE file or at https://opensource.org/licenses/MIT. */ /** * Force a service worker to become active, instead of waiting. This is * normally used in conjunction with `clientsClaim()`. * * @alias workbox.core.skipWaiting */ const skipWaiting = () => { // We need to explicitly call `self.skipWaiting()` here because we're // shadowing `skipWaiting` with this local function. addEventListener('install', () => self.skipWaiting()); }; /* Copyright 2018 Google LLC Use of this source code is governed by an MIT-style license that can be found in the LICENSE file or at https://opensource.org/licenses/MIT. */ try { self.workbox.v = self.workbox.v || {}; } catch (errer) {} // NOOP exports._private = _private; exports.clientsClaim = clientsClaim; exports.cacheNames = cacheNames$1; exports.registerQuotaErrorCallback = registerQuotaErrorCallback; exports.setCacheNameDetails = setCacheNameDetails; exports.skipWaiting = skipWaiting; return exports; }({})); //# sourceMappingURL=workbox-core.dev.js.map
var locale={moduleType:"locale",name:"gl",dictionary:{},format:{days:["Domingo","Luns","Martes","M\xe9rcores","Xoves","Venres","S\xe1bado"],shortDays:["Dom","Lun","Mar","M\xe9r","Xov","Ven","S\xe1b"],months:["Xaneiro","Febreiro","Marzo","Abril","Maio","Xu\xf1o","Xullo","Agosto","Setembro","Outubro","Novembro","Decembro"],shortMonths:["Xan","Feb","Mar","Abr","Mai","Xu\xf1","Xul","Ago","Set","Out","Nov","Dec"],date:"%d/%m/%Y"}};"undefined"==typeof Plotly?(window.PlotlyLocales=window.PlotlyLocales||[],window.PlotlyLocales.push(locale)):Plotly.register(locale);
var _ = require('lodash'), Promise = require('bluebird'), storage = require('../../../storage'), replaceImage, ImageImporter, preProcessPosts, preProcessTags, preProcessUsers; replaceImage = function (markdown, image) { // Normalizes to include a trailing slash if there was one var regex = new RegExp('(/)?' + image.originalPath, 'gm'); return markdown.replace(regex, image.newPath); }; preProcessPosts = function (data, image) { _.each(data.posts, function (post) { post.markdown = replaceImage(post.markdown, image); if (post.html) { post.html = replaceImage(post.html, image); } if (post.image) { post.image = replaceImage(post.image, image); } }); }; preProcessTags = function (data, image) { _.each(data.tags, function (tag) { if (tag.image) { tag.image = replaceImage(tag.image, image); } }); }; preProcessUsers = function (data, image) { _.each(data.users, function (user) { if (user.cover) { user.cover = replaceImage(user.cover, image); } if (user.image) { user.image = replaceImage(user.image, image); } }); }; ImageImporter = { type: 'images', preProcess: function (importData) { if (importData.images && importData.data) { _.each(importData.images, function (image) { preProcessPosts(importData.data.data, image); preProcessTags(importData.data.data, image); preProcessUsers(importData.data.data, image); }); } importData.preProcessedByImage = true; return importData; }, doImport: function (imageData) { var store = storage.getStorage(); return Promise.map(imageData, function (image) { return store.save(image, image.targetDir).then(function (result) { return {originalPath: image.originalPath, newPath: image.newPath, stored: result}; }); }); } }; module.exports = ImageImporter;
/* * DateJS Culture String File * Country Code: en-AU * Name: English (Australia) * Format: "key" : "value" * Key is the en-US term, Value is the Key in the current language. */ Date.CultureStrings = Date.CultureStrings || {}; Date.CultureStrings["en-AU"] = { "name": "en-AU", "englishName": "English (Australia)", "nativeName": "English (Australia)", "Sunday": "Sunday", "Monday": "Monday", "Tuesday": "Tuesday", "Wednesday": "Wednesday", "Thursday": "Thursday", "Friday": "Friday", "Saturday": "Saturday", "Sun": "Sun", "Mon": "Mon", "Tue": "Tue", "Wed": "Wed", "Thu": "Thu", "Fri": "Fri", "Sat": "Sat", "Su": "Su", "Mo": "Mo", "Tu": "Tu", "We": "We", "Th": "Th", "Fr": "Fr", "Sa": "Sa", "S_Sun_Initial": "S", "M_Mon_Initial": "M", "T_Tue_Initial": "T", "W_Wed_Initial": "W", "T_Thu_Initial": "T", "F_Fri_Initial": "F", "S_Sat_Initial": "S", "January": "January", "February": "February", "March": "March", "April": "April", "May": "May", "June": "June", "July": "July", "August": "August", "September": "September", "October": "October", "November": "November", "December": "December", "Jan_Abbr": "Jan", "Feb_Abbr": "Feb", "Mar_Abbr": "Mar", "Apr_Abbr": "Apr", "May_Abbr": "May", "Jun_Abbr": "Jun", "Jul_Abbr": "Jul", "Aug_Abbr": "Aug", "Sep_Abbr": "Sep", "Oct_Abbr": "Oct", "Nov_Abbr": "Nov", "Dec_Abbr": "Dec", "AM": "AM", "PM": "PM", "firstDayOfWeek": 1, "twoDigitYearMax": 2029, "mdy": "dmy", "M/d/yyyy": "d/MM/yyyy", "dddd, MMMM dd, yyyy": "dddd, d MMMM yyyy", "h:mm tt": "h:mm tt", "h:mm:ss tt": "h:mm:ss tt", "dddd, MMMM dd, yyyy h:mm:ss tt": "dddd, d MMMM yyyy h:mm:ss tt", "yyyy-MM-ddTHH:mm:ss": "yyyy-MM-ddTHH:mm:ss", "yyyy-MM-dd HH:mm:ssZ": "yyyy-MM-dd HH:mm:ssZ", "ddd, dd MMM yyyy HH:mm:ss": "ddd, dd MMM yyyy HH:mm:ss", "MMMM dd": "dd MMMM", "MMMM, yyyy": "MMMM yyyy", "/jan(uary)?/": "jan(uary)?", "/feb(ruary)?/": "feb(ruary)?", "/mar(ch)?/": "mar(ch)?", "/apr(il)?/": "apr(il)?", "/may/": "may", "/jun(e)?/": "jun(e)?", "/jul(y)?/": "jul(y)?", "/aug(ust)?/": "aug(ust)?", "/sep(t(ember)?)?/": "sep(t(ember)?)?", "/oct(ober)?/": "oct(ober)?", "/nov(ember)?/": "nov(ember)?", "/dec(ember)?/": "dec(ember)?", "/^su(n(day)?)?/": "^su(n(day)?)?", "/^mo(n(day)?)?/": "^mo(n(day)?)?", "/^tu(e(s(day)?)?)?/": "^tu(e(s(day)?)?)?", "/^we(d(nesday)?)?/": "^we(d(nesday)?)?", "/^th(u(r(s(day)?)?)?)?/": "^th(u(r(s(day)?)?)?)?", "/^fr(i(day)?)?/": "^fr(i(day)?)?", "/^sa(t(urday)?)?/": "^sa(t(urday)?)?", "/^next/": "^next", "/^last|past|prev(ious)?/": "^last|past|prev(ious)?", "/^(\\+|aft(er)?|from|hence)/": "^(\\+|aft(er)?|from|hence)", "/^(\\-|bef(ore)?|ago)/": "^(\\-|bef(ore)?|ago)", "/^yes(terday)?/": "^yes(terday)?", "/^t(od(ay)?)?/": "^t(od(ay)?)?", "/^tom(orrow)?/": "^tom(orrow)?", "/^n(ow)?/": "^n(ow)?", "/^ms|milli(second)?s?/": "^ms|milli(second)?s?", "/^sec(ond)?s?/": "^sec(ond)?s?", "/^mn|min(ute)?s?/": "^mn|min(ute)?s?", "/^h(our)?s?/": "^h(our)?s?", "/^w(eek)?s?/": "^w(eek)?s?", "/^m(onth)?s?/": "^m(onth)?s?", "/^d(ay)?s?/": "^d(ay)?s?", "/^y(ear)?s?/": "^y(ear)?s?", "/^(a|p)/": "^(a|p)", "/^(a\\.?m?\\.?|p\\.?m?\\.?)/": "^(a\\.?m?\\.?|p\\.?m?\\.?)", "/^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\\s*(\\+|\\-)\\s*\\d\\d\\d\\d?)|gmt|utc)/": "^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\\s*(\\+|\\-)\\s*\\d\\d\\d\\d?)|gmt|utc)", "/^\\s*(st|nd|rd|th)/": "^\\s*(st|nd|rd|th)", "/^\\s*(\\:|a(?!u|p)|p)/": "^\\s*(\\:|a(?!u|p)|p)", "LINT": "LINT", "TOT": "TOT", "CHAST": "CHAST", "NZST": "NZST", "NFT": "NFT", "SBT": "SBT", "AEST": "AEST", "ACST": "ACST", "JST": "JST", "CWST": "CWST", "CT": "CT", "ICT": "ICT", "MMT": "MMT", "BIOT": "BST", "NPT": "NPT", "IST": "IST", "PKT": "PKT", "AFT": "AFT", "MSK": "MSK", "IRST": "IRST", "FET": "FET", "EET": "EET", "CET": "CET", "UTC": "UTC", "GMT": "GMT", "CVT": "CVT", "GST": "GST", "BRT": "BRT", "NST": "NST", "AST": "AST", "EST": "EST", "CST": "CST", "MST": "MST", "PST": "PST", "AKST": "AKST", "MIT": "MIT", "HST": "HST", "SST": "SST", "BIT": "BIT", "CHADT": "CHADT", "NZDT": "NZDT", "AEDT": "AEDT", "ACDT": "ACDT", "AZST": "AZST", "IRDT": "IRDT", "EEST": "EEST", "CEST": "CEST", "BST": "BST", "PMDT": "PMDT", "ADT": "ADT", "NDT": "NDT", "EDT": "EDT", "CDT": "CDT", "MDT": "MDT", "PDT": "PDT", "AKDT": "AKDT", "HADT": "HADT" }; Date.CultureStrings.lang = "en-AU";
!function(t){t.datepick.regional.lv={clearText:"Notīrīt",clearStatus:"",closeText:"Aizvērt",closeStatus:"",prevText:"Iepr",prevStatus:"",prevBigText:"&#x3c;&#x3c;",prevBigStatus:"",nextText:"Nāka",nextStatus:"",nextBigText:"&#x3e;&#x3e;",nextBigStatus:"",currentText:"Šodien",currentStatus:"",monthNames:["Janvāris","Februāris","Marts","Aprīlis","Maijs","Jūnijs","Jūlijs","Augusts","Septembris","Oktobris","Novembris","Decembris"],monthNamesShort:["Jan","Feb","Mar","Apr","Mai","Jūn","Jūl","Aug","Sep","Okt","Nov","Dec"],monthStatus:"",yearStatus:"",weekHeader:"Nav",weekStatus:"",dayNames:["svētdiena","pirmdiena","otrdiena","trešdiena","ceturtdiena","piektdiena","sestdiena"],dayNamesShort:["svt","prm","otr","tre","ctr","pkt","sst"],dayNamesMin:["Sv","Pr","Ot","Tr","Ct","Pk","Ss"],dayStatus:"DD",dateStatus:"D, M d",dateFormat:"dd-mm-yy",firstDay:1,initStatus:"",isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},t.datepick.setDefaults(t.datepick.regional.lv)}(jQuery); //# sourceMappingURL=jquery.datepick-lv.min.js.map
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'liststyle', 'ca', { armenian: 'Armenian numbering', bulletedTitle: 'Bulleted List Properties', circle: 'Circle', decimal: 'Decimal (1, 2, 3, etc.)', decimalLeadingZero: 'Decimal leading zero (01, 02, 03, etc.)', disc: 'Disc', georgian: 'Georgian numbering (an, ban, gan, etc.)', lowerAlpha: 'Lower Alpha (a, b, c, d, e, etc.)', lowerGreek: 'Lower Greek (alpha, beta, gamma, etc.)', lowerRoman: 'Lower Roman (i, ii, iii, iv, v, etc.)', none: 'None', notset: '<not set>', numberedTitle: 'Numbered List Properties', square: 'Square', start: 'Start', type: 'Type', upperAlpha: 'Upper Alpha (A, B, C, D, E, etc.)', upperRoman: 'Upper Roman (I, II, III, IV, V, etc.)', validateStartNumber: 'List start number must be a whole number.' });
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'fakeobjects', 'bn', { anchor: 'Anchor', // MISSING flash: 'Flash Animation', // MISSING hiddenfield: 'Hidden Field', // MISSING iframe: 'IFrame', // MISSING unknown: 'Unknown Object' // MISSING });
'use strict'; describe('$compile', function() { function isUnknownElement(el) { return !!el.toString().match(/Unknown/); } function isSVGElement(el) { return !!el.toString().match(/SVG/); } function isHTMLElement(el) { return !!el.toString().match(/HTML/); } function supportsMathML() { var d = document.createElement('div'); d.innerHTML = '<math></math>'; return !isUnknownElement(d.firstChild); } // IE9-11 do not support foreignObject in svg... function supportsForeignObject() { var d = document.createElementNS('http://www.w3.org/2000/svg', 'foreignObject'); return !!d.toString().match(/SVGForeignObject/); } function getChildScopes(scope) { var children = []; if (!scope.$$childHead) { return children; } var childScope = scope.$$childHead; do { children.push(childScope); children = children.concat(getChildScopes(childScope)); } while ((childScope = childScope.$$nextSibling)); return children; } var element, directive, $compile, $rootScope; beforeEach(module(provideLog, function($provide, $compileProvider) { element = null; directive = $compileProvider.directive; directive('log', function(log) { return { restrict: 'CAM', priority:0, compile: valueFn(function(scope, element, attrs) { log(attrs.log || 'LOG'); }) }; }); directive('highLog', function(log) { return { restrict: 'CAM', priority:3, compile: valueFn(function(scope, element, attrs) { log(attrs.highLog || 'HIGH'); })}; }); directive('mediumLog', function(log) { return { restrict: 'CAM', priority:2, compile: valueFn(function(scope, element, attrs) { log(attrs.mediumLog || 'MEDIUM'); })}; }); directive('greet', function() { return { restrict: 'CAM', priority:10, compile: valueFn(function(scope, element, attrs) { element.text("Hello " + attrs.greet); })}; }); directive('set', function() { return function(scope, element, attrs) { element.text(attrs.set); }; }); directive('mediumStop', valueFn({ priority: 2, terminal: true })); directive('stop', valueFn({ terminal: true })); directive('negativeStop', valueFn({ priority: -100, // even with negative priority we still should be able to stop descend terminal: true })); directive('svgContainer', function() { return { template: '<svg width="400" height="400" ng-transclude></svg>', replace: true, transclude: true }; }); directive('svgCustomTranscludeContainer', function() { return { template: '<svg width="400" height="400"></svg>', transclude: true, link: function(scope, element, attr, ctrls, $transclude) { var futureParent = element.children().eq(0); $transclude(function(clone) { futureParent.append(clone); }, futureParent); } }; }); directive('svgCircle', function() { return { template: '<circle cx="2" cy="2" r="1"></circle>', templateNamespace: 'svg', replace: true }; }); directive('myForeignObject', function() { return { template: '<foreignObject width="100" height="100" ng-transclude></foreignObject>', templateNamespace: 'svg', replace: true, transclude: true }; }); return function(_$compile_, _$rootScope_) { $rootScope = _$rootScope_; $compile = _$compile_; }; })); function compile(html) { element = angular.element(html); $compile(element)($rootScope); } afterEach(function() { dealoc(element); }); describe('configuration', function() { it('should register a directive', function() { module(function() { directive('div', function(log) { return { restrict: 'ECA', link: function(scope, element) { log('OK'); element.text('SUCCESS'); } }; }); }); inject(function($compile, $rootScope, log) { element = $compile('<div></div>')($rootScope); expect(element.text()).toEqual('SUCCESS'); expect(log).toEqual('OK'); }); }); it('should allow registration of multiple directives with same name', function() { module(function() { directive('div', function(log) { return { restrict: 'ECA', link: { pre: log.fn('pre1'), post: log.fn('post1') } }; }); directive('div', function(log) { return { restrict: 'ECA', link: { pre: log.fn('pre2'), post: log.fn('post2') } }; }); }); inject(function($compile, $rootScope, log) { element = $compile('<div></div>')($rootScope); expect(log).toEqual('pre1; pre2; post2; post1'); }); }); it('should throw an exception if a directive is called "hasOwnProperty"', function() { module(function() { expect(function() { directive('hasOwnProperty', function() { }); }).toThrowMinErr('ng','badname', "hasOwnProperty is not a valid directive name"); }); inject(function($compile) {}); }); it('should throw an exception if a directive name starts with a non-lowercase letter', function() { module(function() { expect(function() { directive('BadDirectiveName', function() { }); }).toThrowMinErr('$compile','baddir', "Directive name 'BadDirectiveName' is invalid. The first character must be a lowercase letter"); }); inject(function($compile) {}); }); it('should throw an exception if a directive name has leading or trailing whitespace', function() { module(function() { function assertLeadingOrTrailingWhitespaceInDirectiveName(name) { expect(function() { directive(name, function() { }); }).toThrowMinErr( '$compile','baddir', 'Directive name \'' + name + '\' is invalid. ' + "The name should not contain leading or trailing whitespaces"); } assertLeadingOrTrailingWhitespaceInDirectiveName(' leadingWhitespaceDirectiveName'); assertLeadingOrTrailingWhitespaceInDirectiveName('trailingWhitespaceDirectiveName '); assertLeadingOrTrailingWhitespaceInDirectiveName(' leadingAndTrailingWhitespaceDirectiveName '); }); inject(function($compile) {}); }); }); describe('svg namespace transcludes', function() { // this method assumes some sort of sized SVG element is being inspected. function assertIsValidSvgCircle(elem) { expect(isUnknownElement(elem)).toBe(false); expect(isSVGElement(elem)).toBe(true); var box = elem.getBoundingClientRect(); expect(box.width === 0 && box.height === 0).toBe(false); } it('should handle transcluded svg elements', inject(function($compile) { element = jqLite('<div><svg-container>' + '<circle cx="4" cy="4" r="2"></circle>' + '</svg-container></div>'); $compile(element.contents())($rootScope); document.body.appendChild(element[0]); var circle = element.find('circle'); assertIsValidSvgCircle(circle[0]); })); it('should handle custom svg elements inside svg tag', inject(function() { element = jqLite('<div><svg width="300" height="300">' + '<svg-circle></svg-circle>' + '</svg></div>'); $compile(element.contents())($rootScope); document.body.appendChild(element[0]); var circle = element.find('circle'); assertIsValidSvgCircle(circle[0]); })); it('should handle transcluded custom svg elements', inject(function() { element = jqLite('<div><svg-container>' + '<svg-circle></svg-circle>' + '</svg-container></div>'); $compile(element.contents())($rootScope); document.body.appendChild(element[0]); var circle = element.find('circle'); assertIsValidSvgCircle(circle[0]); })); if (supportsForeignObject()) { it('should handle foreignObject', inject(function() { element = jqLite('<div><svg-container>' + '<foreignObject width="100" height="100"><div class="test" style="position:absolute;width:20px;height:20px">test</div></foreignObject>' + '</svg-container></div>'); $compile(element.contents())($rootScope); document.body.appendChild(element[0]); var testElem = element.find('div'); expect(isHTMLElement(testElem[0])).toBe(true); var bounds = testElem[0].getBoundingClientRect(); expect(bounds.width === 20 && bounds.height === 20).toBe(true); })); it('should handle custom svg containers that transclude to foreignObject that transclude html', inject(function() { element = jqLite('<div><svg-container>' + '<my-foreign-object><div class="test" style="width:20px;height:20px">test</div></my-foreign-object>' + '</svg-container></div>'); $compile(element.contents())($rootScope); document.body.appendChild(element[0]); var testElem = element.find('div'); expect(isHTMLElement(testElem[0])).toBe(true); var bounds = testElem[0].getBoundingClientRect(); expect(bounds.width === 20 && bounds.height === 20).toBe(true); })); // NOTE: This test may be redundant. it('should handle custom svg containers that transclude to foreignObject' + ' that transclude to custom svg containers that transclude to custom elements', inject(function() { element = jqLite('<div><svg-container>' + '<my-foreign-object><svg-container><svg-circle></svg-circle></svg-container></my-foreign-object>' + '</svg-container></div>'); $compile(element.contents())($rootScope); document.body.appendChild(element[0]); var circle = element.find('circle'); assertIsValidSvgCircle(circle[0]); })); } it('should handle directives with templates that manually add the transclude further down', inject(function() { element = jqLite('<div><svg-custom-transclude-container>' + '<circle cx="2" cy="2" r="1"></circle></svg-custom-transclude-container>' + '</div>'); $compile(element.contents())($rootScope); document.body.appendChild(element[0]); var circle = element.find('circle'); assertIsValidSvgCircle(circle[0]); })); it('should support directives with SVG templates and a slow url ' + 'that are stamped out later by a transcluding directive', function() { module(function() { directive('svgCircleUrl', valueFn({ replace: true, templateUrl: 'template.html', templateNamespace: 'SVG' })); }); inject(function($compile, $rootScope, $httpBackend) { $httpBackend.expect('GET', 'template.html').respond('<circle></circle>'); element = $compile('<svg><g ng-repeat="l in list"><svg-circle-url></svg-circle-url></g></svg>')($rootScope); // initially the template is not yet loaded $rootScope.$apply(function() { $rootScope.list = [1]; }); expect(element.find('svg-circle-url').length).toBe(1); expect(element.find('circle').length).toBe(0); // template is loaded and replaces the existing nodes $httpBackend.flush(); expect(element.find('svg-circle-url').length).toBe(0); expect(element.find('circle').length).toBe(1); // new entry should immediately use the loaded template $rootScope.$apply(function() { $rootScope.list.push(2); }); expect(element.find('svg-circle-url').length).toBe(0); expect(element.find('circle').length).toBe(2); }); }); }); describe('compile phase', function() { it('should attach scope to the document node when it is compiled explicitly', inject(function($document) { $compile($document)($rootScope); expect($document.scope()).toBe($rootScope); })); it('should wrap root text nodes in spans', inject(function($compile, $rootScope) { element = jqLite('<div>A&lt;a&gt;B&lt;/a&gt;C</div>'); var text = element.contents(); expect(text[0].nodeName).toEqual('#text'); text = $compile(text)($rootScope); expect(text[0].nodeName).toEqual('SPAN'); expect(element.find('span').text()).toEqual('A<a>B</a>C'); })); it('should not wrap root whitespace text nodes in spans', function() { element = jqLite( '<div> <div>A</div>\n ' + // The spaces and newlines here should not get wrapped '<div>B</div>C\t\n ' + // The "C", tabs and spaces here will be wrapped '</div>'); $compile(element.contents())($rootScope); var spans = element.find('span'); expect(spans.length).toEqual(1); expect(spans.text().indexOf('C')).toEqual(0); }); it('should not leak memory when there are top level empty text nodes', function() { // We compile the contents of element (i.e. not element itself) // Then delete these contents and check the cache has been reset to zero // First with only elements at the top level element = jqLite('<div><div></div></div>'); $compile(element.contents())($rootScope); element.empty(); expect(jqLiteCacheSize()).toEqual(0); // Next with non-empty text nodes at the top level // (in this case the compiler will wrap them in a <span>) element = jqLite('<div>xxx</div>'); $compile(element.contents())($rootScope); element.empty(); expect(jqLiteCacheSize()).toEqual(0); // Next with comment nodes at the top level element = jqLite('<div><!-- comment --></div>'); $compile(element.contents())($rootScope); element.empty(); expect(jqLiteCacheSize()).toEqual(0); // Finally with empty text nodes at the top level element = jqLite('<div> \n<div></div> </div>'); $compile(element.contents())($rootScope); element.empty(); expect(jqLiteCacheSize()).toEqual(0); }); it('should not blow up when elements with no childNodes property are compiled', inject( function($compile, $rootScope) { // it turns out that when a browser plugin is bound to an DOM element (typically <object>), // the plugin's context rather than the usual DOM apis are exposed on this element, so // childNodes might not exist. element = jqLite('<div>{{1+2}}</div>'); try { element[0].childNodes[1] = {nodeType: 3, nodeName: 'OBJECT', textContent: 'fake node'}; } catch (e) { } finally { if (!element[0].childNodes[1]) return; //browser doesn't support this kind of mocking } expect(element[0].childNodes[1].textContent).toBe('fake node'); $compile(element)($rootScope); $rootScope.$apply(); // object's children can't be compiled in this case, so we expect them to be raw expect(element.html()).toBe("3"); })); describe('multiple directives per element', function() { it('should allow multiple directives per element', inject(function($compile, $rootScope, log) { element = $compile( '<span greet="angular" log="L" x-high-log="H" data-medium-log="M"></span>')($rootScope); expect(element.text()).toEqual('Hello angular'); expect(log).toEqual('L; M; H'); })); it('should recurse to children', inject(function($compile, $rootScope) { element = $compile('<div>0<a set="hello">1</a>2<b set="angular">3</b>4</div>')($rootScope); expect(element.text()).toEqual('0hello2angular4'); })); it('should allow directives in classes', inject(function($compile, $rootScope, log) { element = $compile('<div class="greet: angular; log:123;"></div>')($rootScope); expect(element.html()).toEqual('Hello angular'); expect(log).toEqual('123'); })); it('should allow directives in SVG element classes', inject(function($compile, $rootScope, log) { if (!window.SVGElement) return; element = $compile('<svg><text class="greet: angular; log:123;"></text></svg>')($rootScope); var text = element.children().eq(0); // In old Safari, SVG elements don't have innerHTML, so element.html() won't work // (https://bugs.webkit.org/show_bug.cgi?id=136903) expect(text.text()).toEqual('Hello angular'); expect(log).toEqual('123'); })); it('should ignore not set CSS classes on SVG elements', inject(function($compile, $rootScope, log) { if (!window.SVGElement) return; // According to spec SVG element className property is readonly, but only FF // implements it this way which causes compile exceptions. element = $compile('<svg><text>{{1}}</text></svg>')($rootScope); $rootScope.$digest(); expect(element.text()).toEqual('1'); })); it('should receive scope, element, and attributes', function() { var injector; module(function() { directive('log', function($injector, $rootScope) { injector = $injector; return { restrict: 'CA', compile: function(element, templateAttr) { expect(typeof templateAttr.$normalize).toBe('function'); expect(typeof templateAttr.$set).toBe('function'); expect(isElement(templateAttr.$$element)).toBeTruthy(); expect(element.text()).toEqual('unlinked'); expect(templateAttr.exp).toEqual('abc'); expect(templateAttr.aa).toEqual('A'); expect(templateAttr.bb).toEqual('B'); expect(templateAttr.cc).toEqual('C'); return function(scope, element, attr) { expect(element.text()).toEqual('unlinked'); expect(attr).toBe(templateAttr); expect(scope).toEqual($rootScope); element.text('worked'); }; } }; }); }); inject(function($rootScope, $compile, $injector) { element = $compile( '<div class="log" exp="abc" aa="A" x-Bb="B" daTa-cC="C">unlinked</div>')($rootScope); expect(element.text()).toEqual('worked'); expect(injector).toBe($injector); // verify that directive is injectable }); }); }); describe('error handling', function() { it('should handle exceptions', function() { module(function($exceptionHandlerProvider) { $exceptionHandlerProvider.mode('log'); directive('factoryError', function() { throw 'FactoryError'; }); directive('templateError', valueFn({ compile: function() { throw 'TemplateError'; } })); directive('linkingError', valueFn(function() { throw 'LinkingError'; })); }); inject(function($rootScope, $compile, $exceptionHandler) { element = $compile('<div factory-error template-error linking-error></div>')($rootScope); expect($exceptionHandler.errors[0]).toEqual('FactoryError'); expect($exceptionHandler.errors[1][0]).toEqual('TemplateError'); expect(ie($exceptionHandler.errors[1][1])). toEqual('<div factory-error linking-error template-error>'); expect($exceptionHandler.errors[2][0]).toEqual('LinkingError'); expect(ie($exceptionHandler.errors[2][1])). toEqual('<div class="ng-scope" factory-error linking-error template-error>'); // crazy stuff to make IE happy function ie(text) { var list = [], parts, elementName; parts = lowercase(text). replace('<', ''). replace('>', ''). split(' '); elementName = parts.shift(); parts.sort(); parts.unshift(elementName); forEach(parts, function(value) { if (value.substring(0,2) !== 'ng') { value = value.replace('=""', ''); var match = value.match(/=(.*)/); if (match && match[1].charAt(0) != '"') { value = value.replace(/=(.*)/, '="$1"'); } list.push(value); } }); return '<' + list.join(' ') + '>'; } }); }); it('should allow changing the template structure after the current node', function() { module(function() { directive('after', valueFn({ compile: function(element) { element.after('<span log>B</span>'); } })); }); inject(function($compile, $rootScope, log) { element = jqLite("<div><div after>A</div></div>"); $compile(element)($rootScope); expect(element.text()).toBe('AB'); expect(log).toEqual('LOG'); }); }); it('should allow changing the template structure after the current node inside ngRepeat', function() { module(function() { directive('after', valueFn({ compile: function(element) { element.after('<span log>B</span>'); } })); }); inject(function($compile, $rootScope, log) { element = jqLite('<div><div ng-repeat="i in [1,2]"><div after>A</div></div></div>'); $compile(element)($rootScope); $rootScope.$digest(); expect(element.text()).toBe('ABAB'); expect(log).toEqual('LOG; LOG'); }); }); it('should allow modifying the DOM structure in post link fn', function() { module(function() { directive('removeNode', valueFn({ link: function($scope, $element) { $element.remove(); } })); }); inject(function($compile, $rootScope) { element = jqLite('<div><div remove-node></div><div>{{test}}</div></div>'); $rootScope.test = 'Hello'; $compile(element)($rootScope); $rootScope.$digest(); expect(element.children().length).toBe(1); expect(element.text()).toBe('Hello'); }); }); }); describe('compiler control', function() { describe('priority', function() { it('should honor priority', inject(function($compile, $rootScope, log) { element = $compile( '<span log="L" x-high-log="H" data-medium-log="M"></span>')($rootScope); expect(log).toEqual('L; M; H'); })); }); describe('terminal', function() { it('should prevent further directives from running', inject(function($rootScope, $compile) { element = $compile('<div negative-stop><a set="FAIL">OK</a></div>')($rootScope); expect(element.text()).toEqual('OK'); } )); it('should prevent further directives from running, but finish current priority level', inject(function($rootScope, $compile, log) { // class is processed after attrs, so putting log in class will put it after // the stop in the current level. This proves that the log runs after stop element = $compile( '<div high-log medium-stop log class="medium-log"><a set="FAIL">OK</a></div>')($rootScope); expect(element.text()).toEqual('OK'); expect(log.toArray().sort()).toEqual(['HIGH', 'MEDIUM']); }) ); }); describe('restrict', function() { it('should allow restriction of availability', function() { module(function() { forEach({div: 'E', attr: 'A', clazz: 'C', comment: 'M', all: 'EACM'}, function(restrict, name) { directive(name, function(log) { return { restrict: restrict, compile: valueFn(function(scope, element, attr) { log(name); }) }; }); }); }); inject(function($rootScope, $compile, log) { dealoc($compile('<span div class="div"></span>')($rootScope)); expect(log).toEqual(''); log.reset(); dealoc($compile('<div></div>')($rootScope)); expect(log).toEqual('div'); log.reset(); dealoc($compile('<attr class="attr"></attr>')($rootScope)); expect(log).toEqual(''); log.reset(); dealoc($compile('<span attr></span>')($rootScope)); expect(log).toEqual('attr'); log.reset(); dealoc($compile('<clazz clazz></clazz>')($rootScope)); expect(log).toEqual(''); log.reset(); dealoc($compile('<span class="clazz"></span>')($rootScope)); expect(log).toEqual('clazz'); log.reset(); dealoc($compile('<!-- directive: comment -->')($rootScope)); expect(log).toEqual('comment'); log.reset(); dealoc($compile('<all class="all" all><!-- directive: all --></all>')($rootScope)); expect(log).toEqual('all; all; all; all'); }); }); it('should use EA rule as the default', function() { module(function() { directive('defaultDir', function(log) { return { compile: function() { log('defaultDir'); } }; }); }); inject(function($rootScope, $compile, log) { dealoc($compile('<span default-dir ></span>')($rootScope)); expect(log).toEqual('defaultDir'); log.reset(); dealoc($compile('<default-dir></default-dir>')($rootScope)); expect(log).toEqual('defaultDir'); log.reset(); dealoc($compile('<span class="default-dir"></span>')($rootScope)); expect(log).toEqual(''); log.reset(); }); }); }); describe('template', function() { beforeEach(module(function() { directive('replace', valueFn({ restrict: 'CAM', replace: true, template: '<div class="log" style="width: 10px" high-log>Replace!</div>', compile: function(element, attr) { attr.$set('compiled', 'COMPILED'); expect(element).toBe(attr.$$element); } })); directive('nomerge', valueFn({ restrict: 'CAM', replace: true, template: '<div class="log" id="myid" high-log>No Merge!</div>', compile: function(element, attr) { attr.$set('compiled', 'COMPILED'); expect(element).toBe(attr.$$element); } })); directive('append', valueFn({ restrict: 'CAM', template: '<div class="log" style="width: 10px" high-log>Append!</div>', compile: function(element, attr) { attr.$set('compiled', 'COMPILED'); expect(element).toBe(attr.$$element); } })); directive('replaceWithInterpolatedClass', valueFn({ replace: true, template: '<div class="class_{{1+1}}">Replace with interpolated class!</div>', compile: function(element, attr) { attr.$set('compiled', 'COMPILED'); expect(element).toBe(attr.$$element); } })); directive('replaceWithInterpolatedStyle', valueFn({ replace: true, template: '<div style="width:{{1+1}}px">Replace with interpolated style!</div>', compile: function(element, attr) { attr.$set('compiled', 'COMPILED'); expect(element).toBe(attr.$$element); } })); directive('replaceWithTr', valueFn({ replace: true, template: '<tr><td>TR</td></tr>' })); directive('replaceWithTd', valueFn({ replace: true, template: '<td>TD</td>' })); directive('replaceWithTh', valueFn({ replace: true, template: '<th>TH</th>' })); directive('replaceWithThead', valueFn({ replace: true, template: '<thead><tr><td>TD</td></tr></thead>' })); directive('replaceWithTbody', valueFn({ replace: true, template: '<tbody><tr><td>TD</td></tr></tbody>' })); directive('replaceWithTfoot', valueFn({ replace: true, template: '<tfoot><tr><td>TD</td></tr></tfoot>' })); directive('replaceWithOption', valueFn({ replace: true, template: '<option>OPTION</option>' })); directive('replaceWithOptgroup', valueFn({ replace: true, template: '<optgroup>OPTGROUP</optgroup>' })); })); it('should replace element with template', inject(function($compile, $rootScope) { element = $compile('<div><div replace>ignore</div><div>')($rootScope); expect(element.text()).toEqual('Replace!'); expect(element.find('div').attr('compiled')).toEqual('COMPILED'); })); it('should append element with template', inject(function($compile, $rootScope) { element = $compile('<div><div append>ignore</div><div>')($rootScope); expect(element.text()).toEqual('Append!'); expect(element.find('div').attr('compiled')).toEqual('COMPILED'); })); it('should compile template when replacing', inject(function($compile, $rootScope, log) { element = $compile('<div><div replace medium-log>ignore</div><div>')($rootScope); $rootScope.$digest(); expect(element.text()).toEqual('Replace!'); expect(log).toEqual('LOG; HIGH; MEDIUM'); })); it('should compile template when appending', inject(function($compile, $rootScope, log) { element = $compile('<div><div append medium-log>ignore</div><div>')($rootScope); $rootScope.$digest(); expect(element.text()).toEqual('Append!'); expect(log).toEqual('LOG; HIGH; MEDIUM'); })); it('should merge attributes including style attr', inject(function($compile, $rootScope) { element = $compile( '<div><div replace class="medium-log" style="height: 20px" ></div><div>')($rootScope); var div = element.find('div'); expect(div.hasClass('medium-log')).toBe(true); expect(div.hasClass('log')).toBe(true); expect(div.css('width')).toBe('10px'); expect(div.css('height')).toBe('20px'); expect(div.attr('replace')).toEqual(''); expect(div.attr('high-log')).toEqual(''); })); it('should not merge attributes if they are the same', inject(function($compile, $rootScope) { element = $compile( '<div><div nomerge class="medium-log" id="myid"></div><div>')($rootScope); var div = element.find('div'); expect(div.hasClass('medium-log')).toBe(true); expect(div.hasClass('log')).toBe(true); expect(div.attr('id')).toEqual('myid'); })); it('should prevent multiple templates per element', inject(function($compile) { try { $compile('<div><span replace class="replace"></span></div>'); this.fail(new Error('should have thrown Multiple directives error')); } catch (e) { expect(e.message).toMatch(/Multiple directives .* asking for template/); } })); it('should play nice with repeater when replacing', inject(function($compile, $rootScope) { element = $compile( '<div>' + '<div ng-repeat="i in [1,2]" replace></div>' + '</div>')($rootScope); $rootScope.$digest(); expect(element.text()).toEqual('Replace!Replace!'); })); it('should play nice with repeater when appending', inject(function($compile, $rootScope) { element = $compile( '<div>' + '<div ng-repeat="i in [1,2]" append></div>' + '</div>')($rootScope); $rootScope.$digest(); expect(element.text()).toEqual('Append!Append!'); })); it('should handle interpolated css class from replacing directive', inject( function($compile, $rootScope) { element = $compile('<div replace-with-interpolated-class></div>')($rootScope); $rootScope.$digest(); expect(element).toHaveClass('class_2'); })); if (!msie || msie > 11) { // style interpolation not working on IE (including IE11). it('should handle interpolated css style from replacing directive', inject( function($compile, $rootScope) { element = $compile('<div replace-with-interpolated-style></div>')($rootScope); $rootScope.$digest(); expect(element.css('width')).toBe('2px'); } )); } it('should merge interpolated css class', inject(function($compile, $rootScope) { element = $compile('<div class="one {{cls}} three" replace></div>')($rootScope); $rootScope.$apply(function() { $rootScope.cls = 'two'; }); expect(element).toHaveClass('one'); expect(element).toHaveClass('two'); // interpolated expect(element).toHaveClass('three'); expect(element).toHaveClass('log'); // merged from replace directive template })); it('should merge interpolated css class with ngRepeat', inject(function($compile, $rootScope) { element = $compile( '<div>' + '<div ng-repeat="i in [1]" class="one {{cls}} three" replace></div>' + '</div>')($rootScope); $rootScope.$apply(function() { $rootScope.cls = 'two'; }); var child = element.find('div').eq(0); expect(child).toHaveClass('one'); expect(child).toHaveClass('two'); // interpolated expect(child).toHaveClass('three'); expect(child).toHaveClass('log'); // merged from replace directive template })); it('should update references to replaced jQuery context', function() { module(function($compileProvider) { $compileProvider.directive('foo', function() { return { replace: true, template: '<div></div>' }; }); }); inject(function($compile, $rootScope) { element = jqLite(document.createElement('span')).attr('foo', ''); expect(nodeName_(element)).toBe('span'); var preCompiledNode = element[0]; var linked = $compile(element)($rootScope); expect(linked).toBe(element); expect(nodeName_(element)).toBe('div'); if (element.context) { expect(element.context).toBe(element[0]); } }); }); it("should fail if replacing and template doesn't have a single root element", function() { module(function() { directive('noRootElem', function() { return { replace: true, template: 'dada' }; }); directive('multiRootElem', function() { return { replace: true, template: '<div></div><div></div>' }; }); directive('singleRootWithWhiteSpace', function() { return { replace: true, template: ' <div></div> \n' }; }); }); inject(function($compile) { expect(function() { $compile('<p no-root-elem></p>'); }).toThrowMinErr("$compile", "tplrt", "Template for directive 'noRootElem' must have exactly one root element. "); expect(function() { $compile('<p multi-root-elem></p>'); }).toThrowMinErr("$compile", "tplrt", "Template for directive 'multiRootElem' must have exactly one root element. "); // ws is ok expect(function() { $compile('<p single-root-with-white-space></p>'); }).not.toThrow(); }); }); it('should support templates with root <tr> tags', inject(function($compile, $rootScope) { expect(function() { element = $compile('<div replace-with-tr></div>')($rootScope); }).not.toThrow(); expect(nodeName_(element)).toMatch(/tr/i); })); it('should support templates with root <td> tags', inject(function($compile, $rootScope) { expect(function() { element = $compile('<div replace-with-td></div>')($rootScope); }).not.toThrow(); expect(nodeName_(element)).toMatch(/td/i); })); it('should support templates with root <th> tags', inject(function($compile, $rootScope) { expect(function() { element = $compile('<div replace-with-th></div>')($rootScope); }).not.toThrow(); expect(nodeName_(element)).toMatch(/th/i); })); it('should support templates with root <thead> tags', inject(function($compile, $rootScope) { expect(function() { element = $compile('<div replace-with-thead></div>')($rootScope); }).not.toThrow(); expect(nodeName_(element)).toMatch(/thead/i); })); it('should support templates with root <tbody> tags', inject(function($compile, $rootScope) { expect(function() { element = $compile('<div replace-with-tbody></div>')($rootScope); }).not.toThrow(); expect(nodeName_(element)).toMatch(/tbody/i); })); it('should support templates with root <tfoot> tags', inject(function($compile, $rootScope) { expect(function() { element = $compile('<div replace-with-tfoot></div>')($rootScope); }).not.toThrow(); expect(nodeName_(element)).toMatch(/tfoot/i); })); it('should support templates with root <option> tags', inject(function($compile, $rootScope) { expect(function() { element = $compile('<div replace-with-option></div>')($rootScope); }).not.toThrow(); expect(nodeName_(element)).toMatch(/option/i); })); it('should support templates with root <optgroup> tags', inject(function($compile, $rootScope) { expect(function() { element = $compile('<div replace-with-optgroup></div>')($rootScope); }).not.toThrow(); expect(nodeName_(element)).toMatch(/optgroup/i); })); it('should support SVG templates using directive.templateNamespace=svg', function() { module(function() { directive('svgAnchor', valueFn({ replace: true, template: '<a xlink:href="{{linkurl}}">{{text}}</a>', templateNamespace: 'SVG', scope: { linkurl: '@svgAnchor', text: '@?' } })); }); inject(function($compile, $rootScope) { element = $compile('<svg><g svg-anchor="/foo/bar" text="foo/bar!"></g></svg>')($rootScope); var child = element.children().eq(0); $rootScope.$digest(); expect(nodeName_(child)).toMatch(/a/i); expect(isSVGElement(child[0])).toBe(true); expect(child[0].href.baseVal).toBe("/foo/bar"); }); }); if (supportsMathML()) { // MathML is only natively supported in Firefox at the time of this test's writing, // and even there, the browser does not export MathML element constructors globally. it('should support MathML templates using directive.templateNamespace=math', function() { module(function() { directive('pow', valueFn({ replace: true, transclude: true, template: '<msup><mn>{{pow}}</mn></msup>', templateNamespace: 'MATH', scope: { pow: '@pow' }, link: function(scope, elm, attr, ctrl, transclude) { transclude(function(node) { elm.prepend(node[0]); }); } })); }); inject(function($compile, $rootScope) { element = $compile('<math><mn pow="2"><mn>8</mn></mn></math>')($rootScope); $rootScope.$digest(); var child = element.children().eq(0); expect(nodeName_(child)).toMatch(/msup/i); expect(isUnknownElement(child[0])).toBe(false); expect(isHTMLElement(child[0])).toBe(false); }); }); } it('should ignore comment nodes when replacing with a template', function() { module(function() { directive('replaceWithComments', valueFn({ replace: true, template: '<!-- ignored comment --><p>Hello, world!</p><!-- ignored comment-->' })); }); inject(function($compile, $rootScope) { expect(function() { element = $compile('<div><div replace-with-comments></div></div>')($rootScope); }).not.toThrow(); expect(element.find('p').length).toBe(1); expect(element.find('p').text()).toBe('Hello, world!'); }); }); it('should keep prototype properties on directive', function() { module(function() { function DirectiveClass() { this.restrict = 'E'; this.template = "<p>{{value}}</p>"; } DirectiveClass.prototype.compile = function() { return function(scope, element, attrs) { scope.value = "Test Value"; }; }; directive('templateUrlWithPrototype', valueFn(new DirectiveClass())); }); inject(function($compile, $rootScope) { element = $compile('<template-url-with-prototype><template-url-with-prototype>')($rootScope); $rootScope.$digest(); expect(element.find("p")[0].innerHTML).toEqual("Test Value"); }); }); }); describe('template as function', function() { beforeEach(module(function() { directive('myDirective', valueFn({ replace: true, template: function($element, $attrs) { expect($element.text()).toBe('original content'); expect($attrs.myDirective).toBe('some value'); return '<div id="templateContent">template content</div>'; }, compile: function($element, $attrs) { expect($element.text()).toBe('template content'); expect($attrs.id).toBe('templateContent'); } })); })); it('should evaluate `template` when defined as fn and use returned string as template', inject( function($compile, $rootScope) { element = $compile('<div my-directive="some value">original content<div>')($rootScope); expect(element.text()).toEqual('template content'); })); }); describe('templateUrl', function() { beforeEach(module( function() { directive('hello', valueFn({ restrict: 'CAM', templateUrl: 'hello.html', transclude: true })); directive('cau', valueFn({ restrict: 'CAM', templateUrl: 'cau.html' })); directive('crossDomainTemplate', valueFn({ restrict: 'CAM', templateUrl: 'http://example.com/should-not-load.html' })); directive('trustedTemplate', function($sce) { return { restrict: 'CAM', templateUrl: function() { return $sce.trustAsResourceUrl('http://example.com/trusted-template.html'); } }; }); directive('cError', valueFn({ restrict: 'CAM', templateUrl:'error.html', compile: function() { throw new Error('cError'); } })); directive('lError', valueFn({ restrict: 'CAM', templateUrl: 'error.html', compile: function() { throw new Error('lError'); } })); directive('iHello', valueFn({ restrict: 'CAM', replace: true, templateUrl: 'hello.html' })); directive('iCau', valueFn({ restrict: 'CAM', replace: true, templateUrl:'cau.html' })); directive('iCError', valueFn({ restrict: 'CAM', replace: true, templateUrl:'error.html', compile: function() { throw new Error('cError'); } })); directive('iLError', valueFn({ restrict: 'CAM', replace: true, templateUrl: 'error.html', compile: function() { throw new Error('lError'); } })); directive('replace', valueFn({ replace: true, template: '<span>Hello, {{name}}!</span>' })); directive('replaceWithTr', valueFn({ replace: true, templateUrl: 'tr.html' })); directive('replaceWithTd', valueFn({ replace: true, templateUrl: 'td.html' })); directive('replaceWithTh', valueFn({ replace: true, templateUrl: 'th.html' })); directive('replaceWithThead', valueFn({ replace: true, templateUrl: 'thead.html' })); directive('replaceWithTbody', valueFn({ replace: true, templateUrl: 'tbody.html' })); directive('replaceWithTfoot', valueFn({ replace: true, templateUrl: 'tfoot.html' })); directive('replaceWithOption', valueFn({ replace: true, templateUrl: 'option.html' })); directive('replaceWithOptgroup', valueFn({ replace: true, templateUrl: 'optgroup.html' })); } )); it('should not load cross domain templates by default', inject( function($compile, $rootScope) { expect(function() { $compile('<div class="crossDomainTemplate"></div>')($rootScope); }).toThrowMinErr('$sce', 'insecurl', 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: http://example.com/should-not-load.html'); } )); it('should trust what is already in the template cache', inject( function($compile, $httpBackend, $rootScope, $templateCache) { $httpBackend.expect('GET', 'http://example.com/should-not-load.html').respond('<span>example.com/remote-version</span>'); $templateCache.put('http://example.com/should-not-load.html', '<span>example.com/cached-version</span>'); element = $compile('<div class="crossDomainTemplate"></div>')($rootScope); expect(sortedHtml(element)).toEqual('<div class="crossDomainTemplate"></div>'); $rootScope.$digest(); expect(sortedHtml(element)).toEqual('<div class="crossDomainTemplate"><span>example.com/cached-version</span></div>'); } )); it('should load cross domain templates when trusted', inject( function($compile, $httpBackend, $rootScope, $sce) { $httpBackend.expect('GET', 'http://example.com/trusted-template.html').respond('<span>example.com/trusted_template_contents</span>'); element = $compile('<div class="trustedTemplate"></div>')($rootScope); expect(sortedHtml(element)). toEqual('<div class="trustedTemplate"></div>'); $httpBackend.flush(); expect(sortedHtml(element)). toEqual('<div class="trustedTemplate"><span>example.com/trusted_template_contents</span></div>'); } )); it('should append template via $http and cache it in $templateCache', inject( function($compile, $httpBackend, $templateCache, $rootScope, $browser) { $httpBackend.expect('GET', 'hello.html').respond('<span>Hello!</span> World!'); $templateCache.put('cau.html', '<span>Cau!</span>'); element = $compile('<div><b class="hello">ignore</b><b class="cau">ignore</b></div>')($rootScope); expect(sortedHtml(element)). toEqual('<div><b class="hello"></b><b class="cau"></b></div>'); $rootScope.$digest(); expect(sortedHtml(element)). toEqual('<div><b class="hello"></b><b class="cau"><span>Cau!</span></b></div>'); $httpBackend.flush(); expect(sortedHtml(element)).toEqual( '<div>' + '<b class="hello"><span>Hello!</span> World!</b>' + '<b class="cau"><span>Cau!</span></b>' + '</div>'); } )); it('should inline template via $http and cache it in $templateCache', inject( function($compile, $httpBackend, $templateCache, $rootScope) { $httpBackend.expect('GET', 'hello.html').respond('<span>Hello!</span>'); $templateCache.put('cau.html', '<span>Cau!</span>'); element = $compile('<div><b class=i-hello>ignore</b><b class=i-cau>ignore</b></div>')($rootScope); expect(sortedHtml(element)). toEqual('<div><b class="i-hello"></b><b class="i-cau"></b></div>'); $rootScope.$digest(); expect(sortedHtml(element)).toBe('<div><b class="i-hello"></b><span class="i-cau">Cau!</span></div>'); $httpBackend.flush(); expect(sortedHtml(element)).toBe('<div><span class="i-hello">Hello!</span><span class="i-cau">Cau!</span></div>'); } )); it('should compile, link and flush the template append', inject( function($compile, $templateCache, $rootScope, $browser) { $templateCache.put('hello.html', '<span>Hello, {{name}}!</span>'); $rootScope.name = 'Elvis'; element = $compile('<div><b class="hello"></b></div>')($rootScope); $rootScope.$digest(); expect(sortedHtml(element)). toEqual('<div><b class="hello"><span>Hello, Elvis!</span></b></div>'); } )); it('should compile, link and flush the template inline', inject( function($compile, $templateCache, $rootScope) { $templateCache.put('hello.html', '<span>Hello, {{name}}!</span>'); $rootScope.name = 'Elvis'; element = $compile('<div><b class=i-hello></b></div>')($rootScope); $rootScope.$digest(); expect(sortedHtml(element)).toBe('<div><span class="i-hello">Hello, Elvis!</span></div>'); } )); it('should compile, flush and link the template append', inject( function($compile, $templateCache, $rootScope) { $templateCache.put('hello.html', '<span>Hello, {{name}}!</span>'); $rootScope.name = 'Elvis'; var template = $compile('<div><b class="hello"></b></div>'); element = template($rootScope); $rootScope.$digest(); expect(sortedHtml(element)). toEqual('<div><b class="hello"><span>Hello, Elvis!</span></b></div>'); } )); it('should compile, flush and link the template inline', inject( function($compile, $templateCache, $rootScope) { $templateCache.put('hello.html', '<span>Hello, {{name}}!</span>'); $rootScope.name = 'Elvis'; var template = $compile('<div><b class=i-hello></b></div>'); element = template($rootScope); $rootScope.$digest(); expect(sortedHtml(element)).toBe('<div><span class="i-hello">Hello, Elvis!</span></div>'); } )); it('should compile template when replacing element in another template', inject(function($compile, $templateCache, $rootScope) { $templateCache.put('hello.html', '<div replace></div>'); $rootScope.name = 'Elvis'; element = $compile('<div><b class="hello"></b></div>')($rootScope); $rootScope.$digest(); expect(sortedHtml(element)). toEqual('<div><b class="hello"><span replace="">Hello, Elvis!</span></b></div>'); })); it('should compile template when replacing root element', inject(function($compile, $templateCache, $rootScope) { $rootScope.name = 'Elvis'; element = $compile('<div replace></div>')($rootScope); $rootScope.$digest(); expect(sortedHtml(element)). toEqual('<span replace="">Hello, Elvis!</span>'); })); it('should resolve widgets after cloning in append mode', function() { module(function($exceptionHandlerProvider) { $exceptionHandlerProvider.mode('log'); }); inject(function($compile, $templateCache, $rootScope, $httpBackend, $browser, $exceptionHandler) { $httpBackend.expect('GET', 'hello.html').respond('<span>{{greeting}} </span>'); $httpBackend.expect('GET', 'error.html').respond('<div></div>'); $templateCache.put('cau.html', '<span>{{name}}</span>'); $rootScope.greeting = 'Hello'; $rootScope.name = 'Elvis'; var template = $compile( '<div>' + '<b class="hello"></b>' + '<b class="cau"></b>' + '<b class=c-error></b>' + '<b class=l-error></b>' + '</div>'); var e1; var e2; e1 = template($rootScope.$new(), noop); // clone expect(e1.text()).toEqual(''); $httpBackend.flush(); e2 = template($rootScope.$new(), noop); // clone $rootScope.$digest(); expect(e1.text()).toEqual('Hello Elvis'); expect(e2.text()).toEqual('Hello Elvis'); expect($exceptionHandler.errors.length).toEqual(2); expect($exceptionHandler.errors[0][0].message).toEqual('cError'); expect($exceptionHandler.errors[1][0].message).toEqual('lError'); dealoc(e1); dealoc(e2); }); }); it('should resolve widgets after cloning in append mode without $templateCache', function() { module(function($exceptionHandlerProvider) { $exceptionHandlerProvider.mode('log'); }); inject(function($compile, $templateCache, $rootScope, $httpBackend, $browser, $exceptionHandler) { $httpBackend.expect('GET', 'cau.html').respond('<span>{{name}}</span>'); $rootScope.name = 'Elvis'; var template = $compile('<div class="cau"></div>'); var e1; var e2; e1 = template($rootScope.$new(), noop); // clone expect(e1.text()).toEqual(''); $httpBackend.flush(); e2 = template($rootScope.$new(), noop); // clone $rootScope.$digest(); expect(e1.text()).toEqual('Elvis'); expect(e2.text()).toEqual('Elvis'); dealoc(e1); dealoc(e2); }); }); it('should resolve widgets after cloning in inline mode', function() { module(function($exceptionHandlerProvider) { $exceptionHandlerProvider.mode('log'); }); inject(function($compile, $templateCache, $rootScope, $httpBackend, $browser, $exceptionHandler) { $httpBackend.expect('GET', 'hello.html').respond('<span>{{greeting}} </span>'); $httpBackend.expect('GET', 'error.html').respond('<div></div>'); $templateCache.put('cau.html', '<span>{{name}}</span>'); $rootScope.greeting = 'Hello'; $rootScope.name = 'Elvis'; var template = $compile( '<div>' + '<b class=i-hello></b>' + '<b class=i-cau></b>' + '<b class=i-c-error></b>' + '<b class=i-l-error></b>' + '</div>'); var e1; var e2; e1 = template($rootScope.$new(), noop); // clone expect(e1.text()).toEqual(''); $httpBackend.flush(); e2 = template($rootScope.$new(), noop); // clone $rootScope.$digest(); expect(e1.text()).toEqual('Hello Elvis'); expect(e2.text()).toEqual('Hello Elvis'); expect($exceptionHandler.errors.length).toEqual(2); expect($exceptionHandler.errors[0][0].message).toEqual('cError'); expect($exceptionHandler.errors[1][0].message).toEqual('lError'); dealoc(e1); dealoc(e2); }); }); it('should resolve widgets after cloning in inline mode without $templateCache', function() { module(function($exceptionHandlerProvider) { $exceptionHandlerProvider.mode('log'); }); inject(function($compile, $templateCache, $rootScope, $httpBackend, $browser, $exceptionHandler) { $httpBackend.expect('GET', 'cau.html').respond('<span>{{name}}</span>'); $rootScope.name = 'Elvis'; var template = $compile('<div class="i-cau"></div>'); var e1; var e2; e1 = template($rootScope.$new(), noop); // clone expect(e1.text()).toEqual(''); $httpBackend.flush(); e2 = template($rootScope.$new(), noop); // clone $rootScope.$digest(); expect(e1.text()).toEqual('Elvis'); expect(e2.text()).toEqual('Elvis'); dealoc(e1); dealoc(e2); }); }); it('should be implicitly terminal and not compile placeholder content in append', inject( function($compile, $templateCache, $rootScope, log) { // we can't compile the contents because that would result in a memory leak $templateCache.put('hello.html', 'Hello!'); element = $compile('<div><b class="hello"><div log></div></b></div>')($rootScope); expect(log).toEqual(''); } )); it('should be implicitly terminal and not compile placeholder content in inline', inject( function($compile, $templateCache, $rootScope, log) { // we can't compile the contents because that would result in a memory leak $templateCache.put('hello.html', 'Hello!'); element = $compile('<div><b class=i-hello><div log></div></b></div>')($rootScope); expect(log).toEqual(''); } )); it('should throw an error and clear element content if the template fails to load', inject( function($compile, $httpBackend, $rootScope) { $httpBackend.expect('GET', 'hello.html').respond(404, 'Not Found!'); element = $compile('<div><b class="hello">content</b></div>')($rootScope); expect(function() { $httpBackend.flush(); }).toThrowMinErr('$compile', 'tpload', 'Failed to load template: hello.html'); expect(sortedHtml(element)).toBe('<div><b class="hello"></b></div>'); } )); it('should prevent multiple templates per element', function() { module(function() { directive('sync', valueFn({ restrict: 'C', template: '<span></span>' })); directive('async', valueFn({ restrict: 'C', templateUrl: 'template.html' })); }); inject(function($compile, $httpBackend) { $httpBackend.whenGET('template.html').respond('<p>template.html</p>'); expect(function() { $compile('<div><div class="sync async"></div></div>'); $httpBackend.flush(); }).toThrowMinErr('$compile', 'multidir', 'Multiple directives [async, sync] asking for template on: ' + '<div class="sync async">'); }); }); it('should copy classes from pre-template node into linked element', function() { module(function() { directive('test', valueFn({ templateUrl: 'test.html', replace: true })); }); inject(function($compile, $templateCache, $rootScope) { var child; $templateCache.put('test.html', '<p class="template-class">Hello</p>'); element = $compile('<div test></div>')($rootScope, function(node) { node.addClass('clonefn-class'); }); $rootScope.$digest(); expect(element).toHaveClass('template-class'); expect(element).toHaveClass('clonefn-class'); }); }); describe('delay compile / linking functions until after template is resolved', function() { var template; beforeEach(module(function() { function logDirective(name, priority, options) { directive(name, function(log) { return (extend({ priority: priority, compile: function() { log(name + '-C'); return { pre: function() { log(name + '-PreL'); }, post: function() { log(name + '-PostL'); } }; } }, options || {})); }); } logDirective('first', 10); logDirective('second', 5, { templateUrl: 'second.html' }); logDirective('third', 3); logDirective('last', 0); logDirective('iFirst', 10, {replace: true}); logDirective('iSecond', 5, {replace: true, templateUrl: 'second.html' }); logDirective('iThird', 3, {replace: true}); logDirective('iLast', 0, {replace: true}); })); it('should flush after link append', inject( function($compile, $rootScope, $httpBackend, log) { $httpBackend.expect('GET', 'second.html').respond('<div third>{{1+2}}</div>'); template = $compile('<div><span first second last></span></div>'); element = template($rootScope); expect(log).toEqual('first-C'); log('FLUSH'); $httpBackend.flush(); $rootScope.$digest(); expect(log).toEqual( 'first-C; FLUSH; second-C; last-C; third-C; ' + 'first-PreL; second-PreL; last-PreL; third-PreL; ' + 'third-PostL; last-PostL; second-PostL; first-PostL'); var span = element.find('span'); expect(span.attr('first')).toEqual(''); expect(span.attr('second')).toEqual(''); expect(span.find('div').attr('third')).toEqual(''); expect(span.attr('last')).toEqual(''); expect(span.text()).toEqual('3'); })); it('should flush after link inline', inject( function($compile, $rootScope, $httpBackend, log) { $httpBackend.expect('GET', 'second.html').respond('<div i-third>{{1+2}}</div>'); template = $compile('<div><span i-first i-second i-last></span></div>'); element = template($rootScope); expect(log).toEqual('iFirst-C'); log('FLUSH'); $httpBackend.flush(); $rootScope.$digest(); expect(log).toEqual( 'iFirst-C; FLUSH; iSecond-C; iThird-C; iLast-C; ' + 'iFirst-PreL; iSecond-PreL; iThird-PreL; iLast-PreL; ' + 'iLast-PostL; iThird-PostL; iSecond-PostL; iFirst-PostL'); var div = element.find('div'); expect(div.attr('i-first')).toEqual(''); expect(div.attr('i-second')).toEqual(''); expect(div.attr('i-third')).toEqual(''); expect(div.attr('i-last')).toEqual(''); expect(div.text()).toEqual('3'); })); it('should flush before link append', inject( function($compile, $rootScope, $httpBackend, log) { $httpBackend.expect('GET', 'second.html').respond('<div third>{{1+2}}</div>'); template = $compile('<div><span first second last></span></div>'); expect(log).toEqual('first-C'); log('FLUSH'); $httpBackend.flush(); expect(log).toEqual('first-C; FLUSH; second-C; last-C; third-C'); element = template($rootScope); $rootScope.$digest(); expect(log).toEqual( 'first-C; FLUSH; second-C; last-C; third-C; ' + 'first-PreL; second-PreL; last-PreL; third-PreL; ' + 'third-PostL; last-PostL; second-PostL; first-PostL'); var span = element.find('span'); expect(span.attr('first')).toEqual(''); expect(span.attr('second')).toEqual(''); expect(span.find('div').attr('third')).toEqual(''); expect(span.attr('last')).toEqual(''); expect(span.text()).toEqual('3'); })); it('should flush before link inline', inject( function($compile, $rootScope, $httpBackend, log) { $httpBackend.expect('GET', 'second.html').respond('<div i-third>{{1+2}}</div>'); template = $compile('<div><span i-first i-second i-last></span></div>'); expect(log).toEqual('iFirst-C'); log('FLUSH'); $httpBackend.flush(); expect(log).toEqual('iFirst-C; FLUSH; iSecond-C; iThird-C; iLast-C'); element = template($rootScope); $rootScope.$digest(); expect(log).toEqual( 'iFirst-C; FLUSH; iSecond-C; iThird-C; iLast-C; ' + 'iFirst-PreL; iSecond-PreL; iThird-PreL; iLast-PreL; ' + 'iLast-PostL; iThird-PostL; iSecond-PostL; iFirst-PostL'); var div = element.find('div'); expect(div.attr('i-first')).toEqual(''); expect(div.attr('i-second')).toEqual(''); expect(div.attr('i-third')).toEqual(''); expect(div.attr('i-last')).toEqual(''); expect(div.text()).toEqual('3'); })); }); it('should allow multiple elements in template', inject(function($compile, $httpBackend) { $httpBackend.expect('GET', 'hello.html').respond('before <b>mid</b> after'); element = jqLite('<div hello></div>'); $compile(element); $httpBackend.flush(); expect(element.text()).toEqual('before mid after'); })); it('should work when directive is on the root element', inject( function($compile, $httpBackend, $rootScope) { $httpBackend.expect('GET', 'hello.html'). respond('<span>3==<span ng-transclude></span></span>'); element = jqLite('<b class="hello">{{1+2}}</b>'); $compile(element)($rootScope); $httpBackend.flush(); expect(element.text()).toEqual('3==3'); } )); it('should work when directive is in a repeater', inject( function($compile, $httpBackend, $rootScope) { $httpBackend.expect('GET', 'hello.html'). respond('<span>i=<span ng-transclude></span>;</span>'); element = jqLite('<div><b class=hello ng-repeat="i in [1,2]">{{i}}</b></div>'); $compile(element)($rootScope); $httpBackend.flush(); expect(element.text()).toEqual('i=1;i=2;'); } )); it("should fail if replacing and template doesn't have a single root element", function() { module(function($exceptionHandlerProvider) { $exceptionHandlerProvider.mode('log'); directive('template', function() { return { replace: true, templateUrl: 'template.html' }; }); }); inject(function($compile, $templateCache, $rootScope, $exceptionHandler) { // no root element $templateCache.put('template.html', 'dada'); $compile('<p template></p>'); $rootScope.$digest(); expect($exceptionHandler.errors.pop().message). toMatch(/\[\$compile:tplrt\] Template for directive 'template' must have exactly one root element\. template\.html/); // multi root $templateCache.put('template.html', '<div></div><div></div>'); $compile('<p template></p>'); $rootScope.$digest(); expect($exceptionHandler.errors.pop().message). toMatch(/\[\$compile:tplrt\] Template for directive 'template' must have exactly one root element\. template\.html/); // ws is ok $templateCache.put('template.html', ' <div></div> \n'); $compile('<p template></p>'); $rootScope.$apply(); expect($exceptionHandler.errors).toEqual([]); }); }); it('should resume delayed compilation without duplicates when in a repeater', function() { // this is a test for a regression // scope creation, isolate watcher setup, controller instantiation, etc should happen // only once even if we are dealing with delayed compilation of a node due to templateUrl // and the template node is in a repeater var controllerSpy = jasmine.createSpy('controller'); module(function($compileProvider) { $compileProvider.directive('delayed', valueFn({ controller: controllerSpy, templateUrl: 'delayed.html', scope: { title: '@' } })); }); inject(function($templateCache, $compile, $rootScope) { $rootScope.coolTitle = 'boom!'; $templateCache.put('delayed.html', '<div>{{title}}</div>'); element = $compile( '<div><div ng-repeat="i in [1,2]"><div delayed title="{{coolTitle + i}}"></div>|</div></div>' )($rootScope); $rootScope.$apply(); expect(controllerSpy.callCount).toBe(2); expect(element.text()).toBe('boom!1|boom!2|'); }); }); it('should support templateUrl with replace', function() { // a regression https://github.com/angular/angular.js/issues/3792 module(function($compileProvider) { $compileProvider.directive('simple', function() { return { templateUrl: '/some.html', replace: true }; }); }); inject(function($templateCache, $rootScope, $compile) { $templateCache.put('/some.html', '<div ng-switch="i">' + '<div ng-switch-when="1">i = 1</div>' + '<div ng-switch-default>I dont know what `i` is.</div>' + '</div>'); element = $compile('<div simple></div>')($rootScope); $rootScope.$apply(function() { $rootScope.i = 1; }); expect(element.html()).toContain('i = 1'); }); }); it('should support templates with root <tr> tags', inject(function($compile, $rootScope, $templateCache) { $templateCache.put('tr.html', '<tr><td>TR</td></tr>'); expect(function() { element = $compile('<div replace-with-tr></div>')($rootScope); }).not.toThrow(); $rootScope.$digest(); expect(nodeName_(element)).toMatch(/tr/i); })); it('should support templates with root <td> tags', inject(function($compile, $rootScope, $templateCache) { $templateCache.put('td.html', '<td>TD</td>'); expect(function() { element = $compile('<div replace-with-td></div>')($rootScope); }).not.toThrow(); $rootScope.$digest(); expect(nodeName_(element)).toMatch(/td/i); })); it('should support templates with root <th> tags', inject(function($compile, $rootScope, $templateCache) { $templateCache.put('th.html', '<th>TH</th>'); expect(function() { element = $compile('<div replace-with-th></div>')($rootScope); }).not.toThrow(); $rootScope.$digest(); expect(nodeName_(element)).toMatch(/th/i); })); it('should support templates with root <thead> tags', inject(function($compile, $rootScope, $templateCache) { $templateCache.put('thead.html', '<thead><tr><td>TD</td></tr></thead>'); expect(function() { element = $compile('<div replace-with-thead></div>')($rootScope); }).not.toThrow(); $rootScope.$digest(); expect(nodeName_(element)).toMatch(/thead/i); })); it('should support templates with root <tbody> tags', inject(function($compile, $rootScope, $templateCache) { $templateCache.put('tbody.html', '<tbody><tr><td>TD</td></tr></tbody>'); expect(function() { element = $compile('<div replace-with-tbody></div>')($rootScope); }).not.toThrow(); $rootScope.$digest(); expect(nodeName_(element)).toMatch(/tbody/i); })); it('should support templates with root <tfoot> tags', inject(function($compile, $rootScope, $templateCache) { $templateCache.put('tfoot.html', '<tfoot><tr><td>TD</td></tr></tfoot>'); expect(function() { element = $compile('<div replace-with-tfoot></div>')($rootScope); }).not.toThrow(); $rootScope.$digest(); expect(nodeName_(element)).toMatch(/tfoot/i); })); it('should support templates with root <option> tags', inject(function($compile, $rootScope, $templateCache) { $templateCache.put('option.html', '<option>OPTION</option>'); expect(function() { element = $compile('<div replace-with-option></div>')($rootScope); }).not.toThrow(); $rootScope.$digest(); expect(nodeName_(element)).toMatch(/option/i); })); it('should support templates with root <optgroup> tags', inject(function($compile, $rootScope, $templateCache) { $templateCache.put('optgroup.html', '<optgroup>OPTGROUP</optgroup>'); expect(function() { element = $compile('<div replace-with-optgroup></div>')($rootScope); }).not.toThrow(); $rootScope.$digest(); expect(nodeName_(element)).toMatch(/optgroup/i); })); it('should support SVG templates using directive.templateNamespace=svg', function() { module(function() { directive('svgAnchor', valueFn({ replace: true, templateUrl: 'template.html', templateNamespace: 'SVG', scope: { linkurl: '@svgAnchor', text: '@?' } })); }); inject(function($compile, $rootScope, $templateCache) { $templateCache.put('template.html', '<a xlink:href="{{linkurl}}">{{text}}</a>'); element = $compile('<svg><g svg-anchor="/foo/bar" text="foo/bar!"></g></svg>')($rootScope); $rootScope.$digest(); var child = element.children().eq(0); expect(nodeName_(child)).toMatch(/a/i); expect(isSVGElement(child[0])).toBe(true); expect(child[0].href.baseVal).toBe("/foo/bar"); }); }); if (supportsMathML()) { // MathML is only natively supported in Firefox at the time of this test's writing, // and even there, the browser does not export MathML element constructors globally. it('should support MathML templates using directive.templateNamespace=math', function() { module(function() { directive('pow', valueFn({ replace: true, transclude: true, templateUrl: 'template.html', templateNamespace: 'math', scope: { pow: '@pow' }, link: function(scope, elm, attr, ctrl, transclude) { transclude(function(node) { elm.prepend(node[0]); }); } })); }); inject(function($compile, $rootScope, $templateCache) { $templateCache.put('template.html', '<msup><mn>{{pow}}</mn></msup>'); element = $compile('<math><mn pow="2"><mn>8</mn></mn></math>')($rootScope); $rootScope.$digest(); var child = element.children().eq(0); expect(nodeName_(child)).toMatch(/msup/i); expect(isUnknownElement(child[0])).toBe(false); expect(isHTMLElement(child[0])).toBe(false); }); }); } it('should ignore comment nodes when replacing with a templateUrl', function() { module(function() { directive('replaceWithComments', valueFn({ replace: true, templateUrl: 'templateWithComments.html' })); }); inject(function($compile, $rootScope, $httpBackend) { $httpBackend.whenGET('templateWithComments.html'). respond('<!-- ignored comment --><p>Hello, world!</p><!-- ignored comment-->'); expect(function() { element = $compile('<div><div replace-with-comments></div></div>')($rootScope); }).not.toThrow(); $httpBackend.flush(); expect(element.find('p').length).toBe(1); expect(element.find('p').text()).toBe('Hello, world!'); }); }); it('should keep prototype properties on sync version of async directive', function() { module(function() { function DirectiveClass() { this.restrict = 'E'; this.templateUrl = "test.html"; } DirectiveClass.prototype.compile = function() { return function(scope, element, attrs) { scope.value = "Test Value"; }; }; directive('templateUrlWithPrototype', valueFn(new DirectiveClass())); }); inject(function($compile, $rootScope, $httpBackend) { $httpBackend.whenGET('test.html'). respond('<p>{{value}}</p>'); element = $compile('<template-url-with-prototype><template-url-with-prototype>')($rootScope); $httpBackend.flush(); $rootScope.$digest(); expect(element.find("p")[0].innerHTML).toEqual("Test Value"); }); }); }); describe('templateUrl as function', function() { beforeEach(module(function() { directive('myDirective', valueFn({ replace: true, templateUrl: function($element, $attrs) { expect($element.text()).toBe('original content'); expect($attrs.myDirective).toBe('some value'); return 'my-directive.html'; }, compile: function($element, $attrs) { expect($element.text()).toBe('template content'); expect($attrs.id).toBe('templateContent'); } })); })); it('should evaluate `templateUrl` when defined as fn and use returned value as url', inject( function($compile, $rootScope, $templateCache) { $templateCache.put('my-directive.html', '<div id="templateContent">template content</span>'); element = $compile('<div my-directive="some value">original content<div>')($rootScope); expect(element.text()).toEqual(''); $rootScope.$digest(); expect(element.text()).toEqual('template content'); })); }); describe('scope', function() { var iscope; beforeEach(module(function() { forEach(['', 'a', 'b'], function(name) { directive('scope' + uppercase(name), function(log) { return { scope: true, restrict: 'CA', compile: function() { return {pre: function(scope, element) { log(scope.$id); expect(element.data('$scope')).toBe(scope); }}; } }; }); directive('iscope' + uppercase(name), function(log) { return { scope: {}, restrict: 'CA', compile: function() { return function(scope, element) { iscope = scope; log(scope.$id); expect(element.data('$isolateScopeNoTemplate')).toBe(scope); }; } }; }); directive('tscope' + uppercase(name), function(log) { return { scope: true, restrict: 'CA', templateUrl: 'tscope.html', compile: function() { return function(scope, element) { log(scope.$id); expect(element.data('$scope')).toBe(scope); }; } }; }); directive('stscope' + uppercase(name), function(log) { return { scope: true, restrict: 'CA', template: '<span></span>', compile: function() { return function(scope, element) { log(scope.$id); expect(element.data('$scope')).toBe(scope); }; } }; }); directive('trscope' + uppercase(name), function(log) { return { scope: true, replace: true, restrict: 'CA', templateUrl: 'trscope.html', compile: function() { return function(scope, element) { log(scope.$id); expect(element.data('$scope')).toBe(scope); }; } }; }); directive('tiscope' + uppercase(name), function(log) { return { scope: {}, restrict: 'CA', templateUrl: 'tiscope.html', compile: function() { return function(scope, element) { iscope = scope; log(scope.$id); expect(element.data('$isolateScope')).toBe(scope); }; } }; }); directive('stiscope' + uppercase(name), function(log) { return { scope: {}, restrict: 'CA', template: '<span></span>', compile: function() { return function(scope, element) { iscope = scope; log(scope.$id); expect(element.data('$isolateScope')).toBe(scope); }; } }; }); }); directive('log', function(log) { return { restrict: 'CA', link: {pre: function(scope) { log('log-' + scope.$id + '-' + (scope.$parent && scope.$parent.$id || 'no-parent')); }} }; }); directive('prototypeMethodNameAsScopeVarA', function() { return { scope: { 'constructor': '=?', 'valueOf': '=' }, restrict: 'AE', template: '<span></span>' }; }); directive('prototypeMethodNameAsScopeVarB', function() { return { scope: { 'constructor': '@?', 'valueOf': '@' }, restrict: 'AE', template: '<span></span>' }; }); directive('prototypeMethodNameAsScopeVarC', function() { return { scope: { 'constructor': '&?', 'valueOf': '&' }, restrict: 'AE', template: '<span></span>' }; }); directive('watchAsScopeVar', function() { return { scope: { 'watch': '=' }, restrict: 'AE', template: '<span></span>' }; }); })); it('should allow creation of new scopes', inject(function($rootScope, $compile, log) { element = $compile('<div><span scope><a log></a></span></div>')($rootScope); expect(log).toEqual('2; log-2-1; LOG'); expect(element.find('span').hasClass('ng-scope')).toBe(true); })); it('should allow creation of new isolated scopes for directives', inject( function($rootScope, $compile, log) { element = $compile('<div><span iscope><a log></a></span></div>')($rootScope); expect(log).toEqual('log-1-no-parent; LOG; 2'); $rootScope.name = 'abc'; expect(iscope.$parent).toBe($rootScope); expect(iscope.name).toBeUndefined(); })); it('should allow creation of new scopes for directives with templates', inject( function($rootScope, $compile, log, $httpBackend) { $httpBackend.expect('GET', 'tscope.html').respond('<a log>{{name}}; scopeId: {{$id}}</a>'); element = $compile('<div><span tscope></span></div>')($rootScope); $httpBackend.flush(); expect(log).toEqual('log-2-1; LOG; 2'); $rootScope.name = 'Jozo'; $rootScope.$apply(); expect(element.text()).toBe('Jozo; scopeId: 2'); expect(element.find('span').scope().$id).toBe(2); })); it('should allow creation of new scopes for replace directives with templates', inject( function($rootScope, $compile, log, $httpBackend) { $httpBackend.expect('GET', 'trscope.html'). respond('<p><a log>{{name}}; scopeId: {{$id}}</a></p>'); element = $compile('<div><span trscope></span></div>')($rootScope); $httpBackend.flush(); expect(log).toEqual('log-2-1; LOG; 2'); $rootScope.name = 'Jozo'; $rootScope.$apply(); expect(element.text()).toBe('Jozo; scopeId: 2'); expect(element.find('a').scope().$id).toBe(2); })); it('should allow creation of new scopes for replace directives with templates in a repeater', inject(function($rootScope, $compile, log, $httpBackend) { $httpBackend.expect('GET', 'trscope.html'). respond('<p><a log>{{name}}; scopeId: {{$id}} |</a></p>'); element = $compile('<div><span ng-repeat="i in [1,2,3]" trscope></span></div>')($rootScope); $httpBackend.flush(); expect(log).toEqual('log-3-2; LOG; 3; log-5-4; LOG; 5; log-7-6; LOG; 7'); $rootScope.name = 'Jozo'; $rootScope.$apply(); expect(element.text()).toBe('Jozo; scopeId: 3 |Jozo; scopeId: 5 |Jozo; scopeId: 7 |'); expect(element.find('p').scope().$id).toBe(3); expect(element.find('a').scope().$id).toBe(3); })); it('should allow creation of new isolated scopes for directives with templates', inject( function($rootScope, $compile, log, $httpBackend) { $httpBackend.expect('GET', 'tiscope.html').respond('<a log></a>'); element = $compile('<div><span tiscope></span></div>')($rootScope); $httpBackend.flush(); expect(log).toEqual('log-2-1; LOG; 2'); $rootScope.name = 'abc'; expect(iscope.$parent).toBe($rootScope); expect(iscope.name).toBeUndefined(); })); it('should correctly create the scope hierachy', inject( function($rootScope, $compile, log) { element = $compile( '<div>' + //1 '<b class=scope>' + //2 '<b class=scope><b class=log></b></b>' + //3 '<b class=log></b>' + '</b>' + '<b class=scope>' + //4 '<b class=log></b>' + '</b>' + '</div>' )($rootScope); expect(log).toEqual('2; 3; log-3-2; LOG; log-2-1; LOG; 4; log-4-1; LOG'); }) ); it('should allow more than one new scope directives per element, but directives should share' + 'the scope', inject( function($rootScope, $compile, log) { element = $compile('<div class="scope-a; scope-b"></div>')($rootScope); expect(log).toEqual('2; 2'); }) ); it('should not allow more than one isolate scope creation per element', inject( function($rootScope, $compile) { expect(function() { $compile('<div class="iscope-a; scope-b"></div>'); }).toThrowMinErr('$compile', 'multidir', 'Multiple directives [iscopeA, scopeB] asking for new/isolated scope on: ' + '<div class="iscope-a; scope-b">'); }) ); it('should not allow more than one isolate/new scope creation per element regardless of `templateUrl`', inject(function($httpBackend) { $httpBackend.expect('GET', 'tiscope.html').respond('<div>Hello, world !</div>'); expect(function() { compile('<div class="tiscope-a; scope-b"></div>'); $httpBackend.flush(); }).toThrowMinErr('$compile', 'multidir', 'Multiple directives [scopeB, tiscopeA] ' + 'asking for new/isolated scope on: <div class="tiscope-a; scope-b ng-scope">'); }) ); it('should not allow more than one isolate scope creation per element regardless of directive priority', function() { module(function($compileProvider) { $compileProvider.directive('highPriorityScope', function() { return { restrict: 'C', priority: 1, scope: true, link: function() {} }; }); }); inject(function($compile) { expect(function() { $compile('<div class="iscope-a; high-priority-scope"></div>'); }).toThrowMinErr('$compile', 'multidir', 'Multiple directives [highPriorityScope, iscopeA] asking for new/isolated scope on: ' + '<div class="iscope-a; high-priority-scope">'); }); }); it('should create new scope even at the root of the template', inject( function($rootScope, $compile, log) { element = $compile('<div scope-a></div>')($rootScope); expect(log).toEqual('2'); }) ); it('should create isolate scope even at the root of the template', inject( function($rootScope, $compile, log) { element = $compile('<div iscope></div>')($rootScope); expect(log).toEqual('2'); }) ); describe('scope()/isolate() scope getters', function() { describe('with no directives', function() { it('should return the scope of the parent node', inject( function($rootScope, $compile) { element = $compile('<div></div>')($rootScope); expect(element.scope()).toBe($rootScope); }) ); }); describe('with new scope directives', function() { it('should return the new scope at the directive element', inject( function($rootScope, $compile) { element = $compile('<div scope></div>')($rootScope); expect(element.scope().$parent).toBe($rootScope); }) ); it('should return the new scope for children in the original template', inject( function($rootScope, $compile) { element = $compile('<div scope><a></a></div>')($rootScope); expect(element.find('a').scope().$parent).toBe($rootScope); }) ); it('should return the new scope for children in the directive template', inject( function($rootScope, $compile, $httpBackend) { $httpBackend.expect('GET', 'tscope.html').respond('<a></a>'); element = $compile('<div tscope></div>')($rootScope); $httpBackend.flush(); expect(element.find('a').scope().$parent).toBe($rootScope); }) ); it('should return the new scope for children in the directive sync template', inject( function($rootScope, $compile) { element = $compile('<div stscope></div>')($rootScope); expect(element.find('span').scope().$parent).toBe($rootScope); }) ); }); describe('with isolate scope directives', function() { it('should return the root scope for directives at the root element', inject( function($rootScope, $compile) { element = $compile('<div iscope></div>')($rootScope); expect(element.scope()).toBe($rootScope); }) ); it('should return the non-isolate scope at the directive element', inject( function($rootScope, $compile) { var directiveElement; element = $compile('<div><div iscope></div></div>')($rootScope); directiveElement = element.children(); expect(directiveElement.scope()).toBe($rootScope); expect(directiveElement.isolateScope().$parent).toBe($rootScope); }) ); it('should return the isolate scope for children in the original template', inject( function($rootScope, $compile) { element = $compile('<div iscope><a></a></div>')($rootScope); expect(element.find('a').scope()).toBe($rootScope); //xx }) ); it('should return the isolate scope for children in directive template', inject( function($rootScope, $compile, $httpBackend) { $httpBackend.expect('GET', 'tiscope.html').respond('<a></a>'); element = $compile('<div tiscope></div>')($rootScope); expect(element.isolateScope()).toBeUndefined(); // this is the current behavior, not desired feature $httpBackend.flush(); expect(element.find('a').scope()).toBe(element.isolateScope()); expect(element.isolateScope()).not.toBe($rootScope); }) ); it('should return the isolate scope for children in directive sync template', inject( function($rootScope, $compile) { element = $compile('<div stiscope></div>')($rootScope); expect(element.find('span').scope()).toBe(element.isolateScope()); expect(element.isolateScope()).not.toBe($rootScope); }) ); it('should handle "=" bindings with same method names in Object.prototype correctly when not present', inject( function($rootScope, $compile) { var func = function() { element = $compile( '<div prototype-method-name-as-scope-var-a></div>' )($rootScope); }; expect(func).not.toThrow(); var scope = element.isolateScope(); expect(element.find('span').scope()).toBe(scope); expect(scope).not.toBe($rootScope); // Not shadowed because optional expect(scope.constructor).toBe($rootScope.constructor); expect(scope.hasOwnProperty('constructor')).toBe(false); // Shadowed with undefined because not optional expect(scope.valueOf).toBeUndefined(); expect(scope.hasOwnProperty('valueOf')).toBe(true); }) ); it('should handle "=" bindings with same method names in Object.prototype correctly when present', inject( function($rootScope, $compile) { $rootScope.constructor = 'constructor'; $rootScope.valueOf = 'valueOf'; var func = function() { element = $compile( '<div prototype-method-name-as-scope-var-a constructor="constructor" value-of="valueOf"></div>' )($rootScope); }; expect(func).not.toThrow(); var scope = element.isolateScope(); expect(element.find('span').scope()).toBe(scope); expect(scope).not.toBe($rootScope); expect(scope.constructor).toBe('constructor'); expect(scope.hasOwnProperty('constructor')).toBe(true); expect(scope.valueOf).toBe('valueOf'); expect(scope.hasOwnProperty('valueOf')).toBe(true); }) ); it('should handle "@" bindings with same method names in Object.prototype correctly when not present', inject( function($rootScope, $compile) { var func = function() { element = $compile('<div prototype-method-name-as-scope-var-b></div>')($rootScope); }; expect(func).not.toThrow(); var scope = element.isolateScope(); expect(element.find('span').scope()).toBe(scope); expect(scope).not.toBe($rootScope); // Does not shadow value because optional expect(scope.constructor).toBe($rootScope.constructor); expect(scope.hasOwnProperty('constructor')).toBe(false); // Shadows value because not optional expect(scope.valueOf).toBeUndefined(); expect(scope.hasOwnProperty('valueOf')).toBe(true); }) ); it('should handle "@" bindings with same method names in Object.prototype correctly when present', inject( function($rootScope, $compile) { var func = function() { element = $compile( '<div prototype-method-name-as-scope-var-b constructor="constructor" value-of="valueOf"></div>' )($rootScope); }; expect(func).not.toThrow(); expect(element.find('span').scope()).toBe(element.isolateScope()); expect(element.isolateScope()).not.toBe($rootScope); expect(element.isolateScope()['constructor']).toBe('constructor'); expect(element.isolateScope()['valueOf']).toBe('valueOf'); }) ); it('should handle "&" bindings with same method names in Object.prototype correctly when not present', inject( function($rootScope, $compile) { var func = function() { element = $compile('<div prototype-method-name-as-scope-var-c></div>')($rootScope); }; expect(func).not.toThrow(); expect(element.find('span').scope()).toBe(element.isolateScope()); expect(element.isolateScope()).not.toBe($rootScope); expect(element.isolateScope()['constructor']).toBe($rootScope.constructor); expect(element.isolateScope()['valueOf']()).toBeUndefined(); }) ); it('should handle "&" bindings with same method names in Object.prototype correctly when present', inject( function($rootScope, $compile) { $rootScope.constructor = function() { return 'constructor'; }; $rootScope.valueOf = function() { return 'valueOf'; }; var func = function() { element = $compile( '<div prototype-method-name-as-scope-var-c constructor="constructor()" value-of="valueOf()"></div>' )($rootScope); }; expect(func).not.toThrow(); expect(element.find('span').scope()).toBe(element.isolateScope()); expect(element.isolateScope()).not.toBe($rootScope); expect(element.isolateScope()['constructor']()).toBe('constructor'); expect(element.isolateScope()['valueOf']()).toBe('valueOf'); }) ); it('should not throw exception when using "watch" as binding in Firefox', inject( function($rootScope, $compile) { $rootScope.watch = 'watch'; var func = function() { element = $compile( '<div watch-as-scope-var watch="watch"></div>' )($rootScope); }; expect(func).not.toThrow(); expect(element.find('span').scope()).toBe(element.isolateScope()); expect(element.isolateScope()).not.toBe($rootScope); expect(element.isolateScope()['watch']).toBe('watch'); }) ); }); describe('with isolate scope directives and directives that manually create a new scope', function() { it('should return the new scope at the directive element', inject( function($rootScope, $compile) { var directiveElement; element = $compile('<div><a ng-if="true" iscope></a></div>')($rootScope); $rootScope.$apply(); directiveElement = element.find('a'); expect(directiveElement.scope().$parent).toBe($rootScope); expect(directiveElement.scope()).not.toBe(directiveElement.isolateScope()); }) ); it('should return the isolate scope for child elements', inject( function($rootScope, $compile, $httpBackend) { var directiveElement, child; $httpBackend.expect('GET', 'tiscope.html').respond('<span></span>'); element = $compile('<div><a ng-if="true" tiscope></a></div>')($rootScope); $rootScope.$apply(); $httpBackend.flush(); directiveElement = element.find('a'); child = directiveElement.find('span'); expect(child.scope()).toBe(directiveElement.isolateScope()); }) ); it('should return the isolate scope for child elements in directive sync template', inject( function($rootScope, $compile) { var directiveElement, child; element = $compile('<div><a ng-if="true" stiscope></a></div>')($rootScope); $rootScope.$apply(); directiveElement = element.find('a'); child = directiveElement.find('span'); expect(child.scope()).toBe(directiveElement.isolateScope()); }) ); }); }); describe('multidir isolated scope error messages', function() { angular.module('fakeIsoledScopeModule', []) .directive('fakeScope', function(log) { return { scope: true, restrict: 'CA', compile: function() { return {pre: function(scope, element) { log(scope.$id); expect(element.data('$scope')).toBe(scope); }}; } }; }) .directive('fakeIScope', function(log) { return { scope: {}, restrict: 'CA', compile: function() { return function(scope, element) { iscope = scope; log(scope.$id); expect(element.data('$isolateScopeNoTemplate')).toBe(scope); }; } }; }); beforeEach(module('fakeIsoledScopeModule', function() { directive('anonymModuleScopeDirective', function(log) { return { scope: true, restrict: 'CA', compile: function() { return {pre: function(scope, element) { log(scope.$id); expect(element.data('$scope')).toBe(scope); }}; } }; }); })); it('should add module name to multidir isolated scope message if directive defined through module', inject( function($rootScope, $compile) { expect(function() { $compile('<div class="fake-scope; fake-i-scope"></div>'); }).toThrowMinErr('$compile', 'multidir', 'Multiple directives [fakeIScope (module: fakeIsoledScopeModule), fakeScope (module: fakeIsoledScopeModule)] ' + 'asking for new/isolated scope on: <div class="fake-scope; fake-i-scope">'); }) ); it('sholdn\'t add module name to multidir isolated scope message if directive is defined directly with $compileProvider', inject( function($rootScope, $compile) { expect(function() { $compile('<div class="anonym-module-scope-directive; fake-i-scope"></div>'); }).toThrowMinErr('$compile', 'multidir', 'Multiple directives [anonymModuleScopeDirective, fakeIScope (module: fakeIsoledScopeModule)] ' + 'asking for new/isolated scope on: <div class="anonym-module-scope-directive; fake-i-scope">'); }) ); }); }); }); }); describe('interpolation', function() { var observeSpy, directiveAttrs, deregisterObserver; beforeEach(module(function() { directive('observer', function() { return function(scope, elm, attr) { directiveAttrs = attr; observeSpy = jasmine.createSpy('$observe attr'); deregisterObserver = attr.$observe('someAttr', observeSpy); }; }); directive('replaceSomeAttr', valueFn({ compile: function(element, attr) { attr.$set('someAttr', 'bar-{{1+1}}'); expect(element).toBe(attr.$$element); } })); })); it('should compile and link both attribute and text bindings', inject( function($rootScope, $compile) { $rootScope.name = 'angular'; element = $compile('<div name="attr: {{name}}">text: {{name}}</div>')($rootScope); $rootScope.$digest(); expect(element.text()).toEqual('text: angular'); expect(element.attr('name')).toEqual('attr: angular'); }) ); it('should one-time bind if the expression starts with two colons', inject( function($rootScope, $compile) { $rootScope.name = 'angular'; element = $compile('<div name="attr: {{::name}}">text: {{::name}}</div>')($rootScope); expect($rootScope.$$watchers.length).toBe(2); $rootScope.$digest(); expect(element.text()).toEqual('text: angular'); expect(element.attr('name')).toEqual('attr: angular'); expect($rootScope.$$watchers.length).toBe(0); $rootScope.name = 'not-angular'; $rootScope.$digest(); expect(element.text()).toEqual('text: angular'); expect(element.attr('name')).toEqual('attr: angular'); }) ); it('should one-time bind if the expression starts with a space and two colons', inject( function($rootScope, $compile) { $rootScope.name = 'angular'; element = $compile('<div name="attr: {{::name}}">text: {{ ::name }}</div>')($rootScope); expect($rootScope.$$watchers.length).toBe(2); $rootScope.$digest(); expect(element.text()).toEqual('text: angular'); expect(element.attr('name')).toEqual('attr: angular'); expect($rootScope.$$watchers.length).toBe(0); $rootScope.name = 'not-angular'; $rootScope.$digest(); expect(element.text()).toEqual('text: angular'); expect(element.attr('name')).toEqual('attr: angular'); }) ); it('should process attribute interpolation in pre-linking phase at priority 100', function() { module(function() { directive('attrLog', function(log) { return { compile: function($element, $attrs) { log('compile=' + $attrs.myName); return { pre: function($scope, $element, $attrs) { log('preLinkP0=' + $attrs.myName); }, post: function($scope, $element, $attrs) { log('postLink=' + $attrs.myName); } }; } }; }); }); module(function() { directive('attrLogHighPriority', function(log) { return { priority: 101, compile: function() { return { pre: function($scope, $element, $attrs) { log('preLinkP101=' + $attrs.myName); } }; } }; }); }); inject(function($rootScope, $compile, log) { element = $compile('<div attr-log-high-priority attr-log my-name="{{name}}"></div>')($rootScope); $rootScope.name = 'angular'; $rootScope.$apply(); log('digest=' + element.attr('my-name')); expect(log).toEqual('compile={{name}}; preLinkP101={{name}}; preLinkP0=; postLink=; digest=angular'); }); }); it('should allow the attribute to be removed before the attribute interpolation', function() { module(function() { directive('removeAttr', function() { return { restrict:'A', compile: function(tElement, tAttr) { tAttr.$set('removeAttr', null); } }; }); }); inject(function($rootScope, $compile) { expect(function() { element = $compile('<div remove-attr="{{ toBeRemoved }}"></div>')($rootScope); }).not.toThrow(); expect(element.attr('remove-attr')).toBeUndefined(); }); }); describe('SCE values', function() { it('should resolve compile and link both attribute and text bindings', inject( function($rootScope, $compile, $sce) { $rootScope.name = $sce.trustAsHtml('angular'); element = $compile('<div name="attr: {{name}}">text: {{name}}</div>')($rootScope); $rootScope.$digest(); expect(element.text()).toEqual('text: angular'); expect(element.attr('name')).toEqual('attr: angular'); })); }); describe('decorating with binding info', function() { it('should not occur if `debugInfoEnabled` is false', function() { module(function($compileProvider) { $compileProvider.debugInfoEnabled(false); }); inject(function($compile, $rootScope) { element = $compile('<div>{{1+2}}</div>')($rootScope); expect(element.hasClass('ng-binding')).toBe(false); expect(element.data('$binding')).toBeUndefined(); }); }); it('should occur if `debugInfoEnabled` is true', function() { module(function($compileProvider) { $compileProvider.debugInfoEnabled(true); }); inject(function($compile, $rootScope) { element = $compile('<div>{{1+2}}</div>')($rootScope); expect(element.hasClass('ng-binding')).toBe(true); expect(element.data('$binding')).toEqual(['1+2']); }); }); }); it('should observe interpolated attrs', inject(function($rootScope, $compile) { $compile('<div some-attr="{{value}}" observer></div>')($rootScope); // should be async expect(observeSpy).not.toHaveBeenCalled(); $rootScope.$apply(function() { $rootScope.value = 'bound-value'; }); expect(observeSpy).toHaveBeenCalledOnceWith('bound-value'); })); it('should return a deregistration function while observing an attribute', inject(function($rootScope, $compile) { $compile('<div some-attr="{{value}}" observer></div>')($rootScope); $rootScope.$apply('value = "first-value"'); expect(observeSpy).toHaveBeenCalledWith('first-value'); deregisterObserver(); $rootScope.$apply('value = "new-value"'); expect(observeSpy).not.toHaveBeenCalledWith('new-value'); })); it('should set interpolated attrs to initial interpolation value', inject(function($rootScope, $compile) { // we need the interpolated attributes to be initialized so that linking fn in a component // can access the value during link $rootScope.whatever = 'test value'; $compile('<div some-attr="{{whatever}}" observer></div>')($rootScope); expect(directiveAttrs.someAttr).toBe($rootScope.whatever); })); it('should allow directive to replace interpolated attributes before attr interpolation compilation', inject( function($compile, $rootScope) { element = $compile('<div some-attr="foo-{{1+1}}" replace-some-attr></div>')($rootScope); $rootScope.$digest(); expect(element.attr('some-attr')).toEqual('bar-2'); })); it('should call observer of non-interpolated attr through $evalAsync', inject(function($rootScope, $compile) { $compile('<div some-attr="nonBound" observer></div>')($rootScope); expect(directiveAttrs.someAttr).toBe('nonBound'); expect(observeSpy).not.toHaveBeenCalled(); $rootScope.$digest(); expect(observeSpy).toHaveBeenCalled(); }) ); it('should call observer only when the attribute value changes', function() { module(function() { directive('observingDirective', function() { return { restrict: 'E', scope: { someAttr: '@' } }; }); }); inject(function($rootScope, $compile) { $compile('<observing-directive observer></observing-directive>')($rootScope); $rootScope.$digest(); expect(observeSpy).not.toHaveBeenCalledWith(undefined); }); }); it('should delegate exceptions to $exceptionHandler', function() { observeSpy = jasmine.createSpy('$observe attr').andThrow('ERROR'); module(function($exceptionHandlerProvider) { $exceptionHandlerProvider.mode('log'); directive('error', function() { return function(scope, elm, attr) { attr.$observe('someAttr', observeSpy); attr.$observe('someAttr', observeSpy); }; }); }); inject(function($compile, $rootScope, $exceptionHandler) { $compile('<div some-attr="{{value}}" error></div>')($rootScope); $rootScope.$digest(); expect(observeSpy).toHaveBeenCalled(); expect(observeSpy.callCount).toBe(2); expect($exceptionHandler.errors).toEqual(['ERROR', 'ERROR']); }); }); it('should translate {{}} in terminal nodes', inject(function($rootScope, $compile) { element = $compile('<select ng:model="x"><option value="">Greet {{name}}!</option></select>')($rootScope); $rootScope.$digest(); expect(sortedHtml(element).replace(' selected="true"', '')). toEqual('<select ng:model="x">' + '<option value="">Greet !</option>' + '</select>'); $rootScope.name = 'Misko'; $rootScope.$digest(); expect(sortedHtml(element).replace(' selected="true"', '')). toEqual('<select ng:model="x">' + '<option value="">Greet Misko!</option>' + '</select>'); })); it('should handle consecutive text elements as a single text element', inject(function($rootScope, $compile) { // No point it running the test, if there is no MutationObserver if (!window.MutationObserver) return; // Create and register the MutationObserver var observer = new window.MutationObserver(noop); observer.observe(document.body, {childList: true, subtree: true}); // Run the actual test var base = jqLite('<div>&mdash; {{ "This doesn\'t." }}</div>'); element = $compile(base)($rootScope); $rootScope.$digest(); expect(element.text()).toBe("— This doesn't."); // Unregister the MutationObserver (and hope it doesn't mess up with subsequent tests) observer.disconnect(); })); it('should support custom start/end interpolation symbols in template and directive template', function() { module(function($interpolateProvider, $compileProvider) { $interpolateProvider.startSymbol('##').endSymbol(']]'); $compileProvider.directive('myDirective', function() { return { template: '<span>{{hello}}|{{hello|uppercase}}</span>' }; }); }); inject(function($compile, $rootScope) { element = $compile('<div>##hello|uppercase]]|<div my-directive></div></div>')($rootScope); $rootScope.hello = 'ahoj'; $rootScope.$digest(); expect(element.text()).toBe('AHOJ|ahoj|AHOJ'); }); }); it('should support custom start/end interpolation symbols in async directive template', function() { module(function($interpolateProvider, $compileProvider) { $interpolateProvider.startSymbol('##').endSymbol(']]'); $compileProvider.directive('myDirective', function() { return { templateUrl: 'myDirective.html' }; }); }); inject(function($compile, $rootScope, $templateCache) { $templateCache.put('myDirective.html', '<span>{{hello}}|{{hello|uppercase}}</span>'); element = $compile('<div>##hello|uppercase]]|<div my-directive></div></div>')($rootScope); $rootScope.hello = 'ahoj'; $rootScope.$digest(); expect(element.text()).toBe('AHOJ|ahoj|AHOJ'); }); }); it('should make attributes observable for terminal directives', function() { module(function() { directive('myAttr', function(log) { return { terminal: true, link: function(scope, element, attrs) { attrs.$observe('myAttr', function(val) { log(val); }); } }; }); }); inject(function($compile, $rootScope, log) { element = $compile('<div my-attr="{{myVal}}"></div>')($rootScope); expect(log).toEqual([]); $rootScope.myVal = 'carrot'; $rootScope.$digest(); expect(log).toEqual(['carrot']); }); }); }); describe('link phase', function() { beforeEach(module(function() { forEach(['a', 'b', 'c'], function(name) { directive(name, function(log) { return { restrict: 'ECA', compile: function() { log('t' + uppercase(name)); return { pre: function() { log('pre' + uppercase(name)); }, post: function linkFn() { log('post' + uppercase(name)); } }; } }; }); }); })); it('should not store linkingFns for noop branches', inject(function($rootScope, $compile) { element = jqLite('<div name="{{a}}"><span>ignore</span></div>'); var linkingFn = $compile(element); // Now prune the branches with no directives element.find('span').remove(); expect(element.find('span').length).toBe(0); // and we should still be able to compile without errors linkingFn($rootScope); })); it('should compile from top to bottom but link from bottom up', inject( function($compile, $rootScope, log) { element = $compile('<a b><c></c></a>')($rootScope); expect(log).toEqual('tA; tB; tC; preA; preB; preC; postC; postB; postA'); } )); it('should support link function on directive object', function() { module(function() { directive('abc', valueFn({ link: function(scope, element, attrs) { element.text(attrs.abc); } })); }); inject(function($compile, $rootScope) { element = $compile('<div abc="WORKS">FAIL</div>')($rootScope); expect(element.text()).toEqual('WORKS'); }); }); it('should support $observe inside link function on directive object', function() { module(function() { directive('testLink', valueFn({ templateUrl: 'test-link.html', link: function(scope, element, attrs) { attrs.$observe('testLink', function(val) { scope.testAttr = val; }); } })); }); inject(function($compile, $rootScope, $templateCache) { $templateCache.put('test-link.html', '{{testAttr}}'); element = $compile('<div test-link="{{1+2}}"></div>')($rootScope); $rootScope.$apply(); expect(element.text()).toBe('3'); }); }); }); describe('attrs', function() { it('should allow setting of attributes', function() { module(function() { directive({ setter: valueFn(function(scope, element, attr) { attr.$set('name', 'abc'); attr.$set('disabled', true); expect(attr.name).toBe('abc'); expect(attr.disabled).toBe(true); }) }); }); inject(function($rootScope, $compile) { element = $compile('<div setter></div>')($rootScope); expect(element.attr('name')).toEqual('abc'); expect(element.attr('disabled')).toEqual('disabled'); }); }); it('should read boolean attributes as boolean only on control elements', function() { var value; module(function() { directive({ input: valueFn({ restrict: 'ECA', link:function(scope, element, attr) { value = attr.required; } }) }); }); inject(function($rootScope, $compile) { element = $compile('<input required></input>')($rootScope); expect(value).toEqual(true); }); }); it('should read boolean attributes as text on non-controll elements', function() { var value; module(function() { directive({ div: valueFn({ restrict: 'ECA', link:function(scope, element, attr) { value = attr.required; } }) }); }); inject(function($rootScope, $compile) { element = $compile('<div required="some text"></div>')($rootScope); expect(value).toEqual('some text'); }); }); it('should create new instance of attr for each template stamping', function() { module(function($provide) { var state = { first: [], second: [] }; $provide.value('state', state); directive({ first: valueFn({ priority: 1, compile: function(templateElement, templateAttr) { return function(scope, element, attr) { state.first.push({ template: {element: templateElement, attr:templateAttr}, link: {element: element, attr: attr} }); }; } }), second: valueFn({ priority: 2, compile: function(templateElement, templateAttr) { return function(scope, element, attr) { state.second.push({ template: {element: templateElement, attr:templateAttr}, link: {element: element, attr: attr} }); }; } }) }); }); inject(function($rootScope, $compile, state) { var template = $compile('<div first second>'); dealoc(template($rootScope.$new(), noop)); dealoc(template($rootScope.$new(), noop)); // instance between directives should be shared expect(state.first[0].template.element).toBe(state.second[0].template.element); expect(state.first[0].template.attr).toBe(state.second[0].template.attr); // the template and the link can not be the same instance expect(state.first[0].template.element).not.toBe(state.first[0].link.element); expect(state.first[0].template.attr).not.toBe(state.first[0].link.attr); // each new template needs to be new instance expect(state.first[0].link.element).not.toBe(state.first[1].link.element); expect(state.first[0].link.attr).not.toBe(state.first[1].link.attr); expect(state.second[0].link.element).not.toBe(state.second[1].link.element); expect(state.second[0].link.attr).not.toBe(state.second[1].link.attr); }); }); it('should properly $observe inside ng-repeat', function() { var spies = []; module(function() { directive('observer', function() { return function(scope, elm, attr) { spies.push(jasmine.createSpy('observer ' + spies.length)); attr.$observe('some', spies[spies.length - 1]); }; }); }); inject(function($compile, $rootScope) { element = $compile('<div><div ng-repeat="i in items">' + '<span some="id_{{i.id}}" observer></span>' + '</div></div>')($rootScope); $rootScope.$apply(function() { $rootScope.items = [{id: 1}, {id: 2}]; }); expect(spies[0]).toHaveBeenCalledOnceWith('id_1'); expect(spies[1]).toHaveBeenCalledOnceWith('id_2'); spies[0].reset(); spies[1].reset(); $rootScope.$apply(function() { $rootScope.items[0].id = 5; }); expect(spies[0]).toHaveBeenCalledOnceWith('id_5'); }); }); describe('$set', function() { var attr; beforeEach(function() { module(function() { directive('input', valueFn({ restrict: 'ECA', link: function(scope, element, attr) { scope.attr = attr; } })); }); inject(function($compile, $rootScope) { element = $compile('<input></input>')($rootScope); attr = $rootScope.attr; expect(attr).toBeDefined(); }); }); it('should set attributes', function() { attr.$set('ngMyAttr', 'value'); expect(element.attr('ng-my-attr')).toEqual('value'); expect(attr.ngMyAttr).toEqual('value'); }); it('should allow overriding of attribute name and remember the name', function() { attr.$set('ngOther', '123', true, 'other'); expect(element.attr('other')).toEqual('123'); expect(attr.ngOther).toEqual('123'); attr.$set('ngOther', '246'); expect(element.attr('other')).toEqual('246'); expect(attr.ngOther).toEqual('246'); }); it('should remove attribute', function() { attr.$set('ngMyAttr', 'value'); expect(element.attr('ng-my-attr')).toEqual('value'); attr.$set('ngMyAttr', undefined); expect(element.attr('ng-my-attr')).toBe(undefined); attr.$set('ngMyAttr', 'value'); attr.$set('ngMyAttr', null); expect(element.attr('ng-my-attr')).toBe(undefined); }); it('should not set DOM element attr if writeAttr false', function() { attr.$set('test', 'value', false); expect(element.attr('test')).toBeUndefined(); expect(attr.test).toBe('value'); }); }); }); describe('isolated locals', function() { var componentScope, regularScope; beforeEach(module(function() { directive('myComponent', function() { return { scope: { attr: '@', attrAlias: '@attr', ref: '=', refAlias: '= ref', reference: '=', optref: '=?', optrefAlias: '=? optref', optreference: '=?', colref: '=*', colrefAlias: '=* colref', expr: '&', optExpr: '&?', exprAlias: '&expr', constructor: '&?' }, link: function(scope) { componentScope = scope; } }; }); directive('badDeclaration', function() { return { scope: { attr: 'xxx' } }; }); directive('storeScope', function() { return { link: function(scope) { regularScope = scope; } }; }); })); it('should give other directives the parent scope', inject(function($rootScope) { compile('<div><input type="text" my-component store-scope ng-model="value"></div>'); $rootScope.$apply(function() { $rootScope.value = 'from-parent'; }); expect(element.find('input').val()).toBe('from-parent'); expect(componentScope).not.toBe(regularScope); expect(componentScope.$parent).toBe(regularScope); })); it('should not give the isolate scope to other directive template', function() { module(function() { directive('otherTplDir', function() { return { template: 'value: {{value}}' }; }); }); inject(function($rootScope) { compile('<div my-component other-tpl-dir>'); $rootScope.$apply(function() { $rootScope.value = 'from-parent'; }); expect(element.html()).toBe('value: from-parent'); }); }); it('should not give the isolate scope to other directive template (with templateUrl)', function() { module(function() { directive('otherTplDir', function() { return { templateUrl: 'other.html' }; }); }); inject(function($rootScope, $templateCache) { $templateCache.put('other.html', 'value: {{value}}'); compile('<div my-component other-tpl-dir>'); $rootScope.$apply(function() { $rootScope.value = 'from-parent'; }); expect(element.html()).toBe('value: from-parent'); }); }); it('should not give the isolate scope to regular child elements', function() { inject(function($rootScope) { compile('<div my-component>value: {{value}}</div>'); $rootScope.$apply(function() { $rootScope.value = 'from-parent'; }); expect(element.html()).toBe('value: from-parent'); }); }); it('should update parent scope when "="-bound NaN changes', inject(function($compile, $rootScope) { $rootScope.num = NaN; compile('<div my-component reference="num"></div>'); var isolateScope = element.isolateScope(); expect(isolateScope.reference).toBeNaN(); isolateScope.$apply(function(scope) { scope.reference = 64; }); expect($rootScope.num).toBe(64); })); it('should update isolate scope when "="-bound NaN changes', inject(function($compile, $rootScope) { $rootScope.num = NaN; compile('<div my-component reference="num"></div>'); var isolateScope = element.isolateScope(); expect(isolateScope.reference).toBeNaN(); $rootScope.$apply(function(scope) { scope.num = 64; }); expect(isolateScope.reference).toBe(64); })); it('should be able to bind attribute names which are present in Object.prototype', function() { module(function() { directive('inProtoAttr', valueFn({ scope: { 'constructor': '@', 'toString': '&', // Spidermonkey extension, may be obsolete in the future 'watch': '=' } })); }); inject(function($rootScope) { expect(function() { compile('<div in-proto-attr constructor="hello, world" watch="[]" ' + 'to-string="value = !value"></div>'); }).not.toThrow(); var isolateScope = element.isolateScope(); expect(typeof isolateScope.constructor).toBe('string'); expect(isArray(isolateScope.watch)).toBe(true); expect(typeof isolateScope.toString).toBe('function'); expect($rootScope.value).toBeUndefined(); isolateScope.toString(); expect($rootScope.value).toBe(true); }); }); it('should be able to interpolate attribute names which are present in Object.prototype', function() { var attrs; module(function() { directive('attrExposer', valueFn({ link: function($scope, $element, $attrs) { attrs = $attrs; } })); }); inject(function($compile, $rootScope) { $compile('<div attr-exposer to-string="{{1 + 1}}">')($rootScope); $rootScope.$apply(); expect(attrs.toString).toBe('2'); }); }); it('should not initialize scope value if optional expression binding is not passed', inject(function($compile) { compile('<div my-component></div>'); var isolateScope = element.isolateScope(); expect(isolateScope.optExpr).toBeUndefined(); })); it('should not initialize scope value if optional expression binding with Object.prototype name is not passed', inject(function($compile) { compile('<div my-component></div>'); var isolateScope = element.isolateScope(); expect(isolateScope.constructor).toBe($rootScope.constructor); })); it('should initialize scope value if optional expression binding is passed', inject(function($compile) { compile('<div my-component opt-expr="value = \'did!\'"></div>'); var isolateScope = element.isolateScope(); expect(typeof isolateScope.optExpr).toBe('function'); expect(isolateScope.optExpr()).toBe('did!'); expect($rootScope.value).toBe('did!'); })); it('should initialize scope value if optional expression binding with Object.prototype name is passed', inject(function($compile) { compile('<div my-component constructor="value = \'did!\'"></div>'); var isolateScope = element.isolateScope(); expect(typeof isolateScope.constructor).toBe('function'); expect(isolateScope.constructor()).toBe('did!'); expect($rootScope.value).toBe('did!'); })); it('should not overwrite @-bound property each digest when not present', function() { module(function($compileProvider) { $compileProvider.directive('testDir', valueFn({ scope: {prop: '@'}, controller: function($scope) { $scope.prop = $scope.prop || 'default'; this.getProp = function() { return $scope.prop; }; }, controllerAs: 'ctrl', template: '<p></p>' })); }); inject(function($compile, $rootScope) { element = $compile('<div test-dir></div>')($rootScope); var scope = element.isolateScope(); expect(scope.ctrl.getProp()).toBe('default'); $rootScope.$digest(); expect(scope.ctrl.getProp()).toBe('default'); }); }); it('should ignore optional "="-bound property if value is the emptry string', function() { module(function($compileProvider) { $compileProvider.directive('testDir', valueFn({ scope: {prop: '=?'}, controller: function($scope) { $scope.prop = $scope.prop || 'default'; this.getProp = function() { return $scope.prop; }; }, controllerAs: 'ctrl', template: '<p></p>' })); }); inject(function($compile, $rootScope) { element = $compile('<div test-dir></div>')($rootScope); var scope = element.isolateScope(); expect(scope.ctrl.getProp()).toBe('default'); $rootScope.$digest(); expect(scope.ctrl.getProp()).toBe('default'); scope.prop = 'foop'; $rootScope.$digest(); expect(scope.ctrl.getProp()).toBe('foop'); }); }); describe('bind-once', function() { function countWatches(scope) { var result = 0; while (scope !== null) { result += (scope.$$watchers && scope.$$watchers.length) || 0; result += countWatches(scope.$$childHead); scope = scope.$$nextSibling; } return result; } it('should be possible to one-time bind a parameter on a component with a template', function() { module(function() { directive('otherTplDir', function() { return { scope: {param1: '=', param2: '='}, template: '1:{{param1}};2:{{param2}};3:{{::param1}};4:{{::param2}}' }; }); }); inject(function($rootScope) { compile('<div other-tpl-dir param1="::foo" param2="bar"></div>'); expect(countWatches($rootScope)).toEqual(6); // 4 -> template watch group, 2 -> '=' $rootScope.$digest(); expect(element.html()).toBe('1:;2:;3:;4:'); expect(countWatches($rootScope)).toEqual(6); $rootScope.foo = 'foo'; $rootScope.$digest(); expect(element.html()).toBe('1:foo;2:;3:foo;4:'); expect(countWatches($rootScope)).toEqual(4); $rootScope.foo = 'baz'; $rootScope.bar = 'bar'; $rootScope.$digest(); expect(element.html()).toBe('1:foo;2:bar;3:foo;4:bar'); expect(countWatches($rootScope)).toEqual(3); $rootScope.bar = 'baz'; $rootScope.$digest(); expect(element.html()).toBe('1:foo;2:baz;3:foo;4:bar'); }); }); it('should be possible to one-time bind a parameter on a component with a template', function() { module(function() { directive('otherTplDir', function() { return { scope: {param1: '@', param2: '@'}, template: '1:{{param1}};2:{{param2}};3:{{::param1}};4:{{::param2}}' }; }); }); inject(function($rootScope) { compile('<div other-tpl-dir param1="{{::foo}}" param2="{{bar}}"></div>'); expect(countWatches($rootScope)).toEqual(6); // 4 -> template watch group, 2 -> {{ }} $rootScope.$digest(); expect(element.html()).toBe('1:;2:;3:;4:'); expect(countWatches($rootScope)).toEqual(4); // (- 2) -> bind-once in template $rootScope.foo = 'foo'; $rootScope.$digest(); expect(element.html()).toBe('1:foo;2:;3:;4:'); expect(countWatches($rootScope)).toEqual(3); $rootScope.foo = 'baz'; $rootScope.bar = 'bar'; $rootScope.$digest(); expect(element.html()).toBe('1:foo;2:bar;3:;4:'); expect(countWatches($rootScope)).toEqual(3); $rootScope.bar = 'baz'; $rootScope.$digest(); expect(element.html()).toBe('1:foo;2:baz;3:;4:'); }); }); it('should be possible to one-time bind a parameter on a component with a template', function() { module(function() { directive('otherTplDir', function() { return { scope: {param1: '=', param2: '='}, templateUrl: 'other.html' }; }); }); inject(function($rootScope, $templateCache) { $templateCache.put('other.html', '1:{{param1}};2:{{param2}};3:{{::param1}};4:{{::param2}}'); compile('<div other-tpl-dir param1="::foo" param2="bar"></div>'); $rootScope.$digest(); expect(element.html()).toBe('1:;2:;3:;4:'); expect(countWatches($rootScope)).toEqual(6); // 4 -> template watch group, 2 -> '=' $rootScope.foo = 'foo'; $rootScope.$digest(); expect(element.html()).toBe('1:foo;2:;3:foo;4:'); expect(countWatches($rootScope)).toEqual(4); $rootScope.foo = 'baz'; $rootScope.bar = 'bar'; $rootScope.$digest(); expect(element.html()).toBe('1:foo;2:bar;3:foo;4:bar'); expect(countWatches($rootScope)).toEqual(3); $rootScope.bar = 'baz'; $rootScope.$digest(); expect(element.html()).toBe('1:foo;2:baz;3:foo;4:bar'); }); }); it('should be possible to one-time bind a parameter on a component with a template', function() { module(function() { directive('otherTplDir', function() { return { scope: {param1: '@', param2: '@'}, templateUrl: 'other.html' }; }); }); inject(function($rootScope, $templateCache) { $templateCache.put('other.html', '1:{{param1}};2:{{param2}};3:{{::param1}};4:{{::param2}}'); compile('<div other-tpl-dir param1="{{::foo}}" param2="{{bar}}"></div>'); $rootScope.$digest(); expect(element.html()).toBe('1:;2:;3:;4:'); expect(countWatches($rootScope)).toEqual(4); // (4 - 2) -> template watch group, 2 -> {{ }} $rootScope.foo = 'foo'; $rootScope.$digest(); expect(element.html()).toBe('1:foo;2:;3:;4:'); expect(countWatches($rootScope)).toEqual(3); $rootScope.foo = 'baz'; $rootScope.bar = 'bar'; $rootScope.$digest(); expect(element.html()).toBe('1:foo;2:bar;3:;4:'); expect(countWatches($rootScope)).toEqual(3); $rootScope.bar = 'baz'; $rootScope.$digest(); expect(element.html()).toBe('1:foo;2:baz;3:;4:'); }); }); it('should continue with a digets cycle when there is a two-way binding from the child to the parent', function() { module(function() { directive('hello', function() { return { restrict: 'E', scope: { greeting: '=' }, template: '<button ng-click="setGreeting()">Say hi!</button>', link: function(scope) { scope.setGreeting = function() { scope.greeting = 'Hello!'; }; } }; }); }); inject(function($rootScope) { compile('<div>' + '<p>{{greeting}}</p>' + '<div><hello greeting="greeting"></hello></div>' + '</div>'); $rootScope.$digest(); browserTrigger(element.find('button'), 'click'); expect(element.find('p').text()).toBe('Hello!'); }); }); }); describe('attribute', function() { it('should copy simple attribute', inject(function() { compile('<div><span my-component attr="some text">'); expect(componentScope.attr).toEqual('some text'); expect(componentScope.attrAlias).toEqual('some text'); expect(componentScope.attrAlias).toEqual(componentScope.attr); })); it('should set up the interpolation before it reaches the link function', inject(function() { $rootScope.name = 'misko'; compile('<div><span my-component attr="hello {{name}}">'); expect(componentScope.attr).toEqual('hello misko'); expect(componentScope.attrAlias).toEqual('hello misko'); })); it('should update when interpolated attribute updates', inject(function() { compile('<div><span my-component attr="hello {{name}}">'); $rootScope.name = 'igor'; $rootScope.$apply(); expect(componentScope.attr).toEqual('hello igor'); expect(componentScope.attrAlias).toEqual('hello igor'); })); }); describe('object reference', function() { it('should update local when origin changes', inject(function() { compile('<div><span my-component ref="name">'); expect(componentScope.ref).toBe(undefined); expect(componentScope.refAlias).toBe(componentScope.ref); $rootScope.name = 'misko'; $rootScope.$apply(); expect($rootScope.name).toBe('misko'); expect(componentScope.ref).toBe('misko'); expect(componentScope.refAlias).toBe('misko'); $rootScope.name = {}; $rootScope.$apply(); expect(componentScope.ref).toBe($rootScope.name); expect(componentScope.refAlias).toBe($rootScope.name); })); it('should update local when both change', inject(function() { compile('<div><span my-component ref="name">'); $rootScope.name = {mark:123}; componentScope.ref = 'misko'; $rootScope.$apply(); expect($rootScope.name).toEqual({mark:123}); expect(componentScope.ref).toBe($rootScope.name); expect(componentScope.refAlias).toBe($rootScope.name); $rootScope.name = 'igor'; componentScope.ref = {}; $rootScope.$apply(); expect($rootScope.name).toEqual('igor'); expect(componentScope.ref).toBe($rootScope.name); expect(componentScope.refAlias).toBe($rootScope.name); })); it('should not break if local and origin both change to the same value', inject(function() { $rootScope.name = 'aaa'; compile('<div><span my-component ref="name">'); //change both sides to the same item withing the same digest cycle componentScope.ref = 'same'; $rootScope.name = 'same'; $rootScope.$apply(); //change origin back to its previous value $rootScope.name = 'aaa'; $rootScope.$apply(); expect($rootScope.name).toBe('aaa'); expect(componentScope.ref).toBe('aaa'); })); it('should complain on non assignable changes', inject(function() { compile('<div><span my-component ref="\'hello \' + name">'); $rootScope.name = 'world'; $rootScope.$apply(); expect(componentScope.ref).toBe('hello world'); componentScope.ref = 'ignore me'; expect($rootScope.$apply). toThrowMinErr("$compile", "nonassign", "Expression ''hello ' + name' used with directive 'myComponent' is non-assignable!"); expect(componentScope.ref).toBe('hello world'); // reset since the exception was rethrown which prevented phase clearing $rootScope.$$phase = null; $rootScope.name = 'misko'; $rootScope.$apply(); expect(componentScope.ref).toBe('hello misko'); })); // regression it('should stabilize model', inject(function() { compile('<div><span my-component reference="name">'); var lastRefValueInParent; $rootScope.$watch('name', function(ref) { lastRefValueInParent = ref; }); $rootScope.name = 'aaa'; $rootScope.$apply(); componentScope.reference = 'new'; $rootScope.$apply(); expect(lastRefValueInParent).toBe('new'); })); describe('literal objects', function() { it('should copy parent changes', inject(function() { compile('<div><span my-component reference="{name: name}">'); $rootScope.name = 'a'; $rootScope.$apply(); expect(componentScope.reference).toEqual({name: 'a'}); $rootScope.name = 'b'; $rootScope.$apply(); expect(componentScope.reference).toEqual({name: 'b'}); })); it('should not change the component when parent does not change', inject(function() { compile('<div><span my-component reference="{name: name}">'); $rootScope.name = 'a'; $rootScope.$apply(); var lastComponentValue = componentScope.reference; $rootScope.$apply(); expect(componentScope.reference).toBe(lastComponentValue); })); it('should complain when the component changes', inject(function() { compile('<div><span my-component reference="{name: name}">'); $rootScope.name = 'a'; $rootScope.$apply(); componentScope.reference = {name: 'b'}; expect(function() { $rootScope.$apply(); }).toThrowMinErr("$compile", "nonassign", "Expression '{name: name}' used with directive 'myComponent' is non-assignable!"); })); it('should work for primitive literals', inject(function() { test('1', 1); test('null', null); test('undefined', undefined); test("'someString'", 'someString'); function test(literalString, literalValue) { compile('<div><span my-component reference="' + literalString + '">'); $rootScope.$apply(); expect(componentScope.reference).toBe(literalValue); dealoc(element); } })); }); }); describe('optional object reference', function() { it('should update local when origin changes', inject(function() { compile('<div><span my-component optref="name">'); expect(componentScope.optRef).toBe(undefined); expect(componentScope.optRefAlias).toBe(componentScope.optRef); $rootScope.name = 'misko'; $rootScope.$apply(); expect(componentScope.optref).toBe($rootScope.name); expect(componentScope.optrefAlias).toBe($rootScope.name); $rootScope.name = {}; $rootScope.$apply(); expect(componentScope.optref).toBe($rootScope.name); expect(componentScope.optrefAlias).toBe($rootScope.name); })); it('should not throw exception when reference does not exist', inject(function() { compile('<div><span my-component>'); expect(componentScope.optref).toBe(undefined); expect(componentScope.optrefAlias).toBe(undefined); expect(componentScope.optreference).toBe(undefined); })); }); describe('collection object reference', function() { it('should update isolate scope when origin scope changes', inject(function() { $rootScope.collection = [{ name: 'Gabriel', value: 18 }, { name: 'Tony', value: 91 }]; $rootScope.query = ""; $rootScope.$apply(); compile('<div><span my-component colref="collection | filter:query">'); expect(componentScope.colref).toEqual($rootScope.collection); expect(componentScope.colrefAlias).toEqual(componentScope.colref); $rootScope.query = "Gab"; $rootScope.$apply(); expect(componentScope.colref).toEqual([$rootScope.collection[0]]); expect(componentScope.colrefAlias).toEqual([$rootScope.collection[0]]); })); it('should update origin scope when isolate scope changes', inject(function() { $rootScope.collection = [{ name: 'Gabriel', value: 18 }, { name: 'Tony', value: 91 }]; compile('<div><span my-component colref="collection">'); var newItem = { name: 'Pablo', value: 10 }; componentScope.colref.push(newItem); componentScope.$apply(); expect($rootScope.collection[2]).toEqual(newItem); })); }); describe('executable expression', function() { it('should allow expression execution with locals', inject(function() { compile('<div><span my-component expr="count = count + offset">'); $rootScope.count = 2; expect(typeof componentScope.expr).toBe('function'); expect(typeof componentScope.exprAlias).toBe('function'); expect(componentScope.expr({offset: 1})).toEqual(3); expect($rootScope.count).toEqual(3); expect(componentScope.exprAlias({offset: 10})).toEqual(13); expect($rootScope.count).toEqual(13); })); }); it('should throw on unknown definition', inject(function() { expect(function() { compile('<div><span bad-declaration>'); }).toThrowMinErr("$compile", "iscp", "Invalid isolate scope definition for directive 'badDeclaration'. Definition: {... attr: 'xxx' ...}"); })); it('should expose a $$isolateBindings property onto the scope', inject(function() { compile('<div><span my-component>'); expect(typeof componentScope.$$isolateBindings).toBe('object'); expect(componentScope.$$isolateBindings.attr.mode).toBe('@'); expect(componentScope.$$isolateBindings.attr.attrName).toBe('attr'); expect(componentScope.$$isolateBindings.attrAlias.attrName).toBe('attr'); expect(componentScope.$$isolateBindings.ref.mode).toBe('='); expect(componentScope.$$isolateBindings.ref.attrName).toBe('ref'); expect(componentScope.$$isolateBindings.refAlias.attrName).toBe('ref'); expect(componentScope.$$isolateBindings.reference.mode).toBe('='); expect(componentScope.$$isolateBindings.reference.attrName).toBe('reference'); expect(componentScope.$$isolateBindings.expr.mode).toBe('&'); expect(componentScope.$$isolateBindings.expr.attrName).toBe('expr'); expect(componentScope.$$isolateBindings.exprAlias.attrName).toBe('expr'); var firstComponentScope = componentScope, first$$isolateBindings = componentScope.$$isolateBindings; dealoc(element); compile('<div><span my-component>'); expect(componentScope).not.toBe(firstComponentScope); expect(componentScope.$$isolateBindings).toBe(first$$isolateBindings); })); it('should expose isolate scope variables on controller with controllerAs when bindToController is true', function() { var controllerCalled = false; module(function($compileProvider) { $compileProvider.directive('fooDir', valueFn({ template: '<p>isolate</p>', scope: { 'data': '=dirData', 'str': '@dirStr', 'fn': '&dirFn' }, controller: function($scope) { expect(this.data).toEqualData({ 'foo': 'bar', 'baz': 'biz' }); expect(this.str).toBe('Hello, world!'); expect(this.fn()).toBe('called!'); controllerCalled = true; }, controllerAs: 'test', bindToController: true })); }); inject(function($compile, $rootScope) { $rootScope.fn = valueFn('called!'); $rootScope.whom = 'world'; $rootScope.remoteData = { 'foo': 'bar', 'baz': 'biz' }; element = $compile('<div foo-dir dir-data="remoteData" ' + 'dir-str="Hello, {{whom}}!" ' + 'dir-fn="fn()"></div>')($rootScope); expect(controllerCalled).toBe(true); }); }); it('should update @-bindings on controller when bindToController and attribute change observed', function() { module(function($compileProvider) { $compileProvider.directive('atBinding', valueFn({ template: '<p>{{At.text}}</p>', scope: { text: '@atBinding' }, controller: function($scope) {}, bindToController: true, controllerAs: 'At' })); }); inject(function($compile, $rootScope) { element = $compile('<div at-binding="Test: {{text}}"></div>')($rootScope); var p = element.find('p'); $rootScope.$digest(); expect(p.text()).toBe('Test: '); $rootScope.text = 'Kittens'; $rootScope.$digest(); expect(p.text()).toBe('Test: Kittens'); }); }); it('should expose isolate scope variables on controller with controllerAs when bindToController is true', function() { var controllerCalled = false; module(function($compileProvider) { $compileProvider.directive('fooDir', valueFn({ templateUrl: 'test.html', scope: { 'data': '=dirData', 'str': '@dirStr', 'fn': '&dirFn' }, controller: function($scope) { expect(this.data).toEqualData({ 'foo': 'bar', 'baz': 'biz' }); expect(this.str).toBe('Hello, world!'); expect(this.fn()).toBe('called!'); controllerCalled = true; }, controllerAs: 'test', bindToController: true })); }); inject(function($compile, $rootScope, $templateCache) { $templateCache.put('test.html', '<p>isolate</p>'); $rootScope.fn = valueFn('called!'); $rootScope.whom = 'world'; $rootScope.remoteData = { 'foo': 'bar', 'baz': 'biz' }; element = $compile('<div foo-dir dir-data="remoteData" ' + 'dir-str="Hello, {{whom}}!" ' + 'dir-fn="fn()"></div>')($rootScope); $rootScope.$digest(); expect(controllerCalled).toBe(true); }); }); it('should throw noctrl when missing controller', function() { module(function($compileProvider) { $compileProvider.directive('noCtrl', valueFn({ templateUrl: 'test.html', scope: { 'data': '=dirData', 'str': '@dirStr', 'fn': '&dirFn' }, controllerAs: 'test', bindToController: true })); }); inject(function($compile, $rootScope) { expect(function() { $compile('<div no-ctrl>')($rootScope); }).toThrowMinErr('$compile', 'noctrl', 'Cannot bind to controller without directive \'noCtrl\'s controller.'); }); }); it('should throw noident when missing controllerAs directive property', function() { module(function($compileProvider) { $compileProvider.directive('noIdent', valueFn({ templateUrl: 'test.html', scope: { 'data': '=dirData', 'str': '@dirStr', 'fn': '&dirFn' }, controller: function() {}, bindToController: true })); }); inject(function($compile, $rootScope) { expect(function() { $compile('<div no-ident>')($rootScope); }).toThrowMinErr('$compile', 'noident', 'Cannot bind to controller without identifier for directive \'noIdent\'.'); }); }); it('should throw noident when missing controller identifier', function() { module(function($compileProvider, $controllerProvider) { $controllerProvider.register('myCtrl', function() {}); $compileProvider.directive('noIdent', valueFn({ templateUrl: 'test.html', scope: { 'data': '=dirData', 'str': '@dirStr', 'fn': '&dirFn' }, controller: 'myCtrl', bindToController: true })); }); inject(function($compile, $rootScope) { expect(function() { $compile('<div no-ident>')($rootScope); }).toThrowMinErr('$compile', 'noident', 'Cannot bind to controller without identifier for directive \'noIdent\'.'); }); }); it('should bind to controller via object notation (isolate scope)', function() { var controllerCalled = false; module(function($compileProvider, $controllerProvider) { $controllerProvider.register('myCtrl', function() { expect(this.data).toEqualData({ 'foo': 'bar', 'baz': 'biz' }); expect(this.str).toBe('Hello, world!'); expect(this.fn()).toBe('called!'); controllerCalled = true; }); $compileProvider.directive('fooDir', valueFn({ templateUrl: 'test.html', bindToController: { 'data': '=dirData', 'str': '@dirStr', 'fn': '&dirFn' }, scope: {}, controller: 'myCtrl as myCtrl' })); }); inject(function($compile, $rootScope, $templateCache) { $templateCache.put('test.html', '<p>isolate</p>'); $rootScope.fn = valueFn('called!'); $rootScope.whom = 'world'; $rootScope.remoteData = { 'foo': 'bar', 'baz': 'biz' }; element = $compile('<div foo-dir dir-data="remoteData" ' + 'dir-str="Hello, {{whom}}!" ' + 'dir-fn="fn()"></div>')($rootScope); $rootScope.$digest(); expect(controllerCalled).toBe(true); }); }); it('should bind to controller via object notation (new scope)', function() { var controllerCalled = false; module(function($compileProvider, $controllerProvider) { $controllerProvider.register('myCtrl', function() { expect(this.data).toEqualData({ 'foo': 'bar', 'baz': 'biz' }); expect(this.str).toBe('Hello, world!'); expect(this.fn()).toBe('called!'); controllerCalled = true; }); $compileProvider.directive('fooDir', valueFn({ templateUrl: 'test.html', bindToController: { 'data': '=dirData', 'str': '@dirStr', 'fn': '&dirFn' }, scope: true, controller: 'myCtrl as myCtrl' })); }); inject(function($compile, $rootScope, $templateCache) { $templateCache.put('test.html', '<p>isolate</p>'); $rootScope.fn = valueFn('called!'); $rootScope.whom = 'world'; $rootScope.remoteData = { 'foo': 'bar', 'baz': 'biz' }; element = $compile('<div foo-dir dir-data="remoteData" ' + 'dir-str="Hello, {{whom}}!" ' + 'dir-fn="fn()"></div>')($rootScope); $rootScope.$digest(); expect(controllerCalled).toBe(true); }); }); it('should put controller in scope when controller identifier present but not using controllerAs', function() { var controllerCalled = false; var myCtrl; module(function($compileProvider, $controllerProvider) { $controllerProvider.register('myCtrl', function() { controllerCalled = true; myCtrl = this; }); $compileProvider.directive('fooDir', valueFn({ templateUrl: 'test.html', bindToController: {}, scope: true, controller: 'myCtrl as theCtrl' })); }); inject(function($compile, $rootScope, $templateCache) { $templateCache.put('test.html', '<p>isolate</p>'); element = $compile('<div foo-dir>')($rootScope); $rootScope.$digest(); expect(controllerCalled).toBe(true); var childScope = element.children().scope(); expect(childScope).not.toBe($rootScope); expect(childScope.theCtrl).toBe(myCtrl); }); }); it('should re-install controllerAs and bindings for returned value from controller (new scope)', function() { var controllerCalled = false; var myCtrl; function MyCtrl() { } MyCtrl.prototype.test = function() { expect(this.data).toEqualData({ 'foo': 'bar', 'baz': 'biz' }); expect(this.str).toBe('Hello, world!'); expect(this.fn()).toBe('called!'); }; module(function($compileProvider, $controllerProvider) { $controllerProvider.register('myCtrl', function() { controllerCalled = true; myCtrl = this; return new MyCtrl(); }); $compileProvider.directive('fooDir', valueFn({ templateUrl: 'test.html', bindToController: { 'data': '=dirData', 'str': '@dirStr', 'fn': '&dirFn' }, scope: true, controller: 'myCtrl as theCtrl' })); }); inject(function($compile, $rootScope, $templateCache) { $templateCache.put('test.html', '<p>isolate</p>'); $rootScope.fn = valueFn('called!'); $rootScope.whom = 'world'; $rootScope.remoteData = { 'foo': 'bar', 'baz': 'biz' }; element = $compile('<div foo-dir dir-data="remoteData" ' + 'dir-str="Hello, {{whom}}!" ' + 'dir-fn="fn()"></div>')($rootScope); $rootScope.$digest(); expect(controllerCalled).toBe(true); var childScope = element.children().scope(); expect(childScope).not.toBe($rootScope); expect(childScope.theCtrl).not.toBe(myCtrl); expect(childScope.theCtrl.constructor).toBe(MyCtrl); childScope.theCtrl.test(); }); }); it('should re-install controllerAs and bindings for returned value from controller (isolate scope)', function() { var controllerCalled = false; var myCtrl; function MyCtrl() { } MyCtrl.prototype.test = function() { expect(this.data).toEqualData({ 'foo': 'bar', 'baz': 'biz' }); expect(this.str).toBe('Hello, world!'); expect(this.fn()).toBe('called!'); }; module(function($compileProvider, $controllerProvider) { $controllerProvider.register('myCtrl', function() { controllerCalled = true; myCtrl = this; return new MyCtrl(); }); $compileProvider.directive('fooDir', valueFn({ templateUrl: 'test.html', bindToController: true, scope: { 'data': '=dirData', 'str': '@dirStr', 'fn': '&dirFn' }, controller: 'myCtrl as theCtrl' })); }); inject(function($compile, $rootScope, $templateCache) { $templateCache.put('test.html', '<p>isolate</p>'); $rootScope.fn = valueFn('called!'); $rootScope.whom = 'world'; $rootScope.remoteData = { 'foo': 'bar', 'baz': 'biz' }; element = $compile('<div foo-dir dir-data="remoteData" ' + 'dir-str="Hello, {{whom}}!" ' + 'dir-fn="fn()"></div>')($rootScope); $rootScope.$digest(); expect(controllerCalled).toBe(true); var childScope = element.children().scope(); expect(childScope).not.toBe($rootScope); expect(childScope.theCtrl).not.toBe(myCtrl); expect(childScope.theCtrl.constructor).toBe(MyCtrl); childScope.theCtrl.test(); }); }); describe('should not overwrite @-bound property each digest when not present', function() { it('when creating new scope', function() { module(function($compileProvider) { $compileProvider.directive('testDir', valueFn({ scope: true, bindToController: { prop: '@' }, controller: function() { var self = this; this.prop = this.prop || 'default'; this.getProp = function() { return self.prop; }; }, controllerAs: 'ctrl', template: '<p></p>' })); }); inject(function($compile, $rootScope) { element = $compile('<div test-dir></div>')($rootScope); var scope = element.scope(); expect(scope.ctrl.getProp()).toBe('default'); $rootScope.$digest(); expect(scope.ctrl.getProp()).toBe('default'); }); }); it('when creating isolate scope', function() { module(function($compileProvider) { $compileProvider.directive('testDir', valueFn({ scope: {}, bindToController: { prop: '@' }, controller: function() { var self = this; this.prop = this.prop || 'default'; this.getProp = function() { return self.prop; }; }, controllerAs: 'ctrl', template: '<p></p>' })); }); inject(function($compile, $rootScope) { element = $compile('<div test-dir></div>')($rootScope); var scope = element.isolateScope(); expect(scope.ctrl.getProp()).toBe('default'); $rootScope.$digest(); expect(scope.ctrl.getProp()).toBe('default'); }); }); }); }); describe('controller', function() { it('should get required controller', function() { module(function() { directive('main', function(log) { return { priority: 2, controller: function() { this.name = 'main'; }, link: function(scope, element, attrs, controller) { log(controller.name); } }; }); directive('dep', function(log) { return { priority: 1, require: 'main', link: function(scope, element, attrs, controller) { log('dep:' + controller.name); } }; }); directive('other', function(log) { return { link: function(scope, element, attrs, controller) { log(!!controller); // should be false } }; }); }); inject(function(log, $compile, $rootScope) { element = $compile('<div main dep other></div>')($rootScope); expect(log).toEqual('false; dep:main; main'); }); }); it('should respect explicit return value from controller', function() { var expectedController; module(function() { directive('logControllerProp', function(log) { return { controller: function($scope) { this.foo = 'baz'; // value should not be used. return expectedController = {foo: 'bar'}; }, link: function(scope, element, attrs, controller) { expect(expectedController).toBeDefined(); expect(controller).toBe(expectedController); expect(controller.foo).toBe('bar'); log('done'); } }; }); }); inject(function(log, $compile, $rootScope) { element = $compile('<log-controller-prop></log-controller-prop>')($rootScope); expect(log).toEqual('done'); expect(element.data('$logControllerPropController')).toBe(expectedController); }); }); it('should get explicit return value of required parent controller', function() { var expectedController; module(function() { directive('nested', function(log) { return { require: '^^?nested', controller: function() { if (!expectedController) expectedController = {foo: 'bar'}; return expectedController; }, link: function(scope, element, attrs, controller) { if (element.parent().length) { expect(expectedController).toBeDefined(); expect(controller).toBe(expectedController); expect(controller.foo).toBe('bar'); log('done'); } } }; }); }); inject(function(log, $compile, $rootScope) { element = $compile('<div nested><div nested></div></div>')($rootScope); expect(log).toEqual('done'); expect(element.data('$nestedController')).toBe(expectedController); }); }); it('should respect explicit controller return value when using controllerAs', function() { module(function() { directive('main', function() { return { templateUrl: 'main.html', scope: {}, controller: function() { this.name = 'lucas'; return {name: 'george'}; }, controllerAs: 'mainCtrl' }; }); }); inject(function($templateCache, $compile, $rootScope) { $templateCache.put('main.html', '<span>template:{{mainCtrl.name}}</span>'); element = $compile('<main/>')($rootScope); $rootScope.$apply(); expect(element.text()).toBe('template:george'); }); }); it('transcluded children should receive explicit return value of parent controller', function() { var expectedController; module(function() { directive('nester', valueFn({ transclude: true, controller: function($transclude) { this.foo = 'baz'; return expectedController = {transclude:$transclude, foo: 'bar'}; }, link: function(scope, el, attr, ctrl) { ctrl.transclude(cloneAttach); function cloneAttach(clone) { el.append(clone); } } })); directive('nested', function(log) { return { require: '^^nester', link: function(scope, element, attrs, controller) { expect(controller).toBeDefined(); expect(controller).toBe(expectedController); log('done'); } }; }); }); inject(function(log, $compile) { element = $compile('<div nester><div nested></div></div>')($rootScope); $rootScope.$apply(); expect(log.toString()).toBe('done'); expect(element.data('$nesterController')).toBe(expectedController); }); }); it('explicit controller return values are ignored if they are primitives', function() { module(function() { directive('logControllerProp', function(log) { return { controller: function($scope) { this.foo = 'baz'; // value *will* be used. return 'bar'; }, link: function(scope, element, attrs, controller) { log(controller.foo); } }; }); }); inject(function(log, $compile, $rootScope) { element = $compile('<log-controller-prop></log-controller-prop>')($rootScope); expect(log).toEqual('baz'); expect(element.data('$logControllerPropController').foo).toEqual('baz'); }); }); it('should correctly assign controller return values for multiple directives', function() { var directiveController, otherDirectiveController; module(function() { directive('myDirective', function(log) { return { scope: true, controller: function($scope) { return directiveController = { foo: 'bar' }; } }; }); directive('myOtherDirective', function(log) { return { controller: function($scope) { return otherDirectiveController = { baz: 'luh' }; } }; }); }); inject(function(log, $compile, $rootScope) { element = $compile('<my-directive my-other-directive></my-directive>')($rootScope); expect(element.data('$myDirectiveController')).toBe(directiveController); expect(element.data('$myOtherDirectiveController')).toBe(otherDirectiveController); }); }); it('should get required parent controller', function() { module(function() { directive('nested', function(log) { return { require: '^^?nested', controller: function($scope) {}, link: function(scope, element, attrs, controller) { log(!!controller); } }; }); }); inject(function(log, $compile, $rootScope) { element = $compile('<div nested><div nested></div></div>')($rootScope); expect(log).toEqual('true; false'); }); }); it('should get required parent controller when the question mark precedes the ^^', function() { module(function() { directive('nested', function(log) { return { require: '?^^nested', controller: function($scope) {}, link: function(scope, element, attrs, controller) { log(!!controller); } }; }); }); inject(function(log, $compile, $rootScope) { element = $compile('<div nested><div nested></div></div>')($rootScope); expect(log).toEqual('true; false'); }); }); it('should throw if required parent is not found', function() { module(function() { directive('nested', function() { return { require: '^^nested', controller: function($scope) {}, link: function(scope, element, attrs, controller) {} }; }); }); inject(function($compile, $rootScope) { expect(function() { element = $compile('<div nested></div>')($rootScope); }).toThrowMinErr('$compile', 'ctreq', "Controller 'nested', required by directive 'nested', can't be found!"); }); }); it('should get required controller via linkingFn (template)', function() { module(function() { directive('dirA', function() { return { controller: function() { this.name = 'dirA'; } }; }); directive('dirB', function(log) { return { require: 'dirA', template: '<p>dirB</p>', link: function(scope, element, attrs, dirAController) { log('dirAController.name: ' + dirAController.name); } }; }); }); inject(function(log, $compile, $rootScope) { element = $compile('<div dir-a dir-b></div>')($rootScope); expect(log).toEqual('dirAController.name: dirA'); }); }); it('should get required controller via linkingFn (templateUrl)', function() { module(function() { directive('dirA', function() { return { controller: function() { this.name = 'dirA'; } }; }); directive('dirB', function(log) { return { require: 'dirA', templateUrl: 'dirB.html', link: function(scope, element, attrs, dirAController) { log('dirAController.name: ' + dirAController.name); } }; }); }); inject(function(log, $compile, $rootScope, $templateCache) { $templateCache.put('dirB.html', '<p>dirB</p>'); element = $compile('<div dir-a dir-b></div>')($rootScope); $rootScope.$digest(); expect(log).toEqual('dirAController.name: dirA'); }); }); it('should require controller of an isolate directive from a non-isolate directive on the ' + 'same element', function() { var IsolateController = function() {}; var isolateDirControllerInNonIsolateDirective; module(function() { directive('isolate', function() { return { scope: {}, controller: IsolateController }; }); directive('nonIsolate', function() { return { require: 'isolate', link: function(_, __, ___, isolateDirController) { isolateDirControllerInNonIsolateDirective = isolateDirController; } }; }); }); inject(function($compile, $rootScope) { element = $compile('<div isolate non-isolate></div>')($rootScope); expect(isolateDirControllerInNonIsolateDirective).toBeDefined(); expect(isolateDirControllerInNonIsolateDirective instanceof IsolateController).toBe(true); }); }); it('should give the isolate scope to the controller of another replaced directives in the template', function() { module(function() { directive('testDirective', function() { return { replace: true, restrict: 'E', scope: {}, template: '<input type="checkbox" ng-model="model">' }; }); }); inject(function($rootScope) { compile('<div><test-directive></test-directive></div>'); element = element.children().eq(0); expect(element[0].checked).toBe(false); element.isolateScope().model = true; $rootScope.$digest(); expect(element[0].checked).toBe(true); }); }); it('should share isolate scope with replaced directives (template)', function() { var normalScope; var isolateScope; module(function() { directive('isolate', function() { return { replace: true, scope: {}, template: '<span ng-init="name=\'WORKS\'">{{name}}</span>', link: function(s) { isolateScope = s; } }; }); directive('nonIsolate', function() { return { link: function(s) { normalScope = s; } }; }); }); inject(function($compile, $rootScope) { element = $compile('<div isolate non-isolate></div>')($rootScope); expect(normalScope).toBe($rootScope); expect(normalScope.name).toEqual(undefined); expect(isolateScope.name).toEqual('WORKS'); $rootScope.$digest(); expect(element.text()).toEqual('WORKS'); }); }); it('should share isolate scope with replaced directives (templateUrl)', function() { var normalScope; var isolateScope; module(function() { directive('isolate', function() { return { replace: true, scope: {}, templateUrl: 'main.html', link: function(s) { isolateScope = s; } }; }); directive('nonIsolate', function() { return { link: function(s) { normalScope = s; } }; }); }); inject(function($compile, $rootScope, $templateCache) { $templateCache.put('main.html', '<span ng-init="name=\'WORKS\'">{{name}}</span>'); element = $compile('<div isolate non-isolate></div>')($rootScope); $rootScope.$apply(); expect(normalScope).toBe($rootScope); expect(normalScope.name).toEqual(undefined); expect(isolateScope.name).toEqual('WORKS'); expect(element.text()).toEqual('WORKS'); }); }); it('should not get confused about where to use isolate scope when a replaced directive is used multiple times', function() { module(function() { directive('isolate', function() { return { replace: true, scope: {}, template: '<span scope-tester="replaced"><span scope-tester="inside"></span></span>' }; }); directive('scopeTester', function(log) { return { link: function($scope, $element) { log($element.attr('scope-tester') + '=' + ($scope.$root === $scope ? 'non-isolate' : 'isolate')); } }; }); }); inject(function($compile, $rootScope, log) { element = $compile('<div>' + '<div isolate scope-tester="outside"></div>' + '<span scope-tester="sibling"></span>' + '</div>')($rootScope); $rootScope.$digest(); expect(log).toEqual('inside=isolate; ' + 'outside replaced=non-isolate; ' + // outside 'outside replaced=isolate; ' + // replaced 'sibling=non-isolate'); }); }); it('should require controller of a non-isolate directive from an isolate directive on the ' + 'same element', function() { var NonIsolateController = function() {}; var nonIsolateDirControllerInIsolateDirective; module(function() { directive('isolate', function() { return { scope: {}, require: 'nonIsolate', link: function(_, __, ___, nonIsolateDirController) { nonIsolateDirControllerInIsolateDirective = nonIsolateDirController; } }; }); directive('nonIsolate', function() { return { controller: NonIsolateController }; }); }); inject(function($compile, $rootScope) { element = $compile('<div isolate non-isolate></div>')($rootScope); expect(nonIsolateDirControllerInIsolateDirective).toBeDefined(); expect(nonIsolateDirControllerInIsolateDirective instanceof NonIsolateController).toBe(true); }); }); it('should support controllerAs', function() { module(function() { directive('main', function() { return { templateUrl: 'main.html', transclude: true, scope: {}, controller: function() { this.name = 'lucas'; }, controllerAs: 'mainCtrl' }; }); }); inject(function($templateCache, $compile, $rootScope) { $templateCache.put('main.html', '<span>template:{{mainCtrl.name}} <div ng-transclude></div></span>'); element = $compile('<div main>transclude:{{mainCtrl.name}}</div>')($rootScope); $rootScope.$apply(); expect(element.text()).toBe('template:lucas transclude:'); }); }); it('should support controller alias', function() { module(function($controllerProvider) { $controllerProvider.register('MainCtrl', function() { this.name = 'lucas'; }); directive('main', function() { return { templateUrl: 'main.html', scope: {}, controller: 'MainCtrl as mainCtrl' }; }); }); inject(function($templateCache, $compile, $rootScope) { $templateCache.put('main.html', '<span>{{mainCtrl.name}}</span>'); element = $compile('<div main></div>')($rootScope); $rootScope.$apply(); expect(element.text()).toBe('lucas'); }); }); it('should require controller on parent element',function() { module(function() { directive('main', function(log) { return { controller: function() { this.name = 'main'; } }; }); directive('dep', function(log) { return { require: '^main', link: function(scope, element, attrs, controller) { log('dep:' + controller.name); } }; }); }); inject(function(log, $compile, $rootScope) { element = $compile('<div main><div dep></div></div>')($rootScope); expect(log).toEqual('dep:main'); }); }); it("should throw an error if required controller can't be found",function() { module(function() { directive('dep', function(log) { return { require: '^main', link: function(scope, element, attrs, controller) { log('dep:' + controller.name); } }; }); }); inject(function(log, $compile, $rootScope) { expect(function() { $compile('<div main><div dep></div></div>')($rootScope); }).toThrowMinErr("$compile", "ctreq", "Controller 'main', required by directive 'dep', can't be found!"); }); }); it("should pass null if required controller can't be found and is optional",function() { module(function() { directive('dep', function(log) { return { require: '?^main', link: function(scope, element, attrs, controller) { log('dep:' + controller); } }; }); }); inject(function(log, $compile, $rootScope) { $compile('<div main><div dep></div></div>')($rootScope); expect(log).toEqual('dep:null'); }); }); it("should pass null if required controller can't be found and is optional with the question mark on the right",function() { module(function() { directive('dep', function(log) { return { require: '^?main', link: function(scope, element, attrs, controller) { log('dep:' + controller); } }; }); }); inject(function(log, $compile, $rootScope) { $compile('<div main><div dep></div></div>')($rootScope); expect(log).toEqual('dep:null'); }); }); it('should have optional controller on current element', function() { module(function() { directive('dep', function(log) { return { require: '?main', link: function(scope, element, attrs, controller) { log('dep:' + !!controller); } }; }); }); inject(function(log, $compile, $rootScope) { element = $compile('<div main><div dep></div></div>')($rootScope); expect(log).toEqual('dep:false'); }); }); it('should support multiple controllers', function() { module(function() { directive('c1', valueFn({ controller: function() { this.name = 'c1'; } })); directive('c2', valueFn({ controller: function() { this.name = 'c2'; } })); directive('dep', function(log) { return { require: ['^c1', '^c2'], link: function(scope, element, attrs, controller) { log('dep:' + controller[0].name + '-' + controller[1].name); } }; }); }); inject(function(log, $compile, $rootScope) { element = $compile('<div c1 c2><div dep></div></div>')($rootScope); expect(log).toEqual('dep:c1-c2'); }); }); it('should instantiate the controller just once when template/templateUrl', function() { var syncCtrlSpy = jasmine.createSpy('sync controller'), asyncCtrlSpy = jasmine.createSpy('async controller'); module(function() { directive('myDirectiveSync', valueFn({ template: '<div>Hello!</div>', controller: syncCtrlSpy })); directive('myDirectiveAsync', valueFn({ templateUrl: 'myDirectiveAsync.html', controller: asyncCtrlSpy, compile: function() { return function() { }; } })); }); inject(function($templateCache, $compile, $rootScope) { expect(syncCtrlSpy).not.toHaveBeenCalled(); expect(asyncCtrlSpy).not.toHaveBeenCalled(); $templateCache.put('myDirectiveAsync.html', '<div>Hello!</div>'); element = $compile('<div>' + '<span xmy-directive-sync></span>' + '<span my-directive-async></span>' + '</div>')($rootScope); expect(syncCtrlSpy).not.toHaveBeenCalled(); expect(asyncCtrlSpy).not.toHaveBeenCalled(); $rootScope.$apply(); //expect(syncCtrlSpy).toHaveBeenCalledOnce(); expect(asyncCtrlSpy).toHaveBeenCalledOnce(); }); }); it('should instantiate controllers in the parent->child order when transluction, templateUrl and replacement ' + 'are in the mix', function() { // When a child controller is in the transclusion that replaces the parent element that has a directive with // a controller, we should ensure that we first instantiate the parent and only then stuff that comes from the // transclusion. // // The transclusion moves the child controller onto the same element as parent controller so both controllers are // on the same level. module(function() { directive('parentDirective', function() { return { transclude: true, replace: true, templateUrl: 'parentDirective.html', controller: function(log) { log('parentController'); } }; }); directive('childDirective', function() { return { require: '^parentDirective', templateUrl: 'childDirective.html', controller: function(log) { log('childController'); } }; }); }); inject(function($templateCache, log, $compile, $rootScope) { $templateCache.put('parentDirective.html', '<div ng-transclude>parentTemplateText;</div>'); $templateCache.put('childDirective.html', '<span>childTemplateText;</span>'); element = $compile('<div parent-directive><div child-directive></div>childContentText;</div>')($rootScope); $rootScope.$apply(); expect(log).toEqual('parentController; childController'); expect(element.text()).toBe('childTemplateText;childContentText;'); }); }); it('should instantiate the controller after the isolate scope bindings are initialized (with template)', function() { module(function() { var Ctrl = function($scope, log) { log('myFoo=' + $scope.myFoo); }; directive('myDirective', function() { return { scope: { myFoo: "=" }, template: '<p>Hello</p>', controller: Ctrl }; }); }); inject(function($templateCache, $compile, $rootScope, log) { $rootScope.foo = "bar"; element = $compile('<div my-directive my-foo="foo"></div>')($rootScope); $rootScope.$apply(); expect(log).toEqual('myFoo=bar'); }); }); it('should instantiate the controller after the isolate scope bindings are initialized (with templateUrl)', function() { module(function() { var Ctrl = function($scope, log) { log('myFoo=' + $scope.myFoo); }; directive('myDirective', function() { return { scope: { myFoo: "=" }, templateUrl: 'hello.html', controller: Ctrl }; }); }); inject(function($templateCache, $compile, $rootScope, log) { $templateCache.put('hello.html', '<p>Hello</p>'); $rootScope.foo = "bar"; element = $compile('<div my-directive my-foo="foo"></div>')($rootScope); $rootScope.$apply(); expect(log).toEqual('myFoo=bar'); }); }); it('should instantiate controllers in the parent->child->baby order when nested transluction, templateUrl and ' + 'replacement are in the mix', function() { // similar to the test above, except that we have one more layer of nesting and nested transclusion module(function() { directive('parentDirective', function() { return { transclude: true, replace: true, templateUrl: 'parentDirective.html', controller: function(log) { log('parentController'); } }; }); directive('childDirective', function() { return { require: '^parentDirective', transclude: true, replace: true, templateUrl: 'childDirective.html', controller: function(log) { log('childController'); } }; }); directive('babyDirective', function() { return { require: '^childDirective', templateUrl: 'babyDirective.html', controller: function(log) { log('babyController'); } }; }); }); inject(function($templateCache, log, $compile, $rootScope) { $templateCache.put('parentDirective.html', '<div ng-transclude>parentTemplateText;</div>'); $templateCache.put('childDirective.html', '<span ng-transclude>childTemplateText;</span>'); $templateCache.put('babyDirective.html', '<span>babyTemplateText;</span>'); element = $compile('<div parent-directive>' + '<div child-directive>' + 'childContentText;' + '<div baby-directive>babyContent;</div>' + '</div>' + '</div>')($rootScope); $rootScope.$apply(); expect(log).toEqual('parentController; childController; babyController'); expect(element.text()).toBe('childContentText;babyTemplateText;'); }); }); it('should allow controller usage in pre-link directive functions with templateUrl', function() { module(function() { var Ctrl = function(log) { log('instance'); }; directive('myDirective', function() { return { scope: true, templateUrl: 'hello.html', controller: Ctrl, compile: function() { return { pre: function(scope, template, attr, ctrl) {}, post: function() {} }; } }; }); }); inject(function($templateCache, $compile, $rootScope, log) { $templateCache.put('hello.html', '<p>Hello</p>'); element = $compile('<div my-directive></div>')($rootScope); $rootScope.$apply(); expect(log).toEqual('instance'); expect(element.text()).toBe('Hello'); }); }); it('should allow controller usage in pre-link directive functions with a template', function() { module(function() { var Ctrl = function(log) { log('instance'); }; directive('myDirective', function() { return { scope: true, template: '<p>Hello</p>', controller: Ctrl, compile: function() { return { pre: function(scope, template, attr, ctrl) {}, post: function() {} }; } }; }); }); inject(function($templateCache, $compile, $rootScope, log) { element = $compile('<div my-directive></div>')($rootScope); $rootScope.$apply(); expect(log).toEqual('instance'); expect(element.text()).toBe('Hello'); }); }); it('should throw ctreq with correct directive name, regardless of order', function() { module(function($compileProvider) { $compileProvider.directive('aDir', valueFn({ restrict: "E", require: "ngModel", link: noop })); }); inject(function($compile, $rootScope) { expect(function() { // a-dir will cause a ctreq error to be thrown. Previously, the error would reference // the last directive in the chain (which in this case would be ngClick), based on // priority and alphabetical ordering. This test verifies that the ordering does not // affect which directive is referenced in the minErr message. element = $compile('<a-dir ng-click="foo=bar"></a-dir>')($rootScope); }).toThrowMinErr('$compile', 'ctreq', "Controller 'ngModel', required by directive 'aDir', can't be found!"); }); }); }); describe('transclude', function() { describe('content transclusion', function() { it('should support transclude directive', function() { module(function() { directive('trans', function() { return { transclude: 'content', replace: true, scope: {}, link: function(scope) { scope.x='iso'; }, template: '<ul><li>W:{{x}}-{{$parent.$id}}-{{$id}};</li><li ng-transclude></li></ul>' }; }); }); inject(function(log, $rootScope, $compile) { element = $compile('<div><div trans>T:{{x}}-{{$parent.$id}}-{{$id}}<span>;</span></div></div>')($rootScope); $rootScope.x = 'root'; $rootScope.$apply(); expect(element.text()).toEqual('W:iso-1-2;T:root-2-3;'); expect(jqLite(element.find('span')[0]).text()).toEqual('T:root-2-3'); expect(jqLite(element.find('span')[1]).text()).toEqual(';'); }); }); it('should transclude transcluded content', function() { module(function() { directive('book', valueFn({ transclude: 'content', template: '<div>book-<div chapter>(<div ng-transclude></div>)</div></div>' })); directive('chapter', valueFn({ transclude: 'content', templateUrl: 'chapter.html' })); directive('section', valueFn({ transclude: 'content', template: '<div>section-!<div ng-transclude></div>!</div></div>' })); return function($httpBackend) { $httpBackend. expect('GET', 'chapter.html'). respond('<div>chapter-<div section>[<div ng-transclude></div>]</div></div>'); }; }); inject(function(log, $rootScope, $compile, $httpBackend) { element = $compile('<div><div book>paragraph</div></div>')($rootScope); $rootScope.$apply(); expect(element.text()).toEqual('book-'); $httpBackend.flush(); $rootScope.$apply(); expect(element.text()).toEqual('book-chapter-section-![(paragraph)]!'); }); }); it('should only allow one content transclusion per element', function() { module(function() { directive('first', valueFn({ transclude: true })); directive('second', valueFn({ transclude: true })); }); inject(function($compile) { expect(function() { $compile('<div first="" second=""></div>'); }).toThrowMinErr('$compile', 'multidir', /Multiple directives \[first, second\] asking for transclusion on: <div .+/); }); }); it('should not leak if two "element" transclusions are on the same element (with debug info)', function() { if (jQuery) { // jQuery 2.x doesn't expose the cache storage. return; } module(function($compileProvider) { $compileProvider.debugInfoEnabled(true); }); inject(function($compile, $rootScope) { expect(jqLiteCacheSize()).toEqual(0); element = $compile('<div><div ng-repeat="x in xs" ng-if="x==1">{{x}}</div></div>')($rootScope); expect(jqLiteCacheSize()).toEqual(1); $rootScope.$apply('xs = [0,1]'); expect(jqLiteCacheSize()).toEqual(2); $rootScope.$apply('xs = [0]'); expect(jqLiteCacheSize()).toEqual(1); $rootScope.$apply('xs = []'); expect(jqLiteCacheSize()).toEqual(1); element.remove(); expect(jqLiteCacheSize()).toEqual(0); }); }); it('should not leak if two "element" transclusions are on the same element (without debug info)', function() { if (jQuery) { // jQuery 2.x doesn't expose the cache storage. return; } module(function($compileProvider) { $compileProvider.debugInfoEnabled(false); }); inject(function($compile, $rootScope) { expect(jqLiteCacheSize()).toEqual(0); element = $compile('<div><div ng-repeat="x in xs" ng-if="x==1">{{x}}</div></div>')($rootScope); expect(jqLiteCacheSize()).toEqual(0); $rootScope.$apply('xs = [0,1]'); expect(jqLiteCacheSize()).toEqual(0); $rootScope.$apply('xs = [0]'); expect(jqLiteCacheSize()).toEqual(0); $rootScope.$apply('xs = []'); expect(jqLiteCacheSize()).toEqual(0); element.remove(); expect(jqLiteCacheSize()).toEqual(0); }); }); it('should not leak if two "element" transclusions are on the same element (with debug info)', function() { if (jQuery) { // jQuery 2.x doesn't expose the cache storage. return; } module(function($compileProvider) { $compileProvider.debugInfoEnabled(true); }); inject(function($compile, $rootScope) { expect(jqLiteCacheSize()).toEqual(0); element = $compile('<div><div ng-repeat="x in xs" ng-if="val">{{x}}</div></div>')($rootScope); $rootScope.$apply('xs = [0,1]'); // At this point we have a bunch of comment placeholders but no real transcluded elements // So the cache only contains the root element's data expect(jqLiteCacheSize()).toEqual(1); $rootScope.$apply('val = true'); // Now we have two concrete transcluded elements plus some comments so two more cache items expect(jqLiteCacheSize()).toEqual(3); $rootScope.$apply('val = false'); // Once again we only have comments so no transcluded elements and the cache is back to just // the root element expect(jqLiteCacheSize()).toEqual(1); element.remove(); // Now we've even removed the root element along with its cache expect(jqLiteCacheSize()).toEqual(0); }); }); it('should not leak when continuing the compilation of elements on a scope that was destroyed', function() { if (jQuery) { // jQuery 2.x doesn't expose the cache storage. return; } var linkFn = jasmine.createSpy('linkFn'); module(function($controllerProvider, $compileProvider) { $controllerProvider.register('Leak', function($scope, $timeout) { $scope.code = 'red'; $timeout(function() { $scope.code = 'blue'; }); }); $compileProvider.directive('isolateRed', function() { return { restrict: 'A', scope: {}, template: '<div red></div>' }; }); $compileProvider.directive('red', function() { return { restrict: 'A', templateUrl: 'red.html', scope: {}, link: linkFn }; }); }); inject(function($compile, $rootScope, $httpBackend, $timeout, $templateCache) { $httpBackend.whenGET('red.html').respond('<p>red.html</p>'); var template = $compile( '<div ng-controller="Leak">' + '<div ng-switch="code">' + '<div ng-switch-when="red">' + '<div isolate-red></div>' + '</div>' + '</div>' + '</div>'); element = template($rootScope); $rootScope.$digest(); $timeout.flush(); $httpBackend.flush(); expect(linkFn).not.toHaveBeenCalled(); expect(jqLiteCacheSize()).toEqual(2); $templateCache.removeAll(); var destroyedScope = $rootScope.$new(); destroyedScope.$destroy(); var clone = template(destroyedScope); $rootScope.$digest(); $timeout.flush(); expect(linkFn).not.toHaveBeenCalled(); }); }); if (jQuery) { describe('cleaning up after a replaced element', function() { var $compile, xs; beforeEach(inject(function(_$compile_) { $compile = _$compile_; xs = [0, 1]; })); function testCleanup() { var privateData, firstRepeatedElem; element = $compile('<div><div ng-repeat="x in xs" ng-click="noop()">{{x}}</div></div>')($rootScope); $rootScope.$apply('xs = [' + xs + ']'); firstRepeatedElem = element.children('.ng-scope').eq(0); expect(firstRepeatedElem.data('$scope')).toBeDefined(); privateData = jQuery._data(firstRepeatedElem[0]); expect(privateData.events).toBeDefined(); expect(privateData.events.click).toBeDefined(); expect(privateData.events.click[0]).toBeDefined(); //Ensure the angular $destroy event is still sent var destroyCount = 0; element.find("div").on("$destroy", function() { destroyCount++; }); $rootScope.$apply('xs = null'); expect(destroyCount).toBe(2); expect(firstRepeatedElem.data('$scope')).not.toBeDefined(); privateData = jQuery._data(firstRepeatedElem[0]); expect(privateData && privateData.events).not.toBeDefined(); } it('should work without external libraries (except jQuery)', testCleanup); it('should work with another library patching jQuery.cleanData after Angular', function() { var cleanedCount = 0; var currentCleanData = jQuery.cleanData; jQuery.cleanData = function(elems) { cleanedCount += elems.length; // Don't return the output and expicitly pass only the first parameter // so that we're sure we're not relying on either of them. jQuery UI patch // behaves in this way. currentCleanData(elems); }; testCleanup(); expect(cleanedCount).toBe(xs.length); // Restore the previous jQuery.cleanData. jQuery.cleanData = currentCleanData; }); }); } it('should add a $$transcluded property onto the transcluded scope', function() { module(function() { directive('trans', function() { return { transclude: true, replace: true, scope: true, template: '<div><span>I:{{$$transcluded}}</span><div ng-transclude></div></div>' }; }); }); inject(function(log, $rootScope, $compile) { element = $compile('<div><div trans>T:{{$$transcluded}}</div></div>')($rootScope); $rootScope.$apply(); expect(jqLite(element.find('span')[0]).text()).toEqual('I:'); expect(jqLite(element.find('span')[1]).text()).toEqual('T:true'); }); }); it('should clear contents of the ng-translude element before appending transcluded content', function() { module(function() { directive('trans', function() { return { transclude: true, template: '<div ng-transclude>old stuff! </div>' }; }); }); inject(function(log, $rootScope, $compile) { element = $compile('<div trans>unicorn!</div>')($rootScope); $rootScope.$apply(); expect(sortedHtml(element.html())).toEqual('<div ng-transclude=""><span>unicorn!</span></div>'); }); }); it('should throw on an ng-transclude element inside no transclusion directive', function() { inject(function($rootScope, $compile) { // we need to do this because different browsers print empty attributes differently try { $compile('<div><div ng-transclude></div></div>')($rootScope); } catch (e) { expect(e.message).toMatch(new RegExp( '^\\[ngTransclude:orphan\\] ' + 'Illegal use of ngTransclude directive in the template! ' + 'No parent directive that requires a transclusion found\\. ' + 'Element: <div ng-transclude.+')); } }); }); it('should not pass transclusion into a template directive when the directive didn\'t request transclusion', function() { module(function($compileProvider) { $compileProvider.directive('transFoo', valueFn({ template: '<div>' + '<div no-trans-bar></div>' + '<div ng-transclude>this one should get replaced with content</div>' + '<div class="foo" ng-transclude></div>' + '</div>', transclude: true })); $compileProvider.directive('noTransBar', valueFn({ template: '<div>' + // This ng-transclude is invalid. It should throw an error. '<div class="bar" ng-transclude></div>' + '</div>', transclude: false })); }); inject(function($compile, $rootScope) { expect(function() { $compile('<div trans-foo>content</div>')($rootScope); }).toThrowMinErr('ngTransclude', 'orphan', 'Illegal use of ngTransclude directive in the template! No parent directive that requires a transclusion found. Element: <div class="bar" ng-transclude="">'); }); }); it('should not pass transclusion into a templateUrl directive', function() { module(function($compileProvider) { $compileProvider.directive('transFoo', valueFn({ template: '<div>' + '<div no-trans-bar></div>' + '<div ng-transclude>this one should get replaced with content</div>' + '<div class="foo" ng-transclude></div>' + '</div>', transclude: true })); $compileProvider.directive('noTransBar', valueFn({ templateUrl: 'noTransBar.html', transclude: false })); }); inject(function($compile, $rootScope, $templateCache) { $templateCache.put('noTransBar.html', '<div>' + // This ng-transclude is invalid. It should throw an error. '<div class="bar" ng-transclude></div>' + '</div>'); expect(function() { element = $compile('<div trans-foo>content</div>')($rootScope); $rootScope.$apply(); }).toThrowMinErr('ngTransclude', 'orphan', 'Illegal use of ngTransclude directive in the template! No parent directive that requires a transclusion found. Element: <div class="bar" ng-transclude="">'); }); }); it('should expose transcludeFn in compile fn even for templateUrl', function() { module(function() { directive('transInCompile', valueFn({ transclude: true, // template: '<div class="foo">whatever</div>', templateUrl: 'foo.html', compile: function(_, __, transclude) { return function(scope, element) { transclude(scope, function(clone, scope) { element.html(''); element.append(clone); }); }; } })); }); inject(function($compile, $rootScope, $templateCache) { $templateCache.put('foo.html', '<div class="foo">whatever</div>'); compile('<div trans-in-compile>transcluded content</div>'); $rootScope.$apply(); expect(trim(element.text())).toBe('transcluded content'); }); }); it('should make the result of a transclusion available to the parent directive in post-linking phase' + '(template)', function() { module(function() { directive('trans', function(log) { return { transclude: true, template: '<div ng-transclude></div>', link: { pre: function($scope, $element) { log('pre(' + $element.text() + ')'); }, post: function($scope, $element) { log('post(' + $element.text() + ')'); } } }; }); }); inject(function(log, $rootScope, $compile) { element = $compile('<div trans><span>unicorn!</span></div>')($rootScope); $rootScope.$apply(); expect(log).toEqual('pre(); post(unicorn!)'); }); }); it('should make the result of a transclusion available to the parent directive in post-linking phase' + '(templateUrl)', function() { // when compiling an async directive the transclusion is always processed before the directive // this is different compared to sync directive. delaying the transclusion makes little sense. module(function() { directive('trans', function(log) { return { transclude: true, templateUrl: 'trans.html', link: { pre: function($scope, $element) { log('pre(' + $element.text() + ')'); }, post: function($scope, $element) { log('post(' + $element.text() + ')'); } } }; }); }); inject(function(log, $rootScope, $compile, $templateCache) { $templateCache.put('trans.html', '<div ng-transclude></div>'); element = $compile('<div trans><span>unicorn!</span></div>')($rootScope); $rootScope.$apply(); expect(log).toEqual('pre(); post(unicorn!)'); }); }); it('should make the result of a transclusion available to the parent *replace* directive in post-linking phase' + '(template)', function() { module(function() { directive('replacedTrans', function(log) { return { transclude: true, replace: true, template: '<div ng-transclude></div>', link: { pre: function($scope, $element) { log('pre(' + $element.text() + ')'); }, post: function($scope, $element) { log('post(' + $element.text() + ')'); } } }; }); }); inject(function(log, $rootScope, $compile) { element = $compile('<div replaced-trans><span>unicorn!</span></div>')($rootScope); $rootScope.$apply(); expect(log).toEqual('pre(); post(unicorn!)'); }); }); it('should make the result of a transclusion available to the parent *replace* directive in post-linking phase' + ' (templateUrl)', function() { module(function() { directive('replacedTrans', function(log) { return { transclude: true, replace: true, templateUrl: 'trans.html', link: { pre: function($scope, $element) { log('pre(' + $element.text() + ')'); }, post: function($scope, $element) { log('post(' + $element.text() + ')'); } } }; }); }); inject(function(log, $rootScope, $compile, $templateCache) { $templateCache.put('trans.html', '<div ng-transclude></div>'); element = $compile('<div replaced-trans><span>unicorn!</span></div>')($rootScope); $rootScope.$apply(); expect(log).toEqual('pre(); post(unicorn!)'); }); }); it('should copy the directive controller to all clones', function() { var transcludeCtrl, cloneCount = 2; module(function() { directive('transclude', valueFn({ transclude: 'content', controller: function($transclude) { transcludeCtrl = this; }, link: function(scope, el, attr, ctrl, $transclude) { var i; for (i = 0; i < cloneCount; i++) { $transclude(cloneAttach); } function cloneAttach(clone) { el.append(clone); } } })); }); inject(function($compile) { element = $compile('<div transclude><span></span></div>')($rootScope); var children = element.children(), i; expect(transcludeCtrl).toBeDefined(); expect(element.data('$transcludeController')).toBe(transcludeCtrl); for (i = 0; i < cloneCount; i++) { expect(children.eq(i).data('$transcludeController')).toBeUndefined(); } }); }); it('should provide the $transclude controller local as 5th argument to the pre and post-link function', function() { var ctrlTransclude, preLinkTransclude, postLinkTransclude; module(function() { directive('transclude', valueFn({ transclude: 'content', controller: function($transclude) { ctrlTransclude = $transclude; }, compile: function() { return { pre: function(scope, el, attr, ctrl, $transclude) { preLinkTransclude = $transclude; }, post: function(scope, el, attr, ctrl, $transclude) { postLinkTransclude = $transclude; } }; } })); }); inject(function($compile) { element = $compile('<div transclude></div>')($rootScope); expect(ctrlTransclude).toBeDefined(); expect(ctrlTransclude).toBe(preLinkTransclude); expect(ctrlTransclude).toBe(postLinkTransclude); }); }); it('should allow an optional scope argument in $transclude', function() { var capturedChildCtrl; module(function() { directive('transclude', valueFn({ transclude: 'content', link: function(scope, element, attr, ctrl, $transclude) { $transclude(scope, function(clone) { element.append(clone); }); } })); }); inject(function($compile) { element = $compile('<div transclude>{{$id}}</div>')($rootScope); $rootScope.$apply(); expect(element.text()).toBe('' + $rootScope.$id); }); }); it('should expose the directive controller to transcluded children', function() { var capturedChildCtrl; module(function() { directive('transclude', valueFn({ transclude: 'content', controller: function() { }, link: function(scope, element, attr, ctrl, $transclude) { $transclude(function(clone) { element.append(clone); }); } })); directive('child', valueFn({ require: '^transclude', link: function(scope, element, attr, ctrl) { capturedChildCtrl = ctrl; } })); }); inject(function($compile) { element = $compile('<div transclude><div child></div></div>')($rootScope); expect(capturedChildCtrl).toBeTruthy(); }); }); // see issue https://github.com/angular/angular.js/issues/9413 describe('passing a parent bound transclude function to the link ' + 'function returned from `$compile`', function() { beforeEach(module(function() { directive('lazyCompile', function($compile) { return { compile: function(tElement, tAttrs) { var content = tElement.contents(); tElement.empty(); return function(scope, element, attrs, ctrls, transcludeFn) { element.append(content); $compile(content)(scope, undefined, { parentBoundTranscludeFn: transcludeFn }); }; } }; }); directive('toggle', valueFn({ scope: {t: '=toggle'}, transclude: true, template: '<div ng-if="t"><lazy-compile><div ng-transclude></div></lazy-compile></div>' })); })); it('should preserve the bound scope', function() { inject(function($compile, $rootScope) { element = $compile( '<div>' + '<div ng-init="outer=true"></div>' + '<div toggle="t">' + '<span ng-if="outer">Success</span><span ng-if="!outer">Error</span>' + '</div>' + '</div>')($rootScope); $rootScope.$apply('t = false'); expect($rootScope.$countChildScopes()).toBe(1); expect(element.text()).toBe(''); $rootScope.$apply('t = true'); expect($rootScope.$countChildScopes()).toBe(4); expect(element.text()).toBe('Success'); $rootScope.$apply('t = false'); expect($rootScope.$countChildScopes()).toBe(1); expect(element.text()).toBe(''); $rootScope.$apply('t = true'); expect($rootScope.$countChildScopes()).toBe(4); expect(element.text()).toBe('Success'); }); }); it('should preserve the bound scope when using recursive transclusion', function() { directive('recursiveTransclude', valueFn({ transclude: true, template: '<div><lazy-compile><div ng-transclude></div></lazy-compile></div>' })); inject(function($compile, $rootScope) { element = $compile( '<div>' + '<div ng-init="outer=true"></div>' + '<div toggle="t">' + '<div recursive-transclude>' + '<span ng-if="outer">Success</span><span ng-if="!outer">Error</span>' + '</div>' + '</div>' + '</div>')($rootScope); $rootScope.$apply('t = false'); expect($rootScope.$countChildScopes()).toBe(1); expect(element.text()).toBe(''); $rootScope.$apply('t = true'); expect($rootScope.$countChildScopes()).toBe(4); expect(element.text()).toBe('Success'); $rootScope.$apply('t = false'); expect($rootScope.$countChildScopes()).toBe(1); expect(element.text()).toBe(''); $rootScope.$apply('t = true'); expect($rootScope.$countChildScopes()).toBe(4); expect(element.text()).toBe('Success'); }); }); }); // see issue https://github.com/angular/angular.js/issues/9095 describe('removing a transcluded element', function() { beforeEach(module(function() { directive('toggle', function() { return { transclude: true, template: '<div ng:if="t"><div ng:transclude></div></div>' }; }); })); it('should not leak the transclude scope when the transcluded content is an element transclusion directive', inject(function($compile, $rootScope) { element = $compile( '<div toggle>' + '<div ng:repeat="msg in [\'msg-1\']">{{ msg }}</div>' + '</div>' )($rootScope); $rootScope.$apply('t = true'); expect(element.text()).toContain('msg-1'); // Expected scopes: $rootScope, ngIf, transclusion, ngRepeat expect($rootScope.$countChildScopes()).toBe(3); $rootScope.$apply('t = false'); expect(element.text()).not.toContain('msg-1'); // Expected scopes: $rootScope expect($rootScope.$countChildScopes()).toBe(0); $rootScope.$apply('t = true'); expect(element.text()).toContain('msg-1'); // Expected scopes: $rootScope, ngIf, transclusion, ngRepeat expect($rootScope.$countChildScopes()).toBe(3); $rootScope.$apply('t = false'); expect(element.text()).not.toContain('msg-1'); // Expected scopes: $rootScope expect($rootScope.$countChildScopes()).toBe(0); })); it('should not leak the transclude scope when the transcluded content is an multi-element transclusion directive', inject(function($compile, $rootScope) { element = $compile( '<div toggle>' + '<div ng:repeat-start="msg in [\'msg-1\']">{{ msg }}</div>' + '<div ng:repeat-end>{{ msg }}</div>' + '</div>' )($rootScope); $rootScope.$apply('t = true'); expect(element.text()).toContain('msg-1msg-1'); // Expected scopes: $rootScope, ngIf, transclusion, ngRepeat expect($rootScope.$countChildScopes()).toBe(3); $rootScope.$apply('t = false'); expect(element.text()).not.toContain('msg-1msg-1'); // Expected scopes: $rootScope expect($rootScope.$countChildScopes()).toBe(0); $rootScope.$apply('t = true'); expect(element.text()).toContain('msg-1msg-1'); // Expected scopes: $rootScope, ngIf, transclusion, ngRepeat expect($rootScope.$countChildScopes()).toBe(3); $rootScope.$apply('t = false'); expect(element.text()).not.toContain('msg-1msg-1'); // Expected scopes: $rootScope expect($rootScope.$countChildScopes()).toBe(0); })); it('should not leak the transclude scope if the transcluded contains only comments', inject(function($compile, $rootScope) { element = $compile( '<div toggle>' + '<!-- some comment -->' + '</div>' )($rootScope); $rootScope.$apply('t = true'); expect(element.html()).toContain('some comment'); // Expected scopes: $rootScope, ngIf, transclusion expect($rootScope.$countChildScopes()).toBe(2); $rootScope.$apply('t = false'); expect(element.html()).not.toContain('some comment'); // Expected scopes: $rootScope expect($rootScope.$countChildScopes()).toBe(0); $rootScope.$apply('t = true'); expect(element.html()).toContain('some comment'); // Expected scopes: $rootScope, ngIf, transclusion expect($rootScope.$countChildScopes()).toBe(2); $rootScope.$apply('t = false'); expect(element.html()).not.toContain('some comment'); // Expected scopes: $rootScope expect($rootScope.$countChildScopes()).toBe(0); })); it('should not leak the transclude scope if the transcluded contains only text nodes', inject(function($compile, $rootScope) { element = $compile( '<div toggle>' + 'some text' + '</div>' )($rootScope); $rootScope.$apply('t = true'); expect(element.html()).toContain('some text'); // Expected scopes: $rootScope, ngIf, transclusion expect($rootScope.$countChildScopes()).toBe(2); $rootScope.$apply('t = false'); expect(element.html()).not.toContain('some text'); // Expected scopes: $rootScope expect($rootScope.$countChildScopes()).toBe(0); $rootScope.$apply('t = true'); expect(element.html()).toContain('some text'); // Expected scopes: $rootScope, ngIf, transclusion expect($rootScope.$countChildScopes()).toBe(2); $rootScope.$apply('t = false'); expect(element.html()).not.toContain('some text'); // Expected scopes: $rootScope expect($rootScope.$countChildScopes()).toBe(0); })); it('should mark as destroyed all sub scopes of the scope being destroyed', inject(function($compile, $rootScope) { element = $compile( '<div toggle>' + '<div ng:repeat="msg in [\'msg-1\']">{{ msg }}</div>' + '</div>' )($rootScope); $rootScope.$apply('t = true'); var childScopes = getChildScopes($rootScope); $rootScope.$apply('t = false'); for (var i = 0; i < childScopes.length; ++i) { expect(childScopes[i].$$destroyed).toBe(true); } })); }); describe('nested transcludes', function() { beforeEach(module(function($compileProvider) { $compileProvider.directive('noop', valueFn({})); $compileProvider.directive('sync', valueFn({ template: '<div ng-transclude></div>', transclude: true })); $compileProvider.directive('async', valueFn({ templateUrl: 'async', transclude: true })); $compileProvider.directive('syncSync', valueFn({ template: '<div noop><div sync><div ng-transclude></div></div></div>', transclude: true })); $compileProvider.directive('syncAsync', valueFn({ template: '<div noop><div async><div ng-transclude></div></div></div>', transclude: true })); $compileProvider.directive('asyncSync', valueFn({ templateUrl: 'asyncSync', transclude: true })); $compileProvider.directive('asyncAsync', valueFn({ templateUrl: 'asyncAsync', transclude: true })); })); beforeEach(inject(function($templateCache) { $templateCache.put('async', '<div ng-transclude></div>'); $templateCache.put('asyncSync', '<div noop><div sync><div ng-transclude></div></div></div>'); $templateCache.put('asyncAsync', '<div noop><div async><div ng-transclude></div></div></div>'); })); it('should allow nested transclude directives with sync template containing sync template', inject(function($compile, $rootScope) { element = $compile('<div sync-sync>transcluded content</div>')($rootScope); $rootScope.$digest(); expect(element.text()).toEqual('transcluded content'); })); it('should allow nested transclude directives with sync template containing async template', inject(function($compile, $rootScope) { element = $compile('<div sync-async>transcluded content</div>')($rootScope); $rootScope.$digest(); expect(element.text()).toEqual('transcluded content'); })); it('should allow nested transclude directives with async template containing sync template', inject(function($compile, $rootScope) { element = $compile('<div async-sync>transcluded content</div>')($rootScope); $rootScope.$digest(); expect(element.text()).toEqual('transcluded content'); })); it('should allow nested transclude directives with async template containing asynch template', inject(function($compile, $rootScope) { element = $compile('<div async-async>transcluded content</div>')($rootScope); $rootScope.$digest(); expect(element.text()).toEqual('transcluded content'); })); it('should not leak memory with nested transclusion', function() { inject(function($compile, $rootScope) { var size; expect(jqLiteCacheSize()).toEqual(0); element = jqLite('<div><ul><li ng-repeat="n in nums">{{n}} => <i ng-if="0 === n%2">Even</i><i ng-if="1 === n%2">Odd</i></li></ul></div>'); $compile(element)($rootScope.$new()); $rootScope.nums = [0,1,2]; $rootScope.$apply(); size = jqLiteCacheSize(); $rootScope.nums = [3,4,5]; $rootScope.$apply(); expect(jqLiteCacheSize()).toEqual(size); element.remove(); expect(jqLiteCacheSize()).toEqual(0); }); }); }); describe('nested isolated scope transcludes', function() { beforeEach(module(function($compileProvider) { $compileProvider.directive('trans', valueFn({ restrict: 'E', template: '<div ng-transclude></div>', transclude: true })); $compileProvider.directive('transAsync', valueFn({ restrict: 'E', templateUrl: 'transAsync', transclude: true })); $compileProvider.directive('iso', valueFn({ restrict: 'E', transclude: true, template: '<trans><span ng-transclude></span></trans>', scope: {} })); $compileProvider.directive('isoAsync1', valueFn({ restrict: 'E', transclude: true, template: '<trans-async><span ng-transclude></span></trans-async>', scope: {} })); $compileProvider.directive('isoAsync2', valueFn({ restrict: 'E', transclude: true, templateUrl: 'isoAsync', scope: {} })); })); beforeEach(inject(function($templateCache) { $templateCache.put('transAsync', '<div ng-transclude></div>'); $templateCache.put('isoAsync', '<trans-async><span ng-transclude></span></trans-async>'); })); it('should pass the outer scope to the transclude on the isolated template sync-sync', inject(function($compile, $rootScope) { $rootScope.val = 'transcluded content'; element = $compile('<iso><span ng-bind="val"></span></iso>')($rootScope); $rootScope.$digest(); expect(element.text()).toEqual('transcluded content'); })); it('should pass the outer scope to the transclude on the isolated template async-sync', inject(function($compile, $rootScope) { $rootScope.val = 'transcluded content'; element = $compile('<iso-async1><span ng-bind="val"></span></iso-async1>')($rootScope); $rootScope.$digest(); expect(element.text()).toEqual('transcluded content'); })); it('should pass the outer scope to the transclude on the isolated template async-async', inject(function($compile, $rootScope) { $rootScope.val = 'transcluded content'; element = $compile('<iso-async2><span ng-bind="val"></span></iso-async2>')($rootScope); $rootScope.$digest(); expect(element.text()).toEqual('transcluded content'); })); }); describe('multiple siblings receiving transclusion', function() { it("should only receive transclude from parent", function() { module(function($compileProvider) { $compileProvider.directive('myExample', valueFn({ scope: {}, link: function link(scope, element, attrs) { var foo = element[0].querySelector('.foo'); scope.children = angular.element(foo).children().length; }, template: '<div>' + '<div>myExample {{children}}!</div>' + '<div ng-if="children">has children</div>' + '<div class="foo" ng-transclude></div>' + '</div>', transclude: true })); }); inject(function($compile, $rootScope) { var element = $compile('<div my-example></div>')($rootScope); $rootScope.$digest(); expect(element.text()).toEqual('myExample 0!'); dealoc(element); element = $compile('<div my-example><p></p></div>')($rootScope); $rootScope.$digest(); expect(element.text()).toEqual('myExample 1!has children'); dealoc(element); }); }); }); }); describe('element transclusion', function() { it('should support basic element transclusion', function() { module(function() { directive('trans', function(log) { return { transclude: 'element', priority: 2, controller: function($transclude) { this.$transclude = $transclude; }, compile: function(element, attrs, template) { log('compile: ' + angular.mock.dump(element)); return function(scope, element, attrs, ctrl) { log('link'); var cursor = element; template(scope.$new(), function(clone) {cursor.after(cursor = clone);}); ctrl.$transclude(function(clone) {cursor.after(clone);}); }; } }; }); }); inject(function(log, $rootScope, $compile) { element = $compile('<div><div high-log trans="text" log>{{$parent.$id}}-{{$id}};</div></div>')($rootScope); $rootScope.$apply(); expect(log).toEqual('compile: <!-- trans: text -->; link; LOG; LOG; HIGH'); expect(element.text()).toEqual('1-2;1-3;'); }); }); it('should only allow one element transclusion per element', function() { module(function() { directive('first', valueFn({ transclude: 'element' })); directive('second', valueFn({ transclude: 'element' })); }); inject(function($compile) { expect(function() { $compile('<div first second></div>'); }).toThrowMinErr('$compile', 'multidir', 'Multiple directives [first, second] asking for transclusion on: ' + '<!-- first: -->'); }); }); it('should only allow one element transclusion per element when directives have different priorities', function() { // we restart compilation in this case and we need to remember the duplicates during the second compile // regression #3893 module(function() { directive('first', valueFn({ transclude: 'element', priority: 100 })); directive('second', valueFn({ transclude: 'element' })); }); inject(function($compile) { expect(function() { $compile('<div first second></div>'); }).toThrowMinErr('$compile', 'multidir', /Multiple directives \[first, second\] asking for transclusion on: <div .+/); }); }); it('should only allow one element transclusion per element when async replace directive is in the mix', function() { module(function() { directive('template', valueFn({ templateUrl: 'template.html', replace: true })); directive('first', valueFn({ transclude: 'element', priority: 100 })); directive('second', valueFn({ transclude: 'element' })); }); inject(function($compile, $httpBackend) { $httpBackend.expectGET('template.html').respond('<p second>template.html</p>'); $compile('<div template first></div>'); expect(function() { $httpBackend.flush(); }).toThrowMinErr('$compile', 'multidir', /Multiple directives \[first, second\] asking for transclusion on: <p .+/); }); }); it('should only allow one element transclusion per element when replace directive is in the mix', function() { module(function() { directive('template', valueFn({ template: '<p second></p>', replace: true })); directive('first', valueFn({ transclude: 'element', priority: 100 })); directive('second', valueFn({ transclude: 'element' })); }); inject(function($compile) { expect(function() { $compile('<div template first></div>'); }).toThrowMinErr('$compile', 'multidir', /Multiple directives \[first, second\] asking for transclusion on: <p .+/); }); }); it('should support transcluded element on root content', function() { var comment; module(function() { directive('transclude', valueFn({ transclude: 'element', compile: function(element, attr, linker) { return function(scope, element, attr) { comment = element; }; } })); }); inject(function($compile, $rootScope) { var element = jqLite('<div>before<div transclude></div>after</div>').contents(); expect(element.length).toEqual(3); expect(nodeName_(element[1])).toBe('div'); $compile(element)($rootScope); expect(nodeName_(element[1])).toBe('#comment'); expect(nodeName_(comment)).toBe('#comment'); }); }); it('should terminate compilation only for element trasclusion', function() { module(function() { directive('elementTrans', function(log) { return { transclude: 'element', priority: 50, compile: log.fn('compile:elementTrans') }; }); directive('regularTrans', function(log) { return { transclude: true, priority: 50, compile: log.fn('compile:regularTrans') }; }); }); inject(function(log, $compile, $rootScope) { $compile('<div><div element-trans log="elem"></div><div regular-trans log="regular"></div></div>')($rootScope); expect(log).toEqual('compile:elementTrans; compile:regularTrans; regular'); }); }); it('should instantiate high priority controllers only once, but low priority ones each time we transclude', function() { module(function() { directive('elementTrans', function(log) { return { transclude: 'element', priority: 50, controller: function($transclude, $element) { log('controller:elementTrans'); $transclude(function(clone) { $element.after(clone); }); $transclude(function(clone) { $element.after(clone); }); $transclude(function(clone) { $element.after(clone); }); } }; }); directive('normalDir', function(log) { return { controller: function() { log('controller:normalDir'); } }; }); }); inject(function($compile, $rootScope, log) { element = $compile('<div><div element-trans normal-dir></div></div>')($rootScope); expect(log).toEqual([ 'controller:elementTrans', 'controller:normalDir', 'controller:normalDir', 'controller:normalDir' ]); }); }); it('should allow to access $transclude in the same directive', function() { var _$transclude; module(function() { directive('transclude', valueFn({ transclude: 'element', controller: function($transclude) { _$transclude = $transclude; } })); }); inject(function($compile) { element = $compile('<div transclude></div>')($rootScope); expect(_$transclude).toBeDefined(); }); }); it('should copy the directive controller to all clones', function() { var transcludeCtrl, cloneCount = 2; module(function() { directive('transclude', valueFn({ transclude: 'element', controller: function() { transcludeCtrl = this; }, link: function(scope, el, attr, ctrl, $transclude) { var i; for (i = 0; i < cloneCount; i++) { $transclude(cloneAttach); } function cloneAttach(clone) { el.after(clone); } } })); }); inject(function($compile) { element = $compile('<div><div transclude></div></div>')($rootScope); var children = element.children(), i; for (i = 0; i < cloneCount; i++) { expect(children.eq(i).data('$transcludeController')).toBe(transcludeCtrl); } }); }); it('should expose the directive controller to transcluded children', function() { var capturedTranscludeCtrl; module(function() { directive('transclude', valueFn({ transclude: 'element', controller: function() { }, link: function(scope, element, attr, ctrl, $transclude) { $transclude(scope, function(clone) { element.after(clone); }); } })); directive('child', valueFn({ require: '^transclude', link: function(scope, element, attr, ctrl) { capturedTranscludeCtrl = ctrl; } })); }); inject(function($compile) { // We need to wrap the transclude directive's element in a parent element so that the // cloned element gets deallocated/cleaned up correctly element = $compile('<div><div transclude><div child></div></div></div>')($rootScope); expect(capturedTranscludeCtrl).toBeTruthy(); }); }); it('should allow access to $transclude in a templateUrl directive', function() { var transclude; module(function() { directive('template', valueFn({ templateUrl: 'template.html', replace: true })); directive('transclude', valueFn({ transclude: 'content', controller: function($transclude) { transclude = $transclude; } })); }); inject(function($compile, $httpBackend) { $httpBackend.expectGET('template.html').respond('<div transclude></div>'); element = $compile('<div template></div>')($rootScope); $httpBackend.flush(); expect(transclude).toBeDefined(); }); }); // issue #6006 it('should link directive with $element as a comment node', function() { module(function($provide) { directive('innerAgain', function(log) { return { transclude: 'element', link: function(scope, element, attr, controllers, transclude) { log('innerAgain:' + lowercase(nodeName_(element)) + ':' + trim(element[0].data)); transclude(scope, function(clone) { element.parent().append(clone); }); } }; }); directive('inner', function(log) { return { replace: true, templateUrl: 'inner.html', link: function(scope, element) { log('inner:' + lowercase(nodeName_(element)) + ':' + trim(element[0].data)); } }; }); directive('outer', function(log) { return { transclude: 'element', link: function(scope, element, attrs, controllers, transclude) { log('outer:' + lowercase(nodeName_(element)) + ':' + trim(element[0].data)); transclude(scope, function(clone) { element.parent().append(clone); }); } }; }); }); inject(function(log, $compile, $rootScope, $templateCache) { $templateCache.put('inner.html', '<div inner-again><p>Content</p></div>'); element = $compile('<div><div outer><div inner></div></div></div>')($rootScope); $rootScope.$digest(); var child = element.children(); expect(log.toArray()).toEqual([ "outer:#comment:outer:", "innerAgain:#comment:innerAgain:", "inner:#comment:innerAgain:" ]); expect(child.length).toBe(1); expect(child.contents().length).toBe(2); expect(lowercase(nodeName_(child.contents().eq(0)))).toBe('#comment'); expect(lowercase(nodeName_(child.contents().eq(1)))).toBe('div'); }); }); }); it('should safely create transclude comment node and not break with "-->"', inject(function($rootScope) { // see: https://github.com/angular/angular.js/issues/1740 element = $compile('<ul><li ng-repeat="item in [\'-->\', \'x\']">{{item}}|</li></ul>')($rootScope); $rootScope.$digest(); expect(element.text()).toBe('-->|x|'); })); // See https://github.com/angular/angular.js/issues/7183 it("should pass transclusion through to template of a 'replace' directive", function() { module(function() { directive('transSync', function() { return { transclude: true, link: function(scope, element, attr, ctrl, transclude) { expect(transclude).toEqual(jasmine.any(Function)); transclude(function(child) { element.append(child); }); } }; }); directive('trans', function($timeout) { return { transclude: true, link: function(scope, element, attrs, ctrl, transclude) { // We use timeout here to simulate how ng-if works $timeout(function() { transclude(function(child) { element.append(child); }); }); } }; }); directive('replaceWithTemplate', function() { return { templateUrl: "template.html", replace: true }; }); }); inject(function($compile, $rootScope, $templateCache, $timeout) { $templateCache.put('template.html', '<div trans-sync>Content To Be Transcluded</div>'); expect(function() { element = $compile('<div><div trans><div replace-with-template></div></div></div>')($rootScope); $timeout.flush(); }).not.toThrow(); expect(element.text()).toEqual('Content To Be Transcluded'); }); }); it('should lazily compile the contents of directives that are transcluded', function() { var innerCompilationCount = 0, transclude; module(function() { directive('trans', valueFn({ transclude: true, controller: function($transclude) { transclude = $transclude; } })); directive('inner', valueFn({ template: '<span>FooBar</span>', compile: function() { innerCompilationCount +=1; } })); }); inject(function($compile, $rootScope) { element = $compile('<trans><inner></inner></trans>')($rootScope); expect(innerCompilationCount).toBe(0); transclude(function(child) { element.append(child); }); expect(innerCompilationCount).toBe(1); expect(element.text()).toBe('FooBar'); }); }); it('should lazily compile the contents of directives that are transcluded with a template', function() { var innerCompilationCount = 0, transclude; module(function() { directive('trans', valueFn({ transclude: true, template: '<div>Baz</div>', controller: function($transclude) { transclude = $transclude; } })); directive('inner', valueFn({ template: '<span>FooBar</span>', compile: function() { innerCompilationCount +=1; } })); }); inject(function($compile, $rootScope) { element = $compile('<trans><inner></inner></trans>')($rootScope); expect(innerCompilationCount).toBe(0); transclude(function(child) { element.append(child); }); expect(innerCompilationCount).toBe(1); expect(element.text()).toBe('BazFooBar'); }); }); it('should lazily compile the contents of directives that are transcluded with a templateUrl', function() { var innerCompilationCount = 0, transclude; module(function() { directive('trans', valueFn({ transclude: true, templateUrl: 'baz.html', controller: function($transclude) { transclude = $transclude; } })); directive('inner', valueFn({ template: '<span>FooBar</span>', compile: function() { innerCompilationCount +=1; } })); }); inject(function($compile, $rootScope, $httpBackend) { $httpBackend.expectGET('baz.html').respond('<div>Baz</div>'); element = $compile('<trans><inner></inner></trans>')($rootScope); $httpBackend.flush(); expect(innerCompilationCount).toBe(0); transclude(function(child) { element.append(child); }); expect(innerCompilationCount).toBe(1); expect(element.text()).toBe('BazFooBar'); }); }); it('should lazily compile the contents of directives that are transclude element', function() { var innerCompilationCount = 0, transclude; module(function() { directive('trans', valueFn({ transclude: 'element', controller: function($transclude) { transclude = $transclude; } })); directive('inner', valueFn({ template: '<span>FooBar</span>', compile: function() { innerCompilationCount +=1; } })); }); inject(function($compile, $rootScope) { element = $compile('<div><trans><inner></inner></trans></div>')($rootScope); expect(innerCompilationCount).toBe(0); transclude(function(child) { element.append(child); }); expect(innerCompilationCount).toBe(1); expect(element.text()).toBe('FooBar'); }); }); it('should lazily compile transcluded directives with ngIf on them', function() { var innerCompilationCount = 0, outerCompilationCount = 0, transclude; module(function() { directive('outer', valueFn({ transclude: true, compile: function() { outerCompilationCount += 1; }, controller: function($transclude) { transclude = $transclude; } })); directive('inner', valueFn({ template: '<span>FooBar</span>', compile: function() { innerCompilationCount +=1; } })); }); inject(function($compile, $rootScope) { $rootScope.shouldCompile = false; element = $compile('<div><outer ng-if="shouldCompile"><inner></inner></outer></div>')($rootScope); expect(outerCompilationCount).toBe(0); expect(innerCompilationCount).toBe(0); expect(transclude).toBeUndefined(); $rootScope.$apply('shouldCompile=true'); expect(outerCompilationCount).toBe(1); expect(innerCompilationCount).toBe(0); expect(transclude).toBeDefined(); transclude(function(child) { element.append(child); }); expect(outerCompilationCount).toBe(1); expect(innerCompilationCount).toBe(1); expect(element.text()).toBe('FooBar'); }); }); it('should eagerly compile multiple directives with transclusion and templateUrl/replace', function() { var innerCompilationCount = 0; module(function() { directive('outer', valueFn({ transclude: true })); directive('outer', valueFn({ templateUrl: 'inner.html', replace: true })); directive('inner', valueFn({ compile: function() { innerCompilationCount +=1; } })); }); inject(function($compile, $rootScope, $httpBackend) { $httpBackend.expectGET('inner.html').respond('<inner></inner>'); element = $compile('<outer></outer>')($rootScope); $httpBackend.flush(); expect(innerCompilationCount).toBe(1); }); }); }); describe('img[src] sanitization', function() { it('should NOT require trusted values for img src', inject(function($rootScope, $compile, $sce) { element = $compile('<img src="{{testUrl}}"></img>')($rootScope); $rootScope.testUrl = 'http://example.com/image.png'; $rootScope.$digest(); expect(element.attr('src')).toEqual('http://example.com/image.png'); // But it should accept trusted values anyway. $rootScope.testUrl = $sce.trustAsUrl('http://example.com/image2.png'); $rootScope.$digest(); expect(element.attr('src')).toEqual('http://example.com/image2.png'); })); it('should not sanitize attributes other than src', inject(function($compile, $rootScope) { /* jshint scripturl:true */ element = $compile('<img title="{{testUrl}}"></img>')($rootScope); $rootScope.testUrl = "javascript:doEvilStuff()"; $rootScope.$apply(); expect(element.attr('title')).toBe('javascript:doEvilStuff()'); })); it('should use $$sanitizeUriProvider for reconfiguration of the src whitelist', function() { module(function($compileProvider, $$sanitizeUriProvider) { var newRe = /javascript:/, returnVal; expect($compileProvider.imgSrcSanitizationWhitelist()).toBe($$sanitizeUriProvider.imgSrcSanitizationWhitelist()); returnVal = $compileProvider.imgSrcSanitizationWhitelist(newRe); expect(returnVal).toBe($compileProvider); expect($$sanitizeUriProvider.imgSrcSanitizationWhitelist()).toBe(newRe); expect($compileProvider.imgSrcSanitizationWhitelist()).toBe(newRe); }); inject(function() { // needed to the module definition above is run... }); }); it('should use $$sanitizeUri', function() { var $$sanitizeUri = jasmine.createSpy('$$sanitizeUri'); module(function($provide) { $provide.value('$$sanitizeUri', $$sanitizeUri); }); inject(function($compile, $rootScope) { element = $compile('<img src="{{testUrl}}"></img>')($rootScope); $rootScope.testUrl = "someUrl"; $$sanitizeUri.andReturn('someSanitizedUrl'); $rootScope.$apply(); expect(element.attr('src')).toBe('someSanitizedUrl'); expect($$sanitizeUri).toHaveBeenCalledWith($rootScope.testUrl, true); }); }); }); describe('img[srcset] sanitization', function() { it('should NOT require trusted values for img srcset', inject(function($rootScope, $compile, $sce) { element = $compile('<img srcset="{{testUrl}}"></img>')($rootScope); $rootScope.testUrl = 'http://example.com/image.png'; $rootScope.$digest(); expect(element.attr('srcset')).toEqual('http://example.com/image.png'); // But it should accept trusted values anyway. $rootScope.testUrl = $sce.trustAsUrl('http://example.com/image2.png'); $rootScope.$digest(); expect(element.attr('srcset')).toEqual('http://example.com/image2.png'); })); it('should use $$sanitizeUri', function() { var $$sanitizeUri = jasmine.createSpy('$$sanitizeUri'); module(function($provide) { $provide.value('$$sanitizeUri', $$sanitizeUri); }); inject(function($compile, $rootScope) { element = $compile('<img srcset="{{testUrl}}"></img>')($rootScope); $rootScope.testUrl = "someUrl"; $$sanitizeUri.andReturn('someSanitizedUrl'); $rootScope.$apply(); expect(element.attr('srcset')).toBe('someSanitizedUrl'); expect($$sanitizeUri).toHaveBeenCalledWith($rootScope.testUrl, true); }); }); it('should sanitize all uris in srcset', inject(function($rootScope, $compile) { /*jshint scripturl:true*/ element = $compile('<img srcset="{{testUrl}}"></img>')($rootScope); var testSet = { 'http://example.com/image.png':'http://example.com/image.png', ' http://example.com/image.png':'http://example.com/image.png', 'http://example.com/image.png ':'http://example.com/image.png', 'http://example.com/image.png 128w':'http://example.com/image.png 128w', 'http://example.com/image.png 2x':'http://example.com/image.png 2x', 'http://example.com/image.png 1.5x':'http://example.com/image.png 1.5x', 'http://example.com/image1.png 1x,http://example.com/image2.png 2x':'http://example.com/image1.png 1x,http://example.com/image2.png 2x', 'http://example.com/image1.png 1x ,http://example.com/image2.png 2x':'http://example.com/image1.png 1x ,http://example.com/image2.png 2x', 'http://example.com/image1.png 1x, http://example.com/image2.png 2x':'http://example.com/image1.png 1x,http://example.com/image2.png 2x', 'http://example.com/image1.png 1x , http://example.com/image2.png 2x':'http://example.com/image1.png 1x ,http://example.com/image2.png 2x', 'http://example.com/image1.png 48w,http://example.com/image2.png 64w':'http://example.com/image1.png 48w,http://example.com/image2.png 64w', //Test regex to make sure doesn't mistake parts of url for width descriptors 'http://example.com/image1.png?w=48w,http://example.com/image2.png 64w':'http://example.com/image1.png?w=48w,http://example.com/image2.png 64w', 'http://example.com/image1.png 1x,http://example.com/image2.png 64w':'http://example.com/image1.png 1x,http://example.com/image2.png 64w', 'http://example.com/image1.png,http://example.com/image2.png':'http://example.com/image1.png ,http://example.com/image2.png', 'http://example.com/image1.png ,http://example.com/image2.png':'http://example.com/image1.png ,http://example.com/image2.png', 'http://example.com/image1.png, http://example.com/image2.png':'http://example.com/image1.png ,http://example.com/image2.png', 'http://example.com/image1.png , http://example.com/image2.png':'http://example.com/image1.png ,http://example.com/image2.png', 'http://example.com/image1.png 1x, http://example.com/image2.png 2x, http://example.com/image3.png 3x': 'http://example.com/image1.png 1x,http://example.com/image2.png 2x,http://example.com/image3.png 3x', 'javascript:doEvilStuff() 2x': 'unsafe:javascript:doEvilStuff() 2x', 'http://example.com/image1.png 1x,javascript:doEvilStuff() 2x':'http://example.com/image1.png 1x,unsafe:javascript:doEvilStuff() 2x', 'http://example.com/image1.jpg?x=a,b 1x,http://example.com/ima,ge2.jpg 2x':'http://example.com/image1.jpg?x=a,b 1x,http://example.com/ima,ge2.jpg 2x', //Test regex to make sure doesn't mistake parts of url for pixel density descriptors 'http://example.com/image1.jpg?x=a2x,b 1x,http://example.com/ima,ge2.jpg 2x':'http://example.com/image1.jpg?x=a2x,b 1x,http://example.com/ima,ge2.jpg 2x' }; forEach(testSet, function(ref, url) { $rootScope.testUrl = url; $rootScope.$digest(); expect(element.attr('srcset')).toEqual(ref); }); })); }); describe('a[href] sanitization', function() { it('should not sanitize href on elements other than anchor', inject(function($compile, $rootScope) { /* jshint scripturl:true */ element = $compile('<div href="{{testUrl}}"></div>')($rootScope); $rootScope.testUrl = "javascript:doEvilStuff()"; $rootScope.$apply(); expect(element.attr('href')).toBe('javascript:doEvilStuff()'); })); it('should not sanitize attributes other than href', inject(function($compile, $rootScope) { /* jshint scripturl:true */ element = $compile('<a title="{{testUrl}}"></a>')($rootScope); $rootScope.testUrl = "javascript:doEvilStuff()"; $rootScope.$apply(); expect(element.attr('title')).toBe('javascript:doEvilStuff()'); })); it('should use $$sanitizeUriProvider for reconfiguration of the href whitelist', function() { module(function($compileProvider, $$sanitizeUriProvider) { var newRe = /javascript:/, returnVal; expect($compileProvider.aHrefSanitizationWhitelist()).toBe($$sanitizeUriProvider.aHrefSanitizationWhitelist()); returnVal = $compileProvider.aHrefSanitizationWhitelist(newRe); expect(returnVal).toBe($compileProvider); expect($$sanitizeUriProvider.aHrefSanitizationWhitelist()).toBe(newRe); expect($compileProvider.aHrefSanitizationWhitelist()).toBe(newRe); }); inject(function() { // needed to the module definition above is run... }); }); it('should use $$sanitizeUri', function() { var $$sanitizeUri = jasmine.createSpy('$$sanitizeUri'); module(function($provide) { $provide.value('$$sanitizeUri', $$sanitizeUri); }); inject(function($compile, $rootScope) { element = $compile('<a href="{{testUrl}}"></a>')($rootScope); $rootScope.testUrl = "someUrl"; $$sanitizeUri.andReturn('someSanitizedUrl'); $rootScope.$apply(); expect(element.attr('href')).toBe('someSanitizedUrl'); expect($$sanitizeUri).toHaveBeenCalledWith($rootScope.testUrl, false); }); }); it('should use $$sanitizeUri when declared via ng-href', function() { var $$sanitizeUri = jasmine.createSpy('$$sanitizeUri'); module(function($provide) { $provide.value('$$sanitizeUri', $$sanitizeUri); }); inject(function($compile, $rootScope) { element = $compile('<a ng-href="{{testUrl}}"></a>')($rootScope); $rootScope.testUrl = "someUrl"; $$sanitizeUri.andReturn('someSanitizedUrl'); $rootScope.$apply(); expect(element.attr('href')).toBe('someSanitizedUrl'); expect($$sanitizeUri).toHaveBeenCalledWith($rootScope.testUrl, false); }); }); it('should use $$sanitizeUri when working with svg and xlink:href', function() { var $$sanitizeUri = jasmine.createSpy('$$sanitizeUri'); module(function($provide) { $provide.value('$$sanitizeUri', $$sanitizeUri); }); inject(function($compile, $rootScope) { element = $compile('<svg><a xlink:href="" ng-href="{{ testUrl }}"></a></svg>')($rootScope); $rootScope.testUrl = "evilUrl"; $$sanitizeUri.andReturn('someSanitizedUrl'); $rootScope.$apply(); expect(element.find('a').prop('href').baseVal).toBe('someSanitizedUrl'); expect($$sanitizeUri).toHaveBeenCalledWith($rootScope.testUrl, false); }); }); it('should use $$sanitizeUri when working with svg and xlink:href', function() { var $$sanitizeUri = jasmine.createSpy('$$sanitizeUri'); module(function($provide) { $provide.value('$$sanitizeUri', $$sanitizeUri); }); inject(function($compile, $rootScope) { element = $compile('<svg><a xlink:href="" ng-href="{{ testUrl }}"></a></svg>')($rootScope); $rootScope.testUrl = "evilUrl"; $$sanitizeUri.andReturn('someSanitizedUrl'); $rootScope.$apply(); expect(element.find('a').prop('href').baseVal).toBe('someSanitizedUrl'); expect($$sanitizeUri).toHaveBeenCalledWith($rootScope.testUrl, false); }); }); }); describe('interpolation on HTML DOM event handler attributes onclick, onXYZ, formaction', function() { it('should disallow interpolation on onclick', inject(function($compile, $rootScope) { // All interpolations are disallowed. $rootScope.onClickJs = ""; expect(function() { $compile('<button onclick="{{onClickJs}}"></script>')($rootScope); }).toThrowMinErr( "$compile", "nodomevents", "Interpolations for HTML DOM event attributes are disallowed. " + "Please use the ng- versions (such as ng-click instead of onclick) instead."); expect(function() { $compile('<button ONCLICK="{{onClickJs}}"></script>')($rootScope); }).toThrowMinErr( "$compile", "nodomevents", "Interpolations for HTML DOM event attributes are disallowed. " + "Please use the ng- versions (such as ng-click instead of onclick) instead."); expect(function() { $compile('<button ng-attr-onclick="{{onClickJs}}"></script>')($rootScope); }).toThrowMinErr( "$compile", "nodomevents", "Interpolations for HTML DOM event attributes are disallowed. " + "Please use the ng- versions (such as ng-click instead of onclick) instead."); })); it('should pass through arbitrary values on onXYZ event attributes that contain a hyphen', inject(function($compile, $rootScope) { /* jshint scripturl:true */ element = $compile('<button on-click="{{onClickJs}}"></script>')($rootScope); $rootScope.onClickJs = 'javascript:doSomething()'; $rootScope.$apply(); expect(element.attr('on-click')).toEqual('javascript:doSomething()'); })); it('should pass through arbitrary values on "on" and "data-on" attributes', inject(function($compile, $rootScope) { element = $compile('<button data-on="{{dataOnVar}}"></script>')($rootScope); $rootScope.dataOnVar = 'data-on text'; $rootScope.$apply(); expect(element.attr('data-on')).toEqual('data-on text'); element = $compile('<button on="{{onVar}}"></script>')($rootScope); $rootScope.onVar = 'on text'; $rootScope.$apply(); expect(element.attr('on')).toEqual('on text'); })); }); describe('iframe[src]', function() { it('should pass through src attributes for the same domain', inject(function($compile, $rootScope, $sce) { element = $compile('<iframe src="{{testUrl}}"></iframe>')($rootScope); $rootScope.testUrl = "different_page"; $rootScope.$apply(); expect(element.attr('src')).toEqual('different_page'); })); it('should clear out src attributes for a different domain', inject(function($compile, $rootScope, $sce) { element = $compile('<iframe src="{{testUrl}}"></iframe>')($rootScope); $rootScope.testUrl = "http://a.different.domain.example.com"; expect(function() { $rootScope.$apply(); }).toThrowMinErr( "$interpolate", "interr", "Can't interpolate: {{testUrl}}\nError: [$sce:insecurl] Blocked " + "loading resource from url not allowed by $sceDelegate policy. URL: " + "http://a.different.domain.example.com"); })); it('should clear out JS src attributes', inject(function($compile, $rootScope, $sce) { /* jshint scripturl:true */ element = $compile('<iframe src="{{testUrl}}"></iframe>')($rootScope); $rootScope.testUrl = "javascript:alert(1);"; expect(function() { $rootScope.$apply(); }).toThrowMinErr( "$interpolate", "interr", "Can't interpolate: {{testUrl}}\nError: [$sce:insecurl] Blocked " + "loading resource from url not allowed by $sceDelegate policy. URL: " + "javascript:alert(1);"); })); it('should clear out non-resource_url src attributes', inject(function($compile, $rootScope, $sce) { /* jshint scripturl:true */ element = $compile('<iframe src="{{testUrl}}"></iframe>')($rootScope); $rootScope.testUrl = $sce.trustAsUrl("javascript:doTrustedStuff()"); expect($rootScope.$apply).toThrowMinErr( "$interpolate", "interr", "Can't interpolate: {{testUrl}}\nError: [$sce:insecurl] Blocked " + "loading resource from url not allowed by $sceDelegate policy. URL: javascript:doTrustedStuff()"); })); it('should pass through $sce.trustAs() values in src attributes', inject(function($compile, $rootScope, $sce) { /* jshint scripturl:true */ element = $compile('<iframe src="{{testUrl}}"></iframe>')($rootScope); $rootScope.testUrl = $sce.trustAsResourceUrl("javascript:doTrustedStuff()"); $rootScope.$apply(); expect(element.attr('src')).toEqual('javascript:doTrustedStuff()'); })); }); describe('form[action]', function() { it('should pass through action attribute for the same domain', inject(function($compile, $rootScope, $sce) { element = $compile('<form action="{{testUrl}}"></form>')($rootScope); $rootScope.testUrl = "different_page"; $rootScope.$apply(); expect(element.attr('action')).toEqual('different_page'); })); it('should clear out action attribute for a different domain', inject(function($compile, $rootScope, $sce) { element = $compile('<form action="{{testUrl}}"></form>')($rootScope); $rootScope.testUrl = "http://a.different.domain.example.com"; expect(function() { $rootScope.$apply(); }).toThrowMinErr( "$interpolate", "interr", "Can't interpolate: {{testUrl}}\nError: [$sce:insecurl] Blocked " + "loading resource from url not allowed by $sceDelegate policy. URL: " + "http://a.different.domain.example.com"); })); it('should clear out JS action attribute', inject(function($compile, $rootScope, $sce) { /* jshint scripturl:true */ element = $compile('<form action="{{testUrl}}"></form>')($rootScope); $rootScope.testUrl = "javascript:alert(1);"; expect(function() { $rootScope.$apply(); }).toThrowMinErr( "$interpolate", "interr", "Can't interpolate: {{testUrl}}\nError: [$sce:insecurl] Blocked " + "loading resource from url not allowed by $sceDelegate policy. URL: " + "javascript:alert(1);"); })); it('should clear out non-resource_url action attribute', inject(function($compile, $rootScope, $sce) { /* jshint scripturl:true */ element = $compile('<form action="{{testUrl}}"></form>')($rootScope); $rootScope.testUrl = $sce.trustAsUrl("javascript:doTrustedStuff()"); expect($rootScope.$apply).toThrowMinErr( "$interpolate", "interr", "Can't interpolate: {{testUrl}}\nError: [$sce:insecurl] Blocked " + "loading resource from url not allowed by $sceDelegate policy. URL: javascript:doTrustedStuff()"); })); it('should pass through $sce.trustAs() values in action attribute', inject(function($compile, $rootScope, $sce) { /* jshint scripturl:true */ element = $compile('<form action="{{testUrl}}"></form>')($rootScope); $rootScope.testUrl = $sce.trustAsResourceUrl("javascript:doTrustedStuff()"); $rootScope.$apply(); expect(element.attr('action')).toEqual('javascript:doTrustedStuff()'); })); }); if (!msie || msie >= 11) { describe('iframe[srcdoc]', function() { it('should NOT set iframe contents for untrusted values', inject(function($compile, $rootScope, $sce) { element = $compile('<iframe srcdoc="{{html}}"></iframe>')($rootScope); $rootScope.html = '<div onclick="">hello</div>'; expect(function() { $rootScope.$digest(); }).toThrowMinErr('$interpolate', 'interr', new RegExp( /Can't interpolate: {{html}}\n/.source + /[^[]*\[\$sce:unsafe\] Attempting to use an unsafe value in a safe context./.source)); })); it('should NOT set html for wrongly typed values', inject(function($rootScope, $compile, $sce) { element = $compile('<iframe srcdoc="{{html}}"></iframe>')($rootScope); $rootScope.html = $sce.trustAsCss('<div onclick="">hello</div>'); expect(function() { $rootScope.$digest(); }).toThrowMinErr('$interpolate', 'interr', new RegExp( /Can't interpolate: {{html}}\n/.source + /[^[]*\[\$sce:unsafe\] Attempting to use an unsafe value in a safe context./.source)); })); it('should set html for trusted values', inject(function($rootScope, $compile, $sce) { element = $compile('<iframe srcdoc="{{html}}"></iframe>')($rootScope); $rootScope.html = $sce.trustAsHtml('<div onclick="">hello</div>'); $rootScope.$digest(); expect(angular.lowercase(element.attr('srcdoc'))).toEqual('<div onclick="">hello</div>'); })); }); } describe('ngAttr* attribute binding', function() { it('should bind after digest but not before', inject(function($compile, $rootScope) { $rootScope.name = "Misko"; element = $compile('<span ng-attr-test="{{name}}"></span>')($rootScope); expect(element.attr('test')).toBeUndefined(); $rootScope.$digest(); expect(element.attr('test')).toBe('Misko'); })); it('should bind after digest but not before when after overridden attribute', inject(function($compile, $rootScope) { $rootScope.name = "Misko"; element = $compile('<span test="123" ng-attr-test="{{name}}"></span>')($rootScope); expect(element.attr('test')).toBe('123'); $rootScope.$digest(); expect(element.attr('test')).toBe('Misko'); })); it('should bind after digest but not before when before overridden attribute', inject(function($compile, $rootScope) { $rootScope.name = "Misko"; element = $compile('<span ng-attr-test="{{name}}" test="123"></span>')($rootScope); expect(element.attr('test')).toBe('123'); $rootScope.$digest(); expect(element.attr('test')).toBe('Misko'); })); it('should remove attribute if any bindings are undefined', inject(function($compile, $rootScope) { element = $compile('<span ng-attr-test="{{name}}{{emphasis}}"></span>')($rootScope); $rootScope.$digest(); expect(element.attr('test')).toBeUndefined(); $rootScope.name = 'caitp'; $rootScope.$digest(); expect(element.attr('test')).toBeUndefined(); $rootScope.emphasis = '!!!'; $rootScope.$digest(); expect(element.attr('test')).toBe('caitp!!!'); })); describe('in directive', function() { beforeEach(module(function() { directive('syncTest', function(log) { return { link: { pre: function(s, e, attr) { log(attr.test); }, post: function(s, e, attr) { log(attr.test); } } }; }); directive('asyncTest', function(log) { return { templateUrl: 'async.html', link: { pre: function(s, e, attr) { log(attr.test); }, post: function(s, e, attr) { log(attr.test); } } }; }); })); beforeEach(inject(function($templateCache) { $templateCache.put('async.html', '<h1>Test</h1>'); })); it('should provide post-digest value in synchronous directive link functions when after overridden attribute', inject(function(log, $rootScope, $compile) { $rootScope.test = "TEST"; element = $compile('<div sync-test test="123" ng-attr-test="{{test}}"></div>')($rootScope); expect(element.attr('test')).toBe('123'); expect(log.toArray()).toEqual(['TEST', 'TEST']); })); it('should provide post-digest value in synchronous directive link functions when before overridden attribute', inject(function(log, $rootScope, $compile) { $rootScope.test = "TEST"; element = $compile('<div sync-test ng-attr-test="{{test}}" test="123"></div>')($rootScope); expect(element.attr('test')).toBe('123'); expect(log.toArray()).toEqual(['TEST', 'TEST']); })); it('should provide post-digest value in asynchronous directive link functions when after overridden attribute', inject(function(log, $rootScope, $compile) { $rootScope.test = "TEST"; element = $compile('<div async-test test="123" ng-attr-test="{{test}}"></div>')($rootScope); expect(element.attr('test')).toBe('123'); $rootScope.$digest(); expect(log.toArray()).toEqual(['TEST', 'TEST']); })); it('should provide post-digest value in asynchronous directive link functions when before overridden attribute', inject(function(log, $rootScope, $compile) { $rootScope.test = "TEST"; element = $compile('<div async-test ng-attr-test="{{test}}" test="123"></div>')($rootScope); expect(element.attr('test')).toBe('123'); $rootScope.$digest(); expect(log.toArray()).toEqual(['TEST', 'TEST']); })); }); it('should work with different prefixes', inject(function($compile, $rootScope) { $rootScope.name = "Misko"; element = $compile('<span ng:attr:test="{{name}}" ng-Attr-test2="{{name}}" ng_Attr_test3="{{name}}"></span>')($rootScope); expect(element.attr('test')).toBeUndefined(); expect(element.attr('test2')).toBeUndefined(); expect(element.attr('test3')).toBeUndefined(); $rootScope.$digest(); expect(element.attr('test')).toBe('Misko'); expect(element.attr('test2')).toBe('Misko'); expect(element.attr('test3')).toBe('Misko'); })); it('should work with the "href" attribute', inject(function($compile, $rootScope) { $rootScope.value = 'test'; element = $compile('<a ng-attr-href="test/{{value}}"></a>')($rootScope); $rootScope.$digest(); expect(element.attr('href')).toBe('test/test'); })); it('should work if they are prefixed with x- or data- and different prefixes', inject(function($compile, $rootScope) { $rootScope.name = "Misko"; element = $compile('<span data-ng-attr-test2="{{name}}" x-ng-attr-test3="{{name}}" data-ng:attr-test4="{{name}}" ' + 'x_ng-attr-test5="{{name}}" data:ng-attr-test6="{{name}}"></span>')($rootScope); expect(element.attr('test2')).toBeUndefined(); expect(element.attr('test3')).toBeUndefined(); expect(element.attr('test4')).toBeUndefined(); expect(element.attr('test5')).toBeUndefined(); expect(element.attr('test6')).toBeUndefined(); $rootScope.$digest(); expect(element.attr('test2')).toBe('Misko'); expect(element.attr('test3')).toBe('Misko'); expect(element.attr('test4')).toBe('Misko'); expect(element.attr('test5')).toBe('Misko'); expect(element.attr('test6')).toBe('Misko'); })); describe('when an attribute has a dash-separated name', function() { it('should work with different prefixes', inject(function($compile, $rootScope) { $rootScope.name = "JamieMason"; element = $compile('<span ng:attr:dash-test="{{name}}" ng-Attr-dash-test2="{{name}}" ng_Attr_dash-test3="{{name}}"></span>')($rootScope); expect(element.attr('dash-test')).toBeUndefined(); expect(element.attr('dash-test2')).toBeUndefined(); expect(element.attr('dash-test3')).toBeUndefined(); $rootScope.$digest(); expect(element.attr('dash-test')).toBe('JamieMason'); expect(element.attr('dash-test2')).toBe('JamieMason'); expect(element.attr('dash-test3')).toBe('JamieMason'); })); it('should work if they are prefixed with x- or data-', inject(function($compile, $rootScope) { $rootScope.name = "JamieMason"; element = $compile('<span data-ng-attr-dash-test2="{{name}}" x-ng-attr-dash-test3="{{name}}" data-ng:attr-dash-test4="{{name}}"></span>')($rootScope); expect(element.attr('dash-test2')).toBeUndefined(); expect(element.attr('dash-test3')).toBeUndefined(); expect(element.attr('dash-test4')).toBeUndefined(); $rootScope.$digest(); expect(element.attr('dash-test2')).toBe('JamieMason'); expect(element.attr('dash-test3')).toBe('JamieMason'); expect(element.attr('dash-test4')).toBe('JamieMason'); })); it('should keep attributes ending with -start single-element directives', function() { module(function($compileProvider) { $compileProvider.directive('dashStarter', function(log) { return { link: function(scope, element, attrs) { log(attrs.onDashStart); } }; }); }); inject(function($compile, $rootScope, log) { $compile('<span data-dash-starter data-on-dash-start="starter"></span>')($rootScope); $rootScope.$digest(); expect(log).toEqual('starter'); }); }); it('should keep attributes ending with -end single-element directives', function() { module(function($compileProvider) { $compileProvider.directive('dashEnder', function(log) { return { link: function(scope, element, attrs) { log(attrs.onDashEnd); } }; }); }); inject(function($compile, $rootScope, log) { $compile('<span data-dash-ender data-on-dash-end="ender"></span>')($rootScope); $rootScope.$digest(); expect(log).toEqual('ender'); }); }); }); }); describe('when an attribute has an underscore-separated name', function() { it('should work with different prefixes', inject(function($compile, $rootScope) { $rootScope.dimensions = "0 0 0 0"; element = $compile('<svg ng:attr:view_box="{{dimensions}}"></svg>')($rootScope); expect(element.attr('viewBox')).toBeUndefined(); $rootScope.$digest(); expect(element.attr('viewBox')).toBe('0 0 0 0'); })); it('should work if they are prefixed with x- or data-', inject(function($compile, $rootScope) { $rootScope.dimensions = "0 0 0 0"; $rootScope.number = 0.42; $rootScope.scale = 1; element = $compile('<svg data-ng-attr-view_box="{{dimensions}}">' + '<filter x-ng-attr-filter_units="{{number}}">' + '<feDiffuseLighting data-ng:attr_surface_scale="{{scale}}">' + '</feDiffuseLighting>' + '<feSpecularLighting x-ng:attr_surface_scale="{{scale}}">' + '</feSpecularLighting></filter></svg>')($rootScope); expect(element.attr('viewBox')).toBeUndefined(); $rootScope.$digest(); expect(element.attr('viewBox')).toBe('0 0 0 0'); expect(element.find('filter').attr('filterUnits')).toBe('0.42'); expect(element.find('feDiffuseLighting').attr('surfaceScale')).toBe('1'); expect(element.find('feSpecularLighting').attr('surfaceScale')).toBe('1'); })); }); describe('multi-element directive', function() { it('should group on link function', inject(function($compile, $rootScope) { $rootScope.show = false; element = $compile( '<div>' + '<span ng-show-start="show"></span>' + '<span ng-show-end></span>' + '</div>')($rootScope); $rootScope.$digest(); var spans = element.find('span'); expect(spans.eq(0)).toBeHidden(); expect(spans.eq(1)).toBeHidden(); })); it('should group on compile function', inject(function($compile, $rootScope) { $rootScope.show = false; element = $compile( '<div>' + '<span ng-repeat-start="i in [1,2]">{{i}}A</span>' + '<span ng-repeat-end>{{i}}B;</span>' + '</div>')($rootScope); $rootScope.$digest(); expect(element.text()).toEqual('1A1B;2A2B;'); })); it('should support grouping over text nodes', inject(function($compile, $rootScope) { $rootScope.show = false; element = $compile( '<div>' + '<span ng-repeat-start="i in [1,2]">{{i}}A</span>' + ':' + // Important: proves that we can iterate over non-elements '<span ng-repeat-end>{{i}}B;</span>' + '</div>')($rootScope); $rootScope.$digest(); expect(element.text()).toEqual('1A:1B;2A:2B;'); })); it('should group on $root compile function', inject(function($compile, $rootScope) { $rootScope.show = false; element = $compile( '<div></div>' + '<span ng-repeat-start="i in [1,2]">{{i}}A</span>' + '<span ng-repeat-end>{{i}}B;</span>' + '<div></div>')($rootScope); $rootScope.$digest(); element = jqLite(element[0].parentNode.childNodes); // reset because repeater is top level. expect(element.text()).toEqual('1A1B;2A2B;'); })); it('should group on nested groups', function() { module(function($compileProvider) { $compileProvider.directive("ngMultiBind", valueFn({ multiElement: true, link: function(scope, element, attr) { element.text(scope.$eval(attr.ngMultiBind)); } })); }); inject(function($compile, $rootScope) { $rootScope.show = false; element = $compile( '<div></div>' + '<div ng-repeat-start="i in [1,2]">{{i}}A</div>' + '<span ng-multi-bind-start="\'.\'"></span>' + '<span ng-multi-bind-end></span>' + '<div ng-repeat-end>{{i}}B;</div>' + '<div></div>')($rootScope); $rootScope.$digest(); element = jqLite(element[0].parentNode.childNodes); // reset because repeater is top level. expect(element.text()).toEqual('1A..1B;2A..2B;'); }); }); it('should group on nested groups of same directive', inject(function($compile, $rootScope) { $rootScope.show = false; element = $compile( '<div></div>' + '<div ng-repeat-start="i in [1,2]">{{i}}(</div>' + '<span ng-repeat-start="j in [2,3]">{{j}}-</span>' + '<span ng-repeat-end>{{j}}</span>' + '<div ng-repeat-end>){{i}};</div>' + '<div></div>')($rootScope); $rootScope.$digest(); element = jqLite(element[0].parentNode.childNodes); // reset because repeater is top level. expect(element.text()).toEqual('1(2-23-3)1;2(2-23-3)2;'); })); it('should set up and destroy the transclusion scopes correctly', inject(function($compile, $rootScope) { element = $compile( '<div>' + '<div ng-if-start="val0"><span ng-if="val1"></span></div>' + '<div ng-if-end><span ng-if="val2"></span></div>' + '</div>' )($rootScope); $rootScope.$apply('val0 = true; val1 = true; val2 = true'); // At this point we should have something like: // // <div class="ng-scope"> // // <!-- ngIf: val0 --> // // <div ng-if-start="val0" class="ng-scope"> // <!-- ngIf: val1 --> // <span ng-if="val1" class="ng-scope"></span> // <!-- end ngIf: val1 --> // </div> // // <div ng-if-end="" class="ng-scope"> // <!-- ngIf: val2 --> // <span ng-if="val2" class="ng-scope"></span> // <!-- end ngIf: val2 --> // </div> // // <!-- end ngIf: val0 --> // </div> var ngIfStartScope = element.find('div').eq(0).scope(); var ngIfEndScope = element.find('div').eq(1).scope(); expect(ngIfStartScope.$id).toEqual(ngIfEndScope.$id); var ngIf1Scope = element.find('span').eq(0).scope(); var ngIf2Scope = element.find('span').eq(1).scope(); expect(ngIf1Scope.$id).not.toEqual(ngIf2Scope.$id); expect(ngIf1Scope.$parent.$id).toEqual(ngIf2Scope.$parent.$id); $rootScope.$apply('val1 = false'); // Now we should have something like: // // <div class="ng-scope"> // <!-- ngIf: val0 --> // <div ng-if-start="val0" class="ng-scope"> // <!-- ngIf: val1 --> // </div> // <div ng-if-end="" class="ng-scope"> // <!-- ngIf: val2 --> // <span ng-if="val2" class="ng-scope"></span> // <!-- end ngIf: val2 --> // </div> // <!-- end ngIf: val0 --> // </div> expect(ngIfStartScope.$$destroyed).not.toEqual(true); expect(ngIf1Scope.$$destroyed).toEqual(true); expect(ngIf2Scope.$$destroyed).not.toEqual(true); $rootScope.$apply('val0 = false'); // Now we should have something like: // // <div class="ng-scope"> // <!-- ngIf: val0 --> // </div> expect(ngIfStartScope.$$destroyed).toEqual(true); expect(ngIf1Scope.$$destroyed).toEqual(true); expect(ngIf2Scope.$$destroyed).toEqual(true); })); it('should set up and destroy the transclusion scopes correctly', inject(function($compile, $rootScope) { element = $compile( '<div>' + '<div ng-repeat-start="val in val0" ng-if="val1"></div>' + '<div ng-repeat-end ng-if="val2"></div>' + '</div>' )($rootScope); // To begin with there is (almost) nothing: // <div class="ng-scope"> // <!-- ngRepeat: val in val0 --> // </div> expect(element.scope().$id).toEqual($rootScope.$id); // Now we create all the elements $rootScope.$apply('val0 = [1]; val1 = true; val2 = true'); // At this point we have: // // <div class="ng-scope"> // // <!-- ngRepeat: val in val0 --> // <!-- ngIf: val1 --> // <div ng-repeat-start="val in val0" class="ng-scope"> // </div> // <!-- end ngIf: val1 --> // // <!-- ngIf: val2 --> // <div ng-repeat-end="" class="ng-scope"> // </div> // <!-- end ngIf: val2 --> // <!-- end ngRepeat: val in val0 --> // </div> var ngIf1Scope = element.find('div').eq(0).scope(); var ngIf2Scope = element.find('div').eq(1).scope(); var ngRepeatScope = ngIf1Scope.$parent; expect(ngIf1Scope.$id).not.toEqual(ngIf2Scope.$id); expect(ngIf1Scope.$parent.$id).toEqual(ngRepeatScope.$id); expect(ngIf2Scope.$parent.$id).toEqual(ngRepeatScope.$id); // What is happening here?? // We seem to have a repeater scope which doesn't actually match to any element expect(ngRepeatScope.$parent.$id).toEqual($rootScope.$id); // Now remove the first ngIf element from the first item in the repeater $rootScope.$apply('val1 = false'); // At this point we should have: // // <div class="ng-scope"> // <!-- ngRepeat: val in val0 --> // // <!-- ngIf: val1 --> // // <!-- ngIf: val2 --> // <div ng-repeat-end="" ng-if="val2" class="ng-scope"></div> // <!-- end ngIf: val2 --> // // <!-- end ngRepeat: val in val0 --> // </div> // expect(ngRepeatScope.$$destroyed).toEqual(false); expect(ngIf1Scope.$$destroyed).toEqual(true); expect(ngIf2Scope.$$destroyed).toEqual(false); // Now remove the second ngIf element from the first item in the repeater $rootScope.$apply('val2 = false'); // We are mostly back to where we started // // <div class="ng-scope"> // <!-- ngRepeat: val in val0 --> // <!-- ngIf: val1 --> // <!-- ngIf: val2 --> // <!-- end ngRepeat: val in val0 --> // </div> expect(ngRepeatScope.$$destroyed).toEqual(false); expect(ngIf1Scope.$$destroyed).toEqual(true); expect(ngIf2Scope.$$destroyed).toEqual(true); // Finally remove the repeat items $rootScope.$apply('val0 = []'); // Somehow this ngRepeat scope knows how to destroy itself... expect(ngRepeatScope.$$destroyed).toEqual(true); expect(ngIf1Scope.$$destroyed).toEqual(true); expect(ngIf2Scope.$$destroyed).toEqual(true); })); it('should throw error if unterminated', function() { module(function($compileProvider) { $compileProvider.directive('foo', function() { return { multiElement: true }; }); }); inject(function($compile, $rootScope) { expect(function() { element = $compile( '<div>' + '<span foo-start></span>' + '</div>'); }).toThrowMinErr("$compile", "uterdir", "Unterminated attribute, found 'foo-start' but no matching 'foo-end' found."); }); }); it('should correctly collect ranges on multiple directives on a single element', function() { module(function($compileProvider) { $compileProvider.directive('emptyDirective', function() { return { multiElement: true, link: function(scope, element) { element.data('x', 'abc'); } }; }); $compileProvider.directive('rangeDirective', function() { return { multiElement: true, link: function(scope) { scope.x = 'X'; scope.y = 'Y'; } }; }); }); inject(function($compile, $rootScope) { element = $compile( '<div>' + '<div range-directive-start empty-directive>{{x}}</div>' + '<div range-directive-end>{{y}}</div>' + '</div>' )($rootScope); $rootScope.$digest(); expect(element.text()).toBe('XY'); expect(angular.element(element[0].firstChild).data('x')).toBe('abc'); }); }); it('should throw error if unterminated (containing termination as a child)', function() { module(function($compileProvider) { $compileProvider.directive('foo', function() { return { multiElement: true }; }); }); inject(function($compile) { expect(function() { element = $compile( '<div>' + '<span foo-start><span foo-end></span></span>' + '</div>'); }).toThrowMinErr("$compile", "uterdir", "Unterminated attribute, found 'foo-start' but no matching 'foo-end' found."); }); }); it('should support data- and x- prefix', inject(function($compile, $rootScope) { $rootScope.show = false; element = $compile( '<div>' + '<span data-ng-show-start="show"></span>' + '<span data-ng-show-end></span>' + '<span x-ng-show-start="show"></span>' + '<span x-ng-show-end></span>' + '</div>')($rootScope); $rootScope.$digest(); var spans = element.find('span'); expect(spans.eq(0)).toBeHidden(); expect(spans.eq(1)).toBeHidden(); expect(spans.eq(2)).toBeHidden(); expect(spans.eq(3)).toBeHidden(); })); }); describe('$animate animation hooks', function() { beforeEach(module('ngAnimateMock')); it('should automatically fire the addClass and removeClass animation hooks', inject(function($compile, $animate, $rootScope) { var data, element = jqLite('<div class="{{val1}} {{val2}} fire"></div>'); $compile(element)($rootScope); $rootScope.$digest(); expect(element.hasClass('fire')).toBe(true); $rootScope.val1 = 'ice'; $rootScope.val2 = 'rice'; $rootScope.$digest(); data = $animate.queue.shift(); expect(data.event).toBe('addClass'); expect(data.args[1]).toBe('ice rice'); expect(element.hasClass('ice')).toBe(true); expect(element.hasClass('rice')).toBe(true); expect(element.hasClass('fire')).toBe(true); $rootScope.val2 = 'dice'; $rootScope.$digest(); data = $animate.queue.shift(); expect(data.event).toBe('addClass'); expect(data.args[1]).toBe('dice'); data = $animate.queue.shift(); expect(data.event).toBe('removeClass'); expect(data.args[1]).toBe('rice'); expect(element.hasClass('ice')).toBe(true); expect(element.hasClass('dice')).toBe(true); expect(element.hasClass('fire')).toBe(true); $rootScope.val1 = ''; $rootScope.val2 = ''; $rootScope.$digest(); data = $animate.queue.shift(); expect(data.event).toBe('removeClass'); expect(data.args[1]).toBe('ice dice'); expect(element.hasClass('ice')).toBe(false); expect(element.hasClass('dice')).toBe(false); expect(element.hasClass('fire')).toBe(true); })); }); });
"use strict"; const conversions = require("webidl-conversions"); const utils = require("./utils.js"); const HTMLElement = require("./HTMLElement.js"); const impl = utils.implSymbol; function HTMLMediaElement() { throw new TypeError("Illegal constructor"); } HTMLMediaElement.prototype = Object.create(HTMLElement.interface.prototype); HTMLMediaElement.prototype.constructor = HTMLMediaElement; HTMLMediaElement.prototype.load = function load() { if (!this || !module.exports.is(this)) { throw new TypeError("Illegal invocation"); } const args = []; for (let i = 0; i < arguments.length && i < 0; ++i) { args[i] = utils.tryImplForWrapper(arguments[i]); } return this[impl].load.apply(this[impl], args); }; HTMLMediaElement.prototype.canPlayType = function canPlayType(type) { if (!this || !module.exports.is(this)) { throw new TypeError("Illegal invocation"); } if (arguments.length < 1) { throw new TypeError("Failed to execute 'canPlayType' on 'HTMLMediaElement': 1 argument required, but only " + arguments.length + " present."); } const args = []; for (let i = 0; i < arguments.length && i < 1; ++i) { args[i] = utils.tryImplForWrapper(arguments[i]); } args[0] = conversions["DOMString"](args[0]); return utils.tryWrapperForImpl(this[impl].canPlayType.apply(this[impl], args)); }; HTMLMediaElement.prototype.play = function play() { if (!this || !module.exports.is(this)) { throw new TypeError("Illegal invocation"); } const args = []; for (let i = 0; i < arguments.length && i < 0; ++i) { args[i] = utils.tryImplForWrapper(arguments[i]); } return this[impl].play.apply(this[impl], args); }; HTMLMediaElement.prototype.pause = function pause() { if (!this || !module.exports.is(this)) { throw new TypeError("Illegal invocation"); } const args = []; for (let i = 0; i < arguments.length && i < 0; ++i) { args[i] = utils.tryImplForWrapper(arguments[i]); } return this[impl].pause.apply(this[impl], args); }; HTMLMediaElement.prototype.addTextTrack = function addTextTrack(kind) { if (!this || !module.exports.is(this)) { throw new TypeError("Illegal invocation"); } if (arguments.length < 1) { throw new TypeError("Failed to execute 'addTextTrack' on 'HTMLMediaElement': 1 argument required, but only " + arguments.length + " present."); } const args = []; for (let i = 0; i < arguments.length && i < 3; ++i) { args[i] = utils.tryImplForWrapper(arguments[i]); } if (args[1] !== undefined) { args[1] = conversions["DOMString"](args[1]); } else { args[1] = ""; } if (args[2] !== undefined) { args[2] = conversions["DOMString"](args[2]); } else { args[2] = ""; } return utils.tryWrapperForImpl(this[impl].addTextTrack.apply(this[impl], args)); }; HTMLMediaElement.prototype.toString = function () { if (this === HTMLMediaElement.prototype) { return "[object HTMLMediaElementPrototype]"; } return HTMLElement.interface.prototype.toString.call(this); }; Object.defineProperty(HTMLMediaElement.prototype, "src", { get() { return this[impl].src; }, set(V) { V = conversions["DOMString"](V); this[impl].src = V; }, enumerable: true, configurable: true }); Object.defineProperty(HTMLMediaElement.prototype, "currentSrc", { get() { return this[impl].currentSrc; }, enumerable: true, configurable: true }); Object.defineProperty(HTMLMediaElement.prototype, "crossOrigin", { get() { const value = this.getAttribute("crossOrigin"); return value === null ? "" : value; }, set(V) { if (V === null || V === undefined) { V = null; } else { V = conversions["DOMString"](V); } this.setAttribute("crossOrigin", V); }, enumerable: true, configurable: true }); Object.defineProperty(HTMLMediaElement, "NETWORK_EMPTY", { value: 0, enumerable: true }); Object.defineProperty(HTMLMediaElement.prototype, "NETWORK_EMPTY", { value: 0, enumerable: true }); Object.defineProperty(HTMLMediaElement, "NETWORK_IDLE", { value: 1, enumerable: true }); Object.defineProperty(HTMLMediaElement.prototype, "NETWORK_IDLE", { value: 1, enumerable: true }); Object.defineProperty(HTMLMediaElement, "NETWORK_LOADING", { value: 2, enumerable: true }); Object.defineProperty(HTMLMediaElement.prototype, "NETWORK_LOADING", { value: 2, enumerable: true }); Object.defineProperty(HTMLMediaElement, "NETWORK_NO_SOURCE", { value: 3, enumerable: true }); Object.defineProperty(HTMLMediaElement.prototype, "NETWORK_NO_SOURCE", { value: 3, enumerable: true }); Object.defineProperty(HTMLMediaElement.prototype, "networkState", { get() { return this[impl].networkState; }, enumerable: true, configurable: true }); Object.defineProperty(HTMLMediaElement.prototype, "preload", { get() { const value = this.getAttribute("preload"); return value === null ? "" : value; }, set(V) { V = conversions["DOMString"](V); this.setAttribute("preload", V); }, enumerable: true, configurable: true }); Object.defineProperty(HTMLMediaElement.prototype, "buffered", { get() { return utils.tryWrapperForImpl(this[impl].buffered); }, enumerable: true, configurable: true }); Object.defineProperty(HTMLMediaElement, "HAVE_NOTHING", { value: 0, enumerable: true }); Object.defineProperty(HTMLMediaElement.prototype, "HAVE_NOTHING", { value: 0, enumerable: true }); Object.defineProperty(HTMLMediaElement, "HAVE_METADATA", { value: 1, enumerable: true }); Object.defineProperty(HTMLMediaElement.prototype, "HAVE_METADATA", { value: 1, enumerable: true }); Object.defineProperty(HTMLMediaElement, "HAVE_CURRENT_DATA", { value: 2, enumerable: true }); Object.defineProperty(HTMLMediaElement.prototype, "HAVE_CURRENT_DATA", { value: 2, enumerable: true }); Object.defineProperty(HTMLMediaElement, "HAVE_FUTURE_DATA", { value: 3, enumerable: true }); Object.defineProperty(HTMLMediaElement.prototype, "HAVE_FUTURE_DATA", { value: 3, enumerable: true }); Object.defineProperty(HTMLMediaElement, "HAVE_ENOUGH_DATA", { value: 4, enumerable: true }); Object.defineProperty(HTMLMediaElement.prototype, "HAVE_ENOUGH_DATA", { value: 4, enumerable: true }); Object.defineProperty(HTMLMediaElement.prototype, "readyState", { get() { return this[impl].readyState; }, enumerable: true, configurable: true }); Object.defineProperty(HTMLMediaElement.prototype, "seeking", { get() { return this[impl].seeking; }, enumerable: true, configurable: true }); Object.defineProperty(HTMLMediaElement.prototype, "currentTime", { get() { return this[impl].currentTime; }, set(V) { V = conversions["double"](V); this[impl].currentTime = V; }, enumerable: true, configurable: true }); Object.defineProperty(HTMLMediaElement.prototype, "duration", { get() { return this[impl].duration; }, enumerable: true, configurable: true }); Object.defineProperty(HTMLMediaElement.prototype, "paused", { get() { return this[impl].paused; }, enumerable: true, configurable: true }); Object.defineProperty(HTMLMediaElement.prototype, "defaultPlaybackRate", { get() { return this[impl].defaultPlaybackRate; }, set(V) { V = conversions["double"](V); this[impl].defaultPlaybackRate = V; }, enumerable: true, configurable: true }); Object.defineProperty(HTMLMediaElement.prototype, "playbackRate", { get() { return this[impl].playbackRate; }, set(V) { V = conversions["double"](V); this[impl].playbackRate = V; }, enumerable: true, configurable: true }); Object.defineProperty(HTMLMediaElement.prototype, "played", { get() { return utils.tryWrapperForImpl(this[impl].played); }, enumerable: true, configurable: true }); Object.defineProperty(HTMLMediaElement.prototype, "seekable", { get() { return utils.tryWrapperForImpl(this[impl].seekable); }, enumerable: true, configurable: true }); Object.defineProperty(HTMLMediaElement.prototype, "ended", { get() { return this[impl].ended; }, enumerable: true, configurable: true }); Object.defineProperty(HTMLMediaElement.prototype, "autoplay", { get() { return this.hasAttribute("autoplay"); }, set(V) { V = conversions["boolean"](V); if (V) { this.setAttribute("autoplay", ""); } else { this.removeAttribute("autoplay"); } }, enumerable: true, configurable: true }); Object.defineProperty(HTMLMediaElement.prototype, "loop", { get() { return this.hasAttribute("loop"); }, set(V) { V = conversions["boolean"](V); if (V) { this.setAttribute("loop", ""); } else { this.removeAttribute("loop"); } }, enumerable: true, configurable: true }); Object.defineProperty(HTMLMediaElement.prototype, "controls", { get() { return this.hasAttribute("controls"); }, set(V) { V = conversions["boolean"](V); if (V) { this.setAttribute("controls", ""); } else { this.removeAttribute("controls"); } }, enumerable: true, configurable: true }); Object.defineProperty(HTMLMediaElement.prototype, "volume", { get() { return this[impl].volume; }, set(V) { V = conversions["double"](V); this[impl].volume = V; }, enumerable: true, configurable: true }); Object.defineProperty(HTMLMediaElement.prototype, "muted", { get() { return this[impl].muted; }, set(V) { V = conversions["boolean"](V); this[impl].muted = V; }, enumerable: true, configurable: true }); Object.defineProperty(HTMLMediaElement.prototype, "defaultMuted", { get() { return this.hasAttribute("muted"); }, set(V) { V = conversions["boolean"](V); if (V) { this.setAttribute("muted", ""); } else { this.removeAttribute("muted"); } }, enumerable: true, configurable: true }); Object.defineProperty(HTMLMediaElement.prototype, "audioTracks", { get() { return utils.tryWrapperForImpl(this[impl].audioTracks); }, enumerable: true, configurable: true }); Object.defineProperty(HTMLMediaElement.prototype, "videoTracks", { get() { return utils.tryWrapperForImpl(this[impl].videoTracks); }, enumerable: true, configurable: true }); Object.defineProperty(HTMLMediaElement.prototype, "textTracks", { get() { return utils.tryWrapperForImpl(this[impl].textTracks); }, enumerable: true, configurable: true }); const iface = { mixedInto: [], is(obj) { if (obj) { if (obj[impl] instanceof Impl.implementation) { return true; } for (let i = 0; i < module.exports.mixedInto.length; ++i) { if (obj instanceof module.exports.mixedInto[i]) { return true; } } } return false; }, isImpl(obj) { if (obj) { if (obj instanceof Impl.implementation) { return true; } const wrapper = utils.wrapperForImpl(obj); for (let i = 0; i < module.exports.mixedInto.length; ++i) { if (wrapper instanceof module.exports.mixedInto[i]) { return true; } } } return false; }, create(constructorArgs, privateData) { let obj = Object.create(HTMLMediaElement.prototype); this.setup(obj, constructorArgs, privateData); return obj; }, createImpl(constructorArgs, privateData) { let obj = Object.create(HTMLMediaElement.prototype); this.setup(obj, constructorArgs, privateData); return utils.implForWrapper(obj); }, _internalSetup(obj) { HTMLElement._internalSetup(obj); }, setup(obj, constructorArgs, privateData) { if (!privateData) privateData = {}; privateData.wrapper = obj; this._internalSetup(obj); obj[impl] = new Impl.implementation(constructorArgs, privateData); obj[impl][utils.wrapperSymbol] = obj; }, interface: HTMLMediaElement, expose: { Window: { HTMLMediaElement: HTMLMediaElement } } }; module.exports = iface; const Impl = require("../nodes/HTMLMediaElement-impl.js");
/** * jQRangeSlider * A javascript slider selector that supports dates * * Copyright (C) Guillaume Gautreau 2012 * Dual licensed under the MIT or GPL Version 2 licenses. * */ (function ($, undefined) { "use strict"; $.widget("ui.rangeSlider", { options: { bounds: {min:0, max:100}, defaultValues: {min:20, max:50}, wheelMode: null, wheelSpeed: 4, arrows: true, valueLabels: "show", formatter: null, durationIn: 0, durationOut: 400, delayOut: 200, range: {min: false, max: false}, step: false, scales: false, enabled: true }, _values: null, _valuesChanged: false, _initialized: false, // Created elements bar: null, leftHandle: null, rightHandle: null, innerBar: null, container: null, arrows: null, labels: null, changing: {min:false, max:false}, changed: {min:false, max:false}, ruler: null, _create: function(){ this._setDefaultValues(); this.labels = {left: null, right:null, leftDisplayed:true, rightDisplayed:true}; this.arrows = {left:null, right:null}; this.changing = {min:false, max:false}; this.changed = {min:false, max:false}; this._createElements(); this._bindResize(); setTimeout($.proxy(this.resize, this), 1); setTimeout($.proxy(this._initValues, this), 1); }, _setDefaultValues: function(){ this._values = { min: this.options.defaultValues.min, max: this.options.defaultValues.max }; }, _bindResize: function(){ var that = this; this._resizeProxy = function(e){ that.resize(e); }; $(window).resize(this._resizeProxy); }, _initWidth: function(){ this.container.css("width", this.element.width() - this.container.outerWidth(true) + this.container.width()); this.innerBar.css("width", this.container.width() - this.innerBar.outerWidth(true) + this.innerBar.width()); }, _initValues: function(){ this._initialized = true; this.values(this._values.min, this._values.max); }, _setOption: function(key, value) { this._setWheelOption(key, value); this._setArrowsOption(key, value); this._setLabelsOption(key, value); this._setLabelsDurations(key, value); this._setFormatterOption(key, value); this._setBoundsOption(key, value); this._setRangeOption(key, value); this._setStepOption(key, value); this._setScalesOption(key, value); this._setEnabledOption(key, value); }, _validProperty: function(object, name, defaultValue){ if (object === null || typeof object[name] === "undefined"){ return defaultValue; } return object[name]; }, _setStepOption: function(key, value){ if (key === "step"){ this.options.step = value; this._leftHandle("option", "step", value); this._rightHandle("option", "step", value); this._changed(true); } }, _setScalesOption: function(key, value){ if (key === "scales"){ if (value === false || value === null){ this.options.scales = false; this._destroyRuler(); }else if (value instanceof Array){ this.options.scales = value; this._updateRuler(); } } }, _setRangeOption: function(key, value){ if (key === "range"){ this._bar("option", "range", value); this.options.range = this._bar("option", "range"); this._changed(true); } }, _setBoundsOption: function(key, value){ if (key === "bounds" && typeof value.min !== "undefined" && typeof value.max !== "undefined"){ this.bounds(value.min, value.max); } }, _setWheelOption: function(key, value){ if (key === "wheelMode" || key === "wheelSpeed"){ this._bar("option", key, value); this.options[key] = this._bar("option", key); } }, _setLabelsOption: function(key, value){ if (key === "valueLabels"){ if (value !== "hide" && value !== "show" && value !== "change"){ return; } this.options.valueLabels = value; if (value !== "hide"){ this._createLabels(); this._leftLabel("update"); this._rightLabel("update"); }else{ this._destroyLabels(); } } }, _setFormatterOption: function(key, value){ if (key === "formatter" && value !== null && typeof value === "function"){ if (this.options.valueLabels !== "hide"){ this._leftLabel("option", "formatter", value); this.options.formatter = this._rightLabel("option", "formatter", value); } } }, _setArrowsOption: function(key, value){ if (key === "arrows" && (value === true || value === false) && value !== this.options.arrows){ if (value === true){ this.element .removeClass("ui-rangeSlider-noArrow") .addClass("ui-rangeSlider-withArrows"); this.arrows.left.css("display", "block"); this.arrows.right.css("display", "block"); this.options.arrows = true; }else if (value === false){ this.element .addClass("ui-rangeSlider-noArrow") .removeClass("ui-rangeSlider-withArrows"); this.arrows.left.css("display", "none"); this.arrows.right.css("display", "none"); this.options.arrows = false; } this._initWidth(); } }, _setLabelsDurations: function(key, value){ if (key === "durationIn" || key === "durationOut" || key === "delayOut"){ if (parseInt(value, 10) !== value) return; if (this.labels.left !== null){ this._leftLabel("option", key, value); } if (this.labels.right !== null){ this._rightLabel("option", key, value); } this.options[key] = value; } }, _setEnabledOption: function(key, value){ if (key === "enabled"){ this.toggle(value); } }, _createElements: function(){ if (this.element.css("position") !== "absolute"){ this.element.css("position", "relative"); } this.element.addClass("ui-rangeSlider"); this.container = $("<div class='ui-rangeSlider-container' />") .css("position", "absolute") .appendTo(this.element); this.innerBar = $("<div class='ui-rangeSlider-innerBar' />") .css("position", "absolute") .css("top", 0) .css("left", 0); this._createHandles(); this._createBar(); this.container.prepend(this.innerBar); this._createArrows(); if (this.options.valueLabels !== "hide"){ this._createLabels(); }else{ this._destroyLabels(); } this._updateRuler(); if (!this.options.enabled) this._toggle(this.options.enabled); }, _createHandle: function(options){ return $("<div />") [this._handleType()](options) .bind("sliderDrag", $.proxy(this._changing, this)) .bind("stop", $.proxy(this._changed, this)); }, _createHandles: function(){ this.leftHandle = this._createHandle({ isLeft: true, bounds: this.options.bounds, value: this._values.min, step: this.options.step }).appendTo(this.container); this.rightHandle = this._createHandle({ isLeft: false, bounds: this.options.bounds, value: this._values.max, step: this.options.step }).appendTo(this.container); }, _createBar: function(){ this.bar = $("<div />") .prependTo(this.container) .bind("sliderDrag scroll zoom", $.proxy(this._changing, this)) .bind("stop", $.proxy(this._changed, this)); this._bar({ leftHandle: this.leftHandle, rightHandle: this.rightHandle, values: {min: this._values.min, max: this._values.max}, type: this._handleType(), range: this.options.range, wheelMode: this.options.wheelMode, wheelSpeed: this.options.wheelSpeed }); this.options.range = this._bar("option", "range"); this.options.wheelMode = this._bar("option", "wheelMode"); this.options.wheelSpeed = this._bar("option", "wheelSpeed"); }, _createArrows: function(){ this.arrows.left = this._createArrow("left"); this.arrows.right = this._createArrow("right"); if (!this.options.arrows){ this.arrows.left.css("display", "none"); this.arrows.right.css("display", "none"); this.element.addClass("ui-rangeSlider-noArrow"); }else{ this.element.addClass("ui-rangeSlider-withArrows"); } }, _createArrow: function(whichOne){ var arrow = $("<div class='ui-rangeSlider-arrow' />") .append("<div class='ui-rangeSlider-arrow-inner' />") .addClass("ui-rangeSlider-" + whichOne + "Arrow") .css("position", "absolute") .css(whichOne, 0) .appendTo(this.element), target; if (whichOne === "right"){ target = $.proxy(this._scrollRightClick, this); }else{ target = $.proxy(this._scrollLeftClick, this); } arrow.bind("mousedown touchstart", target); return arrow; }, _proxy: function(element, type, args){ var array = Array.prototype.slice.call(args); if (element && element[type]){ return element[type].apply(element, array); } return null; }, _handleType: function(){ return "rangeSliderHandle"; }, _barType: function(){ return "rangeSliderBar"; }, _bar: function(){ return this._proxy(this.bar, this._barType(), arguments); }, _labelType: function(){ return "rangeSliderLabel"; }, _leftLabel: function(){ return this._proxy(this.labels.left, this._labelType(), arguments); }, _rightLabel: function(){ return this._proxy(this.labels.right, this._labelType(), arguments); }, _leftHandle: function(){ return this._proxy(this.leftHandle, this._handleType(), arguments); }, _rightHandle: function(){ return this._proxy(this.rightHandle, this._handleType(), arguments); }, _getValue: function(position, handle){ if (handle === this.rightHandle){ position = position - handle.outerWidth(); } return position * (this.options.bounds.max - this.options.bounds.min) / (this.container.innerWidth() - handle.outerWidth(true)) + this.options.bounds.min; }, _trigger: function(eventName){ var that = this; setTimeout(function(){ that.element.trigger(eventName, { label: that.element, values: that.values() }); }, 1); }, _changing: function(){ if(this._updateValues()){ this._trigger("valuesChanging"); this._valuesChanged = true; } }, _deactivateLabels: function(){ if (this.options.valueLabels === "change"){ this._leftLabel("option", "show", "hide"); this._rightLabel("option", "show", "hide"); } }, _reactivateLabels: function(){ if (this.options.valueLabels === "change"){ this._leftLabel("option", "show", "change"); this._rightLabel("option", "show", "change"); } }, _changed: function(isAutomatic){ if (isAutomatic === true){ this._deactivateLabels(); } if (this._updateValues() || this._valuesChanged){ this._trigger("valuesChanged"); if (isAutomatic !== true){ this._trigger("userValuesChanged"); } this._valuesChanged = false; } if (isAutomatic === true){ this._reactivateLabels(); } }, _updateValues: function(){ var left = this._leftHandle("value"), right = this._rightHandle("value"), min = this._min(left, right), max = this._max(left, right), changing = (min !== this._values.min || max !== this._values.max); this._values.min = this._min(left, right); this._values.max = this._max(left, right); return changing; }, _min: function(value1, value2){ return Math.min(value1, value2); }, _max: function(value1, value2){ return Math.max(value1, value2); }, /* * Value labels */ _createLabel: function(label, handle){ var params; if (label === null){ params = this._getLabelConstructorParameters(label, handle); label = $("<div />") .appendTo(this.element) [this._labelType()](params); }else{ params = this._getLabelRefreshParameters(label, handle); label[this._labelType()](params); } return label; }, _getLabelConstructorParameters: function(label, handle){ return { handle: handle, handleType: this._handleType(), formatter: this._getFormatter(), show: this.options.valueLabels, durationIn: this.options.durationIn, durationOut: this.options.durationOut, delayOut: this.options.delayOut }; }, _getLabelRefreshParameters: function(){ return { formatter: this._getFormatter(), show: this.options.valueLabels, durationIn: this.options.durationIn, durationOut: this.options.durationOut, delayOut: this.options.delayOut }; }, _getFormatter: function(){ if (this.options.formatter === false || this.options.formatter === null){ return this._defaultFormatter; } return this.options.formatter; }, _defaultFormatter: function(value){ return Math.round(value); }, _destroyLabel: function(label){ if (label !== null){ label[this._labelType()]("destroy"); label.remove(); label = null; } return label; }, _createLabels: function(){ this.labels.left = this._createLabel(this.labels.left, this.leftHandle); this.labels.right = this._createLabel(this.labels.right, this.rightHandle); this._leftLabel("pair", this.labels.right); }, _destroyLabels: function(){ this.labels.left = this._destroyLabel(this.labels.left); this.labels.right = this._destroyLabel(this.labels.right); }, /* * Scrolling */ _stepRatio: function(){ return this._leftHandle("stepRatio"); }, _scrollRightClick: function(e){ if (!this.options.enabled) return false; e.preventDefault(); this._bar("startScroll"); this._bindStopScroll(); this._continueScrolling("scrollRight", 4 * this._stepRatio(), 1); }, _continueScrolling: function(action, timeout, quantity, timesBeforeSpeedingUp){ if (!this.options.enabled) return false; this._bar(action, quantity); timesBeforeSpeedingUp = timesBeforeSpeedingUp || 5; timesBeforeSpeedingUp--; var that = this, minTimeout = 16, maxQuantity = Math.max(1, 4 / this._stepRatio()); this._scrollTimeout = setTimeout(function(){ if (timesBeforeSpeedingUp === 0){ if (timeout > minTimeout){ timeout = Math.max(minTimeout, timeout / 1.5); } else { quantity = Math.min(maxQuantity, quantity * 2); } timesBeforeSpeedingUp = 5; } that._continueScrolling(action, timeout, quantity, timesBeforeSpeedingUp); }, timeout); }, _scrollLeftClick: function(e){ if (!this.options.enabled) return false; e.preventDefault(); this._bar("startScroll"); this._bindStopScroll(); this._continueScrolling("scrollLeft", 4 * this._stepRatio(), 1); }, _bindStopScroll: function(){ var that = this; this._stopScrollHandle = function(e){ e.preventDefault(); that._stopScroll(); }; $(document).bind("mouseup touchend", this._stopScrollHandle); }, _stopScroll: function(){ $(document).unbind("mouseup touchend", this._stopScrollHandle); this._stopScrollHandle = null; this._bar("stopScroll"); clearTimeout(this._scrollTimeout); }, /* * Ruler */ _createRuler: function(){ this.ruler = $("<div class='ui-rangeSlider-ruler' />").appendTo(this.innerBar); }, _setRulerParameters: function(){ this.ruler.ruler({ min: this.options.bounds.min, max: this.options.bounds.max, scales: this.options.scales }); }, _destroyRuler: function(){ if (this.ruler !== null && $.fn.ruler){ this.ruler.ruler("destroy"); this.ruler.remove(); this.ruler = null; } }, _updateRuler: function(){ this._destroyRuler(); if (this.options.scales === false || !$.fn.ruler){ return; } this._createRuler(); this._setRulerParameters(); }, /* * Public methods */ values: function(min, max){ var val; if (typeof min !== "undefined" && typeof max !== "undefined"){ if (!this._initialized){ this._values.min = min; this._values.max = max; return this._values; } this._deactivateLabels(); val = this._bar("values", min, max); this._changed(true); this._reactivateLabels(); }else{ val = this._bar("values", min, max); } return val; }, min: function(min){ this._values.min = this.values(min, this._values.max).min; return this._values.min; }, max: function(max){ this._values.max = this.values(this._values.min, max).max; return this._values.max; }, bounds: function(min, max){ if (this._isValidValue(min) && this._isValidValue(max) && min < max){ this._setBounds(min, max); this._updateRuler(); this._changed(true); } return this.options.bounds; }, _isValidValue: function(value){ return typeof value !== "undefined" && parseFloat(value) === value; }, _setBounds: function(min, max){ this.options.bounds = {min: min, max: max}; this._leftHandle("option", "bounds", this.options.bounds); this._rightHandle("option", "bounds", this.options.bounds); this._bar("option", "bounds", this.options.bounds); }, zoomIn: function(quantity){ this._bar("zoomIn", quantity) }, zoomOut: function(quantity){ this._bar("zoomOut", quantity); }, scrollLeft: function(quantity){ this._bar("startScroll"); this._bar("scrollLeft", quantity); this._bar("stopScroll"); }, scrollRight: function(quantity){ this._bar("startScroll"); this._bar("scrollRight", quantity); this._bar("stopScroll"); }, /** * Resize */ resize: function(){ this._initWidth(); this._leftHandle("update"); this._rightHandle("update"); this._bar("update"); }, /* * Enable / disable */ enable: function(){ this.toggle(true); }, disable: function(){ this.toggle(false); }, toggle: function(enabled){ if (enabled === undefined) enabled = !this.options.enabled; if (this.options.enabled !== enabled){ this._toggle(enabled); } }, _toggle: function(enabled){ this.options.enabled = enabled; this.element.toggleClass("ui-rangeSlider-disabled", !enabled); var action = enabled ? "enable" : "disable"; this._bar(action); this._leftHandle(action); this._rightHandle(action); this._leftLabel(action); this._rightLabel(action); }, /* * Destroy */ destroy: function(){ this.element.removeClass("ui-rangeSlider-withArrows ui-rangeSlider-noArrow ui-rangeSlider-disabled"); this._destroyWidgets(); this._destroyElements(); this.element.removeClass("ui-rangeSlider"); this.options = null; $(window).unbind("resize", this._resizeProxy); this._resizeProxy = null; this._bindResize = null; $.Widget.prototype.destroy.apply(this, arguments); }, _destroyWidget: function(name){ this["_" + name]("destroy"); this[name].remove(); this[name] = null; }, _destroyWidgets: function(){ this._destroyWidget("bar"); this._destroyWidget("leftHandle"); this._destroyWidget("rightHandle"); this._destroyRuler(); this._destroyLabels(); }, _destroyElements: function(){ this.container.remove(); this.container = null; this.innerBar.remove(); this.innerBar = null; this.arrows.left.remove(); this.arrows.right.remove(); this.arrows = null; } }); }(jQuery));
// For questions about the Malayalam hyphenation patterns // ask Santhosh Thottingal (santhosh dot thottingal at gmail dot com) Hyphenator.languages.ml={ 'leftmin' : 2, 'rightmin' : 2, 'shortestPattern' : 1, 'longestPattern' : 3, 'specialChars' : 'ആഅഇഈഉഊഋഎഏഐഒഔകഗഖഘങചഛജഝഞടഠഡഢണതഥദധനപഫബഭമയരലവശഷസഹളഴറിീാുൂൃെേൊാോൈൌൗ്ഃം‍', 'patterns' : "അ1 ആ1 ഇ1 ഈ1 ഉ1 ഊ1 ഋ1 എ1 ഏ1 ഐ1 ഒ1 ഔ1 ി1 ാ1 ീ1 ു1 ൂ1 ൃ1 െ1 േ1 ൊ1 ോ1 ൌ1 ൗ1 ്2 ഃ1 ം1 2ന്‍ 2ര്‍ 2ല്‍ 2ള്‍ 2ണ്‍ 1ക 1ഗ1 1ഖ 1ഘ 1ങ 1ച 1ഛ 1ജ 1ഝ 1ഞ 1ട 1ഠ 1ഡ 1ഢ 1ണ 1ത 1ഥ 1ദ 1ധ 1ന 1പ 1ഫ 1ബ 1ഭ 1മ 1യ 1ര 1ല 1വ 1ശ 1ഷ 1സ 1ഹ 1ള 1ഴ 1റ" };
/* * /MathJax/jax/output/HTML-CSS/fonts/TeX/SansSerif/Regular/Other.js * * Copyright (c) 2009-2017 The MathJax Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ MathJax.Hub.Insert(MathJax.OutputJax["HTML-CSS"].FONTDATA.FONTS.MathJax_SansSerif,{160:[0,0,250,0,0],305:[444,0,239,74,164],567:[444,205,267,-59,192],915:[691,0,542,87,499],916:[694,0,833,42,790],920:[716,21,778,56,722],923:[694,0,611,28,582],926:[688,0,667,42,624],928:[691,0,708,86,621],931:[694,0,722,55,666],933:[716,0,778,55,722],934:[694,0,722,55,666],936:[694,0,778,55,722],937:[716,0,722,44,677],8211:[312,-236,500,0,499],8212:[312,-236,1000,0,999],8216:[694,-471,278,90,189],8217:[694,-471,278,89,188],8220:[694,-471,500,174,467],8221:[694,-471,500,32,325]});MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir+"/SansSerif/Regular/Other.js");
Package.onUse(function (api) { api.addFiles('thrower.js', 'server'); });
YUI.add("querystring-stringify",function(d){var c=d.namespace("QueryString"),b=[],a=d.Lang;c.escape=encodeURIComponent;c.stringify=function(k,o,e){var g,j,m,h,f,t,r=o&&o.sep?o.sep:"&",p=o&&o.eq?o.eq:"=",q=o&&o.arrayKey?o.arrayKey:false;if(a.isNull(k)||a.isUndefined(k)||a.isFunction(k)){return e?c.escape(e)+p:"";}if(a.isBoolean(k)||Object.prototype.toString.call(k)==="[object Boolean]"){k=+k;}if(a.isNumber(k)||a.isString(k)){return c.escape(e)+p+c.escape(k);}if(a.isArray(k)){t=[];e=q?e+"[]":e;h=k.length;for(m=0;m<h;m++){t.push(c.stringify(k[m],o,e));}return t.join(r);}for(m=b.length-1;m>=0;--m){if(b[m]===k){throw new Error("QueryString.stringify. Cyclical reference");}}b.push(k);t=[];g=e?e+"[":"";j=e?"]":"";for(m in k){if(k.hasOwnProperty(m)){f=g+m+j;t.push(c.stringify(k[m],o,f));}}b.pop();t=t.join(r);if(!t&&e){return e+"=";}return t;};},"@VERSION@",{supersedes:["querystring-stringify-simple"],requires:["yui-base"]});
require('./angular-locale_ta-in'); module.exports = 'ngLocale';
// Helper function to avoid duplication of code function toDateTime(date) { if (date instanceof Date) { return date; } var intDate = Date.parse(date); if (isNaN(intDate)) { return null; } return new Date(intDate); } // Convert to date without the time component function toDate(date) { if (!(date instanceof Date)) { date = toDateTime(date); } if (!date) { return null; } return date; } var validators = module.exports = { isEmail: function(str) { return str.match(/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/); }, isUrl: function(str) { //A modified version of the validator from @diegoperini / https://gist.github.com/729294 return str.length < 2083 && str.match(/^(?!mailto:)(?:(?:https?|ftp):\/\/)?(?:\S+(?::\S*)?@)?(?:(?:(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[0-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))|localhost)(?::\d{2,5})?(?:\/[^\s]*)?$/i); }, //node-js-core isIP : function(str) { if (validators.isIPv4(str)) { return 4; } else if (validators.isIPv6(str)) { return 6; } else { return 0; } }, //node-js-core isIPv4 : function(str) { if (/^(\d?\d?\d)\.(\d?\d?\d)\.(\d?\d?\d)\.(\d?\d?\d)$/.test(str)) { var parts = str.split('.').sort(); // no need to check for < 0 as regex won't match in that case if (parts[3] > 255) { return false; } return true; } return false; }, //node-js-core isIPv6 : function(str) { if (/^::|^::1|^([a-fA-F0-9]{1,4}::?){1,7}([a-fA-F0-9]{1,4})$/.test(str)) { return true; } return false; }, isIPNet: function(str) { return validators.isIP(str) !== 0; }, isAlpha: function(str) { return str.match(/^[a-zA-Z]+$/); }, isAlphanumeric: function(str) { return str.match(/^[a-zA-Z0-9]+$/); }, isNumeric: function(str) { return str.match(/^-?[0-9]+$/); }, isHexadecimal: function(str) { return str.match(/^[0-9a-fA-F]+$/); }, isHexColor: function(str) { return str.match(/^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/); }, isLowercase: function(str) { return str === str.toLowerCase(); }, isUppercase: function(str) { return str === str.toUpperCase(); }, isInt: function(str) { return str.match(/^(?:-?(?:0|[1-9][0-9]*))$/); }, isDecimal: function(str) { return str !== '' && str.match(/^(?:-?(?:[0-9]+))?(?:\.[0-9]*)?(?:[eE][\+\-]?(?:[0-9]+))?$/); }, isFloat: function(str) { return validators.isDecimal(str); }, isDivisibleBy: function(str, n) { return (parseFloat(str) % parseInt(n, 10)) === 0; }, notNull: function(str) { return str !== ''; }, isNull: function(str) { return str === ''; }, notEmpty: function(str) { return !str.match(/^[\s\t\r\n]*$/); }, equals: function(a, b) { return a == b; }, contains: function(str, elem) { return str.indexOf(elem) >= 0 && !!elem; }, notContains: function(str, elem) { return !validators.contains(str, elem); }, regex: function(str, pattern, modifiers) { str += ''; if (Object.prototype.toString.call(pattern).slice(8, -1) !== 'RegExp') { pattern = new RegExp(pattern, modifiers); } return str.match(pattern); }, is: function(str, pattern, modifiers) { return validators.regex(str, pattern, modifiers); }, notRegex: function(str, pattern, modifiers) { return !validators.regex(str, pattern, modifiers); }, not: function(str, pattern, modifiers) { return validators.notRegex(str, pattern, modifiers); }, len: function(str, min, max) { return str.length >= min && (max === undefined || str.length <= max); }, //Thanks to github.com/sreuter for the idea. isUUID: function(str, version) { var pattern; if (version == 3 || version == 'v3') { pattern = /^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i; } else if (version == 4 || version == 'v4') { pattern = /^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i; } else if (version == 5 || version == 'v5') { pattern = /^[0-9A-F]{8}-[0-9A-F]{4}-5[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i; } else { pattern = /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i; } return pattern.test(str); }, isUUIDv3: function(str) { return validators.isUUID(str, 3); }, isUUIDv4: function(str) { return validators.isUUID(str, 4); }, isUUIDv5: function(str) { return validators.isUUID(str, 5); }, isDate: function(str) { var intDate = Date.parse(str); return !isNaN(intDate); }, isAfter: function(str, date) { date = date || new Date(); var origDate = toDate(str); var compDate = toDate(date); return !(origDate && compDate && origDate <= compDate); }, isBefore: function(str, date) { date = date || new Date(); var origDate = toDate(str); var compDate = toDate(date); return !(origDate && compDate && origDate >= compDate); }, isIn: function(str, options) { if (!options || typeof options.indexOf !== 'function') { return false; } if (Array.isArray(options)) { options = options.map(String); } return options.indexOf(str) >= 0; }, notIn: function(str, options) { if (!options || typeof options.indexOf !== 'function') { return false; } if (Array.isArray(options)) { options = options.map(String); } return options.indexOf(str) < 0; }, min: function(str, val) { var number = parseFloat(str); return isNaN(number) || number >= val; }, max: function(str, val) { var number = parseFloat(str); return isNaN(number) || number <= val; }, //Will work against Visa, MasterCard, American Express, Discover, Diners Club, and JCB card numbering formats isCreditCard: function(str) { //remove all dashes, spaces, etc. var sanitized = str.replace(/[^0-9]+/g, ''); if (sanitized.match(/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$/) === null) { return null; } // Doing Luhn check var sum = 0; var digit; var tmpNum; var shouldDouble = false; for (var i = sanitized.length - 1; i >= 0; i--) { digit = sanitized.substring(i, (i + 1)); tmpNum = parseInt(digit, 10); if (shouldDouble) { tmpNum *= 2; if (tmpNum >= 10) { sum += ((tmpNum % 10) + 1); } else { sum += tmpNum; } } else { sum += tmpNum; } if (shouldDouble) { shouldDouble = false; } else { shouldDouble = true; } } if ((sum % 10) === 0) { return sanitized; } else { return null; } } };
// Copyright 2009 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /** * Constructs a ConsArray object. It is used mainly for tree traversal. * In this use case we have lots of arrays that we need to iterate * sequentally. The internal Array implementation is horribly slow * when concatenating on large (10K items) arrays due to memory copying. * That's why we avoid copying memory and insead build a linked list * of arrays to iterate through. * * @constructor */ function ConsArray() { this.tail_ = new ConsArray.Cell(null, null); this.currCell_ = this.tail_; this.currCellPos_ = 0; }; /** * Concatenates another array for iterating. Empty arrays are ignored. * This operation can be safely performed during ongoing ConsArray * iteration. * * @param {Array} arr Array to concatenate. */ ConsArray.prototype.concat = function(arr) { if (arr.length > 0) { this.tail_.data = arr; this.tail_ = this.tail_.next = new ConsArray.Cell(null, null); } }; /** * Whether the end of iteration is reached. */ ConsArray.prototype.atEnd = function() { return this.currCell_ === null || this.currCell_.data === null || this.currCellPos_ >= this.currCell_.data.length; }; /** * Returns the current item, moves to the next one. */ ConsArray.prototype.next = function() { var result = this.currCell_.data[this.currCellPos_++]; if (this.currCellPos_ >= this.currCell_.data.length) { this.currCell_ = this.currCell_.next; this.currCellPos_ = 0; } return result; }; /** * A cell object used for constructing a list in ConsArray. * * @constructor */ ConsArray.Cell = function(data, next) { this.data = data; this.next = next; }; module.exports = ConsArray;
var _ = require('lodash'), errors = require('../errors'), ghostBookshelf = require('./base'), Promise = require('bluebird'), i18n = require('../i18n'), Role, Roles; Role = ghostBookshelf.Model.extend({ tableName: 'roles', users: function users() { return this.belongsToMany('User'); }, permissions: function permissions() { return this.belongsToMany('Permission'); } }, { /** * Returns an array of keys permitted in a method's `options` hash, depending on the current method. * @param {String} methodName The name of the method to check valid options for. * @return {Array} Keys allowed in the `options` hash of the model's method. */ permittedOptions: function permittedOptions(methodName) { var options = ghostBookshelf.Model.permittedOptions(), // whitelists for the `options` hash argument on methods, by method name. // these are the only options that can be passed to Bookshelf / Knex. validOptions = { findOne: ['withRelated'], findAll: ['withRelated'] }; if (validOptions[methodName]) { options = options.concat(validOptions[methodName]); } return options; }, permissible: function permissible(roleModelOrId, action, context, loadedPermissions, hasUserPermission, hasAppPermission) { var self = this, checkAgainst = [], origArgs; // If we passed in an id instead of a model, get the model // then check the permissions if (_.isNumber(roleModelOrId) || _.isString(roleModelOrId)) { // Grab the original args without the first one origArgs = _.toArray(arguments).slice(1); // Get the actual role model return this.findOne({id: roleModelOrId, status: 'all'}).then(function then(foundRoleModel) { // Build up the original args but substitute with actual model var newArgs = [foundRoleModel].concat(origArgs); return self.permissible.apply(self, newArgs); }, errors.logAndThrowError); } if (action === 'assign' && loadedPermissions.user) { if (_.some(loadedPermissions.user.roles, {name: 'Owner'})) { checkAgainst = ['Owner', 'Administrator', 'Editor', 'Author']; } else if (_.some(loadedPermissions.user.roles, {name: 'Administrator'})) { checkAgainst = ['Administrator', 'Editor', 'Author']; } else if (_.some(loadedPermissions.user.roles, {name: 'Editor'})) { checkAgainst = ['Author']; } // Role in the list of permissible roles hasUserPermission = roleModelOrId && _.includes(checkAgainst, roleModelOrId.get('name')); } if (hasUserPermission && hasAppPermission) { return Promise.resolve(); } return Promise.reject(new errors.NoPermissionError(i18n.t('errors.models.role.notEnoughPermission'))); } }); Roles = ghostBookshelf.Collection.extend({ model: Role }); module.exports = { Role: ghostBookshelf.model('Role', Role), Roles: ghostBookshelf.collection('Roles', Roles) };
'use strict' const chalk = require('chalk') const semver = require('semver') const packageConfig = require('../package.json') const shell = require('shelljs') function exec (cmd) { return require('child_process').execSync(cmd).toString().trim() } const versionRequirements = [ { name: 'node', currentVersion: semver.clean(process.version), versionRequirement: packageConfig.engines.node } ] if (shell.which('npm')) { versionRequirements.push({ name: 'npm', currentVersion: exec('npm --version'), versionRequirement: packageConfig.engines.npm }) } module.exports = function () { const warnings = [] for (let i = 0; i < versionRequirements.length; i++) { const mod = versionRequirements[i] if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) { warnings.push(mod.name + ': ' + chalk.red(mod.currentVersion) + ' should be ' + chalk.green(mod.versionRequirement) ) } } if (warnings.length) { console.log('') console.log(chalk.yellow('To use this template, you must update following to modules:')) console.log() for (let i = 0; i < warnings.length; i++) { const warning = warnings[i] console.log(' ' + warning) } console.log() process.exit(1) } }
YUI.add('handlebars-base', function (Y, NAME) { /*! Handlebars.js - Copyright (C) 2011 Yehuda Katz https://raw.github.com/wycats/handlebars.js/master/LICENSE */ // This file contains YUI-specific wrapper code and overrides for the // handlebars-base module. /** Handlebars is a simple template language inspired by Mustache. This is a YUI port of the original Handlebars project, which can be found at <https://github.com/wycats/handlebars.js>. @module handlebars @main handlebars @since 3.5.0 */ /** Provides basic Handlebars template rendering functionality. Use this module when you only need to render pre-compiled templates. @module handlebars @submodule handlebars-base */ /** Handlebars is a simple template language inspired by Mustache. This is a YUI port of the original Handlebars project, which can be found at <https://github.com/wycats/handlebars.js>. @class Handlebars @since 3.5.0 */ var Handlebars = Y.namespace('Handlebars'); /* THIS FILE IS GENERATED BY A BUILD SCRIPT - DO NOT EDIT! */ Handlebars.VERSION = "1.0.0-rc.4"; Handlebars.COMPILER_REVISION = 3; Handlebars.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' }; Handlebars.helpers = {}; Handlebars.partials = {}; var toString = Object.prototype.toString, functionType = '[object Function]', objectType = '[object Object]'; Handlebars.registerHelper = function(name, fn, inverse) { if (toString.call(name) === objectType) { if (inverse || fn) { throw new Handlebars.Exception('Arg not supported with multiple helpers'); } Handlebars.Utils.extend(this.helpers, name); } else { if (inverse) { fn.not = inverse; } this.helpers[name] = fn; } }; Handlebars.registerPartial = function(name, str) { if (toString.call(name) === objectType) { Handlebars.Utils.extend(this.partials, name); } else { this.partials[name] = str; } }; Handlebars.registerHelper('helperMissing', function(arg) { if(arguments.length === 2) { return undefined; } else { throw new Error("Could not find property '" + arg + "'"); } }); Handlebars.registerHelper('blockHelperMissing', function(context, options) { var inverse = options.inverse || function() {}, fn = options.fn; var type = toString.call(context); if(type === functionType) { context = context.call(this); } if(context === true) { return fn(this); } else if(context === false || context == null) { return inverse(this); } else if(type === "[object Array]") { if(context.length > 0) { return Handlebars.helpers.each(context, options); } else { return inverse(this); } } else { return fn(context); } }); Handlebars.K = function() {}; Handlebars.createFrame = Object.create || function(object) { Handlebars.K.prototype = object; var obj = new Handlebars.K(); Handlebars.K.prototype = null; return obj; }; Handlebars.logger = { DEBUG: 0, INFO: 1, WARN: 2, ERROR: 3, level: 3, methodMap: {0: 'debug', 1: 'info', 2: 'warn', 3: 'error'}, // can be overridden in the host environment log: function(level, obj) { if (Handlebars.logger.level <= level) { var method = Handlebars.logger.methodMap[level]; if (typeof console !== 'undefined' && console[method]) { console[method].call(console, obj); } } } }; Handlebars.log = function(level, obj) { Handlebars.logger.log(level, obj); }; Handlebars.registerHelper('each', function(context, options) { var fn = options.fn, inverse = options.inverse; var i = 0, ret = "", data; if (options.data) { data = Handlebars.createFrame(options.data); } if(context && typeof context === 'object') { if(context instanceof Array){ for(var j = context.length; i<j; i++) { if (data) { data.index = i; } ret = ret + fn(context[i], { data: data }); } } else { for(var key in context) { if(context.hasOwnProperty(key)) { if(data) { data.key = key; } ret = ret + fn(context[key], {data: data}); i++; } } } } if(i === 0){ ret = inverse(this); } return ret; }); Handlebars.registerHelper('if', function(context, options) { var type = toString.call(context); if(type === functionType) { context = context.call(this); } if(!context || Handlebars.Utils.isEmpty(context)) { return options.inverse(this); } else { return options.fn(this); } }); Handlebars.registerHelper('unless', function(context, options) { return Handlebars.helpers['if'].call(this, context, {fn: options.inverse, inverse: options.fn}); }); Handlebars.registerHelper('with', function(context, options) { if (!Handlebars.Utils.isEmpty(context)) return options.fn(context); }); Handlebars.registerHelper('log', function(context, options) { var level = options.data && options.data.level != null ? parseInt(options.data.level, 10) : 1; Handlebars.log(level, context); }); /* THIS FILE IS GENERATED BY A BUILD SCRIPT - DO NOT EDIT! */ var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack']; Handlebars.Exception = function(message) { var tmp = Error.prototype.constructor.apply(this, arguments); // 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]]; } }; Handlebars.Exception.prototype = new Error(); // Build out our basic SafeString type Handlebars.SafeString = function(string) { this.string = string; }; Handlebars.SafeString.prototype.toString = function() { return this.string.toString(); }; var escape = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#x27;", "`": "&#x60;" }; var badChars = /[&<>"'`]/g; var possible = /[&<>"'`]/; var escapeChar = function(chr) { return escape[chr] || "&amp;"; }; Handlebars.Utils = { extend: function(obj, value) { for(var key in value) { if(value.hasOwnProperty(key)) { obj[key] = value[key]; } } }, escapeExpression: function(string) { // don't escape SafeStrings, since they're already safe if (string instanceof Handlebars.SafeString) { return string.toString(); } else if (string == null || string === false) { return ""; } // 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.toString(); if(!possible.test(string)) { return string; } return string.replace(badChars, escapeChar); }, isEmpty: function(value) { if (!value && value !== 0) { return true; } else if(toString.call(value) === "[object Array]" && value.length === 0) { return true; } else { return false; } } }; /* THIS FILE IS GENERATED BY A BUILD SCRIPT - DO NOT EDIT! */ Handlebars.VM = { template: function(templateSpec) { // Just add water var container = { escapeExpression: Handlebars.Utils.escapeExpression, invokePartial: Handlebars.VM.invokePartial, programs: [], program: function(i, fn, data) { var programWrapper = this.programs[i]; if(data) { programWrapper = Handlebars.VM.program(i, fn, data); } else if (!programWrapper) { programWrapper = this.programs[i] = Handlebars.VM.program(i, fn); } return programWrapper; }, programWithDepth: Handlebars.VM.programWithDepth, noop: Handlebars.VM.noop, compilerInfo: null }; return function(context, options) { options = options || {}; var result = templateSpec.call(container, Handlebars, context, options.helpers, options.partials, options.data); var compilerInfo = container.compilerInfo || [], compilerRevision = compilerInfo[0] || 1, currentRevision = Handlebars.COMPILER_REVISION; if (compilerRevision !== currentRevision) { if (compilerRevision < currentRevision) { var runtimeVersions = Handlebars.REVISION_CHANGES[currentRevision], compilerVersions = Handlebars.REVISION_CHANGES[compilerRevision]; throw "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 "Template was precompiled with a newer version of Handlebars than the current runtime. "+ "Please update your runtime to a newer version ("+compilerInfo[1]+")."; } } return result; }; }, programWithDepth: function(i, fn, data /*, $depth */) { var args = Array.prototype.slice.call(arguments, 3); var program = function(context, options) { options = options || {}; return fn.apply(this, [context, options.data || data].concat(args)); }; program.program = i; program.depth = args.length; return program; }, program: function(i, fn, data) { var program = function(context, options) { options = options || {}; return fn(context, options.data || data); }; program.program = i; program.depth = 0; return program; }, noop: function() { return ""; }, invokePartial: function(partial, name, context, helpers, partials, data) { var options = { helpers: helpers, partials: partials, data: data }; if(partial === undefined) { throw new Handlebars.Exception("The partial " + name + " could not be found"); } else if(partial instanceof Function) { return partial(context, options); } else if (!Handlebars.compile) { throw new Handlebars.Exception("The partial " + name + " could not be compiled when running in runtime-only mode"); } else { partials[name] = Handlebars.compile(partial, {data: data !== undefined}); return partials[name](context, options); } } }; Handlebars.template = Handlebars.VM.template; // This file contains YUI-specific wrapper code and overrides for the // handlebars-base module. Handlebars.VERSION += '-yui'; /** Registers a helper function that will be made available to all templates. Helper functions receive the current template context as the `this` object, and can also receive arguments passed by the template. @example Y.Handlebars.registerHelper('linkify', function () { return '<a href="' + Y.Escape.html(this.url) + '">' + Y.Escape.html(this.text) + '</a>'; }); var source = '<ul>{{#links}}<li>{{{linkify}}}</li>{{/links}}</ul>'; Y.Handlebars.render(source, { links: [ {url: '/foo', text: 'Foo'}, {url: '/bar', text: 'Bar'}, {url: '/baz', text: 'Baz'} ] }); @method registerHelper @param {String} name Name of this helper. @param {Function} fn Helper function. @param {Boolean} [inverse=false] If `true`, this helper will be considered an "inverse" helper, like "unless". This means it will only be called if the expression given in the template evaluates to a false or empty value. */ /** Registers a partial that will be made available to all templates. A partial is another template that can be used to render part of a larger template. For example, a website with a common header and footer across all its pages might use a template for each page, which would call shared partials to render the headers and footers. Partials may be specified as uncompiled template strings or as compiled template functions. @example Y.Handlebars.registerPartial('header', '<h1>{{title}}</h1>'); Y.Handlebars.registerPartial('footer', 'Copyright (c) 2011 by Me.'); var source = '{{> header}} <p>Mustaches are awesome!</p> {{> footer}}'; Y.Handlebars.render(source, {title: 'My Page About Mustaches'}); @method registerPartial @param {String} name Name of this partial. @param {Function|String} partial Template string or compiled template function. */ /** Converts a precompiled template into a renderable template function. @example <script src="precompiled-template.js"></script> <script> YUI().use('handlebars-base', function (Y) { // Convert the precompiled template function into a renderable template // function. var template = Y.Handlebars.template(precompiledTemplate); // Render it. template({pie: 'Pumpkin'}); }); </script> @method template @param {Function} template Precompiled Handlebars template function. @return {Function} Compiled template function. */ // Alias for Y.Handlebars.template(), used by Y.Template. Handlebars.revive = Handlebars.template; // Make Y.Template.Handlebars an alias for Y.Handlebars. Y.namespace('Template').Handlebars = Handlebars; }, '@VERSION@', {"requires": []});
/*! * Jade - nodes - Each * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca> * MIT Licensed */ /** * Module dependencies. */ var Node = require('./node'); /** * Initialize an `Each` node, representing iteration * * @param {String} obj * @param {String} val * @param {String} key * @param {Block} block * @api public */ var Each = module.exports = function Each(obj, val, key, block) { this.obj = obj; this.val = val; this.key = key; this.block = block; }; /** * Inherit from `Node`. */ Each.prototype.__proto__ = Node.prototype;
/** * @author Jason Dobry <jason.dobry@gmail.com> * @file js-data.js * @version 1.0.0-alpha.5-6 - Homepage <http://www.js-data.io/> * @copyright (c) 2014 Jason Dobry * @license MIT <https://github.com/js-data/js-data/blob/master/LICENSE> * * @overview Data store. */ !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.JSData=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 require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ // Copyright 2012 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Modifications // Copyright 2014 Jason Dobry // // Summary of modifications: // Fixed use of "delete" keyword for IE8 compatibility // Exposed diffObjectFromOldObject on the exported object // Added the "equals" argument to diffObjectFromOldObject to be used to check equality // Added a way to to define a default equality operator for diffObjectFromOldObject // Added a way in diffObjectFromOldObject to ignore changes to certain properties // Removed all code related to: // - ArrayObserver // - ArraySplice // - PathObserver // - CompoundObserver // - Path // - ObserverTransform (function(global) { 'use strict'; var equalityFn = function (a, b) { return a === b; }; var blacklist = []; // Detect and do basic sanity checking on Object/Array.observe. function detectObjectObserve() { if (typeof Object.observe !== 'function' || typeof Array.observe !== 'function') { return false; } var records = []; function callback(recs) { records = recs; } var test = {}; var arr = []; Object.observe(test, callback); Array.observe(arr, callback); test.id = 1; test.id = 2; delete test.id; arr.push(1, 2); arr.length = 0; Object.deliverChangeRecords(callback); if (records.length !== 5) return false; if (records[0].type != 'add' || records[1].type != 'update' || records[2].type != 'delete' || records[3].type != 'splice' || records[4].type != 'splice') { return false; } Object.unobserve(test, callback); Array.unobserve(arr, callback); return true; } var hasObserve = detectObjectObserve(); function detectEval() { // Don't test for eval if we're running in a Chrome App environment. // We check for APIs set that only exist in a Chrome App context. if (typeof chrome !== 'undefined' && chrome.app && chrome.app.runtime) { return false; } try { var f = new Function('', 'return true;'); return f(); } catch (ex) { return false; } } var hasEval = detectEval(); var createObject = ('__proto__' in {}) ? function(obj) { return obj; } : function(obj) { var proto = obj.__proto__; if (!proto) return obj; var newObject = Object.create(proto); Object.getOwnPropertyNames(obj).forEach(function(name) { Object.defineProperty(newObject, name, Object.getOwnPropertyDescriptor(obj, name)); }); return newObject; }; var MAX_DIRTY_CHECK_CYCLES = 1000; function dirtyCheck(observer) { var cycles = 0; while (cycles < MAX_DIRTY_CHECK_CYCLES && observer.check_()) { cycles++; } if (global.testingExposeCycleCount) global.dirtyCheckCycleCount = cycles; return cycles > 0; } function objectIsEmpty(object) { for (var prop in object) return false; return true; } function diffIsEmpty(diff) { return objectIsEmpty(diff.added) && objectIsEmpty(diff.removed) && objectIsEmpty(diff.changed); } function isBlacklisted(prop, bl) { if (!bl || !bl.length) { return false; } var matches; for (var i = 0; i < bl.length; i++) { if ((Object.prototype.toString.call(bl[i]) === '[object RegExp]' && bl[i].test(prop)) || bl[i] === prop) { return matches = prop; } } return !!matches; } function diffObjectFromOldObject(object, oldObject, equals, bl) { var added = {}; var removed = {}; var changed = {}; for (var prop in oldObject) { var newValue = object[prop]; if (isBlacklisted(prop, bl)) continue; if (newValue !== undefined && (equals ? equals(newValue, oldObject[prop]) : newValue === oldObject[prop])) continue; if (!(prop in object)) { removed[prop] = undefined; continue; } if (equals ? !equals(newValue, oldObject[prop]) : newValue !== oldObject[prop]) changed[prop] = newValue; } for (var prop in object) { if (prop in oldObject) continue; if (isBlacklisted(prop, bl)) continue; added[prop] = object[prop]; } if (Array.isArray(object) && object.length !== oldObject.length) changed.length = object.length; return { added: added, removed: removed, changed: changed }; } var eomTasks = []; function runEOMTasks() { if (!eomTasks.length) return false; for (var i = 0; i < eomTasks.length; i++) { eomTasks[i](); } eomTasks.length = 0; return true; } var runEOM = hasObserve ? (function(){ var eomObj = { pingPong: true }; var eomRunScheduled = false; Object.observe(eomObj, function() { runEOMTasks(); eomRunScheduled = false; }); return function(fn) { eomTasks.push(fn); if (!eomRunScheduled) { eomRunScheduled = true; eomObj.pingPong = !eomObj.pingPong; } }; })() : (function() { return function(fn) { eomTasks.push(fn); }; })(); var observedObjectCache = []; function newObservedObject() { var observer; var object; var discardRecords = false; var first = true; function callback(records) { if (observer && observer.state_ === OPENED && !discardRecords) observer.check_(records); } return { open: function(obs) { if (observer) throw Error('ObservedObject in use'); if (!first) Object.deliverChangeRecords(callback); observer = obs; first = false; }, observe: function(obj, arrayObserve) { object = obj; if (arrayObserve) Array.observe(object, callback); else Object.observe(object, callback); }, deliver: function(discard) { discardRecords = discard; Object.deliverChangeRecords(callback); discardRecords = false; }, close: function() { observer = undefined; Object.unobserve(object, callback); observedObjectCache.push(this); } }; } /* * The observedSet abstraction is a perf optimization which reduces the total * number of Object.observe observations of a set of objects. The idea is that * groups of Observers will have some object dependencies in common and this * observed set ensures that each object in the transitive closure of * dependencies is only observed once. The observedSet acts as a write barrier * such that whenever any change comes through, all Observers are checked for * changed values. * * Note that this optimization is explicitly moving work from setup-time to * change-time. * * TODO(rafaelw): Implement "garbage collection". In order to move work off * the critical path, when Observers are closed, their observed objects are * not Object.unobserve(d). As a result, it's possible that if the observedSet * is kept open, but some Observers have been closed, it could cause "leaks" * (prevent otherwise collectable objects from being collected). At some * point, we should implement incremental "gc" which keeps a list of * observedSets which may need clean-up and does small amounts of cleanup on a * timeout until all is clean. */ function getObservedObject(observer, object, arrayObserve) { var dir = observedObjectCache.pop() || newObservedObject(); dir.open(observer); dir.observe(object, arrayObserve); return dir; } var UNOPENED = 0; var OPENED = 1; var CLOSED = 2; var nextObserverId = 1; function Observer() { this.state_ = UNOPENED; this.callback_ = undefined; this.target_ = undefined; // TODO(rafaelw): Should be WeakRef this.directObserver_ = undefined; this.value_ = undefined; this.id_ = nextObserverId++; } Observer.prototype = { open: function(callback, target) { if (this.state_ != UNOPENED) throw Error('Observer has already been opened.'); addToAll(this); this.callback_ = callback; this.target_ = target; this.connect_(); this.state_ = OPENED; return this.value_; }, close: function() { if (this.state_ != OPENED) return; removeFromAll(this); this.disconnect_(); this.value_ = undefined; this.callback_ = undefined; this.target_ = undefined; this.state_ = CLOSED; }, deliver: function() { if (this.state_ != OPENED) return; dirtyCheck(this); }, report_: function(changes) { try { this.callback_.apply(this.target_, changes); } catch (ex) { Observer._errorThrownDuringCallback = true; console.error('Exception caught during observer callback: ' + (ex.stack || ex)); } }, discardChanges: function() { this.check_(undefined, true); return this.value_; } } var collectObservers = !hasObserve; var allObservers; Observer._allObserversCount = 0; if (collectObservers) { allObservers = []; } function addToAll(observer) { Observer._allObserversCount++; if (!collectObservers) return; allObservers.push(observer); } function removeFromAll(observer) { Observer._allObserversCount--; } var runningMicrotaskCheckpoint = false; var hasDebugForceFullDelivery = hasObserve && hasEval && (function() { try { eval('%RunMicrotasks()'); return true; } catch (ex) { return false; } })(); global.Platform = global.Platform || {}; global.Platform.performMicrotaskCheckpoint = function() { if (runningMicrotaskCheckpoint) return; if (hasDebugForceFullDelivery) { eval('%RunMicrotasks()'); return; } if (!collectObservers) return; runningMicrotaskCheckpoint = true; var cycles = 0; var anyChanged, toCheck; do { cycles++; toCheck = allObservers; allObservers = []; anyChanged = false; for (var i = 0; i < toCheck.length; i++) { var observer = toCheck[i]; if (observer.state_ != OPENED) continue; if (observer.check_()) anyChanged = true; allObservers.push(observer); } if (runEOMTasks()) anyChanged = true; } while (cycles < MAX_DIRTY_CHECK_CYCLES && anyChanged); if (global.testingExposeCycleCount) global.dirtyCheckCycleCount = cycles; runningMicrotaskCheckpoint = false; }; if (collectObservers) { global.Platform.clearObservers = function() { allObservers = []; }; } function ObjectObserver(object) { Observer.call(this); this.value_ = object; this.oldObject_ = undefined; } ObjectObserver.prototype = createObject({ __proto__: Observer.prototype, arrayObserve: false, connect_: function(callback, target) { if (hasObserve) { this.directObserver_ = getObservedObject(this, this.value_, this.arrayObserve); } else { this.oldObject_ = this.copyObject(this.value_); } }, copyObject: function(object) { var copy = Array.isArray(object) ? [] : {}; for (var prop in object) { copy[prop] = object[prop]; }; if (Array.isArray(object)) copy.length = object.length; return copy; }, check_: function(changeRecords, skipChanges) { var diff; var oldValues; if (hasObserve) { if (!changeRecords) return false; oldValues = {}; diff = diffObjectFromChangeRecords(this.value_, changeRecords, oldValues); } else { oldValues = this.oldObject_; diff = diffObjectFromOldObject(this.value_, this.oldObject_, equalityFn, blacklist); } if (diffIsEmpty(diff)) return false; if (!hasObserve) this.oldObject_ = this.copyObject(this.value_); this.report_([ diff.added || {}, diff.removed || {}, diff.changed || {}, function(property) { return oldValues[property]; } ]); return true; }, disconnect_: function() { if (hasObserve) { this.directObserver_.close(); this.directObserver_ = undefined; } else { this.oldObject_ = undefined; } }, deliver: function() { if (this.state_ != OPENED) return; if (hasObserve) this.directObserver_.deliver(false); else dirtyCheck(this); }, discardChanges: function() { if (this.directObserver_) this.directObserver_.deliver(true); else this.oldObject_ = this.copyObject(this.value_); return this.value_; } }); var observerSentinel = {}; var expectedRecordTypes = { add: true, update: true, 'delete': true }; function diffObjectFromChangeRecords(object, changeRecords, oldValues) { var added = {}; var removed = {}; for (var i = 0; i < changeRecords.length; i++) { var record = changeRecords[i]; if (!expectedRecordTypes[record.type]) { console.error('Unknown changeRecord type: ' + record.type); console.error(record); continue; } if (!(record.name in oldValues)) oldValues[record.name] = record.oldValue; if (record.type == 'update') continue; if (record.type == 'add') { if (record.name in removed) delete removed[record.name]; else added[record.name] = true; continue; } // type = 'delete' if (record.name in added) { delete added[record.name]; delete oldValues[record.name]; } else { removed[record.name] = true; } } for (var prop in added) added[prop] = object[prop]; for (var prop in removed) removed[prop] = undefined; var changed = {}; for (var prop in oldValues) { if (prop in added || prop in removed) continue; var newValue = object[prop]; if (oldValues[prop] !== newValue) changed[prop] = newValue; } return { added: added, removed: removed, changed: changed }; } global.Observer = Observer; global.diffObjectFromOldObject = diffObjectFromOldObject; global.setEqualityFn = function (fn) { equalityFn = fn; }; global.setBlacklist = function (bl) { blacklist = bl; }; global.Observer.runEOM_ = runEOM; global.Observer.observerSentinel_ = observerSentinel; // for testing. global.Observer.hasObjectObserve = hasObserve; global.ObjectObserver = ObjectObserver; })(exports); },{}],2:[function(require,module,exports){ (function (process,global){ /*! * @overview es6-promise - a tiny implementation of Promises/A+. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) * @license Licensed under MIT license * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE * @version 2.0.0 */ (function() { "use strict"; function $$utils$$objectOrFunction(x) { return typeof x === 'function' || (typeof x === 'object' && x !== null); } function $$utils$$isFunction(x) { return typeof x === 'function'; } function $$utils$$isMaybeThenable(x) { return typeof x === 'object' && x !== null; } var $$utils$$_isArray; if (!Array.isArray) { $$utils$$_isArray = function (x) { return Object.prototype.toString.call(x) === '[object Array]'; }; } else { $$utils$$_isArray = Array.isArray; } var $$utils$$isArray = $$utils$$_isArray; var $$utils$$now = Date.now || function() { return new Date().getTime(); }; function $$utils$$F() { } var $$utils$$o_create = (Object.create || function (o) { if (arguments.length > 1) { throw new Error('Second argument not supported'); } if (typeof o !== 'object') { throw new TypeError('Argument must be an object'); } $$utils$$F.prototype = o; return new $$utils$$F(); }); var $$asap$$len = 0; var $$asap$$default = function asap(callback, arg) { $$asap$$queue[$$asap$$len] = callback; $$asap$$queue[$$asap$$len + 1] = arg; $$asap$$len += 2; if ($$asap$$len === 2) { // If len is 1, that means that we need to schedule an async flush. // If additional callbacks are queued before the queue is flushed, they // will be processed by this flush that we are scheduling. $$asap$$scheduleFlush(); } }; var $$asap$$browserGlobal = (typeof window !== 'undefined') ? window : {}; var $$asap$$BrowserMutationObserver = $$asap$$browserGlobal.MutationObserver || $$asap$$browserGlobal.WebKitMutationObserver; // test for web worker but not in IE10 var $$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; // node function $$asap$$useNextTick() { return function() { process.nextTick($$asap$$flush); }; } function $$asap$$useMutationObserver() { var iterations = 0; var observer = new $$asap$$BrowserMutationObserver($$asap$$flush); var node = document.createTextNode(''); observer.observe(node, { characterData: true }); return function() { node.data = (iterations = ++iterations % 2); }; } // web worker function $$asap$$useMessageChannel() { var channel = new MessageChannel(); channel.port1.onmessage = $$asap$$flush; return function () { channel.port2.postMessage(0); }; } function $$asap$$useSetTimeout() { return function() { setTimeout($$asap$$flush, 1); }; } var $$asap$$queue = new Array(1000); function $$asap$$flush() { for (var i = 0; i < $$asap$$len; i+=2) { var callback = $$asap$$queue[i]; var arg = $$asap$$queue[i+1]; callback(arg); $$asap$$queue[i] = undefined; $$asap$$queue[i+1] = undefined; } $$asap$$len = 0; } var $$asap$$scheduleFlush; // Decide what async method to use to triggering processing of queued callbacks: if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { $$asap$$scheduleFlush = $$asap$$useNextTick(); } else if ($$asap$$BrowserMutationObserver) { $$asap$$scheduleFlush = $$asap$$useMutationObserver(); } else if ($$asap$$isWorker) { $$asap$$scheduleFlush = $$asap$$useMessageChannel(); } else { $$asap$$scheduleFlush = $$asap$$useSetTimeout(); } function $$$internal$$noop() {} var $$$internal$$PENDING = void 0; var $$$internal$$FULFILLED = 1; var $$$internal$$REJECTED = 2; var $$$internal$$GET_THEN_ERROR = new $$$internal$$ErrorObject(); function $$$internal$$selfFullfillment() { return new TypeError("You cannot resolve a promise with itself"); } function $$$internal$$cannotReturnOwn() { return new TypeError('A promises callback cannot return that same promise.') } function $$$internal$$getThen(promise) { try { return promise.then; } catch(error) { $$$internal$$GET_THEN_ERROR.error = error; return $$$internal$$GET_THEN_ERROR; } } function $$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { try { then.call(value, fulfillmentHandler, rejectionHandler); } catch(e) { return e; } } function $$$internal$$handleForeignThenable(promise, thenable, then) { $$asap$$default(function(promise) { var sealed = false; var error = $$$internal$$tryThen(then, thenable, function(value) { if (sealed) { return; } sealed = true; if (thenable !== value) { $$$internal$$resolve(promise, value); } else { $$$internal$$fulfill(promise, value); } }, function(reason) { if (sealed) { return; } sealed = true; $$$internal$$reject(promise, reason); }, 'Settle: ' + (promise._label || ' unknown promise')); if (!sealed && error) { sealed = true; $$$internal$$reject(promise, error); } }, promise); } function $$$internal$$handleOwnThenable(promise, thenable) { if (thenable._state === $$$internal$$FULFILLED) { $$$internal$$fulfill(promise, thenable._result); } else if (promise._state === $$$internal$$REJECTED) { $$$internal$$reject(promise, thenable._result); } else { $$$internal$$subscribe(thenable, undefined, function(value) { $$$internal$$resolve(promise, value); }, function(reason) { $$$internal$$reject(promise, reason); }); } } function $$$internal$$handleMaybeThenable(promise, maybeThenable) { if (maybeThenable.constructor === promise.constructor) { $$$internal$$handleOwnThenable(promise, maybeThenable); } else { var then = $$$internal$$getThen(maybeThenable); if (then === $$$internal$$GET_THEN_ERROR) { $$$internal$$reject(promise, $$$internal$$GET_THEN_ERROR.error); } else if (then === undefined) { $$$internal$$fulfill(promise, maybeThenable); } else if ($$utils$$isFunction(then)) { $$$internal$$handleForeignThenable(promise, maybeThenable, then); } else { $$$internal$$fulfill(promise, maybeThenable); } } } function $$$internal$$resolve(promise, value) { if (promise === value) { $$$internal$$reject(promise, $$$internal$$selfFullfillment()); } else if ($$utils$$objectOrFunction(value)) { $$$internal$$handleMaybeThenable(promise, value); } else { $$$internal$$fulfill(promise, value); } } function $$$internal$$publishRejection(promise) { if (promise._onerror) { promise._onerror(promise._result); } $$$internal$$publish(promise); } function $$$internal$$fulfill(promise, value) { if (promise._state !== $$$internal$$PENDING) { return; } promise._result = value; promise._state = $$$internal$$FULFILLED; if (promise._subscribers.length === 0) { } else { $$asap$$default($$$internal$$publish, promise); } } function $$$internal$$reject(promise, reason) { if (promise._state !== $$$internal$$PENDING) { return; } promise._state = $$$internal$$REJECTED; promise._result = reason; $$asap$$default($$$internal$$publishRejection, promise); } function $$$internal$$subscribe(parent, child, onFulfillment, onRejection) { var subscribers = parent._subscribers; var length = subscribers.length; parent._onerror = null; subscribers[length] = child; subscribers[length + $$$internal$$FULFILLED] = onFulfillment; subscribers[length + $$$internal$$REJECTED] = onRejection; if (length === 0 && parent._state) { $$asap$$default($$$internal$$publish, parent); } } function $$$internal$$publish(promise) { var subscribers = promise._subscribers; var settled = promise._state; if (subscribers.length === 0) { return; } var child, callback, detail = promise._result; for (var i = 0; i < subscribers.length; i += 3) { child = subscribers[i]; callback = subscribers[i + settled]; if (child) { $$$internal$$invokeCallback(settled, child, callback, detail); } else { callback(detail); } } promise._subscribers.length = 0; } function $$$internal$$ErrorObject() { this.error = null; } var $$$internal$$TRY_CATCH_ERROR = new $$$internal$$ErrorObject(); function $$$internal$$tryCatch(callback, detail) { try { return callback(detail); } catch(e) { $$$internal$$TRY_CATCH_ERROR.error = e; return $$$internal$$TRY_CATCH_ERROR; } } function $$$internal$$invokeCallback(settled, promise, callback, detail) { var hasCallback = $$utils$$isFunction(callback), value, error, succeeded, failed; if (hasCallback) { value = $$$internal$$tryCatch(callback, detail); if (value === $$$internal$$TRY_CATCH_ERROR) { failed = true; error = value.error; value = null; } else { succeeded = true; } if (promise === value) { $$$internal$$reject(promise, $$$internal$$cannotReturnOwn()); return; } } else { value = detail; succeeded = true; } if (promise._state !== $$$internal$$PENDING) { // noop } else if (hasCallback && succeeded) { $$$internal$$resolve(promise, value); } else if (failed) { $$$internal$$reject(promise, error); } else if (settled === $$$internal$$FULFILLED) { $$$internal$$fulfill(promise, value); } else if (settled === $$$internal$$REJECTED) { $$$internal$$reject(promise, value); } } function $$$internal$$initializePromise(promise, resolver) { try { resolver(function resolvePromise(value){ $$$internal$$resolve(promise, value); }, function rejectPromise(reason) { $$$internal$$reject(promise, reason); }); } catch(e) { $$$internal$$reject(promise, e); } } function $$$enumerator$$makeSettledResult(state, position, value) { if (state === $$$internal$$FULFILLED) { return { state: 'fulfilled', value: value }; } else { return { state: 'rejected', reason: value }; } } function $$$enumerator$$Enumerator(Constructor, input, abortOnReject, label) { this._instanceConstructor = Constructor; this.promise = new Constructor($$$internal$$noop, label); this._abortOnReject = abortOnReject; if (this._validateInput(input)) { this._input = input; this.length = input.length; this._remaining = input.length; this._init(); if (this.length === 0) { $$$internal$$fulfill(this.promise, this._result); } else { this.length = this.length || 0; this._enumerate(); if (this._remaining === 0) { $$$internal$$fulfill(this.promise, this._result); } } } else { $$$internal$$reject(this.promise, this._validationError()); } } $$$enumerator$$Enumerator.prototype._validateInput = function(input) { return $$utils$$isArray(input); }; $$$enumerator$$Enumerator.prototype._validationError = function() { return new Error('Array Methods must be provided an Array'); }; $$$enumerator$$Enumerator.prototype._init = function() { this._result = new Array(this.length); }; var $$$enumerator$$default = $$$enumerator$$Enumerator; $$$enumerator$$Enumerator.prototype._enumerate = function() { var length = this.length; var promise = this.promise; var input = this._input; for (var i = 0; promise._state === $$$internal$$PENDING && i < length; i++) { this._eachEntry(input[i], i); } }; $$$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) { var c = this._instanceConstructor; if ($$utils$$isMaybeThenable(entry)) { if (entry.constructor === c && entry._state !== $$$internal$$PENDING) { entry._onerror = null; this._settledAt(entry._state, i, entry._result); } else { this._willSettleAt(c.resolve(entry), i); } } else { this._remaining--; this._result[i] = this._makeResult($$$internal$$FULFILLED, i, entry); } }; $$$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) { var promise = this.promise; if (promise._state === $$$internal$$PENDING) { this._remaining--; if (this._abortOnReject && state === $$$internal$$REJECTED) { $$$internal$$reject(promise, value); } else { this._result[i] = this._makeResult(state, i, value); } } if (this._remaining === 0) { $$$internal$$fulfill(promise, this._result); } }; $$$enumerator$$Enumerator.prototype._makeResult = function(state, i, value) { return value; }; $$$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) { var enumerator = this; $$$internal$$subscribe(promise, undefined, function(value) { enumerator._settledAt($$$internal$$FULFILLED, i, value); }, function(reason) { enumerator._settledAt($$$internal$$REJECTED, i, reason); }); }; var $$promise$all$$default = function all(entries, label) { return new $$$enumerator$$default(this, entries, true /* abort on reject */, label).promise; }; var $$promise$race$$default = function race(entries, label) { /*jshint validthis:true */ var Constructor = this; var promise = new Constructor($$$internal$$noop, label); if (!$$utils$$isArray(entries)) { $$$internal$$reject(promise, new TypeError('You must pass an array to race.')); return promise; } var length = entries.length; function onFulfillment(value) { $$$internal$$resolve(promise, value); } function onRejection(reason) { $$$internal$$reject(promise, reason); } for (var i = 0; promise._state === $$$internal$$PENDING && i < length; i++) { $$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); } return promise; }; var $$promise$resolve$$default = function resolve(object, label) { /*jshint validthis:true */ var Constructor = this; if (object && typeof object === 'object' && object.constructor === Constructor) { return object; } var promise = new Constructor($$$internal$$noop, label); $$$internal$$resolve(promise, object); return promise; }; var $$promise$reject$$default = function reject(reason, label) { /*jshint validthis:true */ var Constructor = this; var promise = new Constructor($$$internal$$noop, label); $$$internal$$reject(promise, reason); return promise; }; var $$es6$promise$promise$$counter = 0; function $$es6$promise$promise$$needsResolver() { throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); } function $$es6$promise$promise$$needsNew() { throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); } var $$es6$promise$promise$$default = $$es6$promise$promise$$Promise; /** Promise objects represent the eventual result of an asynchronous operation. The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise’s eventual value or the reason why the promise cannot be fulfilled. Terminology ----------- - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - `thenable` is an object or function that defines a `then` method. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - `exception` is a value that is thrown using the throw statement. - `reason` is a value that indicates why a promise was rejected. - `settled` the final resting state of a promise, fulfilled or rejected. A promise can be in one of three states: pending, fulfilled, or rejected. Promises that are fulfilled have a fulfillment value and are in the fulfilled state. Promises that are rejected have a rejection reason and are in the rejected state. A fulfillment value is never a thenable. Promises can also be said to *resolve* a value. If this value is also a promise, then the original promise's settled state will match the value's settled state. So a promise that *resolves* a promise that rejects will itself reject, and a promise that *resolves* a promise that fulfills will itself fulfill. Basic Usage: ------------ ```js var promise = new Promise(function(resolve, reject) { // on success resolve(value); // on failure reject(reason); }); promise.then(function(value) { // on fulfillment }, function(reason) { // on rejection }); ``` Advanced Usage: --------------- Promises shine when abstracting away asynchronous interactions such as `XMLHttpRequest`s. ```js function getJSON(url) { return new Promise(function(resolve, reject){ var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onreadystatechange = handler; xhr.responseType = 'json'; xhr.setRequestHeader('Accept', 'application/json'); xhr.send(); function handler() { if (this.readyState === this.DONE) { if (this.status === 200) { resolve(this.response); } else { reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); } } }; }); } getJSON('/posts.json').then(function(json) { // on fulfillment }, function(reason) { // on rejection }); ``` Unlike callbacks, promises are great composable primitives. ```js Promise.all([ getJSON('/posts'), getJSON('/comments') ]).then(function(values){ values[0] // => postsJSON values[1] // => commentsJSON return values; }); ``` @class Promise @param {function} resolver @param {String} label optional string for labeling the promise. Useful for tooling. @constructor */ function $$es6$promise$promise$$Promise(resolver, label) { this._id = $$es6$promise$promise$$counter++; this._label = label; this._state = undefined; this._result = undefined; this._subscribers = []; if ($$$internal$$noop !== resolver) { if (!$$utils$$isFunction(resolver)) { $$es6$promise$promise$$needsResolver(); } if (!(this instanceof $$es6$promise$promise$$Promise)) { $$es6$promise$promise$$needsNew(); } $$$internal$$initializePromise(this, resolver); } } $$es6$promise$promise$$Promise.all = $$promise$all$$default; $$es6$promise$promise$$Promise.race = $$promise$race$$default; $$es6$promise$promise$$Promise.resolve = $$promise$resolve$$default; $$es6$promise$promise$$Promise.reject = $$promise$reject$$default; $$es6$promise$promise$$Promise.prototype = { constructor: $$es6$promise$promise$$Promise, /** The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. ```js findUser().then(function(user){ // user is available }, function(reason){ // user is unavailable, and you are given the reason why }); ``` Chaining -------- The return value of `then` is itself a promise. This second, 'downstream' promise is resolved with the return value of the first promise's fulfillment or rejection handler, or rejected if the handler throws an exception. ```js findUser().then(function (user) { return user.name; }, function (reason) { return 'default name'; }).then(function (userName) { // If `findUser` fulfilled, `userName` will be the user's name, otherwise it // will be `'default name'` }); findUser().then(function (user) { throw new Error('Found user, but still unhappy'); }, function (reason) { throw new Error('`findUser` rejected and we're unhappy'); }).then(function (value) { // never reached }, function (reason) { // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. }); ``` If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. ```js findUser().then(function (user) { throw new PedagogicalException('Upstream error'); }).then(function (value) { // never reached }).then(function (value) { // never reached }, function (reason) { // The `PedgagocialException` is propagated all the way down to here }); ``` Assimilation ------------ Sometimes the value you want to propagate to a downstream promise can only be retrieved asynchronously. This can be achieved by returning a promise in the fulfillment or rejection handler. The downstream promise will then be pending until the returned promise is settled. This is called *assimilation*. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // The user's comments are now available }); ``` If the assimliated promise rejects, then the downstream promise will also reject. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // If `findCommentsByAuthor` fulfills, we'll have the value here }, function (reason) { // If `findCommentsByAuthor` rejects, we'll have the reason here }); ``` Simple Example -------------- Synchronous Example ```javascript var result; try { result = findResult(); // success } catch(reason) { // failure } ``` Errback Example ```js findResult(function(result, err){ if (err) { // failure } else { // success } }); ``` Promise Example; ```javascript findResult().then(function(result){ // success }, function(reason){ // failure }); ``` Advanced Example -------------- Synchronous Example ```javascript var author, books; try { author = findAuthor(); books = findBooksByAuthor(author); // success } catch(reason) { // failure } ``` Errback Example ```js function foundBooks(books) { } function failure(reason) { } findAuthor(function(author, err){ if (err) { failure(err); // failure } else { try { findBoooksByAuthor(author, function(books, err) { if (err) { failure(err); } else { try { foundBooks(books); } catch(reason) { failure(reason); } } }); } catch(error) { failure(err); } // success } }); ``` Promise Example; ```javascript findAuthor(). then(findBooksByAuthor). then(function(books){ // found books }).catch(function(reason){ // something went wrong }); ``` @method then @param {Function} onFulfilled @param {Function} onRejected @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} */ then: function(onFulfillment, onRejection, label) { var parent = this; var state = parent._state; if (state === $$$internal$$FULFILLED && !onFulfillment || state === $$$internal$$REJECTED && !onRejection) { return this; } parent._onerror = null; var child = new this.constructor($$$internal$$noop, label); var result = parent._result; if (state) { var callback = arguments[state - 1]; $$asap$$default(function(){ $$$internal$$invokeCallback(state, child, callback, result); }); } else { $$$internal$$subscribe(parent, child, onFulfillment, onRejection); } return child; }, /** `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same as the catch block of a try/catch statement. ```js function findAuthor(){ throw new Error('couldn't find that author'); } // synchronous try { findAuthor(); } catch(reason) { // something went wrong } // async with promises findAuthor().catch(function(reason){ // something went wrong }); ``` @method catch @param {Function} onRejection @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} */ 'catch': function(onRejection, label) { return this.then(null, onRejection, label); } }; var $$es6$promise$polyfill$$default = function polyfill() { var local; if (typeof global !== 'undefined') { local = global; } else if (typeof window !== 'undefined' && window.document) { local = window; } else { local = self; } var es6PromiseSupport = "Promise" in local && // Some of these methods are missing from // Firefox/Chrome experimental implementations "resolve" in local.Promise && "reject" in local.Promise && "all" in local.Promise && "race" in local.Promise && // Older version of the spec had a resolver object // as the arg rather than a function (function() { var resolve; new local.Promise(function(r) { resolve = r; }); return $$utils$$isFunction(resolve); }()); if (!es6PromiseSupport) { local.Promise = $$es6$promise$promise$$default; } }; var es6$promise$umd$$ES6Promise = { Promise: $$es6$promise$promise$$default, polyfill: $$es6$promise$polyfill$$default }; /* global define:true module:true window: true */ if (typeof define === 'function' && define['amd']) { define(function() { return es6$promise$umd$$ES6Promise; }); } else if (typeof module !== 'undefined' && module['exports']) { module['exports'] = es6$promise$umd$$ES6Promise; } else if (typeof this !== 'undefined') { this['ES6Promise'] = es6$promise$umd$$ES6Promise; } }).call(this); }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":3}],3:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; process.nextTick = (function () { var canSetImmediate = typeof window !== 'undefined' && window.setImmediate; var canMutationObserver = typeof window !== 'undefined' && window.MutationObserver; var canPost = typeof window !== 'undefined' && window.postMessage && window.addEventListener ; if (canSetImmediate) { return function (f) { return window.setImmediate(f) }; } var queue = []; if (canMutationObserver) { var hiddenDiv = document.createElement("div"); var observer = new MutationObserver(function () { var queueList = queue.slice(); queue.length = 0; queueList.forEach(function (fn) { fn(); }); }); observer.observe(hiddenDiv, { attributes: true }); return function nextTick(fn) { if (!queue.length) { hiddenDiv.setAttribute('yes', 'no'); } queue.push(fn); }; } if (canPost) { window.addEventListener('message', function (ev) { var source = ev.source; if ((source === window || source === null) && ev.data === 'process-tick') { ev.stopPropagation(); if (queue.length > 0) { var fn = queue.shift(); fn(); } } }, true); return function nextTick(fn) { queue.push(fn); window.postMessage('process-tick', '*'); }; } return function nextTick(fn) { setTimeout(fn, 0); }; })(); process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; },{}],4:[function(require,module,exports){ var indexOf = require('./indexOf'); /** * If array contains values. */ function contains(arr, val) { return indexOf(arr, val) !== -1; } module.exports = contains; },{"./indexOf":6}],5:[function(require,module,exports){ /** * Array forEach */ function forEach(arr, callback, thisObj) { if (arr == null) { return; } var i = -1, len = arr.length; while (++i < len) { // we iterate over sparse items since there is no way to make it // work properly on IE 7-8. see #64 if ( callback.call(thisObj, arr[i], i, arr) === false ) { break; } } } module.exports = forEach; },{}],6:[function(require,module,exports){ /** * Array.indexOf */ function indexOf(arr, item, fromIndex) { fromIndex = fromIndex || 0; if (arr == null) { return -1; } var len = arr.length, i = fromIndex < 0 ? len + fromIndex : fromIndex; while (i < len) { // we iterate over sparse items since there is no way to make it // work properly on IE 7-8. see #64 if (arr[i] === item) { return i; } i++; } return -1; } module.exports = indexOf; },{}],7:[function(require,module,exports){ var indexOf = require('./indexOf'); /** * Remove a single item from the array. * (it won't remove duplicates, just a single item) */ function remove(arr, item){ var idx = indexOf(arr, item); if (idx !== -1) arr.splice(idx, 1); } module.exports = remove; },{"./indexOf":6}],8:[function(require,module,exports){ /** * Create slice of source array or array-like object */ function slice(arr, start, end){ var len = arr.length; if (start == null) { start = 0; } else if (start < 0) { start = Math.max(len + start, 0); } else { start = Math.min(start, len); } if (end == null) { end = len; } else if (end < 0) { end = Math.max(len + end, 0); } else { end = Math.min(end, len); } var result = []; while (start < end) { result.push(arr[start++]); } return result; } module.exports = slice; },{}],9:[function(require,module,exports){ /** * Merge sort (http://en.wikipedia.org/wiki/Merge_sort) */ function mergeSort(arr, compareFn) { if (arr == null) { return []; } else if (arr.length < 2) { return arr; } if (compareFn == null) { compareFn = defaultCompare; } var mid, left, right; mid = ~~(arr.length / 2); left = mergeSort( arr.slice(0, mid), compareFn ); right = mergeSort( arr.slice(mid, arr.length), compareFn ); return merge(left, right, compareFn); } function defaultCompare(a, b) { return a < b ? -1 : (a > b? 1 : 0); } function merge(left, right, compareFn) { var result = []; while (left.length && right.length) { if (compareFn(left[0], right[0]) <= 0) { // if 0 it should preserve same order (stable) result.push(left.shift()); } else { result.push(right.shift()); } } if (left.length) { result.push.apply(result, left); } if (right.length) { result.push.apply(result, right); } return result; } module.exports = mergeSort; },{}],10:[function(require,module,exports){ /** * Checks if the value is created by the `Object` constructor. */ function isPlainObject(value) { return (!!value && typeof value === 'object' && value.constructor === Object); } module.exports = isPlainObject; },{}],11:[function(require,module,exports){ /** * Typecast a value to a String, using an empty string value for null or * undefined. */ function toString(val){ return val == null ? '' : val.toString(); } module.exports = toString; },{}],12:[function(require,module,exports){ var forOwn = require('./forOwn'); var isPlainObject = require('../lang/isPlainObject'); /** * Mixes objects into the target object, recursively mixing existing child * objects. */ function deepMixIn(target, objects) { var i = 0, n = arguments.length, obj; while(++i < n){ obj = arguments[i]; if (obj) { forOwn(obj, copyProp, target); } } return target; } function copyProp(val, key) { var existing = this[key]; if (isPlainObject(val) && isPlainObject(existing)) { deepMixIn(existing, val); } else { this[key] = val; } } module.exports = deepMixIn; },{"../lang/isPlainObject":10,"./forOwn":14}],13:[function(require,module,exports){ var hasOwn = require('./hasOwn'); var _hasDontEnumBug, _dontEnums; function checkDontEnum(){ _dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ]; _hasDontEnumBug = true; for (var key in {'toString': null}) { _hasDontEnumBug = false; } } /** * Similar to Array/forEach but works over object properties and fixes Don't * Enum bug on IE. * based on: http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation */ function forIn(obj, fn, thisObj){ var key, i = 0; // no need to check if argument is a real object that way we can use // it for arrays, functions, date, etc. //post-pone check till needed if (_hasDontEnumBug == null) checkDontEnum(); for (key in obj) { if (exec(fn, obj, key, thisObj) === false) { break; } } if (_hasDontEnumBug) { var ctor = obj.constructor, isProto = !!ctor && obj === ctor.prototype; while (key = _dontEnums[i++]) { // For constructor, if it is a prototype object the constructor // is always non-enumerable unless defined otherwise (and // enumerated above). For non-prototype objects, it will have // to be defined on this object, since it cannot be defined on // any prototype objects. // // For other [[DontEnum]] properties, check if the value is // different than Object prototype value. if ( (key !== 'constructor' || (!isProto && hasOwn(obj, key))) && obj[key] !== Object.prototype[key] ) { if (exec(fn, obj, key, thisObj) === false) { break; } } } } } function exec(fn, obj, key, thisObj){ return fn.call(thisObj, obj[key], key, obj); } module.exports = forIn; },{"./hasOwn":15}],14:[function(require,module,exports){ var hasOwn = require('./hasOwn'); var forIn = require('./forIn'); /** * Similar to Array/forEach but works over object properties and fixes Don't * Enum bug on IE. * based on: http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation */ function forOwn(obj, fn, thisObj){ forIn(obj, function(val, key){ if (hasOwn(obj, key)) { return fn.call(thisObj, obj[key], key, obj); } }); } module.exports = forOwn; },{"./forIn":13,"./hasOwn":15}],15:[function(require,module,exports){ /** * Safer Object.hasOwnProperty */ function hasOwn(obj, prop){ return Object.prototype.hasOwnProperty.call(obj, prop); } module.exports = hasOwn; },{}],16:[function(require,module,exports){ var forEach = require('../array/forEach'); /** * Create nested object if non-existent */ function namespace(obj, path){ if (!path) return obj; forEach(path.split('.'), function(key){ if (!obj[key]) { obj[key] = {}; } obj = obj[key]; }); return obj; } module.exports = namespace; },{"../array/forEach":5}],17:[function(require,module,exports){ var slice = require('../array/slice'); /** * Return a copy of the object, filtered to only have values for the whitelisted keys. */ function pick(obj, var_keys){ var keys = typeof arguments[1] !== 'string'? arguments[1] : slice(arguments, 1), out = {}, i = 0, key; while (key = keys[i++]) { out[key] = obj[key]; } return out; } module.exports = pick; },{"../array/slice":8}],18:[function(require,module,exports){ var namespace = require('./namespace'); /** * set "nested" object property */ function set(obj, prop, val){ var parts = (/^(.+)\.(.+)$/).exec(prop); if (parts){ namespace(obj, parts[1])[parts[2]] = val; } else { obj[prop] = val; } } module.exports = set; },{"./namespace":16}],19:[function(require,module,exports){ var toString = require('../lang/toString'); var replaceAccents = require('./replaceAccents'); var removeNonWord = require('./removeNonWord'); var upperCase = require('./upperCase'); var lowerCase = require('./lowerCase'); /** * Convert string to camelCase text. */ function camelCase(str){ str = toString(str); str = replaceAccents(str); str = removeNonWord(str) .replace(/[\-_]/g, ' ') //convert all hyphens and underscores to spaces .replace(/\s[a-z]/g, upperCase) //convert first char of each word to UPPERCASE .replace(/\s+/g, '') //remove spaces .replace(/^[A-Z]/g, lowerCase); //convert first char to lowercase return str; } module.exports = camelCase; },{"../lang/toString":11,"./lowerCase":20,"./removeNonWord":22,"./replaceAccents":23,"./upperCase":24}],20:[function(require,module,exports){ var toString = require('../lang/toString'); /** * "Safer" String.toLowerCase() */ function lowerCase(str){ str = toString(str); return str.toLowerCase(); } module.exports = lowerCase; },{"../lang/toString":11}],21:[function(require,module,exports){ var toString = require('../lang/toString'); var camelCase = require('./camelCase'); var upperCase = require('./upperCase'); /** * camelCase + UPPERCASE first char */ function pascalCase(str){ str = toString(str); return camelCase(str).replace(/^[a-z]/, upperCase); } module.exports = pascalCase; },{"../lang/toString":11,"./camelCase":19,"./upperCase":24}],22:[function(require,module,exports){ var toString = require('../lang/toString'); // This pattern is generated by the _build/pattern-removeNonWord.js script var PATTERN = /[^\x20\x2D0-9A-Z\x5Fa-z\xC0-\xD6\xD8-\xF6\xF8-\xFF]/g; /** * Remove non-word chars. */ function removeNonWord(str){ str = toString(str); return str.replace(PATTERN, ''); } module.exports = removeNonWord; },{"../lang/toString":11}],23:[function(require,module,exports){ var toString = require('../lang/toString'); /** * Replaces all accented chars with regular ones */ function replaceAccents(str){ str = toString(str); // verifies if the String has accents and replace them if (str.search(/[\xC0-\xFF]/g) > -1) { str = str .replace(/[\xC0-\xC5]/g, "A") .replace(/[\xC6]/g, "AE") .replace(/[\xC7]/g, "C") .replace(/[\xC8-\xCB]/g, "E") .replace(/[\xCC-\xCF]/g, "I") .replace(/[\xD0]/g, "D") .replace(/[\xD1]/g, "N") .replace(/[\xD2-\xD6\xD8]/g, "O") .replace(/[\xD9-\xDC]/g, "U") .replace(/[\xDD]/g, "Y") .replace(/[\xDE]/g, "P") .replace(/[\xE0-\xE5]/g, "a") .replace(/[\xE6]/g, "ae") .replace(/[\xE7]/g, "c") .replace(/[\xE8-\xEB]/g, "e") .replace(/[\xEC-\xEF]/g, "i") .replace(/[\xF1]/g, "n") .replace(/[\xF2-\xF6\xF8]/g, "o") .replace(/[\xF9-\xFC]/g, "u") .replace(/[\xFE]/g, "p") .replace(/[\xFD\xFF]/g, "y"); } return str; } module.exports = replaceAccents; },{"../lang/toString":11}],24:[function(require,module,exports){ var toString = require('../lang/toString'); /** * "Safer" String.toUpperCase() */ function upperCase(str){ str = toString(str); return str.toUpperCase(); } module.exports = upperCase; },{"../lang/toString":11}],25:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function create(resourceName, attrs, options) { var _this = this; var definition = _this.definitions[resourceName]; options = options || {}; attrs = attrs || {}; var promise = new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils.isObject(attrs)) { reject(new DSErrors.IA('"attrs" must be an object!')); } else { options = DSUtils._(definition, options); resolve(attrs); } }); if (definition && options.upsert && attrs[definition.idAttribute]) { return _this.update(resourceName, attrs[definition.idAttribute], attrs, options); } else { return promise .then(function (attrs) { return options.beforeValidate.call(attrs, options, attrs); }) .then(function (attrs) { return options.validate.call(attrs, options, attrs); }) .then(function (attrs) { return options.afterValidate.call(attrs, options, attrs); }) .then(function (attrs) { return options.beforeCreate.call(attrs, options, attrs); }) .then(function (attrs) { if (options.notify) { _this.emit(options, 'beforeCreate', DSUtils.copy(attrs)); } return _this.getAdapter(options).create(definition, attrs, options); }) .then(function (attrs) { return options.afterCreate.call(attrs, options, attrs); }) .then(function (attrs) { if (options.notify) { _this.emit(options, 'afterCreate', DSUtils.copy(attrs)); } if (options.cacheResponse) { var created = _this.inject(definition.name, attrs, options); var id = created[definition.idAttribute]; _this.store[resourceName].completedQueries[id] = new Date().getTime(); return created; } else { return _this.createInstance(resourceName, attrs, options); } }); } } module.exports = create; },{"../../errors":46,"../../utils":48}],26:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function destroy(resourceName, id, options) { var _this = this; var definition = _this.definitions[resourceName]; var item; return new DSUtils.Promise(function (resolve, reject) { id = DSUtils.resolveId(definition, id); if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { reject(new DSErrors.IA('"id" must be a string or a number!')); } else { item = _this.get(resourceName, id) || { id: id }; options = DSUtils._(definition, options); resolve(item); } }) .then(function (attrs) { return options.beforeDestroy.call(attrs, options, attrs); }) .then(function (attrs) { if (options.notify) { _this.emit(options, 'beforeDestroy', DSUtils.copy(attrs)); } if (options.eagerEject) { _this.eject(resourceName, id); } return _this.getAdapter(options).destroy(definition, id, options); }) .then(function () { return options.afterDestroy.call(item, options, item); }) .then(function (item) { if (options.notify) { _this.emit(options, 'afterDestroy', DSUtils.copy(item)); } _this.eject(resourceName, id); return id; })['catch'](function (err) { if (options && options.eagerEject && item) { _this.inject(resourceName, item, { notify: false }); } throw err; }); } module.exports = destroy; },{"../../errors":46,"../../utils":48}],27:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function destroyAll(resourceName, params, options) { var _this = this; var definition = _this.definitions[resourceName]; var ejected, toEject; params = params || {}; return new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils.isObject(params)) { reject(new DSErrors.IA('"params" must be an object!')); } else { options = DSUtils._(definition, options); resolve(); } }).then(function () { toEject = _this.defaults.defaultFilter.call(_this, resourceName, params); return options.beforeDestroy(options, toEject); }).then(function () { if (options.notify) { _this.emit(options, 'beforeDestroy', DSUtils.copy(toEject)); } if (options.eagerEject) { ejected = _this.ejectAll(resourceName, params); } return _this.getAdapter(options).destroyAll(definition, params, options); }).then(function () { return options.afterDestroy(options, toEject); }).then(function () { if (options.notify) { _this.emit(options, 'afterDestroy', DSUtils.copy(toEject)); } return ejected || _this.ejectAll(resourceName, params); })['catch'](function (err) { if (options && options.eagerEject && ejected) { _this.inject(resourceName, ejected, { notify: false }); } throw err; }); } module.exports = destroyAll; },{"../../errors":46,"../../utils":48}],28:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function find(resourceName, id, options) { var _this = this; var definition = _this.definitions[resourceName]; var resource = _this.store[resourceName]; return new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { reject(new DSErrors.IA('"id" must be a string or a number!')); } else { options = DSUtils._(definition, options); if (options.bypassCache || !options.cacheResponse) { delete resource.completedQueries[id]; } if (id in resource.completedQueries) { resolve(_this.get(resourceName, id)); } else { resolve(); } } }).then(function (item) { if (!(id in resource.completedQueries)) { if (!(id in resource.pendingQueries)) { resource.pendingQueries[id] = _this.getAdapter(options).find(definition, id, options) .then(function (data) { // Query is no longer pending delete resource.pendingQueries[id]; if (options.cacheResponse) { resource.completedQueries[id] = new Date().getTime(); return _this.inject(resourceName, data, options); } else { return _this.createInstance(resourceName, data, options); } }); } return resource.pendingQueries[id]; } else { return item; } })['catch'](function (err) { if (resource) { delete resource.pendingQueries[id]; } throw err; }); } module.exports = find; },{"../../errors":46,"../../utils":48}],29:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function processResults(data, resourceName, queryHash, options) { var _this = this; var resource = _this.store[resourceName]; var idAttribute = _this.definitions[resourceName].idAttribute; var date = new Date().getTime(); data = data || []; // Query is no longer pending delete resource.pendingQueries[queryHash]; resource.completedQueries[queryHash] = date; // Update modified timestamp of collection resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); // Merge the new values into the cache var injected = _this.inject(resourceName, data, options); // Make sure each object is added to completedQueries if (DSUtils.isArray(injected)) { DSUtils.forEach(injected, function (item) { if (item && item[idAttribute]) { resource.completedQueries[item[idAttribute]] = date; } }); } else { console.warn(errorPrefix(resourceName) + 'response is expected to be an array!'); resource.completedQueries[injected[idAttribute]] = date; } return injected; } function findAll(resourceName, params, options) { var _this = this; var definition = _this.definitions[resourceName]; var resource = _this.store[resourceName]; var queryHash; return new DSUtils.Promise(function (resolve, reject) { params = params || {}; if (!_this.definitions[resourceName]) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils.isObject(params)) { reject(new DSErrors.IA('"params" must be an object!')); } else { options = DSUtils._(definition, options); queryHash = DSUtils.toJson(params); if (options.bypassCache || !options.cacheResponse) { delete resource.completedQueries[queryHash]; } if (queryHash in resource.completedQueries) { resolve(_this.filter(resourceName, params, options)); } else { resolve(); } } }).then(function (items) { if (!(queryHash in resource.completedQueries)) { if (!(queryHash in resource.pendingQueries)) { resource.pendingQueries[queryHash] = _this.getAdapter(options).findAll(definition, params, options) .then(function (data) { delete resource.pendingQueries[queryHash]; if (options.cacheResponse) { return processResults.call(_this, data, resourceName, queryHash, options); } else { DSUtils.forEach(data, function (item, i) { data[i] = _this.createInstance(resourceName, item, options); }); return data; } }); } return resource.pendingQueries[queryHash]; } else { return items; } })['catch'](function (err) { if (resource) { delete resource.pendingQueries[queryHash]; } throw err; }); } module.exports = findAll; },{"../../errors":46,"../../utils":48}],30:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function reap(resourceName, options) { var _this = this; var definition = _this.definitions[resourceName]; var resource = _this.store[resourceName]; return new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new _this.errors.NER(resourceName)); } else { options = DSUtils._(definition, options); if (!options.hasOwnProperty('notify')) { options.notify = false; } var items = []; var now = new Date().getTime(); var expiredItem; while ((expiredItem = resource.expiresHeap.peek()) && expiredItem.expires < now) { items.push(expiredItem.item); delete expiredItem.item; resource.expiresHeap.pop(); } resolve(items); } }).then(function (items) { if (options.isInterval || options.notify) { definition.beforeReap(options, items); _this.emit(options, 'beforeReap', DSUtils.copy(items)); } if (options.reapAction === 'inject') { DSUtils.forEach(items, function (item) { var id = item[definition.idAttribute]; resource.expiresHeap.push({ item: item, timestamp: resource.saved[id], expires: definition.maxAge ? resource.saved[id] + definition.maxAge : Number.MAX_VALUE }); }); } else if (options.reapAction === 'eject') { DSUtils.forEach(items, function (item) { _this.eject(resourceName, item[definition.idAttribute]); }); } else if (options.reapAction === 'refresh') { var tasks = []; DSUtils.forEach(items, function (item) { tasks.push(_this.refresh(resourceName, item[definition.idAttribute])); }); return DSUtils.Promise.all(tasks); } return items; }).then(function (items) { if (options.isInterval || options.notify) { definition.afterReap(options, items); _this.emit(options, 'afterReap', DSUtils.copy(items)); } return items; }); } function refresh(resourceName, id, options) { var _this = this; return new DSUtils.Promise(function (resolve, reject) { var definition = _this.definitions[resourceName]; id = DSUtils.resolveId(_this.definitions[resourceName], id); if (!definition) { reject(new _this.errors.NER(resourceName)); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { reject(new DSErrors.IA('"id" must be a string or a number!')); } else { options = DSUtils._(definition, options); options.bypassCache = true; resolve(_this.get(resourceName, id)); } }).then(function (item) { if (item) { return _this.find(resourceName, id, options); } else { return item; } }); } module.exports = { create: require('./create'), destroy: require('./destroy'), destroyAll: require('./destroyAll'), find: require('./find'), findAll: require('./findAll'), loadRelations: require('./loadRelations'), reap: reap, refresh: refresh, save: require('./save'), update: require('./update'), updateAll: require('./updateAll') }; },{"../../errors":46,"../../utils":48,"./create":25,"./destroy":26,"./destroyAll":27,"./find":28,"./findAll":29,"./loadRelations":31,"./save":32,"./update":33,"./updateAll":34}],31:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function loadRelations(resourceName, instance, relations, options) { var _this = this; var definition = _this.definitions[resourceName]; var fields = []; return new DSUtils.Promise(function (resolve, reject) { if (DSUtils.isString(instance) || DSUtils.isNumber(instance)) { instance = _this.get(resourceName, instance); } if (DSUtils.isString(relations)) { relations = [relations]; } if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils.isObject(instance)) { reject(new DSErrors.IA('"instance(id)" must be a string, number or object!')); } else if (!DSUtils.isArray(relations)) { reject(new DSErrors.IA('"relations" must be a string or an array!')); } else { options = DSUtils._(definition, options); if (!options.hasOwnProperty('findBelongsTo')) { options.findBelongsTo = true; } if (!options.hasOwnProperty('findHasMany')) { options.findHasMany = true; } var tasks = []; DSUtils.forEach(definition.relationList, function (def) { var relationName = def.relation; if (DSUtils.contains(relations, relationName)) { var task; var params = {}; if (options.allowSimpleWhere) { params[def.foreignKey] = instance[definition.idAttribute]; } else { params.where = {}; params.where[def.foreignKey] = { '==': instance[definition.idAttribute] }; } if (def.type === 'hasMany' && params[def.foreignKey]) { task = _this.findAll(relationName, params, options); } else if (def.type === 'hasOne') { if (def.localKey && instance[def.localKey]) { task = _this.find(relationName, instance[def.localKey], options); } else if (def.foreignKey && params[def.foreignKey]) { task = _this.findAll(relationName, params, options).then(function (hasOnes) { return hasOnes.length ? hasOnes[0] : null; }); } } else if (instance[def.localKey]) { task = _this.find(relationName, instance[def.localKey], options); } if (task) { tasks.push(task); fields.push(def.localField); } } }); resolve(tasks); } }) .then(function (tasks) { return DSUtils.Promise.all(tasks); }) .then(function (loadedRelations) { DSUtils.forEach(fields, function (field, index) { instance[field] = loadedRelations[index]; }); return instance; }); } module.exports = loadRelations; },{"../../errors":46,"../../utils":48}],32:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function save(resourceName, id, options) { var _this = this; var definition = _this.definitions[resourceName]; var item; return new DSUtils.Promise(function (resolve, reject) { id = DSUtils.resolveId(definition, id); if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { reject(new DSErrors.IA('"id" must be a string or a number!')); } else if (!_this.get(resourceName, id)) { reject(new DSErrors.R('id "' + id + '" not found in cache!')); } else { item = _this.get(resourceName, id); options = DSUtils._(definition, options); resolve(item); } }).then(function (attrs) { return options.beforeValidate.call(attrs, options, attrs); }) .then(function (attrs) { return options.validate.call(attrs, options, attrs); }) .then(function (attrs) { return options.afterValidate.call(attrs, options, attrs); }) .then(function (attrs) { return options.beforeUpdate.call(attrs, options, attrs); }) .then(function (attrs) { if (options.notify) { _this.emit(options, 'beforeUpdate', DSUtils.copy(attrs)); } if (options.changesOnly) { var resource = _this.store[resourceName]; if (DSUtils.w) { resource.observers[id].deliver(); } var toKeep = []; var changes = _this.changes(resourceName, id); for (var key in changes.added) { toKeep.push(key); } for (key in changes.changed) { toKeep.push(key); } changes = DSUtils.pick(attrs, toKeep); if (DSUtils.isEmpty(changes)) { // no changes, return return attrs; } else { attrs = changes; } } return _this.getAdapter(options).update(definition, id, attrs, options); }) .then(function (data) { return options.afterUpdate.call(data, options, data); }) .then(function (attrs) { if (options.notify) { _this.emit(options, 'afterUpdate', DSUtils.copy(attrs)); } if (options.cacheResponse) { return _this.inject(definition.name, attrs, options); } else { return attrs; } }); } module.exports = save; },{"../../errors":46,"../../utils":48}],33:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function update(resourceName, id, attrs, options) { var _this = this; var definition = _this.definitions[resourceName]; return new DSUtils.Promise(function (resolve, reject) { id = DSUtils.resolveId(definition, id); if (!definition) { reject(new DSErrors.NER(resourceName)); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { reject(new DSErrors.IA('"id" must be a string or a number!')); } else { options = DSUtils._(definition, options); resolve(attrs); } }).then(function (attrs) { return options.beforeValidate.call(attrs, options, attrs); }) .then(function (attrs) { return options.validate.call(attrs, options, attrs); }) .then(function (attrs) { return options.afterValidate.call(attrs, options, attrs); }) .then(function (attrs) { return options.beforeUpdate.call(attrs, options, attrs); }) .then(function (attrs) { if (options.notify) { _this.emit(options, 'beforeUpdate', DSUtils.copy(attrs)); } return _this.getAdapter(options).update(definition, id, attrs, options); }) .then(function (data) { return options.afterUpdate.call(data, options, data); }) .then(function (attrs) { if (options.notify) { _this.emit(options, 'afterUpdate', DSUtils.copy(attrs)); } if (options.cacheResponse) { return _this.inject(definition.name, attrs, options); } else { return attrs; } }); } module.exports = update; },{"../../errors":46,"../../utils":48}],34:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function updateAll(resourceName, attrs, params, options) { var _this = this; var definition = _this.definitions[resourceName]; return new DSUtils.Promise(function (resolve, reject) { if (!definition) { reject(new DSErrors.NER(resourceName)); } else { options = DSUtils._(definition, options); resolve(attrs); } }).then(function (attrs) { return options.beforeValidate.call(attrs, options, attrs); }) .then(function (attrs) { return options.validate.call(attrs, options, attrs); }) .then(function (attrs) { return options.afterValidate.call(attrs, options, attrs); }) .then(function (attrs) { return options.beforeUpdate.call(attrs, options, attrs); }) .then(function (attrs) { if (options.notify) { _this.emit(options, 'beforeUpdate', DSUtils.copy(attrs)); } return _this.getAdapter(options).updateAll(definition, attrs, params, options); }) .then(function (data) { return options.afterUpdate.call(data, options, data); }) .then(function (data) { if (options.notify) { _this.emit(options, 'afterUpdate', DSUtils.copy(attrs)); } if (options.cacheResponse) { return _this.inject(definition.name, data, options); } else { return data; } }); } module.exports = updateAll; },{"../../errors":46,"../../utils":48}],35:[function(require,module,exports){ var DSUtils = require('../utils'); var DSErrors = require('../errors'); var syncMethods = require('./sync_methods'); var asyncMethods = require('./async_methods'); var Schemator; function lifecycleNoopCb(resource, attrs, cb) { cb(null, attrs); } function lifecycleNoop(resource, attrs) { return attrs; } function compare(orderBy, index, a, b) { var def = orderBy[index]; var cA = a[def[0]], cB = b[def[0]]; if (DSUtils.isString(cA)) { cA = DSUtils.upperCase(cA); } if (DSUtils.isString(cB)) { cB = DSUtils.upperCase(cB); } if (def[1] === 'DESC') { if (cB < cA) { return -1; } else if (cB > cA) { return 1; } else { if (index < orderBy.length - 1) { return compare(orderBy, index + 1, a, b); } else { return 0; } } } else { if (cA < cB) { return -1; } else if (cA > cB) { return 1; } else { if (index < orderBy.length - 1) { return compare(orderBy, index + 1, a, b); } else { return 0; } } } } function Defaults() { } var defaultsPrototype = Defaults.prototype; defaultsPrototype.idAttribute = 'id'; defaultsPrototype.basePath = ''; defaultsPrototype.endpoint = ''; defaultsPrototype.useClass = true; defaultsPrototype.keepChangeHistory = false; defaultsPrototype.resetHistoryOnInject = true; defaultsPrototype.eagerEject = false; // TODO: Implement eagerInject in DS#create defaultsPrototype.eagerInject = false; defaultsPrototype.allowSimpleWhere = true; defaultsPrototype.defaultAdapter = 'http'; defaultsPrototype.loadFromServer = false; defaultsPrototype.notify = !!DSUtils.w; defaultsPrototype.upsert = !!DSUtils.w; defaultsPrototype.cacheResponse = !!DSUtils.w; defaultsPrototype.bypassCache = false; defaultsPrototype.ignoreMissing = false; defaultsPrototype.findInverseLinks = true; defaultsPrototype.findBelongsTo = true; defaultsPrototype.findHasOne = true; defaultsPrototype.findHasMany = true; defaultsPrototype.reapInterval = !!DSUtils.w ? 30000 : false; defaultsPrototype.reapAction = !!DSUtils.w ? 'inject' : 'none'; defaultsPrototype.maxAge = false; defaultsPrototype.ignoredChanges = [/\$/]; defaultsPrototype.beforeValidate = lifecycleNoopCb; defaultsPrototype.validate = lifecycleNoopCb; defaultsPrototype.afterValidate = lifecycleNoopCb; defaultsPrototype.beforeCreate = lifecycleNoopCb; defaultsPrototype.afterCreate = lifecycleNoopCb; defaultsPrototype.beforeUpdate = lifecycleNoopCb; defaultsPrototype.afterUpdate = lifecycleNoopCb; defaultsPrototype.beforeDestroy = lifecycleNoopCb; defaultsPrototype.afterDestroy = lifecycleNoopCb; defaultsPrototype.beforeCreateInstance = lifecycleNoop; defaultsPrototype.afterCreateInstance = lifecycleNoop; defaultsPrototype.beforeInject = lifecycleNoop; defaultsPrototype.afterInject = lifecycleNoop; defaultsPrototype.beforeEject = lifecycleNoop; defaultsPrototype.afterEject = lifecycleNoop; defaultsPrototype.beforeReap = lifecycleNoop; defaultsPrototype.afterReap = lifecycleNoop; defaultsPrototype.defaultFilter = function (collection, resourceName, params, options) { var _this = this; var filtered = collection; var where = null; var reserved = { skip: '', offset: '', where: '', limit: '', orderBy: '', sort: '' }; params = params || {}; options = options || {}; if (DSUtils.isObject(params.where)) { where = params.where; } else { where = {}; } if (options.allowSimpleWhere) { DSUtils.forOwn(params, function (value, key) { if (!(key in reserved) && !(key in where)) { where[key] = { '==': value }; } }); } if (DSUtils.isEmpty(where)) { where = null; } if (where) { filtered = DSUtils.filter(filtered, function (attrs) { var first = true; var keep = true; DSUtils.forOwn(where, function (clause, field) { if (DSUtils.isString(clause)) { clause = { '===': clause }; } else if (DSUtils.isNumber(clause) || DSUtils.isBoolean(clause)) { clause = { '==': clause }; } if (DSUtils.isObject(clause)) { DSUtils.forOwn(clause, function (term, op) { var expr; var isOr = op[0] === '|'; var val = attrs[field]; op = isOr ? op.substr(1) : op; if (op === '==') { expr = val == term; } else if (op === '===') { expr = val === term; } else if (op === '!=') { expr = val != term; } else if (op === '!==') { expr = val !== term; } else if (op === '>') { expr = val > term; } else if (op === '>=') { expr = val >= term; } else if (op === '<') { expr = val < term; } else if (op === '<=') { expr = val <= term; } else if (op === 'isectEmpty') { expr = !DSUtils.intersection((val || []), (term || [])).length; } else if (op === 'isectNotEmpty') { expr = DSUtils.intersection((val || []), (term || [])).length; } else if (op === 'in') { if (DSUtils.isString(term)) { expr = term.indexOf(val) !== -1; } else { expr = DSUtils.contains(term, val); } } else if (op === 'notIn') { if (DSUtils.isString(term)) { expr = term.indexOf(val) === -1; } else { expr = !DSUtils.contains(term, val); } } if (expr !== undefined) { keep = first ? expr : (isOr ? keep || expr : keep && expr); } first = false; }); } }); return keep; }); } var orderBy = null; if (DSUtils.isString(params.orderBy)) { orderBy = [ [params.orderBy, 'ASC'] ]; } else if (DSUtils.isArray(params.orderBy)) { orderBy = params.orderBy; } if (!orderBy && DSUtils.isString(params.sort)) { orderBy = [ [params.sort, 'ASC'] ]; } else if (!orderBy && DSUtils.isArray(params.sort)) { orderBy = params.sort; } // Apply 'orderBy' if (orderBy) { var index = 0; DSUtils.forEach(orderBy, function (def, i) { if (DSUtils.isString(def)) { orderBy[i] = [def, 'ASC']; } else if (!DSUtils.isArray(def)) { throw new _this.errors.IllegalArgumentError('DS.filter(resourceName[, params][, options]): ' + DSUtils.toJson(def) + ': Must be a string or an array!', { params: { 'orderBy[i]': { actual: typeof def, expected: 'string|array' } } }); } }); filtered = DSUtils.sort(filtered, function (a, b) { return compare(orderBy, index, a, b); }); } var limit = DSUtils.isNumber(params.limit) ? params.limit : null; var skip = null; if (DSUtils.isNumber(params.skip)) { skip = params.skip; } else if (DSUtils.isNumber(params.offset)) { skip = params.offset; } // Apply 'limit' and 'skip' if (limit && skip) { filtered = DSUtils.slice(filtered, skip, Math.min(filtered.length, skip + limit)); } else if (DSUtils.isNumber(limit)) { filtered = DSUtils.slice(filtered, 0, Math.min(filtered.length, limit)); } else if (DSUtils.isNumber(skip)) { if (skip < filtered.length) { filtered = DSUtils.slice(filtered, skip); } else { filtered = []; } } return filtered; }; function DS(options) { options = options || {}; try { Schemator = require('js-data-schema'); } catch (e) { } if (!Schemator) { try { Schemator = window.Schemator; } catch (e) { } } if (Schemator || options.schemator) { this.schemator = options.schemator || new Schemator(); } this.store = {}; this.definitions = {}; this.adapters = {}; this.defaults = new Defaults(); this.observe = DSUtils.observe; DSUtils.deepMixIn(this.defaults, options); } var dsPrototype = DS.prototype; dsPrototype.getAdapter = function (options) { options = options || {}; return this.adapters[options.adapter] || this.adapters[options.defaultAdapter]; }; dsPrototype.registerAdapter = function (name, Adapter, options) { options = options || {}; if (DSUtils.isFunction(Adapter)) { this.adapters[name] = new Adapter(options); } else { this.adapters[name] = Adapter; } if (options.default) { this.defaults.defaultAdapter = name; } }; dsPrototype.emit = function (definition, event) { var args = Array.prototype.slice.call(arguments, 2); args.unshift(definition.name); args.unshift('DS.' + event); definition.emit.apply(definition, args); }; dsPrototype.errors = require('../errors'); dsPrototype.utils = DSUtils; DSUtils.deepMixIn(dsPrototype, syncMethods); DSUtils.deepMixIn(dsPrototype, asyncMethods); module.exports = DS; },{"../errors":46,"../utils":48,"./async_methods":30,"./sync_methods":40,"js-data-schema":"js-data-schema"}],36:[function(require,module,exports){ /*jshint evil:true, loopfunc:true*/ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function Resource(options) { DSUtils.deepMixIn(this, options); if ('endpoint' in options) { this.endpoint = options.endpoint; } else { this.endpoint = this.name; } } var instanceMethods = [ 'compute', 'refresh', 'save', 'update', 'destroy', 'loadRelations', 'changeHistory', 'changes', 'hasChanges', 'lastModified', 'lastSaved', 'link', 'linkInverse', 'previous', 'unlinkInverse' ]; function defineResource(definition) { var _this = this; var definitions = _this.definitions; if (DSUtils.isString(definition)) { definition = { name: definition.replace(/\s/gi, '') }; } if (!DSUtils.isObject(definition)) { throw new DSErrors.IA('"definition" must be an object!'); } else if (!DSUtils.isString(definition.name)) { throw new DSErrors.IA('"name" must be a string!'); } else if (_this.store[definition.name]) { throw new DSErrors.R(definition.name + ' is already registered!'); } try { // Inherit from global defaults Resource.prototype = _this.defaults; definitions[definition.name] = new Resource(definition); var def = definitions[definition.name]; if (!DSUtils.isString(def.idAttribute)) { throw new DSErrors.IA('"idAttribute" must be a string!'); } // Setup nested parent configuration if (def.relations) { def.relationList = []; def.relationFields = []; DSUtils.forOwn(def.relations, function (relatedModels, type) { DSUtils.forOwn(relatedModels, function (defs, relationName) { if (!DSUtils.isArray(defs)) { relatedModels[relationName] = [defs]; } DSUtils.forEach(relatedModels[relationName], function (d) { d.type = type; d.relation = relationName; d.name = def.name; def.relationList.push(d); def.relationFields.push(d.localField); }); }); }); if (def.relations.belongsTo) { DSUtils.forOwn(def.relations.belongsTo, function (relatedModel, modelName) { DSUtils.forEach(relatedModel, function (relation) { if (relation.parent) { def.parent = modelName; def.parentKey = relation.localKey; } }); }); } if (typeof Object.freeze === 'function') { Object.freeze(def.relations); Object.freeze(def.relationList); } } def.getEndpoint = function (attrs, options) { options = DSUtils.deepMixIn({}, options); var parent = this.parent; var parentKey = this.parentKey; var item; var endpoint; var thisEndpoint = options.endpoint || this.endpoint; var parentDef = definitions[parent]; delete options.endpoint; options = options || {}; options.params = options.params || {}; if (parent && parentKey && parentDef && options.params[parentKey] !== false) { if (DSUtils.isNumber(attrs) || DSUtils.isString(attrs)) { item = _this.get(this.name, attrs); } if (DSUtils.isObject(attrs) && parentKey in attrs) { delete options.params[parentKey]; endpoint = DSUtils.makePath(parentDef.getEndpoint(attrs, options), attrs[parentKey], thisEndpoint); } else if (item && parentKey in item) { delete options.params[parentKey]; endpoint = DSUtils.makePath(parentDef.getEndpoint(attrs, options), item[parentKey], thisEndpoint); } else if (options && options.params[parentKey]) { endpoint = DSUtils.makePath(parentDef.getEndpoint(attrs, options), options.params[parentKey], thisEndpoint); delete options.params[parentKey]; } } if (options.params[parentKey] === false) { delete options.params[parentKey]; } return endpoint || thisEndpoint; }; // Remove this in v0.11.0 and make a breaking change notice // the the `filter` option has been renamed to `defaultFilter` if (def.filter) { def.defaultFilter = def.filter; delete def.filter; } // Create the wrapper class for the new resource def['class'] = DSUtils.pascalCase(definition.name); try { eval('function ' + def['class'] + '() {}'); def[def['class']] = eval(def['class']); } catch (e) { def[def['class']] = function () { }; } // Apply developer-defined methods if (def.methods) { DSUtils.deepMixIn(def[def['class']].prototype, def.methods); } // Prepare for computed properties if (def.computed) { DSUtils.forOwn(def.computed, function (fn, field) { if (DSUtils.isFunction(fn)) { def.computed[field] = [fn]; fn = def.computed[field]; } if (def.methods && field in def.methods) { console.warn('Computed property "' + field + '" conflicts with previously defined prototype method!'); } var deps; if (fn.length === 1) { var match = fn[0].toString().match(/function.*?\(([\s\S]*?)\)/); deps = match[1].split(','); def.computed[field] = deps.concat(fn); fn = def.computed[field]; if (deps.length) { console.warn('Use the computed property array syntax for compatibility with minified code!'); } } deps = fn.slice(0, fn.length - 1); DSUtils.forEach(deps, function (val, index) { deps[index] = val.trim(); }); fn.deps = DSUtils.filter(deps, function (dep) { return !!dep; }); }); } if (definition.schema && _this.schemator) { def.schema = _this.schemator.defineSchema(def.name, definition.schema); if (!definition.hasOwnProperty('validate')) { def.validate = function (resourceName, attrs, cb) { def.schema.validate(attrs, { ignoreMissing: def.ignoreMissing }, function (err) { if (err) { return cb(err); } else { return cb(null, attrs); } }); }; } } DSUtils.forEach(instanceMethods, function (name) { def[def['class']].prototype['DS' + DSUtils.pascalCase(name)] = function () { var args = Array.prototype.slice.call(arguments); args.unshift(this[def.idAttribute] || this); args.unshift(def.name); return _this[name].apply(_this, args); }; }); // Initialize store data for the new resource _this.store[def.name] = { collection: [], expiresHeap: new DSUtils.DSBinaryHeap(function (x) { return x.expires; }, function (x, y) { return x.item === y; }), completedQueries: {}, pendingQueries: {}, index: {}, modified: {}, saved: {}, previousAttributes: {}, observers: {}, changeHistories: {}, changeHistory: [], collectionModified: 0 }; if (def.reapInterval) { setInterval(function () { _this.reap(def.name, { isInterval: true }); }, def.reapInterval); } // Proxy DS methods with shorthand ones for (var key in _this) { if (typeof _this[key] === 'function' && key !== 'defineResource') { (function (k) { def[k] = function () { var args = Array.prototype.slice.call(arguments); args.unshift(def.name); return _this[k].apply(_this, args); }; })(key); } } def.beforeValidate = DSUtils.promisify(def.beforeValidate); def.validate = DSUtils.promisify(def.validate); def.afterValidate = DSUtils.promisify(def.afterValidate); def.beforeCreate = DSUtils.promisify(def.beforeCreate); def.afterCreate = DSUtils.promisify(def.afterCreate); def.beforeUpdate = DSUtils.promisify(def.beforeUpdate); def.afterUpdate = DSUtils.promisify(def.afterUpdate); def.beforeDestroy = DSUtils.promisify(def.beforeDestroy); def.afterDestroy = DSUtils.promisify(def.afterDestroy); // Mix-in events DSUtils.Events(def); return def; } catch (err) { delete definitions[definition.name]; delete _this.store[definition.name]; throw err; } } module.exports = defineResource; },{"../../errors":46,"../../utils":48}],37:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function eject(resourceName, id, options) { var _this = this; var definition = _this.definitions[resourceName]; var resource = _this.store[resourceName]; var item; var found = false; id = DSUtils.resolveId(definition, id); if (!definition) { throw new DSErrors.NER(resourceName); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { throw new DSErrors.IA('"id" must be a string or a number!'); } options = DSUtils._(definition, options); for (var i = 0; i < resource.collection.length; i++) { if (resource.collection[i][definition.idAttribute] == id) { item = resource.collection[i]; resource.expiresHeap.remove(item); found = true; break; } } if (found) { if (options.notify) { definition.beforeEject(options, item); _this.emit(options, 'beforeEject', DSUtils.copy(item)); } _this.unlinkInverse(definition.name, id); resource.collection.splice(i, 1); if (DSUtils.w) { resource.observers[id].close(); } delete resource.observers[id]; delete resource.index[id]; delete resource.previousAttributes[id]; delete resource.completedQueries[id]; delete resource.pendingQueries[id]; DSUtils.forEach(resource.changeHistories[id], function (changeRecord) { DSUtils.remove(resource.changeHistory, changeRecord); }); delete resource.changeHistories[id]; delete resource.modified[id]; delete resource.saved[id]; resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); if (options.notify) { definition.afterEject(options, item); _this.emit(options, 'afterEject', DSUtils.copy(item)); } return item; } } module.exports = eject; },{"../../errors":46,"../../utils":48}],38:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function ejectAll(resourceName, params, options) { var _this = this; var definition = _this.definitions[resourceName]; params = params || {}; if (!definition) { throw new DSErrors.NER(resourceName); } else if (!DSUtils.isObject(params)) { throw new DSErrors.IA('"params" must be an object!'); } var resource = _this.store[resourceName]; if (DSUtils.isEmpty(params)) { resource.completedQueries = {}; } var queryHash = DSUtils.toJson(params); var items = _this.filter(definition.name, params); var ids = []; DSUtils.forEach(items, function (item) { if (item && item[definition.idAttribute]) { ids.push(item[definition.idAttribute]); } }); DSUtils.forEach(ids, function (id) { _this.eject(definition.name, id, options); }); delete resource.completedQueries[queryHash]; resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); return items; } module.exports = ejectAll; },{"../../errors":46,"../../utils":48}],39:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function filter(resourceName, params, options) { var _this = this; var definition = _this.definitions[resourceName]; var resource = _this.store[resourceName]; if (!definition) { throw new DSErrors.NER(resourceName); } else if (params && !DSUtils.isObject(params)) { throw new DSErrors.IA('"params" must be an object!'); } options = DSUtils._(definition, options); // Protect against null params = params || {}; var queryHash = DSUtils.toJson(params); if (!(queryHash in resource.completedQueries) && options.loadFromServer) { // This particular query has never been completed if (!resource.pendingQueries[queryHash]) { // This particular query has never even been started _this.findAll(resourceName, params, options); } } return definition.defaultFilter.call(_this, resource.collection, resourceName, params, options); } module.exports = filter; },{"../../errors":46,"../../utils":48}],40:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); var NER = DSErrors.NER; var IA = DSErrors.IA; function changes(resourceName, id, options) { var _this = this; var definition = _this.definitions[resourceName]; options = options || {}; id = DSUtils.resolveId(definition, id); if (!definition) { throw new NER(resourceName); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { throw new IA('"id" must be a string or a number!'); } options = DSUtils._(definition, options); var item = _this.get(resourceName, id); if (item) { if (DSUtils.w) { _this.store[resourceName].observers[id].deliver(); } var diff = DSUtils.diffObjectFromOldObject(item, _this.store[resourceName].previousAttributes[id], DSUtils.equals, options.ignoredChanges); DSUtils.forOwn(diff, function (changeset, name) { var toKeep = []; DSUtils.forOwn(changeset, function (value, field) { if (!DSUtils.isFunction(value)) { toKeep.push(field); } }); diff[name] = DSUtils.pick(diff[name], toKeep); }); DSUtils.forEach(definition.relationFields, function (field) { delete diff.added[field]; delete diff.removed[field]; delete diff.changed[field]; }); return diff; } } function changeHistory(resourceName, id) { var _this = this; var definition = _this.definitions[resourceName]; var resource = _this.store[resourceName]; id = DSUtils.resolveId(definition, id); if (resourceName && !_this.definitions[resourceName]) { throw new NER(resourceName); } else if (id && !DSUtils.isString(id) && !DSUtils.isNumber(id)) { throw new IA('"id" must be a string or a number!'); } if (!definition.keepChangeHistory) { console.warn('changeHistory is disabled for this resource!'); } else { if (resourceName) { var item = _this.get(resourceName, id); if (item) { return resource.changeHistories[id]; } } else { return resource.changeHistory; } } } function compute(resourceName, instance) { var _this = this; var definition = _this.definitions[resourceName]; instance = DSUtils.resolveItem(_this.store[resourceName], instance); if (!definition) { throw new NER(resourceName); } else if (!DSUtils.isObject(instance) && !DSUtils.isString(instance) && !DSUtils.isNumber(instance)) { throw new IA('"instance" must be an object, string or number!'); } if (DSUtils.isString(instance) || DSUtils.isNumber(instance)) { instance = _this.get(resourceName, instance); } DSUtils.forOwn(definition.computed, function (fn, field) { DSUtils.compute.call(instance, fn, field); }); return instance; } function createInstance(resourceName, attrs, options) { var definition = this.definitions[resourceName]; var item; attrs = attrs || {}; if (!definition) { throw new NER(resourceName); } else if (attrs && !DSUtils.isObject(attrs)) { throw new IA('"attrs" must be an object!'); } options = DSUtils._(definition, options); if (options.notify) { options.beforeCreateInstance(options, attrs); } if (options.useClass) { var Constructor = definition[definition.class]; item = new Constructor(); } else { item = {}; } DSUtils.deepMixIn(item, attrs); if (options.notify) { options.afterCreateInstance(options, attrs); } return item; } function diffIsEmpty(diff) { return !(DSUtils.isEmpty(diff.added) && DSUtils.isEmpty(diff.removed) && DSUtils.isEmpty(diff.changed)); } function digest() { this.observe.Platform.performMicrotaskCheckpoint(); } function get(resourceName, id, options) { var _this = this; var definition = _this.definitions[resourceName]; if (!definition) { throw new NER(resourceName); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { throw new IA('"id" must be a string or a number!'); } options = DSUtils._(definition, options); // cache miss, request resource from server var item = _this.store[resourceName].index[id]; if (!item && options.loadFromServer) { _this.find(resourceName, id, options); } // return resource from cache return item; } function getAll(resourceName, ids) { var _this = this; var resource = _this.store[resourceName]; var collection = []; if (!_this.definitions[resourceName]) { throw new NER(resourceName); } else if (ids && !DSUtils.isArray(ids)) { throw new IA('"ids" must be an array!'); } if (DSUtils.isArray(ids)) { var length = ids.length; for (var i = 0; i < length; i++) { if (resource.index[ids[i]]) { collection.push(resource.index[ids[i]]); } } } else { collection = resource.collection.slice(); } return collection; } function hasChanges(resourceName, id) { var _this = this; id = DSUtils.resolveId(_this.definitions[resourceName], id); if (!_this.definitions[resourceName]) { throw new NER(resourceName); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { throw new IA('"id" must be a string or a number!'); } // return resource from cache if (_this.get(resourceName, id)) { return diffIsEmpty(_this.changes(resourceName, id)); } else { return false; } } function lastModified(resourceName, id) { var definition = this.definitions[resourceName]; var resource = this.store[resourceName]; id = DSUtils.resolveId(definition, id); if (!definition) { throw new NER(resourceName); } if (id) { if (!(id in resource.modified)) { resource.modified[id] = 0; } return resource.modified[id]; } return resource.collectionModified; } function lastSaved(resourceName, id) { var definition = this.definitions[resourceName]; var resource = this.store[resourceName]; id = DSUtils.resolveId(definition, id); if (!definition) { throw new NER(resourceName); } if (!(id in resource.saved)) { resource.saved[id] = 0; } return resource.saved[id]; } function previous(resourceName, id) { var _this = this; var definition = _this.definitions[resourceName]; var resource = _this.store[resourceName]; id = DSUtils.resolveId(definition, id); if (!definition) { throw new NER(resourceName); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { throw new IA('"id" must be a string or a number!'); } // return resource from cache return resource.previousAttributes[id] ? DSUtils.copy(resource.previousAttributes[id]) : undefined; } module.exports = { changes: changes, changeHistory: changeHistory, compute: compute, createInstance: createInstance, defineResource: require('./defineResource'), digest: digest, eject: require('./eject'), ejectAll: require('./ejectAll'), filter: require('./filter'), get: get, getAll: getAll, hasChanges: hasChanges, inject: require('./inject'), lastModified: lastModified, lastSaved: lastSaved, link: require('./link'), linkAll: require('./linkAll'), linkInverse: require('./linkInverse'), previous: previous, unlinkInverse: require('./unlinkInverse') }; },{"../../errors":46,"../../utils":48,"./defineResource":36,"./eject":37,"./ejectAll":38,"./filter":39,"./inject":41,"./link":42,"./linkAll":43,"./linkInverse":44,"./unlinkInverse":45}],41:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function _getReactFunction(DS, definition, resource) { var name = definition.name; return function _react(added, removed, changed, oldValueFn, firstTime) { var target = this; var item; var innerId = (oldValueFn && oldValueFn(definition.idAttribute)) ? oldValueFn(definition.idAttribute) : target[definition.idAttribute]; DSUtils.forEach(definition.relationFields, function (field) { delete added[field]; delete removed[field]; delete changed[field]; }); if (!DSUtils.isEmpty(added) || !DSUtils.isEmpty(removed) || !DSUtils.isEmpty(changed) || firstTime) { item = DS.get(name, innerId); resource.modified[innerId] = DSUtils.updateTimestamp(resource.modified[innerId]); resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); if (definition.keepChangeHistory) { var changeRecord = { resourceName: name, target: item, added: added, removed: removed, changed: changed, timestamp: resource.modified[innerId] }; resource.changeHistories[innerId].push(changeRecord); resource.changeHistory.push(changeRecord); } } if (definition.computed) { item = item || DS.get(name, innerId); DSUtils.forOwn(definition.computed, function (fn, field) { var compute = false; // check if required fields changed DSUtils.forEach(fn.deps, function (dep) { if (dep in added || dep in removed || dep in changed || !(field in item)) { compute = true; } }); compute = compute || !fn.deps.length; if (compute) { DSUtils.compute.call(item, fn, field); } }); } if (definition.relations) { item = item || DS.get(name, innerId); DSUtils.forEach(definition.relationList, function (def) { if (item[def.localField] && (def.localKey in added || def.localKey in removed || def.localKey in changed)) { DS.link(name, item[definition.idAttribute], [def.relation]); } }); } if (definition.idAttribute in changed) { console.error('Doh! You just changed the primary key of an object! Your data for the' + name + '" resource is now in an undefined (probably broken) state.'); } }; } function _inject(definition, resource, attrs, options) { var _this = this; var _react = _getReactFunction(_this, definition, resource, attrs, options); var injected; if (DSUtils.isArray(attrs)) { injected = []; for (var i = 0; i < attrs.length; i++) { injected.push(_inject.call(_this, definition, resource, attrs[i], options)); } } else { // check if "idAttribute" is a computed property var c = definition.computed; var idA = definition.idAttribute; if (c && c[idA]) { var args = []; DSUtils.forEach(c[idA].deps, function (dep) { args.push(attrs[dep]); }); attrs[idA] = c[idA][c[idA].length - 1].apply(attrs, args); } if (!(idA in attrs)) { var error = new DSErrors.R(definition.name + '.inject: "attrs" must contain the property specified by `idAttribute`!'); console.error(error); throw error; } else { try { DSUtils.forEach(definition.relationList, function (def) { var relationName = def.relation; var relationDef = _this.definitions[relationName]; var toInject = attrs[def.localField]; if (toInject) { if (!relationDef) { throw new DSErrors.R(definition.name + ' relation is defined but the resource is not!'); } if (DSUtils.isArray(toInject)) { var items = []; DSUtils.forEach(toInject, function (toInjectItem) { if (toInjectItem !== _this.store[relationName][toInjectItem[relationDef.idAttribute]]) { try { var injectedItem = _this.inject(relationName, toInjectItem, options); if (def.foreignKey) { injectedItem[def.foreignKey] = attrs[definition.idAttribute]; } items.push(injectedItem); } catch (err) { console.error(definition.name + ': Failed to inject ' + def.type + ' relation: "' + relationName + '"!', err); } } }); attrs[def.localField] = items; } else { if (toInject !== _this.store[relationName][toInject[relationDef.idAttribute]]) { try { attrs[def.localField] = _this.inject(relationName, attrs[def.localField], options); if (def.foreignKey) { attrs[def.localField][def.foreignKey] = attrs[definition.idAttribute]; } } catch (err) { console.error(definition.name + ': Failed to inject ' + def.type + ' relation: "' + relationName + '"!', err); } } } } }); var id = attrs[idA]; var item = _this.get(definition.name, id); var initialLastModified = item ? resource.modified[id] : 0; if (!item) { if (options.useClass) { if (attrs instanceof definition[definition['class']]) { item = attrs; } else { item = new definition[definition['class']](); } } else { item = {}; } resource.previousAttributes[id] = DSUtils.copy(attrs); DSUtils.deepMixIn(item, attrs); resource.collection.push(item); resource.changeHistories[id] = []; if (DSUtils.w) { resource.observers[id] = new _this.observe.ObjectObserver(item); resource.observers[id].open(_react, item); } resource.index[id] = item; _react.call(item, {}, {}, {}, null, true); } else { DSUtils.deepMixIn(item, attrs); if (definition.resetHistoryOnInject) { resource.previousAttributes[id] = {}; DSUtils.deepMixIn(resource.previousAttributes[id], attrs); if (resource.changeHistories[id].length) { DSUtils.forEach(resource.changeHistories[id], function (changeRecord) { DSUtils.remove(resource.changeHistory, changeRecord); }); resource.changeHistories[id].splice(0, resource.changeHistories[id].length); } } if (DSUtils.w) { resource.observers[id].deliver(); } } resource.saved[id] = DSUtils.updateTimestamp(resource.saved[id]); resource.modified[id] = initialLastModified && resource.modified[id] === initialLastModified ? DSUtils.updateTimestamp(resource.modified[id]) : resource.modified[id]; resource.expiresHeap.remove(item); resource.expiresHeap.push({ item: item, timestamp: resource.saved[id], expires: definition.maxAge ? resource.saved[id] + definition.maxAge : Number.MAX_VALUE }); injected = item; } catch (err) { console.error(err.stack); console.error('inject failed!', definition.name, attrs); } } } return injected; } function _link(definition, injected, options) { var _this = this; DSUtils.forEach(definition.relationList, function (def) { if (options.findBelongsTo && def.type === 'belongsTo' && injected[definition.idAttribute]) { _this.link(definition.name, injected[definition.idAttribute], [def.relation]); } else if ((options.findHasMany && def.type === 'hasMany') || (options.findHasOne && def.type === 'hasOne')) { _this.link(definition.name, injected[definition.idAttribute], [def.relation]); } }); } function inject(resourceName, attrs, options) { var _this = this; var definition = _this.definitions[resourceName]; var resource = _this.store[resourceName]; var injected; if (!definition) { throw new DSErrors.NER(resourceName); } else if (!DSUtils.isObject(attrs) && !DSUtils.isArray(attrs)) { throw new DSErrors.IA(resourceName + '.inject: "attrs" must be an object or an array!'); } var name = definition.name; options = DSUtils._(definition, options); if (options.notify) { options.beforeInject(options, attrs); _this.emit(options, 'beforeInject', DSUtils.copy(attrs)); } injected = _inject.call(_this, definition, resource, attrs, options); resource.collectionModified = DSUtils.updateTimestamp(resource.collectionModified); if (options.findInverseLinks) { if (DSUtils.isArray(injected)) { if (injected.length) { _this.linkInverse(name, injected[0][definition.idAttribute]); } } else { _this.linkInverse(name, injected[definition.idAttribute]); } } if (DSUtils.isArray(injected)) { DSUtils.forEach(injected, function (injectedI) { _link.call(_this, definition, injectedI, options); }); } else { _link.call(_this, definition, injected, options); } if (options.notify) { options.afterInject(options, injected); _this.emit(options, 'afterInject', DSUtils.copy(injected)); } return injected; } module.exports = inject; },{"../../errors":46,"../../utils":48}],42:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function link(resourceName, id, relations) { var _this = this; var definition = _this.definitions[resourceName]; relations = relations || []; id = DSUtils.resolveId(definition, id); if (!definition) { throw new DSErrors.NER(resourceName); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { throw new DSErrors.IA('"id" must be a string or a number!'); } else if (!DSUtils.isArray(relations)) { throw new DSErrors.IA('"relations" must be an array!'); } var linked = _this.get(resourceName, id); if (linked) { DSUtils.forEach(definition.relationList, function (def) { var relationName = def.relation; if (relations.length && !DSUtils.contains(relations, relationName)) { return; } var params = {}; if (def.type === 'belongsTo') { var parent = linked[def.localKey] ? _this.get(relationName, linked[def.localKey]) : null; if (parent) { linked[def.localField] = parent; } } else if (def.type === 'hasMany') { params[def.foreignKey] = linked[definition.idAttribute]; linked[def.localField] = _this.defaults.constructor.prototype.defaultFilter.call(_this, _this.store[relationName].collection, relationName, params, { allowSimpleWhere: true }); } else if (def.type === 'hasOne') { params[def.foreignKey] = linked[definition.idAttribute]; var children = _this.defaults.constructor.prototype.defaultFilter.call(_this, _this.store[relationName].collection, relationName, params, { allowSimpleWhere: true }); if (children.length) { linked[def.localField] = children[0]; } } }); } return linked; } module.exports = link; },{"../../errors":46,"../../utils":48}],43:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function linkAll(resourceName, params, relations) { var _this = this; var definition = _this.definitions[resourceName]; relations = relations || []; if (!definition) { throw new DSErrors.NER(resourceName); } else if (!DSUtils.isArray(relations)) { throw new DSErrors.IA('"relations" must be an array!'); } var linked = _this.filter(resourceName, params); if (linked) { DSUtils.forEach(definition.relationList, function (def) { var relationName = def.relation; if (relations.length && !DSUtils.contains(relations, relationName)) { return; } if (def.type === 'belongsTo') { DSUtils.forEach(linked, function (injectedItem) { var parent = injectedItem[def.localKey] ? _this.get(relationName, injectedItem[def.localKey]) : null; if (parent) { injectedItem[def.localField] = parent; } }); } else if (def.type === 'hasMany') { DSUtils.forEach(linked, function (injectedItem) { var params = {}; params[def.foreignKey] = injectedItem[definition.idAttribute]; injectedItem[def.localField] = _this.defaults.constructor.prototype.defaultFilter.call(_this, _this.store[relationName].collection, relationName, params, { allowSimpleWhere: true }); }); } else if (def.type === 'hasOne') { DSUtils.forEach(linked, function (injectedItem) { var params = {}; params[def.foreignKey] = injectedItem[definition.idAttribute]; var children = _this.defaults.constructor.prototype.defaultFilter.call(_this, _this.store[relationName].collection, relationName, params, { allowSimpleWhere: true }); if (children.length) { injectedItem[def.localField] = children[0]; } }); } }); } return linked; } module.exports = linkAll; },{"../../errors":46,"../../utils":48}],44:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function linkInverse(resourceName, id, relations) { var _this = this; var definition = _this.definitions[resourceName]; relations = relations || []; id = DSUtils.resolveId(definition, id); if (!definition) { throw new DSErrors.NER(resourceName); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { throw new DSErrors.IA('"id" must be a string or a number!'); } else if (!DSUtils.isArray(relations)) { throw new DSErrors.IA('"relations" must be an array!'); } var linked = _this.get(resourceName, id); if (linked) { DSUtils.forOwn(_this.definitions, function (d) { DSUtils.forOwn(d.relations, function (relatedModels) { DSUtils.forOwn(relatedModels, function (defs, relationName) { if (relations.length && !DSUtils.contains(relations, d.name)) { return; } if (definition.name === relationName) { _this.linkAll(d.name, {}, [definition.name]); } }); }); }); } return linked; } module.exports = linkInverse; },{"../../errors":46,"../../utils":48}],45:[function(require,module,exports){ var DSUtils = require('../../utils'); var DSErrors = require('../../errors'); function unlinkInverse(resourceName, id, relations) { var _this = this; var definition = _this.definitions[resourceName]; relations = relations || []; id = DSUtils.resolveId(definition, id); if (!definition) { throw new DSErrors.NER(resourceName); } else if (!DSUtils.isString(id) && !DSUtils.isNumber(id)) { throw new DSErrors.IA('"id" must be a string or a number!'); } else if (!DSUtils.isArray(relations)) { throw new DSErrors.IA('"relations" must be an array!'); } var linked = _this.get(resourceName, id); if (linked) { DSUtils.forOwn(_this.definitions, function (d) { DSUtils.forOwn(d.relations, function (relatedModels) { DSUtils.forOwn(relatedModels, function (defs, relationName) { if (definition.name === relationName) { DSUtils.forEach(defs, function (def) { DSUtils.forEach(_this.store[def.name].collection, function (item) { if (def.type === 'hasMany' && item[def.localField]) { var index; DSUtils.forEach(item[def.localField], function (subItem, i) { if (subItem === linked) { index = i; } }); item[def.localField].splice(index, 1); } else if (item[def.localField] === linked) { delete item[def.localField]; } }); }); } }); }); }); } return linked; } module.exports = unlinkInverse; },{"../../errors":46,"../../utils":48}],46:[function(require,module,exports){ function IllegalArgumentError(message) { Error.call(this); if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } this.type = this.constructor.name; this.message = message || 'Illegal Argument!'; } IllegalArgumentError.prototype = new Error(); IllegalArgumentError.prototype.constructor = IllegalArgumentError; function RuntimeError(message) { Error.call(this); if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } this.type = this.constructor.name; this.message = message || 'RuntimeError Error!'; } RuntimeError.prototype = new Error(); RuntimeError.prototype.constructor = RuntimeError; function NonexistentResourceError(resourceName) { Error.call(this); if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } this.type = this.constructor.name; this.message = (resourceName || '') + ' is not a registered resource!'; } NonexistentResourceError.prototype = new Error(); NonexistentResourceError.prototype.constructor = NonexistentResourceError; module.exports = { IllegalArgumentError: IllegalArgumentError, IA: IllegalArgumentError, RuntimeError: RuntimeError, R: RuntimeError, NonexistentResourceError: NonexistentResourceError, NER: NonexistentResourceError }; },{}],47:[function(require,module,exports){ var DS = require('./datastore'); module.exports = { DS: DS, createStore: function (options) { return new DS(options); }, DSUtils: require('./utils'), DSErrors: require('./errors') }; },{"./datastore":35,"./errors":46,"./utils":48}],48:[function(require,module,exports){ /* jshint -W041 */ var w, _Promise; var objectProto = Object.prototype; var toString = objectProto.toString; var DSErrors = require('./errors'); var forEach = require('mout/array/forEach'); var slice = require('mout/array/slice'); var forOwn = require('mout/object/forOwn'); var observe = require('../lib/observe-js/observe-js'); var es6Promise = require('es6-promise'); es6Promise.polyfill(); var isArray = Array.isArray || function isArray(value) { return toString.call(value) == '[object Array]' || false; }; function isRegExp(value) { return toString.call(value) == '[object RegExp]' || false; } // adapted from lodash.isBoolean function isBoolean(value) { return (value === true || value === false || value && typeof value == 'object' && toString.call(value) == '[object Boolean]') || false; } // adapted from lodash.isString function isString(value) { return typeof value == 'string' || (value && typeof value == 'object' && toString.call(value) == '[object String]') || false; } function isObject(value) { return toString.call(value) == '[object Object]' || false; } // adapted from lodash.isDate function isDate(value) { return (value && typeof value == 'object' && toString.call(value) == '[object Date]') || false; } // adapted from lodash.isNumber function isNumber(value) { var type = typeof value; return type == 'number' || (value && type == 'object' && toString.call(value) == '[object Number]') || false; } // adapted from lodash.isFunction function isFunction(value) { return typeof value == 'function' || (value && toString.call(value) === '[object Function]') || false; } // adapted from mout.isEmpty function isEmpty(val) { if (val == null) { // typeof null == 'object' so we check it first return true; } else if (typeof val === 'string' || isArray(val)) { return !val.length; } else if (typeof val === 'object') { var result = true; forOwn(val, function () { result = false; return false; // break loop }); return result; } else { return true; } } function intersection(array1, array2) { if (!array1 || !array2) { return []; } var result = []; var item; for (var i = 0, length = array1.length; i < length; i++) { item = array1[i]; if (DSUtils.contains(result, item)) { continue; } if (DSUtils.contains(array2, item)) { result.push(item); } } return result; } function filter(array, cb, thisObj) { var results = []; forEach(array, function (value, key, arr) { if (cb(value, key, arr)) { results.push(value); } }, thisObj); return results; } function finallyPolyfill(cb) { var constructor = this.constructor; return this.then(function (value) { return constructor.resolve(cb()).then(function () { return value; }); }, function (reason) { return constructor.resolve(cb()).then(function () { throw reason; }); }); } try { w = window; if (!w.Promise.prototype['finally']) { w.Promise.prototype['finally'] = finallyPolyfill; } _Promise = w.Promise; w = {}; } catch (e) { w = null; _Promise = require('bluebird'); } function updateTimestamp(timestamp) { var newTimestamp = typeof Date.now === 'function' ? Date.now() : new Date().getTime(); if (timestamp && newTimestamp <= timestamp) { return timestamp + 1; } else { return newTimestamp; } } function Events(target) { var events = {}; target = target || this; target.on = function (type, func, ctx) { events[type] = events[type] || []; events[type].push({ f: func, c: ctx }); }; target.off = function (type, func) { var listeners = events[type]; if (!listeners) { events = {}; } else if (func) { for (var i = 0; i < listeners.length; i++) { if (listeners[i] === func) { listeners.splice(i, 1); break; } } } else { listeners.splice(0, listeners.length); } }; target.emit = function () { var args = Array.prototype.slice.call(arguments); var listeners = events[args.shift()] || []; if (listeners) { for (var i = 0; i < listeners.length; i++) { listeners[i].f.apply(listeners[i].c, args); } } }; } /** * @method bubbleUp * @param {array} heap The heap. * @param {function} weightFunc The weight function. * @param {number} n The index of the element to bubble up. */ function bubbleUp(heap, weightFunc, n) { var element = heap[n]; var weight = weightFunc(element); // When at 0, an element can not go up any further. while (n > 0) { // Compute the parent element's index, and fetch it. var parentN = Math.floor((n + 1) / 2) - 1; var parent = heap[parentN]; // If the parent has a lesser weight, things are in order and we // are done. if (weight >= weightFunc(parent)) { break; } else { heap[parentN] = element; heap[n] = parent; n = parentN; } } } /** * @method bubbleDown * @param {array} heap The heap. * @param {function} weightFunc The weight function. * @param {number} n The index of the element to sink down. */ function bubbleDown(heap, weightFunc, n) { var length = heap.length; var node = heap[n]; var nodeWeight = weightFunc(node); while (true) { var child2N = (n + 1) * 2, child1N = child2N - 1; var swap = null; if (child1N < length) { var child1 = heap[child1N], child1Weight = weightFunc(child1); // If the score is less than our node's, we need to swap. if (child1Weight < nodeWeight) { swap = child1N; } } // Do the same checks for the other child. if (child2N < length) { var child2 = heap[child2N], child2Weight = weightFunc(child2); if (child2Weight < (swap === null ? nodeWeight : weightFunc(heap[child1N]))) { swap = child2N; } } if (swap === null) { break; } else { heap[n] = heap[swap]; heap[swap] = node; n = swap; } } } function DSBinaryHeap(weightFunc, compareFunc) { if (weightFunc && !isFunction(weightFunc)) { throw new Error('DSBinaryHeap(weightFunc): weightFunc: must be a function!'); } weightFunc = weightFunc || function (x) { return x; }; compareFunc = compareFunc || function (x, y) { return x === y; }; this.weightFunc = weightFunc; this.compareFunc = compareFunc; this.heap = []; } var dsp = DSBinaryHeap.prototype; dsp.push = function (node) { this.heap.push(node); bubbleUp(this.heap, this.weightFunc, this.heap.length - 1); }; dsp.peek = function () { return this.heap[0]; }; dsp.pop = function () { var front = this.heap[0], end = this.heap.pop(); if (this.heap.length > 0) { this.heap[0] = end; bubbleDown(this.heap, this.weightFunc, 0); } return front; }; dsp.remove = function (node) { var length = this.heap.length; for (var i = 0; i < length; i++) { if (this.compareFunc(this.heap[i], node)) { var removed = this.heap[i]; var end = this.heap.pop(); if (i !== length - 1) { this.heap[i] = end; bubbleUp(this.heap, this.weightFunc, i); bubbleDown(this.heap, this.weightFunc, i); } return removed; } } return null; }; dsp.removeAll = function () { this.heap = []; }; dsp.size = function () { return this.heap.length; }; var toPromisify = [ 'beforeValidate', 'validate', 'afterValidate', 'beforeCreate', 'afterCreate', 'beforeUpdate', 'afterUpdate', 'beforeDestroy', 'afterDestroy' ]; // adapted from angular.copy function copy(source, destination, stackSource, stackDest) { 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 new Error('Cannot 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 { 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; } } } } return destination; } // adapted from angular.equals 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) && isRegExp(o2)) { return o1.toString() == o2.toString(); } else { if (isArray(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; } function resolveId(definition, idOrInstance) { if (this.isString(idOrInstance) || isNumber(idOrInstance)) { return idOrInstance; } else if (idOrInstance && definition) { return idOrInstance[definition.idAttribute] || idOrInstance; } else { return idOrInstance; } } function resolveItem(resource, idOrInstance) { if (resource && (isString(idOrInstance) || isNumber(idOrInstance))) { return resource.index[idOrInstance] || idOrInstance; } else { return idOrInstance; } } function isValidString(val) { return (val != null && val !== ''); } function join(items, separator) { separator = separator || ''; return filter(items, isValidString).join(separator); } function makePath(var_args) { var result = join(slice(arguments), '/'); return result.replace(/([^:\/]|^)\/{2,}/g, '$1/'); } observe.setEqualityFn(equals); var DSUtils = { // Options that inherit from defaults _: function (parent, options) { var _this = this; options = options || {}; if (options && options.constructor === parent.constructor) { return options; } else if (!isObject(options)) { throw new DSErrors.IA('"options" must be an object!'); } forEach(toPromisify, function (name) { if (typeof options[name] === 'function' && options[name].toString().indexOf('var args = Array') === -1) { options[name] = _this.promisify(options[name]); } }); var O = function Options(attrs) { var self = this; forOwn(attrs, function (value, key) { self[key] = value; }); }; O.prototype = parent; return new O(options); }, compute: function (fn, field) { var _this = this; var args = []; forEach(fn.deps, function (dep) { args.push(_this[dep]); }); // compute property _this[field] = fn[fn.length - 1].apply(_this, args); }, contains: require('mout/array/contains'), copy: copy, deepMixIn: require('mout/object/deepMixIn'), diffObjectFromOldObject: observe.diffObjectFromOldObject, DSBinaryHeap: DSBinaryHeap, equals: equals, Events: Events, filter: filter, forEach: forEach, forOwn: forOwn, fromJson: function (json) { return isString(json) ? JSON.parse(json) : json; }, intersection: intersection, isArray: isArray, isBoolean: isBoolean, isDate: isDate, isEmpty: isEmpty, isFunction: isFunction, isObject: isObject, isNumber: isNumber, isRegExp: isRegExp, isString: isString, makePath: makePath, observe: observe, pascalCase: require('mout/string/pascalCase'), pick: require('mout/object/pick'), Promise: _Promise, promisify: function (fn, target) { var Promise = this.Promise; if (!fn) { return; } else if (typeof fn !== 'function') { throw new Error('Can only promisify functions!'); } return function () { var args = Array.prototype.slice.apply(arguments); return new Promise(function (resolve, reject) { args.push(function (err, result) { if (err) { reject(err); } else { resolve(result); } }); try { var promise = fn.apply(target || this, args); if (promise && promise.then) { promise.then(resolve, reject); } } catch (err) { reject(err); } }); }; }, remove: require('mout/array/remove'), set: require('mout/object/set'), slice: slice, sort: require('mout/array/sort'), toJson: JSON.stringify, updateTimestamp: updateTimestamp, upperCase: require('mout/string/upperCase'), resolveItem: resolveItem, resolveId: resolveId, w: w }; module.exports = DSUtils; },{"../lib/observe-js/observe-js":1,"./errors":46,"bluebird":"bluebird","es6-promise":2,"mout/array/contains":4,"mout/array/forEach":5,"mout/array/remove":7,"mout/array/slice":8,"mout/array/sort":9,"mout/object/deepMixIn":12,"mout/object/forOwn":14,"mout/object/pick":17,"mout/object/set":18,"mout/string/pascalCase":21,"mout/string/upperCase":24}]},{},[47])(47) });
/*! * Qoopido.js library v3.6.5, 2015-7-1 * https://github.com/dlueth/qoopido.js * (c) 2015 Dirk Lueth * Dual licensed under MIT and GPL */ !function(t){window.qoopido.register("polyfill/string/lcfirst",t)}(function(){"use strict";return String.prototype.lcfirst||(String.prototype.lcfirst=function(){var t=this;return t.charAt(0).toLowerCase()+t.slice(1)}),String.prototype.lcfirst});
$(window).load(function() { var lineChartData = { labels : ["January","February","March","April","May","June","July"], datasets : [ { fillColor : "rgba(220,220,220,0.5)", strokeColor : "rgba(220,220,220,1)", pointColor : "rgba(220,220,220,1)", pointStrokeColor : "#fff", data : [65,59,90,81,56,55,40] }, { fillColor : "rgba(151,187,205,0.5)", strokeColor : "rgba(151,187,205,1)", pointColor : "rgba(151,187,205,1)", pointStrokeColor : "#fff", data : [28,48,40,19,96,27,100] } ] }; var barChartData = { labels : ["January","February","March","April","May","June","July"], datasets : [ { fillColor : "rgba(220,220,220,0.5)", strokeColor : "rgba(220,220,220,1)", data : [65,59,90,81,56,55,40] }, { fillColor : "rgba(151,187,205,0.5)", strokeColor : "rgba(151,187,205,1)", data : [28,48,40,19,96,27,100] } ] }; var radarChartData = { labels : ["A","B","C","D","E","F","G"], datasets : [ { fillColor : "rgba(220,220,220,0.5)", strokeColor : "rgba(220,220,220,1)", pointColor : "rgba(220,220,220,1)", pointStrokeColor : "#fff", data : [65,59,90,81,56,55,40] }, { fillColor : "rgba(151,187,205,0.5)", strokeColor : "rgba(151,187,205,1)", pointColor : "rgba(151,187,205,1)", pointStrokeColor : "#fff", data : [28,48,40,19,96,27,100] } ] }; var pieChartData = [ { value: 30, color:"#F38630" }, { value : 50, color : "#E0E4CC" }, { value : 100, color : "#69D2E7" } ]; var polarAreaChartData = [ { value : 62, color: "#D97041" }, { value : 70, color: "#C7604C" }, { value : 41, color: "#21323D" }, { value : 24, color: "#9D9B7F" }, { value : 55, color: "#7D4F6D" }, { value : 18, color: "#584A5E" } ]; var doughnutChartData = [ { value: 30, color:"#F7464A" }, { value : 50, color : "#46BFBD" }, { value : 100, color : "#FDB45C" }, { value : 40, color : "#949FB1" }, { value : 120, color : "#4D5360" } ]; var globalGraphSettings = {animation : Modernizr.canvas}; setIntroChart(); function setIntroChart(){ var ctx = document.getElementById("introChart").getContext("2d"); new Chart(ctx).Line(lineChartData,{animation: Modernizr.canvas, scaleShowLabels : false, scaleFontColor : "#767C8D"}); }; function showLineChart(){ var ctx = document.getElementById("lineChartCanvas").getContext("2d"); new Chart(ctx).Line(lineChartData,globalGraphSettings); }; function showBarChart(){ var ctx = document.getElementById("barChartCanvas").getContext("2d"); new Chart(ctx).Bar(barChartData,globalGraphSettings); }; function showRadarChart(){ var ctx = document.getElementById("radarChartCanvas").getContext("2d"); new Chart(ctx).Radar(radarChartData,globalGraphSettings); } function showPolarAreaChart(){ var ctx = document.getElementById("polarAreaChartCanvas").getContext("2d"); new Chart(ctx).PolarArea(polarAreaChartData,globalGraphSettings); } function showPieChart(){ var ctx = document.getElementById("pieChartCanvas").getContext("2d"); new Chart(ctx).Pie(pieChartData,globalGraphSettings); }; function showDoughnutChart(){ var ctx = document.getElementById("doughnutChartCanvas").getContext("2d"); new Chart(ctx).Doughnut(doughnutChartData,globalGraphSettings); }; var graphInitDelay = 300; //Set up each of the inview events here. $("#lineChart").on("inview",function(){ var $this = $(this); $this.removeClass("hidden").off("inview"); setTimeout(showLineChart,graphInitDelay); }); $("#barChart").on("inview",function(){ var $this = $(this); $this.removeClass("hidden").off("inview"); setTimeout(showBarChart,graphInitDelay); }); $("#radarChart").on("inview",function(){ var $this = $(this); $this.removeClass("hidden").off("inview"); setTimeout(showRadarChart,graphInitDelay); }); $("#pieChart").on("inview",function(){ var $this = $(this); $this.removeClass("hidden").off("inview"); setTimeout(showPieChart,graphInitDelay); }); $("#polarAreaChart").on("inview",function(){ var $this = $(this); $this.removeClass("hidden").off("inview"); setTimeout(showPolarAreaChart,graphInitDelay); }); $("#doughnutChart").on("inview",function(){ var $this = $(this); $this.removeClass("hidden").off("inview"); setTimeout(showDoughnutChart,graphInitDelay); }); }); /** * author Christopher Blum * - based on the idea of Remy Sharp, http://remysharp.com/2009/01/26/element-in-view-event-plugin/ * - forked from http://github.com/zuk/jquery.inview/ */ (function ($) { var inviewObjects = {}, viewportSize, viewportOffset, d = document, w = window, documentElement = d.documentElement, expando = $.expando; $.event.special.inview = { add: function(data) { inviewObjects[data.guid + "-" + this[expando]] = { data: data, $element: $(this) }; }, remove: function(data) { try { delete inviewObjects[data.guid + "-" + this[expando]]; } catch(e) {} } }; function getViewportSize() { var mode, domObject, size = { height: w.innerHeight, width: w.innerWidth }; // if this is correct then return it. iPad has compat Mode, so will // go into check clientHeight/clientWidth (which has the wrong value). if (!size.height) { mode = d.compatMode; if (mode || !$.support.boxModel) { // IE, Gecko domObject = mode === 'CSS1Compat' ? documentElement : // Standards d.body; // Quirks size = { height: domObject.clientHeight, width: domObject.clientWidth }; } } return size; } function getViewportOffset() { return { top: w.pageYOffset || documentElement.scrollTop || d.body.scrollTop, left: w.pageXOffset || documentElement.scrollLeft || d.body.scrollLeft }; } function checkInView() { var $elements = $(), elementsLength, i = 0; $.each(inviewObjects, function(i, inviewObject) { var selector = inviewObject.data.selector, $element = inviewObject.$element; $elements = $elements.add(selector ? $element.find(selector) : $element); }); elementsLength = $elements.length; if (elementsLength) { viewportSize = viewportSize || getViewportSize(); viewportOffset = viewportOffset || getViewportOffset(); for (; i<elementsLength; i++) { // Ignore elements that are not in the DOM tree if (!$.contains(documentElement, $elements[i])) { continue; } var $element = $($elements[i]), elementSize = { height: $element.height(), width: $element.width() }, elementOffset = $element.offset(), inView = $element.data('inview'), visiblePartX, visiblePartY, visiblePartsMerged; // Don't ask me why because I haven't figured out yet: // viewportOffset and viewportSize are sometimes suddenly null in Firefox 5. // Even though it sounds weird: // It seems that the execution of this function is interferred by the onresize/onscroll event // where viewportOffset and viewportSize are unset if (!viewportOffset || !viewportSize) { return; } if (elementOffset.top + elementSize.height > viewportOffset.top && elementOffset.top < viewportOffset.top + viewportSize.height && elementOffset.left + elementSize.width > viewportOffset.left && elementOffset.left < viewportOffset.left + viewportSize.width) { visiblePartX = (viewportOffset.left > elementOffset.left ? 'right' : (viewportOffset.left + viewportSize.width) < (elementOffset.left + elementSize.width) ? 'left' : 'both'); visiblePartY = (viewportOffset.top > elementOffset.top ? 'bottom' : (viewportOffset.top + viewportSize.height) < (elementOffset.top + elementSize.height) ? 'top' : 'both'); visiblePartsMerged = visiblePartX + "-" + visiblePartY; if (!inView || inView !== visiblePartsMerged) { $element.data('inview', visiblePartsMerged).trigger('inview', [true, visiblePartX, visiblePartY]); } } else if (inView) { $element.data('inview', false).trigger('inview', [false]); } } } } $(w).bind("scroll resize", function() { viewportSize = viewportOffset = null; }); // IE < 9 scrolls to focused elements without firing the "scroll" event if (!documentElement.addEventListener && documentElement.attachEvent) { documentElement.attachEvent("onfocusin", function() { viewportOffset = null; }); } // Use setInterval in order to also make sure this captures elements within // "overflow:scroll" elements or elements that appeared in the dom tree due to // dom manipulation and reflow // old: $(window).scroll(checkInView); // // By the way, iOS (iPad, iPhone, ...) seems to not execute, or at least delays // intervals while the user scrolls. Therefore the inview event might fire a bit late there setInterval(checkInView, 250); })(jQuery);
/* 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/cldr/monetary",["../_base/kernel","../_base/lang"],function(_1,_2){ var _3={}; _2.setObject("dojo.cldr.monetary",_3); _3.getData=function(_4){ var _5={ADP:0,AFN:0,ALL:0,AMD:0,BHD:3,BIF:0,BYR:0,CLF:0,CLP:0,COP:0,CRC:0,DJF:0,ESP:0,GNF:0,GYD:0,HUF:0,IDR:0,IQD:0,IRR:3,ISK:0,ITL:0,JOD:3,JPY:0,KMF:0,KPW:0,KRW:0,KWD:3,LAK:0,LBP:0,LUF:0,LYD:3,MGA:0,MGF:0,MMK:0,MNT:0,MRO:0,MUR:0,OMR:3,PKR:2,PYG:0,RSD:0,RWF:0,SLL:0,SOS:0,STD:0,SYP:0,TMM:0,TND:3,TRL:0,TZS:0,UGX:0,UZS:0,VND:0,VUV:0,XAF:0,XOF:0,XPF:0,YER:0,ZMK:0,ZWD:0}; var _6={}; var _7=_5[_4],_8=_6[_4]; if(typeof _7=="undefined"){ _7=2; } if(typeof _8=="undefined"){ _8=0; } return {places:_7,round:_8}; }; return _3; });